net.go 19 KB

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