net.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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. requestTimeout time.Duration) (*http.Client, string, error) {
  215. // Change the scheme to "http"; otherwise http.Transport will try to do
  216. // another TLS handshake inside the explicit TLS session. Also need to
  217. // force an explicit port, as the default for "http", 80, won't talk TLS.
  218. urlComponents, err := url.Parse(requestUrl)
  219. if err != nil {
  220. return nil, "", common.ContextError(err)
  221. }
  222. urlComponents.Scheme = "http"
  223. host, port, err := net.SplitHostPort(urlComponents.Host)
  224. if err != nil {
  225. // Assume there's no port
  226. host = urlComponents.Host
  227. port = ""
  228. }
  229. if port == "" {
  230. port = "443"
  231. }
  232. urlComponents.Host = net.JoinHostPort(host, port)
  233. // Note: IndistinguishableTLS mode doesn't support VerifyLegacyCertificate
  234. useIndistinguishableTLS := dialConfig.UseIndistinguishableTLS && verifyLegacyCertificate == nil
  235. dialer := NewCustomTLSDialer(
  236. // Note: when verifyLegacyCertificate is not nil, some
  237. // of the other CustomTLSConfig is overridden.
  238. &CustomTLSConfig{
  239. Dial: NewTCPDialer(dialConfig),
  240. VerifyLegacyCertificate: verifyLegacyCertificate,
  241. SNIServerName: host,
  242. SkipVerify: false,
  243. UseIndistinguishableTLS: useIndistinguishableTLS,
  244. TrustedCACertificatesFilename: dialConfig.TrustedCACertificatesFilename,
  245. })
  246. transport := &http.Transport{
  247. Dial: dialer,
  248. }
  249. httpClient := &http.Client{
  250. Timeout: requestTimeout,
  251. Transport: transport,
  252. }
  253. return httpClient, urlComponents.String(), nil
  254. }
  255. // MakeTunneledHttpClient returns a net/http.Client which is
  256. // configured to use custom dialing features including tunneled
  257. // dialing and, optionally, UseTrustedCACertificatesForStockTLS.
  258. // Unlike MakeUntunneledHttpsClient and makePsiphonHttpsClient,
  259. // This http.Client uses stock TLS and no scheme transformation
  260. // hack is required.
  261. func MakeTunneledHttpClient(
  262. config *Config,
  263. tunnel *Tunnel,
  264. requestTimeout time.Duration) (*http.Client, error) {
  265. tunneledDialer := func(_, addr string) (conn net.Conn, err error) {
  266. return tunnel.sshClient.Dial("tcp", addr)
  267. }
  268. transport := &http.Transport{
  269. Dial: tunneledDialer,
  270. }
  271. if config.UseTrustedCACertificatesForStockTLS {
  272. if config.TrustedCACertificatesFilename == "" {
  273. return nil, common.ContextError(errors.New(
  274. "UseTrustedCACertificatesForStockTLS requires TrustedCACertificatesFilename"))
  275. }
  276. rootCAs := x509.NewCertPool()
  277. certData, err := ioutil.ReadFile(config.TrustedCACertificatesFilename)
  278. if err != nil {
  279. return nil, common.ContextError(err)
  280. }
  281. rootCAs.AppendCertsFromPEM(certData)
  282. transport.TLSClientConfig = &tls.Config{RootCAs: rootCAs}
  283. }
  284. return &http.Client{
  285. Transport: transport,
  286. Timeout: requestTimeout,
  287. }, nil
  288. }
  289. // MakeDownloadHttpClient is a resusable helper that sets up a
  290. // http.Client for use either untunneled or through a tunnel.
  291. // See MakeUntunneledHttpsClient for a note about request URL
  292. // rewritting.
  293. func MakeDownloadHttpClient(
  294. config *Config,
  295. tunnel *Tunnel,
  296. untunneledDialConfig *DialConfig,
  297. requestUrl string,
  298. requestTimeout time.Duration) (*http.Client, string, error) {
  299. var httpClient *http.Client
  300. var err error
  301. if tunnel != nil {
  302. // MakeTunneledHttpClient works with both "http" and "https" schemes
  303. httpClient, err = MakeTunneledHttpClient(config, tunnel, requestTimeout)
  304. if err != nil {
  305. return nil, "", common.ContextError(err)
  306. }
  307. } else {
  308. urlComponents, err := url.Parse(requestUrl)
  309. if err != nil {
  310. return nil, "", common.ContextError(err)
  311. }
  312. // MakeUntunneledHttpsClient works only with "https" schemes
  313. if urlComponents.Scheme == "https" {
  314. httpClient, requestUrl, err = MakeUntunneledHttpsClient(
  315. untunneledDialConfig, nil, requestUrl, requestTimeout)
  316. if err != nil {
  317. return nil, "", common.ContextError(err)
  318. }
  319. } else {
  320. httpClient = &http.Client{
  321. Timeout: requestTimeout,
  322. Transport: &http.Transport{
  323. Dial: NewTCPDialer(untunneledDialConfig),
  324. },
  325. }
  326. }
  327. }
  328. return httpClient, requestUrl, nil
  329. }
  330. // ResumeDownload is a resuable helper that downloads requestUrl via the
  331. // httpClient, storing the result in downloadFilename when the download is
  332. // complete. Intermediate, partial downloads state is stored in
  333. // downloadFilename.part and downloadFilename.part.etag.
  334. // Any existing downloadFilename file will be overwritten.
  335. //
  336. // In the case where the remote object has changed while a partial download
  337. // is to be resumed, the partial state is reset and resumeDownload fails.
  338. // The caller must restart the download.
  339. //
  340. // When ifNoneMatchETag is specified, no download is made if the remote
  341. // object has the same ETag. ifNoneMatchETag has an effect only when no
  342. // partial download is in progress.
  343. //
  344. func ResumeDownload(
  345. httpClient *http.Client,
  346. requestUrl string,
  347. downloadFilename string,
  348. ifNoneMatchETag string) (int64, string, error) {
  349. partialFilename := fmt.Sprintf("%s.part", downloadFilename)
  350. partialETagFilename := fmt.Sprintf("%s.part.etag", downloadFilename)
  351. file, err := os.OpenFile(partialFilename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
  352. if err != nil {
  353. return 0, "", common.ContextError(err)
  354. }
  355. defer file.Close()
  356. fileInfo, err := file.Stat()
  357. if err != nil {
  358. return 0, "", common.ContextError(err)
  359. }
  360. // A partial download should have an ETag which is to be sent with the
  361. // Range request to ensure that the source object is the same as the
  362. // one that is partially downloaded.
  363. var partialETag []byte
  364. if fileInfo.Size() > 0 {
  365. partialETag, err = ioutil.ReadFile(partialETagFilename)
  366. // When the ETag can't be loaded, delete the partial download. To keep the
  367. // code simple, there is no immediate, inline retry here, on the assumption
  368. // that the controller's upgradeDownloader will shortly call DownloadUpgrade
  369. // again.
  370. if err != nil {
  371. os.Remove(partialFilename)
  372. os.Remove(partialETagFilename)
  373. return 0, "", common.ContextError(
  374. fmt.Errorf("failed to load partial download ETag: %s", err))
  375. }
  376. }
  377. request, err := http.NewRequest("GET", requestUrl, nil)
  378. if err != nil {
  379. return 0, "", common.ContextError(err)
  380. }
  381. request.Header.Add("Range", fmt.Sprintf("bytes=%d-", fileInfo.Size()))
  382. if partialETag != nil {
  383. // Note: not using If-Range, since not all host servers support it.
  384. // Using If-Match means we need to check for status code 412 and reset
  385. // when the ETag has changed since the last partial download.
  386. request.Header.Add("If-Match", string(partialETag))
  387. } else if ifNoneMatchETag != "" {
  388. // Can't specify both If-Match and If-None-Match. Behavior is undefined.
  389. // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
  390. // So for downloaders that store an ETag and wish to use that to prevent
  391. // redundant downloads, that ETag is sent as If-None-Match in the case
  392. // where a partial download is not in progress. When a partial download
  393. // is in progress, the partial ETag is sent as If-Match: either that's
  394. // a version that was never fully received, or it's no longer current in
  395. // which case the response will be StatusPreconditionFailed, the partial
  396. // download will be discarded, and then the next retry will use
  397. // If-None-Match.
  398. // Note: in this case, fileInfo.Size() == 0
  399. request.Header.Add("If-None-Match", ifNoneMatchETag)
  400. }
  401. response, err := httpClient.Do(request)
  402. // The resumeable download may ask for bytes past the resource range
  403. // since it doesn't store the "completed download" state. In this case,
  404. // the HTTP server returns 416. Otherwise, we expect 206. We may also
  405. // receive 412 on ETag mismatch.
  406. if err == nil &&
  407. (response.StatusCode != http.StatusPartialContent &&
  408. response.StatusCode != http.StatusRequestedRangeNotSatisfiable &&
  409. response.StatusCode != http.StatusPreconditionFailed &&
  410. response.StatusCode != http.StatusNotModified) {
  411. response.Body.Close()
  412. err = fmt.Errorf("unexpected response status code: %d", response.StatusCode)
  413. }
  414. if err != nil {
  415. return 0, "", common.ContextError(err)
  416. }
  417. defer response.Body.Close()
  418. responseETag := response.Header.Get("ETag")
  419. if response.StatusCode == http.StatusPreconditionFailed {
  420. // When the ETag no longer matches, delete the partial download. As above,
  421. // simply failing and relying on the caller's retry schedule.
  422. os.Remove(partialFilename)
  423. os.Remove(partialETagFilename)
  424. return 0, "", common.ContextError(errors.New("partial download ETag mismatch"))
  425. } else if response.StatusCode == http.StatusNotModified {
  426. // This status code is possible in the "If-None-Match" case. Don't leave
  427. // any partial download in progress. Caller should check that responseETag
  428. // matches ifNoneMatchETag.
  429. os.Remove(partialFilename)
  430. os.Remove(partialETagFilename)
  431. return 0, responseETag, nil
  432. }
  433. // Not making failure to write ETag file fatal, in case the entire download
  434. // succeeds in this one request.
  435. ioutil.WriteFile(partialETagFilename, []byte(responseETag), 0600)
  436. // A partial download occurs when this copy is interrupted. The io.Copy
  437. // will fail, leaving a partial download in place (.part and .part.etag).
  438. n, err := io.Copy(NewSyncFileWriter(file), response.Body)
  439. // From this point, n bytes are indicated as downloaded, even if there is
  440. // an error; the caller may use this to report partial download progress.
  441. if err != nil {
  442. return n, "", common.ContextError(err)
  443. }
  444. // Ensure the file is flushed to disk. The deferred close
  445. // will be a noop when this succeeds.
  446. err = file.Close()
  447. if err != nil {
  448. return n, "", common.ContextError(err)
  449. }
  450. // Remove if exists, to enable rename
  451. os.Remove(downloadFilename)
  452. err = os.Rename(partialFilename, downloadFilename)
  453. if err != nil {
  454. return n, "", common.ContextError(err)
  455. }
  456. os.Remove(partialETagFilename)
  457. return n, responseETag, nil
  458. }