net.go 18 KB

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