net.go 19 KB

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