net.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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-Inc/dns"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  35. )
  36. const DNS_PORT = 53
  37. // DialConfig contains parameters to determine the behavior
  38. // of a Psiphon dialer (TCPDial, MeekDial, etc.)
  39. type DialConfig struct {
  40. // UpstreamProxyUrl specifies a proxy to connect through.
  41. // E.g., "http://proxyhost:8080"
  42. // "socks5://user:password@proxyhost:1080"
  43. // "socks4a://proxyhost:1080"
  44. // "http://NTDOMAIN\NTUser:password@proxyhost:3375"
  45. //
  46. // Certain tunnel protocols require HTTP CONNECT support
  47. // when a HTTP proxy is specified. If CONNECT is not
  48. // supported, those protocols will not connect.
  49. UpstreamProxyUrl string
  50. // CustomHeaders is a set of additional arbitrary HTTP headers that are
  51. // added to all plaintext HTTP requests and requests made through an HTTP
  52. // upstream proxy when specified by UpstreamProxyUrl.
  53. CustomHeaders http.Header
  54. // BindToDevice parameters are used to exclude connections and
  55. // associated DNS requests from VPN routing.
  56. // When DeviceBinder is set, any underlying socket is
  57. // submitted to the device binding servicebefore connecting.
  58. // The service should bind the socket to a device so that it doesn't route
  59. // through a VPN interface. This service is also used to bind UDP sockets used
  60. // for DNS requests, in which case DnsServerGetter is used to get the
  61. // current active untunneled network DNS server.
  62. DeviceBinder DeviceBinder
  63. DnsServerGetter DnsServerGetter
  64. IPv6Synthesizer IPv6Synthesizer
  65. // UseIndistinguishableTLS specifies whether to try to use an
  66. // alternative stack for TLS. From a circumvention perspective,
  67. // Go's TLS has a distinct fingerprint that may be used for blocking.
  68. // Only applies to TLS connections.
  69. UseIndistinguishableTLS bool
  70. // TrustedCACertificatesFilename specifies a file containing trusted
  71. // CA certs. The file contents should be compatible with OpenSSL's
  72. // SSL_CTX_load_verify_locations.
  73. // Only applies to UseIndistinguishableTLS connections.
  74. TrustedCACertificatesFilename string
  75. // DeviceRegion is the reported region the host device is running in.
  76. // When set, this value may be used, pre-connection, to select performance
  77. // or circumvention optimization strategies for the given region.
  78. DeviceRegion 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. }
  86. // NetworkConnectivityChecker defines the interface to the external
  87. // HasNetworkConnectivity provider
  88. type NetworkConnectivityChecker interface {
  89. // TODO: change to bool return value once gobind supports that type
  90. HasNetworkConnectivity() int
  91. }
  92. // DeviceBinder defines the interface to the external BindToDevice provider
  93. type DeviceBinder interface {
  94. BindToDevice(fileDescriptor int) error
  95. }
  96. // DnsServerGetter defines the interface to the external GetDnsServer provider
  97. type DnsServerGetter interface {
  98. GetPrimaryDnsServer() string
  99. GetSecondaryDnsServer() string
  100. }
  101. // IPv6Synthesizer defines the interface to the external IPv6Synthesize provider
  102. type IPv6Synthesizer interface {
  103. IPv6Synthesize(IPv4Addr string) string
  104. }
  105. // Dialer is a custom network dialer.
  106. type Dialer func(context.Context, string, string) (net.Conn, error)
  107. // LocalProxyRelay sends to remoteConn bytes received from localConn,
  108. // and sends to localConn bytes received from remoteConn.
  109. func LocalProxyRelay(proxyType string, localConn, remoteConn net.Conn) {
  110. copyWaitGroup := new(sync.WaitGroup)
  111. copyWaitGroup.Add(1)
  112. go func() {
  113. defer copyWaitGroup.Done()
  114. _, err := io.Copy(localConn, remoteConn)
  115. if err != nil {
  116. err = fmt.Errorf("Relay failed: %s", common.ContextError(err))
  117. NoticeLocalProxyError(proxyType, err)
  118. }
  119. }()
  120. _, err := io.Copy(remoteConn, localConn)
  121. if err != nil {
  122. err = fmt.Errorf("Relay failed: %s", common.ContextError(err))
  123. NoticeLocalProxyError(proxyType, err)
  124. }
  125. copyWaitGroup.Wait()
  126. }
  127. // WaitForNetworkConnectivity uses a NetworkConnectivityChecker to
  128. // periodically check for network connectivity. It returns true if
  129. // no NetworkConnectivityChecker is provided (waiting is disabled)
  130. // or when NetworkConnectivityChecker.HasNetworkConnectivity()
  131. // indicates connectivity. It waits and polls the checker once a second.
  132. // When the context is done, false is returned immediately.
  133. func WaitForNetworkConnectivity(
  134. ctx context.Context, connectivityChecker NetworkConnectivityChecker) bool {
  135. if connectivityChecker == nil || 1 == connectivityChecker.HasNetworkConnectivity() {
  136. return true
  137. }
  138. NoticeInfo("waiting for network connectivity")
  139. ticker := time.NewTicker(1 * time.Second)
  140. defer ticker.Stop()
  141. for {
  142. if 1 == connectivityChecker.HasNetworkConnectivity() {
  143. return true
  144. }
  145. select {
  146. case <-ticker.C:
  147. // Check HasNetworkConnectivity again
  148. case <-ctx.Done():
  149. return false
  150. }
  151. }
  152. }
  153. // ResolveIP uses a custom dns stack to make a DNS query over the
  154. // given TCP or UDP conn. This is used, e.g., when we need to ensure
  155. // that a DNS connection bypasses a VPN interface (BindToDevice) or
  156. // when we need to ensure that a DNS connection is tunneled.
  157. // Caller must set timeouts or interruptibility as required for conn.
  158. func ResolveIP(host string, conn net.Conn) (addrs []net.IP, ttls []time.Duration, err error) {
  159. // Send the DNS query
  160. dnsConn := &dns.Conn{Conn: conn}
  161. defer dnsConn.Close()
  162. query := new(dns.Msg)
  163. query.SetQuestion(dns.Fqdn(host), dns.TypeA)
  164. query.RecursionDesired = true
  165. dnsConn.WriteMsg(query)
  166. // Process the response
  167. response, err := dnsConn.ReadMsg()
  168. if err != nil {
  169. return nil, nil, common.ContextError(err)
  170. }
  171. addrs = make([]net.IP, 0)
  172. ttls = make([]time.Duration, 0)
  173. for _, answer := range response.Answer {
  174. if a, ok := answer.(*dns.A); ok {
  175. addrs = append(addrs, a.A)
  176. ttl := time.Duration(a.Hdr.Ttl) * time.Second
  177. ttls = append(ttls, ttl)
  178. }
  179. }
  180. return addrs, ttls, nil
  181. }
  182. // MakeUntunneledHTTPClient returns a net/http.Client which is
  183. // configured to use custom dialing features -- including BindToDevice,
  184. // UseIndistinguishableTLS, etc. If verifyLegacyCertificate is not nil,
  185. // it's used for certificate verification.
  186. // The context is applied to underlying TCP dials. The caller is responsible
  187. // for applying the context to requests made with the returned http.Client.
  188. func MakeUntunneledHTTPClient(
  189. ctx context.Context,
  190. untunneledDialConfig *DialConfig,
  191. verifyLegacyCertificate *x509.Certificate,
  192. skipVerify bool) (*http.Client, error) {
  193. // Note: IndistinguishableTLS mode doesn't support VerifyLegacyCertificate
  194. useIndistinguishableTLS := untunneledDialConfig.UseIndistinguishableTLS &&
  195. verifyLegacyCertificate == nil
  196. dialer := NewTCPDialer(untunneledDialConfig)
  197. tlsDialer := NewCustomTLSDialer(
  198. // Note: when verifyLegacyCertificate is not nil, some
  199. // of the other CustomTLSConfig is overridden.
  200. &CustomTLSConfig{
  201. Dial: dialer,
  202. VerifyLegacyCertificate: verifyLegacyCertificate,
  203. UseDialAddrSNI: true,
  204. SNIServerName: "",
  205. SkipVerify: skipVerify,
  206. UseIndistinguishableTLS: useIndistinguishableTLS,
  207. TrustedCACertificatesFilename: untunneledDialConfig.TrustedCACertificatesFilename,
  208. })
  209. transport := &http.Transport{
  210. Dial: func(network, addr string) (net.Conn, error) {
  211. return dialer(ctx, network, addr)
  212. },
  213. DialTLS: func(network, addr string) (net.Conn, error) {
  214. return tlsDialer(ctx, network, addr)
  215. },
  216. }
  217. httpClient := &http.Client{
  218. Transport: transport,
  219. }
  220. return httpClient, nil
  221. }
  222. // MakeTunneledHTTPClient returns a net/http.Client which is
  223. // configured to use custom dialing features including tunneled
  224. // dialing and, optionally, UseTrustedCACertificatesForStockTLS.
  225. // This http.Client uses stock TLS for HTTPS.
  226. func MakeTunneledHTTPClient(
  227. config *Config,
  228. tunnel *Tunnel,
  229. skipVerify bool) (*http.Client, error) {
  230. // Note: there is no dial context since SSH port forward dials cannot
  231. // be interrupted directly. Closing the tunnel will interrupt the dials.
  232. tunneledDialer := func(_, addr string) (conn net.Conn, err error) {
  233. return tunnel.sshClient.Dial("tcp", addr)
  234. }
  235. transport := &http.Transport{
  236. Dial: tunneledDialer,
  237. }
  238. if skipVerify {
  239. transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
  240. } else if config.UseTrustedCACertificatesForStockTLS {
  241. if config.TrustedCACertificatesFilename == "" {
  242. return nil, common.ContextError(errors.New(
  243. "UseTrustedCACertificatesForStockTLS requires TrustedCACertificatesFilename"))
  244. }
  245. rootCAs := x509.NewCertPool()
  246. certData, err := ioutil.ReadFile(config.TrustedCACertificatesFilename)
  247. if err != nil {
  248. return nil, common.ContextError(err)
  249. }
  250. rootCAs.AppendCertsFromPEM(certData)
  251. transport.TLSClientConfig = &tls.Config{RootCAs: rootCAs}
  252. }
  253. return &http.Client{
  254. Transport: transport,
  255. }, nil
  256. }
  257. // MakeDownloadHTTPClient is a helper that sets up a http.Client
  258. // for use either untunneled or through a tunnel.
  259. func MakeDownloadHTTPClient(
  260. ctx context.Context,
  261. config *Config,
  262. tunnel *Tunnel,
  263. untunneledDialConfig *DialConfig,
  264. skipVerify bool) (*http.Client, error) {
  265. var httpClient *http.Client
  266. var err error
  267. if tunnel != nil {
  268. httpClient, err = MakeTunneledHTTPClient(
  269. config, tunnel, skipVerify)
  270. if err != nil {
  271. return nil, common.ContextError(err)
  272. }
  273. } else {
  274. httpClient, err = MakeUntunneledHTTPClient(
  275. ctx, untunneledDialConfig, nil, skipVerify)
  276. if err != nil {
  277. return nil, common.ContextError(err)
  278. }
  279. }
  280. return httpClient, nil
  281. }
  282. // ResumeDownload is a reusable helper that downloads requestUrl via the
  283. // httpClient, storing the result in downloadFilename when the download is
  284. // complete. Intermediate, partial downloads state is stored in
  285. // downloadFilename.part and downloadFilename.part.etag.
  286. // Any existing downloadFilename file will be overwritten.
  287. //
  288. // In the case where the remote object has changed while a partial download
  289. // is to be resumed, the partial state is reset and resumeDownload fails.
  290. // The caller must restart the download.
  291. //
  292. // When ifNoneMatchETag is specified, no download is made if the remote
  293. // object has the same ETag. ifNoneMatchETag has an effect only when no
  294. // partial download is in progress.
  295. //
  296. func ResumeDownload(
  297. ctx context.Context,
  298. httpClient *http.Client,
  299. downloadURL string,
  300. userAgent string,
  301. downloadFilename string,
  302. ifNoneMatchETag string) (int64, string, error) {
  303. partialFilename := fmt.Sprintf("%s.part", downloadFilename)
  304. partialETagFilename := fmt.Sprintf("%s.part.etag", downloadFilename)
  305. file, err := os.OpenFile(partialFilename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
  306. if err != nil {
  307. return 0, "", common.ContextError(err)
  308. }
  309. defer file.Close()
  310. fileInfo, err := file.Stat()
  311. if err != nil {
  312. return 0, "", common.ContextError(err)
  313. }
  314. // A partial download should have an ETag which is to be sent with the
  315. // Range request to ensure that the source object is the same as the
  316. // one that is partially downloaded.
  317. var partialETag []byte
  318. if fileInfo.Size() > 0 {
  319. partialETag, err = ioutil.ReadFile(partialETagFilename)
  320. // When the ETag can't be loaded, delete the partial download. To keep the
  321. // code simple, there is no immediate, inline retry here, on the assumption
  322. // that the controller's upgradeDownloader will shortly call DownloadUpgrade
  323. // again.
  324. if err != nil {
  325. // On Windows, file must be closed before it can be deleted
  326. file.Close()
  327. tempErr := os.Remove(partialFilename)
  328. if tempErr != nil && !os.IsNotExist(tempErr) {
  329. NoticeAlert("reset partial download failed: %s", tempErr)
  330. }
  331. tempErr = os.Remove(partialETagFilename)
  332. if tempErr != nil && !os.IsNotExist(tempErr) {
  333. NoticeAlert("reset partial download ETag failed: %s", tempErr)
  334. }
  335. return 0, "", common.ContextError(
  336. fmt.Errorf("failed to load partial download ETag: %s", err))
  337. }
  338. }
  339. request, err := http.NewRequest("GET", downloadURL, nil)
  340. if err != nil {
  341. return 0, "", common.ContextError(err)
  342. }
  343. request = request.WithContext(ctx)
  344. request.Header.Set("User-Agent", userAgent)
  345. request.Header.Add("Range", fmt.Sprintf("bytes=%d-", fileInfo.Size()))
  346. if partialETag != nil {
  347. // Note: not using If-Range, since not all host servers support it.
  348. // Using If-Match means we need to check for status code 412 and reset
  349. // when the ETag has changed since the last partial download.
  350. request.Header.Add("If-Match", string(partialETag))
  351. } else if ifNoneMatchETag != "" {
  352. // Can't specify both If-Match and If-None-Match. Behavior is undefined.
  353. // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
  354. // So for downloaders that store an ETag and wish to use that to prevent
  355. // redundant downloads, that ETag is sent as If-None-Match in the case
  356. // where a partial download is not in progress. When a partial download
  357. // is in progress, the partial ETag is sent as If-Match: either that's
  358. // a version that was never fully received, or it's no longer current in
  359. // which case the response will be StatusPreconditionFailed, the partial
  360. // download will be discarded, and then the next retry will use
  361. // If-None-Match.
  362. // Note: in this case, fileInfo.Size() == 0
  363. request.Header.Add("If-None-Match", ifNoneMatchETag)
  364. }
  365. response, err := httpClient.Do(request)
  366. // The resumeable download may ask for bytes past the resource range
  367. // since it doesn't store the "completed download" state. In this case,
  368. // the HTTP server returns 416. Otherwise, we expect 206. We may also
  369. // receive 412 on ETag mismatch.
  370. if err == nil &&
  371. (response.StatusCode != http.StatusPartialContent &&
  372. // Certain http servers return 200 OK where we expect 206, so accept that.
  373. response.StatusCode != http.StatusOK &&
  374. response.StatusCode != http.StatusRequestedRangeNotSatisfiable &&
  375. response.StatusCode != http.StatusPreconditionFailed &&
  376. response.StatusCode != http.StatusNotModified) {
  377. response.Body.Close()
  378. err = fmt.Errorf("unexpected response status code: %d", response.StatusCode)
  379. }
  380. if err != nil {
  381. return 0, "", common.ContextError(err)
  382. }
  383. defer response.Body.Close()
  384. responseETag := response.Header.Get("ETag")
  385. if response.StatusCode == http.StatusPreconditionFailed {
  386. // When the ETag no longer matches, delete the partial download. As above,
  387. // simply failing and relying on the caller's retry schedule.
  388. os.Remove(partialFilename)
  389. os.Remove(partialETagFilename)
  390. return 0, "", common.ContextError(errors.New("partial download ETag mismatch"))
  391. } else if response.StatusCode == http.StatusNotModified {
  392. // This status code is possible in the "If-None-Match" case. Don't leave
  393. // any partial download in progress. Caller should check that responseETag
  394. // matches ifNoneMatchETag.
  395. os.Remove(partialFilename)
  396. os.Remove(partialETagFilename)
  397. return 0, responseETag, nil
  398. }
  399. // Not making failure to write ETag file fatal, in case the entire download
  400. // succeeds in this one request.
  401. ioutil.WriteFile(partialETagFilename, []byte(responseETag), 0600)
  402. // A partial download occurs when this copy is interrupted. The io.Copy
  403. // will fail, leaving a partial download in place (.part and .part.etag).
  404. n, err := io.Copy(NewSyncFileWriter(file), response.Body)
  405. // From this point, n bytes are indicated as downloaded, even if there is
  406. // an error; the caller may use this to report partial download progress.
  407. if err != nil {
  408. return n, "", common.ContextError(err)
  409. }
  410. // Ensure the file is flushed to disk. The deferred close
  411. // will be a noop when this succeeds.
  412. err = file.Close()
  413. if err != nil {
  414. return n, "", common.ContextError(err)
  415. }
  416. // Remove if exists, to enable rename
  417. os.Remove(downloadFilename)
  418. err = os.Rename(partialFilename, downloadFilename)
  419. if err != nil {
  420. return n, "", common.ContextError(err)
  421. }
  422. os.Remove(partialETagFilename)
  423. return n, responseETag, nil
  424. }