net.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. /*
  2. * Copyright (c) 2015, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package psiphon
  20. import (
  21. "context"
  22. "crypto/tls"
  23. "crypto/x509"
  24. "errors"
  25. "fmt"
  26. "io"
  27. "io/ioutil"
  28. "net"
  29. "net/http"
  30. "os"
  31. "sync"
  32. "sync/atomic"
  33. "time"
  34. "github.com/Psiphon-Labs/dns"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/fragmentor"
  37. )
  38. const DNS_PORT = 53
  39. // DialConfig contains parameters to determine the behavior
  40. // of a Psiphon dialer (TCPDial, UDPDial, MeekDial, etc.)
  41. type DialConfig struct {
  42. // UpstreamProxyURL specifies a proxy to connect through.
  43. // E.g., "http://proxyhost:8080"
  44. // "socks5://user:password@proxyhost:1080"
  45. // "socks4a://proxyhost:1080"
  46. // "http://NTDOMAIN\NTUser:password@proxyhost:3375"
  47. //
  48. // Certain tunnel protocols require HTTP CONNECT support
  49. // when a HTTP proxy is specified. If CONNECT is not
  50. // supported, those protocols will not connect.
  51. //
  52. // UpstreamProxyURL is not used by UDPDial.
  53. UpstreamProxyURL string
  54. // CustomHeaders is a set of additional arbitrary HTTP headers that are
  55. // added to all plaintext HTTP requests and requests made through an HTTP
  56. // upstream proxy when specified by UpstreamProxyURL.
  57. CustomHeaders http.Header
  58. // BindToDevice parameters are used to exclude connections and
  59. // associated DNS requests from VPN routing.
  60. // When DeviceBinder is set, any underlying socket is
  61. // submitted to the device binding servicebefore connecting.
  62. // The service should bind the socket to a device so that it doesn't route
  63. // through a VPN interface. This service is also used to bind UDP sockets used
  64. // for DNS requests, in which case DnsServerGetter is used to get the
  65. // current active untunneled network DNS server.
  66. DeviceBinder DeviceBinder
  67. DnsServerGetter DnsServerGetter
  68. IPv6Synthesizer IPv6Synthesizer
  69. // TrustedCACertificatesFilename specifies a file containing trusted
  70. // CA certs. See Config.TrustedCACertificatesFilename.
  71. TrustedCACertificatesFilename string
  72. // ResolvedIPCallback, when set, is called with the IP address that was
  73. // dialed. This is either the specified IP address in the dial address,
  74. // or the resolved IP address in the case where the dial address is a
  75. // domain name.
  76. // The callback may be invoked by a concurrent goroutine.
  77. ResolvedIPCallback func(string)
  78. // FragmentorConfig specifies whether to layer a fragmentor.Conn on top
  79. // of dialed TCP conns, and the fragmentation configuration to use.
  80. FragmentorConfig *fragmentor.Config
  81. }
  82. // NetworkConnectivityChecker defines the interface to the external
  83. // HasNetworkConnectivity provider, which call into the host application to
  84. // check for network connectivity.
  85. type NetworkConnectivityChecker interface {
  86. // TODO: change to bool return value once gobind supports that type
  87. HasNetworkConnectivity() int
  88. }
  89. // DeviceBinder defines the interface to the external BindToDevice provider
  90. // which calls into the host application to bind sockets to specific devices.
  91. // This is used for VPN routing exclusion.
  92. // The string return value should report device information for diagnostics.
  93. type DeviceBinder interface {
  94. BindToDevice(fileDescriptor int) (string, error)
  95. }
  96. // DnsServerGetter defines the interface to the external GetDnsServer provider
  97. // which calls into the host application to discover the native network DNS
  98. // server settings.
  99. type DnsServerGetter interface {
  100. GetPrimaryDnsServer() string
  101. GetSecondaryDnsServer() string
  102. }
  103. // IPv6Synthesizer defines the interface to the external IPv6Synthesize
  104. // provider which calls into the host application to synthesize IPv6 addresses
  105. // from IPv4 ones. This is used to correctly lookup IPs on DNS64/NAT64
  106. // networks.
  107. type IPv6Synthesizer interface {
  108. IPv6Synthesize(IPv4Addr string) string
  109. }
  110. // NetworkIDGetter defines the interface to the external GetNetworkID
  111. // provider, which returns an identifier for the host's current active
  112. // network.
  113. //
  114. // The identifier is a string that should indicate the network type and
  115. // identity; for example "WIFI-<BSSID>" or "MOBILE-<MCC/MNC>". As this network
  116. // ID is personally identifying, it is only used locally in the client to
  117. // determine network context and is not sent to the Psiphon server. The
  118. // identifer will be logged in diagnostics messages; in this case only the
  119. // substring before the first "-" is logged, so all PII must appear after the
  120. // first "-".
  121. //
  122. // NetworkIDGetter.GetNetworkID should always return an identifier value, as
  123. // logic that uses GetNetworkID, including tactics, is intended to proceed
  124. // regardless of whether an accurate network identifier can be obtained. By
  125. // convention, the provider should return "UNKNOWN" when an accurate network
  126. // identifier cannot be obtained. Best-effort is acceptable: e.g., return just
  127. // "WIFI" when only the type of the network but no details can be determined.
  128. type NetworkIDGetter interface {
  129. GetNetworkID() string
  130. }
  131. // Dialer is a custom network dialer.
  132. type Dialer func(context.Context, string, string) (net.Conn, error)
  133. // NetDialer implements an interface that matches net.Dialer.
  134. // Limitation: only "tcp" Dials are supported.
  135. type NetDialer struct {
  136. dialTCP Dialer
  137. }
  138. // NewNetDialer creates a new NetDialer.
  139. func NewNetDialer(config *DialConfig) *NetDialer {
  140. return &NetDialer{
  141. dialTCP: NewTCPDialer(config),
  142. }
  143. }
  144. func (d *NetDialer) Dial(network, address string) (net.Conn, error) {
  145. return d.DialContext(context.Background(), network, address)
  146. }
  147. func (d *NetDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
  148. switch network {
  149. case "tcp":
  150. return d.dialTCP(ctx, "tcp", address)
  151. default:
  152. return nil, common.ContextError(fmt.Errorf("unsupported network: %s", network))
  153. }
  154. }
  155. // LocalProxyRelay sends to remoteConn bytes received from localConn,
  156. // and sends to localConn bytes received from remoteConn.
  157. //
  158. // LocalProxyRelay must close localConn in order to interrupt blocking
  159. // I/O calls when the upstream port forward is closed. remoteConn is
  160. // also closed before returning.
  161. func LocalProxyRelay(proxyType string, localConn, remoteConn net.Conn) {
  162. closing := int32(0)
  163. copyWaitGroup := new(sync.WaitGroup)
  164. copyWaitGroup.Add(1)
  165. go func() {
  166. defer copyWaitGroup.Done()
  167. _, err := io.Copy(localConn, remoteConn)
  168. if err != nil && atomic.LoadInt32(&closing) != 1 {
  169. err = fmt.Errorf("Relay failed: %s", common.ContextError(err))
  170. NoticeLocalProxyError(proxyType, err)
  171. }
  172. // When the server closes a port forward, ex. due to idle timeout,
  173. // remoteConn.Read will return EOF, which causes the downstream io.Copy to
  174. // return (with a nil error). To ensure the downstream local proxy
  175. // connection also closes at this point, we interrupt the blocking upstream
  176. // io.Copy by closing localConn.
  177. atomic.StoreInt32(&closing, 1)
  178. localConn.Close()
  179. }()
  180. _, err := io.Copy(remoteConn, localConn)
  181. if err != nil && atomic.LoadInt32(&closing) != 1 {
  182. err = fmt.Errorf("Relay failed: %s", common.ContextError(err))
  183. NoticeLocalProxyError(proxyType, err)
  184. }
  185. // When a local proxy peer connection closes, localConn.Read will return EOF.
  186. // As above, close the other end of the relay to ensure immediate shutdown,
  187. // as no more data can be relayed.
  188. atomic.StoreInt32(&closing, 1)
  189. remoteConn.Close()
  190. copyWaitGroup.Wait()
  191. }
  192. // WaitForNetworkConnectivity uses a NetworkConnectivityChecker to
  193. // periodically check for network connectivity. It returns true if
  194. // no NetworkConnectivityChecker is provided (waiting is disabled)
  195. // or when NetworkConnectivityChecker.HasNetworkConnectivity()
  196. // indicates connectivity. It waits and polls the checker once a second.
  197. // When the context is done, false is returned immediately.
  198. func WaitForNetworkConnectivity(
  199. ctx context.Context, connectivityChecker NetworkConnectivityChecker) bool {
  200. if connectivityChecker == nil || 1 == connectivityChecker.HasNetworkConnectivity() {
  201. return true
  202. }
  203. NoticeInfo("waiting for network connectivity")
  204. ticker := time.NewTicker(1 * time.Second)
  205. defer ticker.Stop()
  206. for {
  207. if 1 == connectivityChecker.HasNetworkConnectivity() {
  208. return true
  209. }
  210. select {
  211. case <-ticker.C:
  212. // Check HasNetworkConnectivity again
  213. case <-ctx.Done():
  214. return false
  215. }
  216. }
  217. }
  218. // ResolveIP uses a custom dns stack to make a DNS query over the
  219. // given TCP or UDP conn. This is used, e.g., when we need to ensure
  220. // that a DNS connection bypasses a VPN interface (BindToDevice) or
  221. // when we need to ensure that a DNS connection is tunneled.
  222. // Caller must set timeouts or interruptibility as required for conn.
  223. func ResolveIP(host string, conn net.Conn) (addrs []net.IP, ttls []time.Duration, err error) {
  224. // Send the DNS query
  225. dnsConn := &dns.Conn{Conn: conn}
  226. defer dnsConn.Close()
  227. query := new(dns.Msg)
  228. query.SetQuestion(dns.Fqdn(host), dns.TypeA)
  229. query.RecursionDesired = true
  230. dnsConn.WriteMsg(query)
  231. // Process the response
  232. response, err := dnsConn.ReadMsg()
  233. if err != nil {
  234. return nil, nil, common.ContextError(err)
  235. }
  236. addrs = make([]net.IP, 0)
  237. ttls = make([]time.Duration, 0)
  238. for _, answer := range response.Answer {
  239. if a, ok := answer.(*dns.A); ok {
  240. addrs = append(addrs, a.A)
  241. ttl := time.Duration(a.Hdr.Ttl) * time.Second
  242. ttls = append(ttls, ttl)
  243. }
  244. }
  245. return addrs, ttls, nil
  246. }
  247. // MakeUntunneledHTTPClient returns a net/http.Client which is configured to
  248. // use custom dialing features -- including BindToDevice, etc. If
  249. // verifyLegacyCertificate is not nil, it's used for certificate verification.
  250. // The context is applied to underlying TCP dials. The caller is responsible
  251. // for applying the context to requests made with the returned http.Client.
  252. func MakeUntunneledHTTPClient(
  253. ctx context.Context,
  254. config *Config,
  255. untunneledDialConfig *DialConfig,
  256. verifyLegacyCertificate *x509.Certificate,
  257. skipVerify bool) (*http.Client, error) {
  258. dialer := NewTCPDialer(untunneledDialConfig)
  259. // Note: when verifyLegacyCertificate is not nil, some
  260. // of the other CustomTLSConfig is overridden.
  261. tlsConfig := &CustomTLSConfig{
  262. ClientParameters: config.clientParameters,
  263. Dial: dialer,
  264. VerifyLegacyCertificate: verifyLegacyCertificate,
  265. UseDialAddrSNI: true,
  266. SNIServerName: "",
  267. SkipVerify: skipVerify,
  268. TrustedCACertificatesFilename: untunneledDialConfig.TrustedCACertificatesFilename,
  269. }
  270. tlsConfig.EnableClientSessionCache(config.clientParameters)
  271. tlsDialer := NewCustomTLSDialer(tlsConfig)
  272. transport := &http.Transport{
  273. Dial: func(network, addr string) (net.Conn, error) {
  274. return dialer(ctx, network, addr)
  275. },
  276. DialTLS: func(network, addr string) (net.Conn, error) {
  277. return tlsDialer(ctx, network, addr)
  278. },
  279. }
  280. httpClient := &http.Client{
  281. Transport: transport,
  282. }
  283. return httpClient, nil
  284. }
  285. // MakeTunneledHTTPClient returns a net/http.Client which is
  286. // configured to use custom dialing features including tunneled
  287. // dialing and, optionally, UseTrustedCACertificatesForStockTLS.
  288. // This http.Client uses stock TLS for HTTPS.
  289. func MakeTunneledHTTPClient(
  290. config *Config,
  291. tunnel *Tunnel,
  292. skipVerify bool) (*http.Client, error) {
  293. // Note: there is no dial context since SSH port forward dials cannot
  294. // be interrupted directly. Closing the tunnel will interrupt the dials.
  295. tunneledDialer := func(_, addr string) (conn net.Conn, err error) {
  296. return tunnel.sshClient.Dial("tcp", addr)
  297. }
  298. transport := &http.Transport{
  299. Dial: tunneledDialer,
  300. }
  301. if skipVerify {
  302. transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
  303. } else if config.TrustedCACertificatesFilename != "" {
  304. rootCAs := x509.NewCertPool()
  305. certData, err := ioutil.ReadFile(config.TrustedCACertificatesFilename)
  306. if err != nil {
  307. return nil, common.ContextError(err)
  308. }
  309. rootCAs.AppendCertsFromPEM(certData)
  310. transport.TLSClientConfig = &tls.Config{RootCAs: rootCAs}
  311. }
  312. return &http.Client{
  313. Transport: transport,
  314. }, nil
  315. }
  316. // MakeDownloadHTTPClient is a helper that sets up a http.Client
  317. // for use either untunneled or through a tunnel.
  318. func MakeDownloadHTTPClient(
  319. ctx context.Context,
  320. config *Config,
  321. tunnel *Tunnel,
  322. untunneledDialConfig *DialConfig,
  323. skipVerify bool) (*http.Client, error) {
  324. var httpClient *http.Client
  325. var err error
  326. if tunnel != nil {
  327. httpClient, err = MakeTunneledHTTPClient(
  328. config, tunnel, skipVerify)
  329. if err != nil {
  330. return nil, common.ContextError(err)
  331. }
  332. } else {
  333. httpClient, err = MakeUntunneledHTTPClient(
  334. ctx, config, untunneledDialConfig, nil, skipVerify)
  335. if err != nil {
  336. return nil, common.ContextError(err)
  337. }
  338. }
  339. return httpClient, nil
  340. }
  341. // ResumeDownload is a reusable helper that downloads requestUrl via the
  342. // httpClient, storing the result in downloadFilename when the download is
  343. // complete. Intermediate, partial downloads state is stored in
  344. // downloadFilename.part and downloadFilename.part.etag.
  345. // Any existing downloadFilename file will be overwritten.
  346. //
  347. // In the case where the remote object has changed while a partial download
  348. // is to be resumed, the partial state is reset and resumeDownload fails.
  349. // The caller must restart the download.
  350. //
  351. // When ifNoneMatchETag is specified, no download is made if the remote
  352. // object has the same ETag. ifNoneMatchETag has an effect only when no
  353. // partial download is in progress.
  354. //
  355. func ResumeDownload(
  356. ctx context.Context,
  357. httpClient *http.Client,
  358. downloadURL string,
  359. userAgent string,
  360. downloadFilename string,
  361. ifNoneMatchETag string) (int64, string, error) {
  362. partialFilename := fmt.Sprintf("%s.part", downloadFilename)
  363. partialETagFilename := fmt.Sprintf("%s.part.etag", downloadFilename)
  364. file, err := os.OpenFile(partialFilename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
  365. if err != nil {
  366. return 0, "", common.ContextError(err)
  367. }
  368. defer file.Close()
  369. fileInfo, err := file.Stat()
  370. if err != nil {
  371. return 0, "", common.ContextError(err)
  372. }
  373. // A partial download should have an ETag which is to be sent with the
  374. // Range request to ensure that the source object is the same as the
  375. // one that is partially downloaded.
  376. var partialETag []byte
  377. if fileInfo.Size() > 0 {
  378. partialETag, err = ioutil.ReadFile(partialETagFilename)
  379. // When the ETag can't be loaded, delete the partial download. To keep the
  380. // code simple, there is no immediate, inline retry here, on the assumption
  381. // that the controller's upgradeDownloader will shortly call DownloadUpgrade
  382. // again.
  383. if err != nil {
  384. // On Windows, file must be closed before it can be deleted
  385. file.Close()
  386. tempErr := os.Remove(partialFilename)
  387. if tempErr != nil && !os.IsNotExist(tempErr) {
  388. NoticeAlert("reset partial download failed: %s", tempErr)
  389. }
  390. tempErr = os.Remove(partialETagFilename)
  391. if tempErr != nil && !os.IsNotExist(tempErr) {
  392. NoticeAlert("reset partial download ETag failed: %s", tempErr)
  393. }
  394. return 0, "", common.ContextError(
  395. fmt.Errorf("failed to load partial download ETag: %s", err))
  396. }
  397. }
  398. request, err := http.NewRequest("GET", downloadURL, nil)
  399. if err != nil {
  400. return 0, "", common.ContextError(err)
  401. }
  402. request = request.WithContext(ctx)
  403. request.Header.Set("User-Agent", userAgent)
  404. request.Header.Add("Range", fmt.Sprintf("bytes=%d-", fileInfo.Size()))
  405. if partialETag != nil {
  406. // Note: not using If-Range, since not all host servers support it.
  407. // Using If-Match means we need to check for status code 412 and reset
  408. // when the ETag has changed since the last partial download.
  409. request.Header.Add("If-Match", string(partialETag))
  410. } else if ifNoneMatchETag != "" {
  411. // Can't specify both If-Match and If-None-Match. Behavior is undefined.
  412. // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
  413. // So for downloaders that store an ETag and wish to use that to prevent
  414. // redundant downloads, that ETag is sent as If-None-Match in the case
  415. // where a partial download is not in progress. When a partial download
  416. // is in progress, the partial ETag is sent as If-Match: either that's
  417. // a version that was never fully received, or it's no longer current in
  418. // which case the response will be StatusPreconditionFailed, the partial
  419. // download will be discarded, and then the next retry will use
  420. // If-None-Match.
  421. // Note: in this case, fileInfo.Size() == 0
  422. request.Header.Add("If-None-Match", ifNoneMatchETag)
  423. }
  424. response, err := httpClient.Do(request)
  425. // The resumeable download may ask for bytes past the resource range
  426. // since it doesn't store the "completed download" state. In this case,
  427. // the HTTP server returns 416. Otherwise, we expect 206. We may also
  428. // receive 412 on ETag mismatch.
  429. if err == nil &&
  430. (response.StatusCode != http.StatusPartialContent &&
  431. // Certain http servers return 200 OK where we expect 206, so accept that.
  432. response.StatusCode != http.StatusOK &&
  433. response.StatusCode != http.StatusRequestedRangeNotSatisfiable &&
  434. response.StatusCode != http.StatusPreconditionFailed &&
  435. response.StatusCode != http.StatusNotModified) {
  436. response.Body.Close()
  437. err = fmt.Errorf("unexpected response status code: %d", response.StatusCode)
  438. }
  439. if err != nil {
  440. return 0, "", common.ContextError(err)
  441. }
  442. defer response.Body.Close()
  443. responseETag := response.Header.Get("ETag")
  444. if response.StatusCode == http.StatusPreconditionFailed {
  445. // When the ETag no longer matches, delete the partial download. As above,
  446. // simply failing and relying on the caller's retry schedule.
  447. os.Remove(partialFilename)
  448. os.Remove(partialETagFilename)
  449. return 0, "", common.ContextError(errors.New("partial download ETag mismatch"))
  450. } else if response.StatusCode == http.StatusNotModified {
  451. // This status code is possible in the "If-None-Match" case. Don't leave
  452. // any partial download in progress. Caller should check that responseETag
  453. // matches ifNoneMatchETag.
  454. os.Remove(partialFilename)
  455. os.Remove(partialETagFilename)
  456. return 0, responseETag, nil
  457. }
  458. // Not making failure to write ETag file fatal, in case the entire download
  459. // succeeds in this one request.
  460. ioutil.WriteFile(partialETagFilename, []byte(responseETag), 0600)
  461. // A partial download occurs when this copy is interrupted. The io.Copy
  462. // will fail, leaving a partial download in place (.part and .part.etag).
  463. n, err := io.Copy(NewSyncFileWriter(file), response.Body)
  464. // From this point, n bytes are indicated as downloaded, even if there is
  465. // an error; the caller may use this to report partial download progress.
  466. if err != nil {
  467. return n, "", common.ContextError(err)
  468. }
  469. // Ensure the file is flushed to disk. The deferred close
  470. // will be a noop when this succeeds.
  471. err = file.Close()
  472. if err != nil {
  473. return n, "", common.ContextError(err)
  474. }
  475. // Remove if exists, to enable rename
  476. os.Remove(downloadFilename)
  477. err = os.Rename(partialFilename, downloadFilename)
  478. if err != nil {
  479. return n, "", common.ContextError(err)
  480. }
  481. os.Remove(partialETagFilename)
  482. return n, responseETag, nil
  483. }