net.go 20 KB

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