net.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  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. "crypto/tls"
  22. "crypto/x509"
  23. "errors"
  24. "fmt"
  25. "io"
  26. "io/ioutil"
  27. "net"
  28. "net/http"
  29. "net/url"
  30. "os"
  31. "reflect"
  32. "sync"
  33. "time"
  34. "github.com/Psiphon-Inc/dns"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  36. )
  37. const DNS_PORT = 53
  38. // DialConfig contains parameters to determine the behavior
  39. // of a Psiphon dialer (TCPDial, 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. UpstreamProxyUrl string
  51. // CustomHeaders is a set of additional arbitrary HTTP headers that are
  52. // added to all plaintext HTTP requests and requests made through an HTTP
  53. // upstream proxy when specified by UpstreamProxyUrl.
  54. CustomHeaders http.Header
  55. ConnectTimeout time.Duration
  56. // PendingConns is used to track and interrupt dials in progress.
  57. // Dials may be interrupted using PendingConns.CloseAll(). Once instantiated,
  58. // a conn is added to pendingConns before the network connect begins and
  59. // removed from pendingConns once the connect succeeds or fails.
  60. // May be nil.
  61. PendingConns *common.Conns
  62. // BindToDevice parameters are used to exclude connections and
  63. // associated DNS requests from VPN routing.
  64. // When DeviceBinder is set, any underlying socket is
  65. // submitted to the device binding servicebefore connecting.
  66. // The service should bind the socket to a device so that it doesn't route
  67. // through a VPN interface. This service is also used to bind UDP sockets used
  68. // for DNS requests, in which case DnsServerGetter is used to get the
  69. // current active untunneled network DNS server.
  70. DeviceBinder DeviceBinder
  71. DnsServerGetter DnsServerGetter
  72. IPv6Synthesizer IPv6Synthesizer
  73. // UseIndistinguishableTLS specifies whether to try to use an
  74. // alternative stack for TLS. From a circumvention perspective,
  75. // Go's TLS has a distinct fingerprint that may be used for blocking.
  76. // Only applies to TLS connections.
  77. UseIndistinguishableTLS bool
  78. // TrustedCACertificatesFilename specifies a file containing trusted
  79. // CA certs. The file contents should be compatible with OpenSSL's
  80. // SSL_CTX_load_verify_locations.
  81. // Only applies to UseIndistinguishableTLS connections.
  82. TrustedCACertificatesFilename string
  83. // DeviceRegion is the reported region the host device is running in.
  84. // When set, this value may be used, pre-connection, to select performance
  85. // or circumvention optimization strategies for the given region.
  86. DeviceRegion string
  87. // ResolvedIPCallback, when set, is called with the IP address that was
  88. // dialed. This is either the specified IP address in the dial address,
  89. // or the resolved IP address in the case where the dial address is a
  90. // domain name.
  91. // The callback may be invoked by a concurrent goroutine.
  92. ResolvedIPCallback func(string)
  93. }
  94. // NetworkConnectivityChecker defines the interface to the external
  95. // HasNetworkConnectivity provider
  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. type DeviceBinder interface {
  102. BindToDevice(fileDescriptor int) error
  103. }
  104. // DnsServerGetter defines the interface to the external GetDnsServer provider
  105. type DnsServerGetter interface {
  106. GetPrimaryDnsServer() string
  107. GetSecondaryDnsServer() string
  108. }
  109. // IPv6Synthesizer defines the interface to the external IPv6Synthesize provider
  110. type IPv6Synthesizer interface {
  111. IPv6Synthesize(IPv4Addr string) string
  112. }
  113. // TimeoutError implements the error interface
  114. type TimeoutError struct{}
  115. func (TimeoutError) Error() string { return "timed out" }
  116. func (TimeoutError) Timeout() bool { return true }
  117. func (TimeoutError) Temporary() bool { return true }
  118. // Dialer is a custom dialer compatible with http.Transport.Dial.
  119. type Dialer func(string, string) (net.Conn, error)
  120. // LocalProxyRelay sends to remoteConn bytes received from localConn,
  121. // and sends to localConn bytes received from remoteConn.
  122. func LocalProxyRelay(proxyType string, localConn, remoteConn net.Conn) {
  123. copyWaitGroup := new(sync.WaitGroup)
  124. copyWaitGroup.Add(1)
  125. go func() {
  126. defer copyWaitGroup.Done()
  127. _, err := io.Copy(localConn, remoteConn)
  128. if err != nil {
  129. err = fmt.Errorf("Relay failed: %s", common.ContextError(err))
  130. NoticeLocalProxyError(proxyType, err)
  131. }
  132. }()
  133. _, err := io.Copy(remoteConn, localConn)
  134. if err != nil {
  135. err = fmt.Errorf("Relay failed: %s", common.ContextError(err))
  136. NoticeLocalProxyError(proxyType, err)
  137. }
  138. copyWaitGroup.Wait()
  139. }
  140. // WaitForNetworkConnectivity uses a NetworkConnectivityChecker to
  141. // periodically check for network connectivity. It returns true if
  142. // no NetworkConnectivityChecker is provided (waiting is disabled)
  143. // or when NetworkConnectivityChecker.HasNetworkConnectivity()
  144. // indicates connectivity. It waits and polls the checker once a second.
  145. // If any stop is broadcast, false is returned immediately.
  146. func WaitForNetworkConnectivity(
  147. connectivityChecker NetworkConnectivityChecker, stopBroadcasts ...<-chan struct{}) bool {
  148. if connectivityChecker == nil || 1 == connectivityChecker.HasNetworkConnectivity() {
  149. return true
  150. }
  151. NoticeInfo("waiting for network connectivity")
  152. ticker := time.NewTicker(1 * time.Second)
  153. for {
  154. if 1 == connectivityChecker.HasNetworkConnectivity() {
  155. return true
  156. }
  157. selectCases := make([]reflect.SelectCase, 1+len(stopBroadcasts))
  158. selectCases[0] = reflect.SelectCase{
  159. Dir: reflect.SelectRecv, Chan: reflect.ValueOf(ticker.C)}
  160. for i, stopBroadcast := range stopBroadcasts {
  161. selectCases[i+1] = reflect.SelectCase{
  162. Dir: reflect.SelectRecv, Chan: reflect.ValueOf(stopBroadcast)}
  163. }
  164. chosen, _, ok := reflect.Select(selectCases)
  165. if chosen == 0 && ok {
  166. // Ticker case, so check again
  167. } else {
  168. // Stop case
  169. return false
  170. }
  171. }
  172. }
  173. // ResolveIP uses a custom dns stack to make a DNS query over the
  174. // given TCP or UDP conn. This is used, e.g., when we need to ensure
  175. // that a DNS connection bypasses a VPN interface (BindToDevice) or
  176. // when we need to ensure that a DNS connection is tunneled.
  177. // Caller must set timeouts or interruptibility as required for conn.
  178. func ResolveIP(host string, conn net.Conn) (addrs []net.IP, ttls []time.Duration, err error) {
  179. // Send the DNS query
  180. dnsConn := &dns.Conn{Conn: conn}
  181. defer dnsConn.Close()
  182. query := new(dns.Msg)
  183. query.SetQuestion(dns.Fqdn(host), dns.TypeA)
  184. query.RecursionDesired = true
  185. dnsConn.WriteMsg(query)
  186. // Process the response
  187. response, err := dnsConn.ReadMsg()
  188. if err != nil {
  189. return nil, nil, common.ContextError(err)
  190. }
  191. addrs = make([]net.IP, 0)
  192. ttls = make([]time.Duration, 0)
  193. for _, answer := range response.Answer {
  194. if a, ok := answer.(*dns.A); ok {
  195. addrs = append(addrs, a.A)
  196. ttl := time.Duration(a.Hdr.Ttl) * time.Second
  197. ttls = append(ttls, ttl)
  198. }
  199. }
  200. return addrs, ttls, nil
  201. }
  202. // MakeUntunneledHttpsClient returns a net/http.Client which is
  203. // configured to use custom dialing features -- including BindToDevice,
  204. // UseIndistinguishableTLS, etc. -- for a specific HTTPS request URL.
  205. // If verifyLegacyCertificate is not nil, it's used for certificate
  206. // verification.
  207. //
  208. // Because UseIndistinguishableTLS requires a hack to work with
  209. // net/http, MakeUntunneledHttpClient may return a modified request URL
  210. // to be used. Callers should always use this return value to make
  211. // requests, not the input value.
  212. //
  213. // MakeUntunneledHttpsClient ignores the input requestUrl scheme,
  214. // which may be "http" or "https", and always performs HTTPS requests.
  215. func MakeUntunneledHttpsClient(
  216. dialConfig *DialConfig,
  217. verifyLegacyCertificate *x509.Certificate,
  218. requestUrl string,
  219. skipVerify bool,
  220. requestTimeout time.Duration) (*http.Client, string, error) {
  221. // Change the scheme to "http"; otherwise http.Transport will try to do
  222. // another TLS handshake inside the explicit TLS session. Also need to
  223. // force an explicit port, as the default for "http", 80, won't talk TLS.
  224. //
  225. // TODO: set http.Transport.DialTLS instead of Dial to avoid this hack?
  226. // See: https://golang.org/pkg/net/http/#Transport. DialTLS was added in
  227. // Go 1.4 but this code may pre-date that.
  228. urlComponents, err := url.Parse(requestUrl)
  229. if err != nil {
  230. return nil, "", common.ContextError(err)
  231. }
  232. urlComponents.Scheme = "http"
  233. host, port, err := net.SplitHostPort(urlComponents.Host)
  234. if err != nil {
  235. // Assume there's no port
  236. host = urlComponents.Host
  237. port = ""
  238. }
  239. if port == "" {
  240. port = "443"
  241. }
  242. urlComponents.Host = net.JoinHostPort(host, port)
  243. // Note: IndistinguishableTLS mode doesn't support VerifyLegacyCertificate
  244. useIndistinguishableTLS := dialConfig.UseIndistinguishableTLS && verifyLegacyCertificate == nil
  245. dialer := NewCustomTLSDialer(
  246. // Note: when verifyLegacyCertificate is not nil, some
  247. // of the other CustomTLSConfig is overridden.
  248. &CustomTLSConfig{
  249. Dial: NewTCPDialer(dialConfig),
  250. VerifyLegacyCertificate: verifyLegacyCertificate,
  251. SNIServerName: host,
  252. SkipVerify: skipVerify,
  253. UseIndistinguishableTLS: useIndistinguishableTLS,
  254. TrustedCACertificatesFilename: dialConfig.TrustedCACertificatesFilename,
  255. })
  256. transport := &http.Transport{
  257. Dial: dialer,
  258. }
  259. httpClient := &http.Client{
  260. Timeout: requestTimeout,
  261. Transport: transport,
  262. }
  263. return httpClient, urlComponents.String(), nil
  264. }
  265. // MakeTunneledHttpClient returns a net/http.Client which is
  266. // configured to use custom dialing features including tunneled
  267. // dialing and, optionally, UseTrustedCACertificatesForStockTLS.
  268. // Unlike MakeUntunneledHttpsClient and makePsiphonHttpsClient,
  269. // This http.Client uses stock TLS and no scheme transformation
  270. // hack is required.
  271. func MakeTunneledHttpClient(
  272. config *Config,
  273. tunnel *Tunnel,
  274. skipVerify bool,
  275. requestTimeout time.Duration) (*http.Client, error) {
  276. tunneledDialer := func(_, addr string) (conn net.Conn, err error) {
  277. return tunnel.sshClient.Dial("tcp", addr)
  278. }
  279. transport := &http.Transport{
  280. Dial: tunneledDialer,
  281. }
  282. if skipVerify {
  283. transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
  284. } else if config.UseTrustedCACertificatesForStockTLS {
  285. if config.TrustedCACertificatesFilename == "" {
  286. return nil, common.ContextError(errors.New(
  287. "UseTrustedCACertificatesForStockTLS requires TrustedCACertificatesFilename"))
  288. }
  289. rootCAs := x509.NewCertPool()
  290. certData, err := ioutil.ReadFile(config.TrustedCACertificatesFilename)
  291. if err != nil {
  292. return nil, common.ContextError(err)
  293. }
  294. rootCAs.AppendCertsFromPEM(certData)
  295. transport.TLSClientConfig = &tls.Config{RootCAs: rootCAs}
  296. }
  297. return &http.Client{
  298. Transport: transport,
  299. Timeout: requestTimeout,
  300. }, nil
  301. }
  302. // MakeDownloadHttpClient is a resusable helper that sets up a
  303. // http.Client for use either untunneled or through a tunnel.
  304. // See MakeUntunneledHttpsClient for a note about request URL
  305. // rewritting.
  306. func MakeDownloadHttpClient(
  307. config *Config,
  308. tunnel *Tunnel,
  309. untunneledDialConfig *DialConfig,
  310. requestUrl string,
  311. skipVerify bool,
  312. requestTimeout time.Duration) (*http.Client, string, error) {
  313. var httpClient *http.Client
  314. var err error
  315. if tunnel != nil {
  316. // MakeTunneledHttpClient works with both "http" and "https" schemes
  317. httpClient, err = MakeTunneledHttpClient(
  318. config, tunnel, skipVerify, requestTimeout)
  319. if err != nil {
  320. return nil, "", common.ContextError(err)
  321. }
  322. } else {
  323. urlComponents, err := url.Parse(requestUrl)
  324. if err != nil {
  325. return nil, "", common.ContextError(err)
  326. }
  327. // MakeUntunneledHttpsClient works only with "https" schemes
  328. if urlComponents.Scheme == "https" {
  329. httpClient, requestUrl, err = MakeUntunneledHttpsClient(
  330. untunneledDialConfig, nil, requestUrl, skipVerify, requestTimeout)
  331. if err != nil {
  332. return nil, "", common.ContextError(err)
  333. }
  334. } else {
  335. httpClient = &http.Client{
  336. Timeout: requestTimeout,
  337. Transport: &http.Transport{
  338. Dial: NewTCPDialer(untunneledDialConfig),
  339. },
  340. }
  341. }
  342. }
  343. return httpClient, requestUrl, nil
  344. }
  345. // ResumeDownload is a resuable helper that downloads requestUrl via the
  346. // httpClient, storing the result in downloadFilename when the download is
  347. // complete. Intermediate, partial downloads state is stored in
  348. // downloadFilename.part and downloadFilename.part.etag.
  349. // Any existing downloadFilename file will be overwritten.
  350. //
  351. // In the case where the remote object has changed while a partial download
  352. // is to be resumed, the partial state is reset and resumeDownload fails.
  353. // The caller must restart the download.
  354. //
  355. // When ifNoneMatchETag is specified, no download is made if the remote
  356. // object has the same ETag. ifNoneMatchETag has an effect only when no
  357. // partial download is in progress.
  358. //
  359. func ResumeDownload(
  360. httpClient *http.Client,
  361. requestUrl string,
  362. userAgent string,
  363. downloadFilename string,
  364. ifNoneMatchETag string) (int64, string, error) {
  365. partialFilename := fmt.Sprintf("%s.part", downloadFilename)
  366. partialETagFilename := fmt.Sprintf("%s.part.etag", downloadFilename)
  367. file, err := os.OpenFile(partialFilename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
  368. if err != nil {
  369. return 0, "", common.ContextError(err)
  370. }
  371. defer file.Close()
  372. fileInfo, err := file.Stat()
  373. if err != nil {
  374. return 0, "", common.ContextError(err)
  375. }
  376. // A partial download should have an ETag which is to be sent with the
  377. // Range request to ensure that the source object is the same as the
  378. // one that is partially downloaded.
  379. var partialETag []byte
  380. if fileInfo.Size() > 0 {
  381. partialETag, err = ioutil.ReadFile(partialETagFilename)
  382. // When the ETag can't be loaded, delete the partial download. To keep the
  383. // code simple, there is no immediate, inline retry here, on the assumption
  384. // that the controller's upgradeDownloader will shortly call DownloadUpgrade
  385. // again.
  386. if err != nil {
  387. // On Windows, file must be closed before it can be deleted
  388. file.Close()
  389. tempErr := os.Remove(partialFilename)
  390. if tempErr != nil && !os.IsNotExist(tempErr) {
  391. NoticeAlert("reset partial download failed: %s", tempErr)
  392. }
  393. tempErr = os.Remove(partialETagFilename)
  394. if tempErr != nil && !os.IsNotExist(tempErr) {
  395. NoticeAlert("reset partial download ETag failed: %s", tempErr)
  396. }
  397. return 0, "", common.ContextError(
  398. fmt.Errorf("failed to load partial download ETag: %s", err))
  399. }
  400. }
  401. request, err := http.NewRequest("GET", requestUrl, nil)
  402. if err != nil {
  403. return 0, "", common.ContextError(err)
  404. }
  405. request.Header.Set("User-Agent", userAgent)
  406. request.Header.Add("Range", fmt.Sprintf("bytes=%d-", fileInfo.Size()))
  407. if partialETag != nil {
  408. // Note: not using If-Range, since not all host servers support it.
  409. // Using If-Match means we need to check for status code 412 and reset
  410. // when the ETag has changed since the last partial download.
  411. request.Header.Add("If-Match", string(partialETag))
  412. } else if ifNoneMatchETag != "" {
  413. // Can't specify both If-Match and If-None-Match. Behavior is undefined.
  414. // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
  415. // So for downloaders that store an ETag and wish to use that to prevent
  416. // redundant downloads, that ETag is sent as If-None-Match in the case
  417. // where a partial download is not in progress. When a partial download
  418. // is in progress, the partial ETag is sent as If-Match: either that's
  419. // a version that was never fully received, or it's no longer current in
  420. // which case the response will be StatusPreconditionFailed, the partial
  421. // download will be discarded, and then the next retry will use
  422. // If-None-Match.
  423. // Note: in this case, fileInfo.Size() == 0
  424. request.Header.Add("If-None-Match", ifNoneMatchETag)
  425. }
  426. response, err := httpClient.Do(request)
  427. // The resumeable download may ask for bytes past the resource range
  428. // since it doesn't store the "completed download" state. In this case,
  429. // the HTTP server returns 416. Otherwise, we expect 206. We may also
  430. // receive 412 on ETag mismatch.
  431. if err == nil &&
  432. (response.StatusCode != http.StatusPartialContent &&
  433. // Certain http servers return 200 OK where we expect 206, so accept that.
  434. response.StatusCode != http.StatusOK &&
  435. response.StatusCode != http.StatusRequestedRangeNotSatisfiable &&
  436. response.StatusCode != http.StatusPreconditionFailed &&
  437. response.StatusCode != http.StatusNotModified) {
  438. response.Body.Close()
  439. err = fmt.Errorf("unexpected response status code: %d", response.StatusCode)
  440. }
  441. if err != nil {
  442. return 0, "", common.ContextError(err)
  443. }
  444. defer response.Body.Close()
  445. responseETag := response.Header.Get("ETag")
  446. if response.StatusCode == http.StatusPreconditionFailed {
  447. // When the ETag no longer matches, delete the partial download. As above,
  448. // simply failing and relying on the caller's retry schedule.
  449. os.Remove(partialFilename)
  450. os.Remove(partialETagFilename)
  451. return 0, "", common.ContextError(errors.New("partial download ETag mismatch"))
  452. } else if response.StatusCode == http.StatusNotModified {
  453. // This status code is possible in the "If-None-Match" case. Don't leave
  454. // any partial download in progress. Caller should check that responseETag
  455. // matches ifNoneMatchETag.
  456. os.Remove(partialFilename)
  457. os.Remove(partialETagFilename)
  458. return 0, responseETag, nil
  459. }
  460. // Not making failure to write ETag file fatal, in case the entire download
  461. // succeeds in this one request.
  462. ioutil.WriteFile(partialETagFilename, []byte(responseETag), 0600)
  463. // A partial download occurs when this copy is interrupted. The io.Copy
  464. // will fail, leaving a partial download in place (.part and .part.etag).
  465. n, err := io.Copy(NewSyncFileWriter(file), response.Body)
  466. // From this point, n bytes are indicated as downloaded, even if there is
  467. // an error; the caller may use this to report partial download progress.
  468. if err != nil {
  469. return n, "", common.ContextError(err)
  470. }
  471. // Ensure the file is flushed to disk. The deferred close
  472. // will be a noop when this succeeds.
  473. err = file.Close()
  474. if err != nil {
  475. return n, "", common.ContextError(err)
  476. }
  477. // Remove if exists, to enable rename
  478. os.Remove(downloadFilename)
  479. err = os.Rename(partialFilename, downloadFilename)
  480. if err != nil {
  481. return n, "", common.ContextError(err)
  482. }
  483. os.Remove(partialETagFilename)
  484. return n, responseETag, nil
  485. }