net.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  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. "strings"
  32. "sync"
  33. "sync/atomic"
  34. "time"
  35. "github.com/Psiphon-Labs/dns"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  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, common.ContextError(fmt.Errorf("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. err = fmt.Errorf("Relay failed: %s", common.ContextError(err))
  173. NoticeLocalProxyError(proxyType, err)
  174. }
  175. // When the server closes a port forward, ex. due to idle timeout,
  176. // remoteConn.Read will return EOF, which causes the downstream io.Copy to
  177. // return (with a nil error). To ensure the downstream local proxy
  178. // connection also closes at this point, we interrupt the blocking upstream
  179. // io.Copy by closing localConn.
  180. atomic.StoreInt32(&closing, 1)
  181. localConn.Close()
  182. }()
  183. _, err := io.Copy(remoteConn, localConn)
  184. if err != nil && atomic.LoadInt32(&closing) != 1 {
  185. err = fmt.Errorf("Relay failed: %s", common.ContextError(err))
  186. NoticeLocalProxyError(proxyType, err)
  187. }
  188. // When a local proxy peer connection closes, localConn.Read will return EOF.
  189. // As above, close the other end of the relay to ensure immediate shutdown,
  190. // as no more data can be relayed.
  191. atomic.StoreInt32(&closing, 1)
  192. remoteConn.Close()
  193. copyWaitGroup.Wait()
  194. }
  195. // WaitForNetworkConnectivity uses a NetworkConnectivityChecker to
  196. // periodically check for network connectivity. It returns true if
  197. // no NetworkConnectivityChecker is provided (waiting is disabled)
  198. // or when NetworkConnectivityChecker.HasNetworkConnectivity()
  199. // indicates connectivity. It waits and polls the checker once a second.
  200. // When the context is done, false is returned immediately.
  201. func WaitForNetworkConnectivity(
  202. ctx context.Context, connectivityChecker NetworkConnectivityChecker) bool {
  203. if connectivityChecker == nil || 1 == connectivityChecker.HasNetworkConnectivity() {
  204. return true
  205. }
  206. NoticeInfo("waiting for network connectivity")
  207. ticker := time.NewTicker(1 * time.Second)
  208. defer ticker.Stop()
  209. for {
  210. if 1 == connectivityChecker.HasNetworkConnectivity() {
  211. return true
  212. }
  213. select {
  214. case <-ticker.C:
  215. // Check HasNetworkConnectivity again
  216. case <-ctx.Done():
  217. return false
  218. }
  219. }
  220. }
  221. // ResolveIP uses a custom dns stack to make a DNS query over the
  222. // given TCP or UDP conn. This is used, e.g., when we need to ensure
  223. // that a DNS connection bypasses a VPN interface (BindToDevice) or
  224. // when we need to ensure that a DNS connection is tunneled.
  225. // Caller must set timeouts or interruptibility as required for conn.
  226. func ResolveIP(host string, conn net.Conn) (addrs []net.IP, ttls []time.Duration, err error) {
  227. // Send the DNS query
  228. dnsConn := &dns.Conn{Conn: conn}
  229. defer dnsConn.Close()
  230. query := new(dns.Msg)
  231. query.SetQuestion(dns.Fqdn(host), dns.TypeA)
  232. query.RecursionDesired = true
  233. dnsConn.WriteMsg(query)
  234. // Process the response
  235. response, err := dnsConn.ReadMsg()
  236. if err != nil {
  237. return nil, nil, common.ContextError(err)
  238. }
  239. addrs = make([]net.IP, 0)
  240. ttls = make([]time.Duration, 0)
  241. for _, answer := range response.Answer {
  242. if a, ok := answer.(*dns.A); ok {
  243. addrs = append(addrs, a.A)
  244. ttl := time.Duration(a.Hdr.Ttl) * time.Second
  245. ttls = append(ttls, ttl)
  246. }
  247. }
  248. return addrs, ttls, nil
  249. }
  250. // MakeUntunneledHTTPClient returns a net/http.Client which is configured to
  251. // use custom dialing features -- including BindToDevice, etc. If
  252. // verifyLegacyCertificate is not nil, it's used for certificate verification.
  253. // The context is applied to underlying TCP dials. The caller is responsible
  254. // for applying the context to requests made with the returned http.Client.
  255. func MakeUntunneledHTTPClient(
  256. ctx context.Context,
  257. config *Config,
  258. untunneledDialConfig *DialConfig,
  259. verifyLegacyCertificate *x509.Certificate,
  260. skipVerify bool) (*http.Client, error) {
  261. dialer := NewTCPDialer(untunneledDialConfig)
  262. // Note: when verifyLegacyCertificate is not nil, some
  263. // of the other CustomTLSConfig is overridden.
  264. tlsConfig := &CustomTLSConfig{
  265. ClientParameters: config.clientParameters,
  266. Dial: dialer,
  267. VerifyLegacyCertificate: verifyLegacyCertificate,
  268. UseDialAddrSNI: true,
  269. SNIServerName: "",
  270. SkipVerify: skipVerify,
  271. TrustedCACertificatesFilename: untunneledDialConfig.TrustedCACertificatesFilename,
  272. }
  273. tlsConfig.EnableClientSessionCache(config.clientParameters)
  274. tlsDialer := NewCustomTLSDialer(tlsConfig)
  275. transport := &http.Transport{
  276. Dial: func(network, addr string) (net.Conn, error) {
  277. return dialer(ctx, network, addr)
  278. },
  279. DialTLS: func(network, addr string) (net.Conn, error) {
  280. return tlsDialer(ctx, network, addr)
  281. },
  282. }
  283. httpClient := &http.Client{
  284. Transport: transport,
  285. }
  286. return httpClient, nil
  287. }
  288. // MakeTunneledHTTPClient returns a net/http.Client which is
  289. // configured to use custom dialing features including tunneled
  290. // dialing and, optionally, UseTrustedCACertificatesForStockTLS.
  291. // This http.Client uses stock TLS for HTTPS.
  292. func MakeTunneledHTTPClient(
  293. config *Config,
  294. tunnel *Tunnel,
  295. skipVerify bool) (*http.Client, error) {
  296. // Note: there is no dial context since SSH port forward dials cannot
  297. // be interrupted directly. Closing the tunnel will interrupt the dials.
  298. tunneledDialer := func(_, addr string) (conn net.Conn, err error) {
  299. return tunnel.sshClient.Dial("tcp", addr)
  300. }
  301. transport := &http.Transport{
  302. Dial: tunneledDialer,
  303. }
  304. if skipVerify {
  305. transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
  306. } else if config.TrustedCACertificatesFilename != "" {
  307. rootCAs := x509.NewCertPool()
  308. certData, err := ioutil.ReadFile(config.TrustedCACertificatesFilename)
  309. if err != nil {
  310. return nil, common.ContextError(err)
  311. }
  312. rootCAs.AppendCertsFromPEM(certData)
  313. transport.TLSClientConfig = &tls.Config{RootCAs: rootCAs}
  314. }
  315. return &http.Client{
  316. Transport: transport,
  317. }, nil
  318. }
  319. // MakeDownloadHTTPClient is a helper that sets up a http.Client
  320. // for use either untunneled or through a tunnel.
  321. func MakeDownloadHTTPClient(
  322. ctx context.Context,
  323. config *Config,
  324. tunnel *Tunnel,
  325. untunneledDialConfig *DialConfig,
  326. skipVerify bool) (*http.Client, error) {
  327. var httpClient *http.Client
  328. var err error
  329. if tunnel != nil {
  330. httpClient, err = MakeTunneledHTTPClient(
  331. config, tunnel, skipVerify)
  332. if err != nil {
  333. return nil, common.ContextError(err)
  334. }
  335. } else {
  336. httpClient, err = MakeUntunneledHTTPClient(
  337. ctx, config, untunneledDialConfig, nil, skipVerify)
  338. if err != nil {
  339. return nil, common.ContextError(err)
  340. }
  341. }
  342. return httpClient, nil
  343. }
  344. // ResumeDownload is a reusable helper that downloads requestUrl via the
  345. // httpClient, storing the result in downloadFilename when the download is
  346. // complete. Intermediate, partial downloads state is stored in
  347. // downloadFilename.part and downloadFilename.part.etag.
  348. // Any existing downloadFilename file will be overwritten.
  349. //
  350. // In the case where the remote object has changed while a partial download
  351. // is to be resumed, the partial state is reset and resumeDownload fails.
  352. // The caller must restart the download.
  353. //
  354. // When ifNoneMatchETag is specified, no download is made if the remote
  355. // object has the same ETag. ifNoneMatchETag has an effect only when no
  356. // partial download is in progress.
  357. //
  358. func ResumeDownload(
  359. ctx context.Context,
  360. httpClient *http.Client,
  361. downloadURL string,
  362. userAgent string,
  363. downloadFilename string,
  364. ifNoneMatchETag string) (int64, string, error) {
  365. partialFilename := fmt.Sprintf("%s.part", downloadFilename)
  366. partialETagFilename := fmt.Sprintf("%s.part.etag", downloadFilename)
  367. file, err := os.OpenFile(partialFilename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
  368. if err != nil {
  369. return 0, "", common.ContextError(err)
  370. }
  371. defer file.Close()
  372. fileInfo, err := file.Stat()
  373. if err != nil {
  374. return 0, "", common.ContextError(err)
  375. }
  376. // A partial download should have an ETag which is to be sent with the
  377. // Range request to ensure that the source object is the same as the
  378. // one that is partially downloaded.
  379. var partialETag []byte
  380. if fileInfo.Size() > 0 {
  381. partialETag, err = ioutil.ReadFile(partialETagFilename)
  382. // When the ETag can't be loaded, delete the partial download. To keep the
  383. // code simple, there is no immediate, inline retry here, on the assumption
  384. // that the controller's upgradeDownloader will shortly call DownloadUpgrade
  385. // again.
  386. if err != nil {
  387. // On Windows, file must be closed before it can be deleted
  388. file.Close()
  389. tempErr := os.Remove(partialFilename)
  390. if tempErr != nil && !os.IsNotExist(tempErr) {
  391. NoticeAlert("reset partial download failed: %s", tempErr)
  392. }
  393. tempErr = os.Remove(partialETagFilename)
  394. if tempErr != nil && !os.IsNotExist(tempErr) {
  395. NoticeAlert("reset partial download ETag failed: %s", tempErr)
  396. }
  397. return 0, "", common.ContextError(
  398. fmt.Errorf("failed to load partial download ETag: %s", err))
  399. }
  400. }
  401. request, err := http.NewRequest("GET", downloadURL, nil)
  402. if err != nil {
  403. return 0, "", common.ContextError(err)
  404. }
  405. request = request.WithContext(ctx)
  406. request.Header.Set("User-Agent", userAgent)
  407. request.Header.Add("Range", fmt.Sprintf("bytes=%d-", fileInfo.Size()))
  408. if partialETag != nil {
  409. // Note: not using If-Range, since not all host servers support it.
  410. // Using If-Match means we need to check for status code 412 and reset
  411. // when the ETag has changed since the last partial download.
  412. request.Header.Add("If-Match", string(partialETag))
  413. } else if ifNoneMatchETag != "" {
  414. // Can't specify both If-Match and If-None-Match. Behavior is undefined.
  415. // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
  416. // So for downloaders that store an ETag and wish to use that to prevent
  417. // redundant downloads, that ETag is sent as If-None-Match in the case
  418. // where a partial download is not in progress. When a partial download
  419. // is in progress, the partial ETag is sent as If-Match: either that's
  420. // a version that was never fully received, or it's no longer current in
  421. // which case the response will be StatusPreconditionFailed, the partial
  422. // download will be discarded, and then the next retry will use
  423. // If-None-Match.
  424. // Note: in this case, fileInfo.Size() == 0
  425. request.Header.Add("If-None-Match", ifNoneMatchETag)
  426. }
  427. response, err := httpClient.Do(request)
  428. // The resumeable download may ask for bytes past the resource range
  429. // since it doesn't store the "completed download" state. In this case,
  430. // the HTTP server returns 416. Otherwise, we expect 206. We may also
  431. // receive 412 on ETag mismatch.
  432. if err == nil &&
  433. (response.StatusCode != http.StatusPartialContent &&
  434. // Certain http servers return 200 OK where we expect 206, so accept that.
  435. response.StatusCode != http.StatusOK &&
  436. response.StatusCode != http.StatusRequestedRangeNotSatisfiable &&
  437. response.StatusCode != http.StatusPreconditionFailed &&
  438. response.StatusCode != http.StatusNotModified) {
  439. response.Body.Close()
  440. err = fmt.Errorf("unexpected response status code: %d", response.StatusCode)
  441. }
  442. if err != nil {
  443. // Redact URL from "net/http" error message.
  444. if !GetEmitNetworkParameters() {
  445. errStr := err.Error()
  446. err = errors.New(strings.Replace(errStr, downloadURL, "[redacted]", -1))
  447. }
  448. return 0, "", common.ContextError(err)
  449. }
  450. defer response.Body.Close()
  451. responseETag := response.Header.Get("ETag")
  452. if response.StatusCode == http.StatusPreconditionFailed {
  453. // When the ETag no longer matches, delete the partial download. As above,
  454. // simply failing and relying on the caller's retry schedule.
  455. os.Remove(partialFilename)
  456. os.Remove(partialETagFilename)
  457. return 0, "", common.ContextError(errors.New("partial download ETag mismatch"))
  458. } else if response.StatusCode == http.StatusNotModified {
  459. // This status code is possible in the "If-None-Match" case. Don't leave
  460. // any partial download in progress. Caller should check that responseETag
  461. // matches ifNoneMatchETag.
  462. os.Remove(partialFilename)
  463. os.Remove(partialETagFilename)
  464. return 0, responseETag, nil
  465. }
  466. // Not making failure to write ETag file fatal, in case the entire download
  467. // succeeds in this one request.
  468. ioutil.WriteFile(partialETagFilename, []byte(responseETag), 0600)
  469. // A partial download occurs when this copy is interrupted. The io.Copy
  470. // will fail, leaving a partial download in place (.part and .part.etag).
  471. n, err := io.Copy(NewSyncFileWriter(file), response.Body)
  472. // From this point, n bytes are indicated as downloaded, even if there is
  473. // an error; the caller may use this to report partial download progress.
  474. if err != nil {
  475. return n, "", common.ContextError(err)
  476. }
  477. // Ensure the file is flushed to disk. The deferred close
  478. // will be a noop when this succeeds.
  479. err = file.Close()
  480. if err != nil {
  481. return n, "", common.ContextError(err)
  482. }
  483. // Remove if exists, to enable rename
  484. os.Remove(downloadFilename)
  485. err = os.Rename(partialFilename, downloadFilename)
  486. if err != nil {
  487. return n, "", common.ContextError(err)
  488. }
  489. os.Remove(partialETagFilename)
  490. return n, responseETag, nil
  491. }