net.go 18 KB

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