net.go 18 KB

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