net.go 18 KB

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