net.go 18 KB

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