net.go 17 KB

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