net.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  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. std_errors "errors"
  25. "fmt"
  26. "io"
  27. "io/ioutil"
  28. "net"
  29. "net/http"
  30. "os"
  31. "strings"
  32. "sync"
  33. "sync/atomic"
  34. "time"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/fragmentor"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  41. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/resolver"
  42. "golang.org/x/net/bpf"
  43. )
  44. // DialConfig contains parameters to determine the behavior
  45. // of a Psiphon dialer (TCPDial, UDPDial, MeekDial, etc.)
  46. type DialConfig struct {
  47. // DiagnosticID is the server ID to record in any diagnostics notices.
  48. DiagnosticID string
  49. // UpstreamProxyURL specifies a proxy to connect through.
  50. // E.g., "http://proxyhost:8080"
  51. // "socks5://user:password@proxyhost:1080"
  52. // "socks4a://proxyhost:1080"
  53. // "http://NTDOMAIN\NTUser:password@proxyhost:3375"
  54. //
  55. // Certain tunnel protocols require HTTP CONNECT support
  56. // when a HTTP proxy is specified. If CONNECT is not
  57. // supported, those protocols will not connect.
  58. //
  59. // UpstreamProxyURL is not used by UDPDial.
  60. UpstreamProxyURL string
  61. // CustomHeaders is a set of additional arbitrary HTTP headers that are
  62. // added to all plaintext HTTP requests and requests made through an HTTP
  63. // upstream proxy when specified by UpstreamProxyURL.
  64. CustomHeaders http.Header
  65. // BPFProgramInstructions specifies a BPF program to attach to the dial
  66. // socket before connecting.
  67. BPFProgramInstructions []bpf.RawInstruction
  68. // DeviceBinder, when not nil, is applied when dialing UDP/TCP. See:
  69. // DeviceBinder doc.
  70. DeviceBinder DeviceBinder
  71. // IPv6Synthesizer, when not nil, is applied when dialing UDP/TCP. See:
  72. // IPv6Synthesizer doc.
  73. IPv6Synthesizer IPv6Synthesizer
  74. // ResolveIP is used to resolve destination domains. ResolveIP should
  75. // return either at least one IP address or an error.
  76. ResolveIP func(context.Context, string) ([]net.IP, error)
  77. // ResolvedIPCallback, when set, is called with the IP address that was
  78. // dialed. This is either the specified IP address in the dial address,
  79. // or the resolved IP address in the case where the dial address is a
  80. // domain name.
  81. // The callback may be invoked by a concurrent goroutine.
  82. ResolvedIPCallback func(string)
  83. // TrustedCACertificatesFilename specifies a file containing trusted
  84. // CA certs. See Config.TrustedCACertificatesFilename.
  85. TrustedCACertificatesFilename string
  86. // FragmentorConfig specifies whether to layer a fragmentor.Conn on top
  87. // of dialed TCP conns, and the fragmentation configuration to use.
  88. FragmentorConfig *fragmentor.Config
  89. // UpstreamProxyErrorCallback is called when a dial fails due to an upstream
  90. // proxy error. As the upstream proxy is user configured, the error message
  91. // may need to be relayed to the user.
  92. UpstreamProxyErrorCallback func(error)
  93. // CustomDialer overrides the dialer created by NewNetDialer/NewTCPDialer.
  94. // When CustomDialer is set, all other DialConfig parameters are ignored by
  95. // NewNetDialer/NewTCPDialer. Other DialConfig consumers may still reference
  96. // other DialConfig parameters; for example MeekConfig still uses
  97. // TrustedCACertificatesFilename.
  98. CustomDialer common.Dialer
  99. }
  100. // WithoutFragmentor returns a copy of the DialConfig with any fragmentor
  101. // configuration disabled. The return value is not a deep copy and may be the
  102. // input DialConfig; it should not be modified.
  103. func (config *DialConfig) WithoutFragmentor() *DialConfig {
  104. if config.FragmentorConfig == nil {
  105. return config
  106. }
  107. newConfig := new(DialConfig)
  108. *newConfig = *config
  109. newConfig.FragmentorConfig = nil
  110. return newConfig
  111. }
  112. // NetworkConnectivityChecker defines the interface to the external
  113. // HasNetworkConnectivity provider, which call into the host application to
  114. // check for network connectivity.
  115. type NetworkConnectivityChecker interface {
  116. // TODO: change to bool return value once gobind supports that type
  117. HasNetworkConnectivity() int
  118. }
  119. // DeviceBinder defines the interface to the external BindToDevice provider
  120. // which calls into the host application to bind sockets to specific devices.
  121. // This is used for VPN routing exclusion.
  122. // The string return value should report device information for diagnostics.
  123. type DeviceBinder interface {
  124. BindToDevice(fileDescriptor int) (string, error)
  125. }
  126. // DNSServerGetter defines the interface to the external GetDNSServers provider
  127. // which calls into the host application to discover the native network DNS
  128. // server settings.
  129. type DNSServerGetter interface {
  130. GetDNSServers() []string
  131. }
  132. // IPv6Synthesizer defines the interface to the external IPv6Synthesize
  133. // provider which calls into the host application to synthesize IPv6 addresses
  134. // from IPv4 ones. This is used to correctly lookup IPs on DNS64/NAT64
  135. // networks.
  136. type IPv6Synthesizer interface {
  137. IPv6Synthesize(IPv4Addr string) string
  138. }
  139. // HasIPv6RouteGetter defines the interface to the external HasIPv6Route
  140. // provider which calls into the host application to determine if the host
  141. // has an IPv6 route.
  142. type HasIPv6RouteGetter interface {
  143. // TODO: change to bool return value once gobind supports that type
  144. HasIPv6Route() int
  145. }
  146. // NetworkIDGetter defines the interface to the external GetNetworkID
  147. // provider, which returns an identifier for the host's current active
  148. // network.
  149. //
  150. // The identifier is a string that should indicate the network type and
  151. // identity; for example "WIFI-<BSSID>" or "MOBILE-<MCC/MNC>". As this network
  152. // ID is personally identifying, it is only used locally in the client to
  153. // determine network context and is not sent to the Psiphon server. The
  154. // identifer will be logged in diagnostics messages; in this case only the
  155. // substring before the first "-" is logged, so all PII must appear after the
  156. // first "-".
  157. //
  158. // NetworkIDGetter.GetNetworkID should always return an identifier value, as
  159. // logic that uses GetNetworkID, including tactics, is intended to proceed
  160. // regardless of whether an accurate network identifier can be obtained. By
  161. // convention, the provider should return "UNKNOWN" when an accurate network
  162. // identifier cannot be obtained. Best-effort is acceptable: e.g., return just
  163. // "WIFI" when only the type of the network but no details can be determined.
  164. type NetworkIDGetter interface {
  165. GetNetworkID() string
  166. }
  167. // RefractionNetworkingDialer implements psiphon/common/refraction.Dialer.
  168. type RefractionNetworkingDialer struct {
  169. config *DialConfig
  170. }
  171. // NewRefractionNetworkingDialer creates a new RefractionNetworkingDialer.
  172. func NewRefractionNetworkingDialer(config *DialConfig) *RefractionNetworkingDialer {
  173. return &RefractionNetworkingDialer{
  174. config: config,
  175. }
  176. }
  177. func (d *RefractionNetworkingDialer) DialContext(
  178. ctx context.Context,
  179. network string,
  180. laddr string,
  181. raddr string) (net.Conn, error) {
  182. switch network {
  183. case "tcp", "tcp4", "tcp6":
  184. if laddr != "" {
  185. return nil, errors.TraceNew("unexpected laddr for tcp dial")
  186. }
  187. conn, err := DialTCP(ctx, raddr, d.config)
  188. if err != nil {
  189. return nil, errors.Trace(err)
  190. }
  191. return conn, nil
  192. case "udp", "udp4", "udp6":
  193. udpConn, _, err := NewUDPConn(ctx, network, true, laddr, raddr, d.config)
  194. if err != nil {
  195. return nil, errors.Trace(err)
  196. }
  197. // Ensure blocked packet writes eventually timeout.
  198. conn := &common.WriteTimeoutUDPConn{
  199. UDPConn: udpConn,
  200. }
  201. return conn, nil
  202. default:
  203. return nil, errors.Tracef("unsupported network: %s", network)
  204. }
  205. }
  206. // LocalProxyRelay sends to remoteConn bytes received from localConn,
  207. // and sends to localConn bytes received from remoteConn.
  208. //
  209. // LocalProxyRelay must close localConn in order to interrupt blocking
  210. // I/O calls when the upstream port forward is closed. remoteConn is
  211. // also closed before returning.
  212. func LocalProxyRelay(config *Config, proxyType string, localConn, remoteConn net.Conn) {
  213. closing := int32(0)
  214. copyWaitGroup := new(sync.WaitGroup)
  215. copyWaitGroup.Add(1)
  216. go func() {
  217. defer copyWaitGroup.Done()
  218. _, err := RelayCopyBuffer(config, localConn, remoteConn)
  219. if err != nil && atomic.LoadInt32(&closing) != 1 {
  220. NoticeLocalProxyError(proxyType, errors.TraceMsg(err, "Relay failed"))
  221. }
  222. // When the server closes a port forward, ex. due to idle timeout,
  223. // remoteConn.Read will return EOF, which causes the downstream io.Copy to
  224. // return (with a nil error). To ensure the downstream local proxy
  225. // connection also closes at this point, we interrupt the blocking upstream
  226. // io.Copy by closing localConn.
  227. atomic.StoreInt32(&closing, 1)
  228. localConn.Close()
  229. }()
  230. _, err := RelayCopyBuffer(config, remoteConn, localConn)
  231. if err != nil && atomic.LoadInt32(&closing) != 1 {
  232. NoticeLocalProxyError(proxyType, errors.TraceMsg(err, "Relay failed"))
  233. }
  234. // When a local proxy peer connection closes, localConn.Read will return EOF.
  235. // As above, close the other end of the relay to ensure immediate shutdown,
  236. // as no more data can be relayed.
  237. atomic.StoreInt32(&closing, 1)
  238. remoteConn.Close()
  239. copyWaitGroup.Wait()
  240. }
  241. // RelayCopyBuffer performs an io.Copy, optionally using a smaller buffer when
  242. // config.LimitRelayBufferSizes is set.
  243. func RelayCopyBuffer(config *Config, dst io.Writer, src io.Reader) (int64, error) {
  244. // By default, io.CopyBuffer will allocate a 32K buffer when a nil buffer
  245. // is passed in. When configured, make and specify a smaller buffer. But
  246. // only if src doesn't implement WriterTo and dst doesn't implement
  247. // ReaderFrom, as in those cases io.CopyBuffer entirely avoids a buffer
  248. // allocation.
  249. var buffer []byte
  250. if config.LimitRelayBufferSizes {
  251. _, isWT := src.(io.WriterTo)
  252. _, isRF := dst.(io.ReaderFrom)
  253. if !isWT && !isRF {
  254. buffer = make([]byte, 4096)
  255. }
  256. }
  257. // Do not wrap any I/O errors
  258. return io.CopyBuffer(dst, src, buffer)
  259. }
  260. // WaitForNetworkConnectivity uses a NetworkConnectivityChecker to
  261. // periodically check for network connectivity. It returns true if
  262. // no NetworkConnectivityChecker is provided (waiting is disabled)
  263. // or when NetworkConnectivityChecker.HasNetworkConnectivity()
  264. // indicates connectivity. It waits and polls the checker once a second.
  265. // When the context is done, false is returned immediately.
  266. func WaitForNetworkConnectivity(
  267. ctx context.Context, connectivityChecker NetworkConnectivityChecker) bool {
  268. if connectivityChecker == nil || connectivityChecker.HasNetworkConnectivity() == 1 {
  269. return true
  270. }
  271. NoticeInfo("waiting for network connectivity")
  272. ticker := time.NewTicker(1 * time.Second)
  273. defer ticker.Stop()
  274. for {
  275. if connectivityChecker.HasNetworkConnectivity() == 1 {
  276. return true
  277. }
  278. select {
  279. case <-ticker.C:
  280. // Check HasNetworkConnectivity again
  281. case <-ctx.Done():
  282. return false
  283. }
  284. }
  285. }
  286. // New Resolver creates a new resolver using the specified config.
  287. // useBindToDevice indicates whether to apply config.BindToDevice, when it
  288. // exists; set useBindToDevice to false when the resolve doesn't need to be
  289. // excluded from any VPN routing.
  290. func NewResolver(config *Config, useBindToDevice bool) *resolver.Resolver {
  291. p := config.GetParameters().Get()
  292. networkConfig := &resolver.NetworkConfig{
  293. LogWarning: func(err error) { NoticeWarning("ResolveIP: %v", err) },
  294. LogHostnames: config.EmitDiagnosticNetworkParameters,
  295. CacheExtensionInitialTTL: p.Duration(parameters.DNSResolverCacheExtensionInitialTTL),
  296. CacheExtensionVerifiedTTL: p.Duration(parameters.DNSResolverCacheExtensionVerifiedTTL),
  297. }
  298. if config.DNSServerGetter != nil {
  299. networkConfig.GetDNSServers = config.DNSServerGetter.GetDNSServers
  300. }
  301. if useBindToDevice && config.DeviceBinder != nil {
  302. networkConfig.BindToDevice = config.DeviceBinder.BindToDevice
  303. networkConfig.AllowDefaultResolverWithBindToDevice =
  304. config.AllowDefaultDNSResolverWithBindToDevice
  305. }
  306. if config.IPv6Synthesizer != nil {
  307. networkConfig.IPv6Synthesize = config.IPv6Synthesizer.IPv6Synthesize
  308. }
  309. if config.HasIPv6RouteGetter != nil {
  310. networkConfig.HasIPv6Route = func() bool {
  311. return config.HasIPv6RouteGetter.HasIPv6Route() == 1
  312. }
  313. }
  314. return resolver.NewResolver(networkConfig, config.GetNetworkID())
  315. }
  316. // UntunneledResolveIP is used to resolve domains for untunneled dials,
  317. // including remote server list and upgrade downloads.
  318. func UntunneledResolveIP(
  319. ctx context.Context,
  320. config *Config,
  321. resolver *resolver.Resolver,
  322. hostname string,
  323. frontingProviderID string) ([]net.IP, error) {
  324. // Limitations: for untunneled resolves, there is currently no resolve
  325. // parameter replay, and no support for pre-resolved IPs.
  326. params, err := resolver.MakeResolveParameters(
  327. config.GetParameters().Get(), frontingProviderID, hostname)
  328. if err != nil {
  329. return nil, errors.Trace(err)
  330. }
  331. IPs, err := resolver.ResolveIP(
  332. ctx,
  333. config.GetNetworkID(),
  334. params,
  335. hostname)
  336. if err != nil {
  337. return nil, errors.Trace(err)
  338. }
  339. return IPs, nil
  340. }
  341. // makeFrontedHTTPClient returns a net/http.Client which is
  342. // configured to use domain fronting and custom dialing features -- including
  343. // BindToDevice, etc. One or more fronting specs must be provided, i.e.
  344. // len(frontingSpecs) must be greater than 0. A function is returned which,
  345. // if non-nil, can be called after each request made with the net/http.Client
  346. // completes to retrieve the set of API parameter values applied to the request.
  347. //
  348. // The context is applied to underlying TCP dials. The caller is responsible
  349. // for applying the context to requests made with the returned http.Client.
  350. //
  351. // Warning: it is not safe to call makeFrontedHTTPClient concurrently with the
  352. // same dialConfig when tunneled is true because dialConfig will be used
  353. // directly, instead of copied, which can lead to a crash when fields not safe
  354. // for concurrent use are present.
  355. func makeFrontedHTTPClient(
  356. ctx context.Context,
  357. config *Config,
  358. tunneled bool,
  359. dialConfig *DialConfig,
  360. frontingSpecs parameters.FrontingSpecs,
  361. selectedFrontingProviderID func(string),
  362. skipVerify bool,
  363. disableSystemRootCAs bool) (*http.Client, func() common.APIParameters, error) {
  364. frontingProviderID,
  365. meekFrontingDialAddress,
  366. meekSNIServerName,
  367. meekVerifyServerName,
  368. meekVerifyPins,
  369. meekFrontingHost, err := parameters.FrontingSpecs(frontingSpecs).SelectParameters()
  370. if err != nil {
  371. return nil, nil, errors.Trace(err)
  372. }
  373. if selectedFrontingProviderID != nil {
  374. selectedFrontingProviderID(frontingProviderID)
  375. }
  376. meekDialAddress := net.JoinHostPort(meekFrontingDialAddress, "443")
  377. meekHostHeader := meekFrontingHost
  378. p := config.GetParameters().Get()
  379. effectiveTunnelProtocol := protocol.TUNNEL_PROTOCOL_FRONTED_MEEK
  380. requireTLS12SessionTickets := protocol.TunnelProtocolRequiresTLS12SessionTickets(
  381. effectiveTunnelProtocol)
  382. requireTLS13Support := protocol.TunnelProtocolRequiresTLS13Support(effectiveTunnelProtocol)
  383. isFronted := true
  384. tlsProfile, tlsVersion, randomizedTLSProfileSeed, err := SelectTLSProfile(
  385. requireTLS12SessionTickets, requireTLS13Support, isFronted, frontingProviderID, p)
  386. if err != nil {
  387. return nil, nil, errors.Trace(err)
  388. }
  389. if tlsProfile == "" && (requireTLS12SessionTickets || requireTLS13Support) {
  390. return nil, nil, errors.TraceNew("required TLS profile not found")
  391. }
  392. noDefaultTLSSessionID := p.WeightedCoinFlip(
  393. parameters.NoDefaultTLSSessionIDProbability)
  394. // For a FrontingSpec, an SNI value of "" indicates to disable/omit SNI, so
  395. // never transform in that case.
  396. var meekTransformedHostName bool
  397. if meekSNIServerName != "" {
  398. if p.WeightedCoinFlip(parameters.TransformHostNameProbability) {
  399. meekSNIServerName = selectHostName(effectiveTunnelProtocol, p)
  400. meekTransformedHostName = true
  401. }
  402. }
  403. addPsiphonFrontingHeader := false
  404. if frontingProviderID != "" {
  405. addPsiphonFrontingHeader = common.Contains(
  406. p.LabeledTunnelProtocols(
  407. parameters.AddFrontingProviderPsiphonFrontingHeader, frontingProviderID),
  408. effectiveTunnelProtocol)
  409. }
  410. networkLatencyMultiplierMin := p.Float(parameters.NetworkLatencyMultiplierMin)
  411. networkLatencyMultiplierMax := p.Float(parameters.NetworkLatencyMultiplierMax)
  412. networkLatencyMultiplier := prng.ExpFloat64Range(
  413. networkLatencyMultiplierMin,
  414. networkLatencyMultiplierMax,
  415. p.Float(parameters.NetworkLatencyMultiplierLambda))
  416. tlsFragmentClientHello := false
  417. if meekSNIServerName != "" {
  418. tlsFragmentorLimitProtocols := p.TunnelProtocols(parameters.TLSFragmentClientHelloLimitProtocols)
  419. if len(tlsFragmentorLimitProtocols) == 0 || common.Contains(tlsFragmentorLimitProtocols, effectiveTunnelProtocol) {
  420. if net.ParseIP(meekSNIServerName) == nil {
  421. tlsFragmentClientHello = p.WeightedCoinFlip(parameters.TLSFragmentClientHelloProbability)
  422. }
  423. }
  424. }
  425. meekConfig := &MeekConfig{
  426. DiagnosticID: frontingProviderID,
  427. Parameters: config.GetParameters(),
  428. Mode: MeekModePlaintextRoundTrip,
  429. DialAddress: meekDialAddress,
  430. UseHTTPS: true,
  431. TLSProfile: tlsProfile,
  432. TLSFragmentClientHello: tlsFragmentClientHello,
  433. NoDefaultTLSSessionID: noDefaultTLSSessionID,
  434. RandomizedTLSProfileSeed: randomizedTLSProfileSeed,
  435. SNIServerName: meekSNIServerName,
  436. AddPsiphonFrontingHeader: addPsiphonFrontingHeader,
  437. HostHeader: meekHostHeader,
  438. TransformedHostName: meekTransformedHostName,
  439. ClientTunnelProtocol: effectiveTunnelProtocol,
  440. NetworkLatencyMultiplier: networkLatencyMultiplier,
  441. }
  442. if !skipVerify {
  443. meekConfig.DisableSystemRootCAs = disableSystemRootCAs
  444. if !meekConfig.DisableSystemRootCAs {
  445. meekConfig.VerifyServerName = meekVerifyServerName
  446. meekConfig.VerifyPins = meekVerifyPins
  447. }
  448. }
  449. var resolvedIPAddress atomic.Value
  450. resolvedIPAddress.Store("")
  451. var meekDialConfig *DialConfig
  452. if tunneled {
  453. meekDialConfig = dialConfig
  454. } else {
  455. // The default untunneled dial config does not support pre-resolved IPs so
  456. // redefine the dial config to override ResolveIP with an implementation
  457. // that enables their use by passing the fronting provider ID into
  458. // UntunneledResolveIP.
  459. meekDialConfig = &DialConfig{
  460. UpstreamProxyURL: dialConfig.UpstreamProxyURL,
  461. CustomHeaders: makeDialCustomHeaders(config, p),
  462. DeviceBinder: dialConfig.DeviceBinder,
  463. IPv6Synthesizer: dialConfig.IPv6Synthesizer,
  464. ResolveIP: func(ctx context.Context, hostname string) ([]net.IP, error) {
  465. IPs, err := UntunneledResolveIP(
  466. ctx, config, config.GetResolver(), hostname, frontingProviderID)
  467. if err != nil {
  468. return nil, errors.Trace(err)
  469. }
  470. return IPs, nil
  471. },
  472. ResolvedIPCallback: func(IPAddress string) {
  473. resolvedIPAddress.Store(IPAddress)
  474. },
  475. }
  476. }
  477. selectedUserAgent, userAgent := selectUserAgentIfUnset(p, meekDialConfig.CustomHeaders)
  478. if selectedUserAgent {
  479. if meekDialConfig.CustomHeaders == nil {
  480. meekDialConfig.CustomHeaders = make(http.Header)
  481. }
  482. meekDialConfig.CustomHeaders.Set("User-Agent", userAgent)
  483. }
  484. // Use MeekConn to domain front requests.
  485. //
  486. // DialMeek will create a TLS connection immediately. We will delay
  487. // initializing the MeekConn-based RoundTripper until we know it's needed.
  488. // This is implemented by passing in a RoundTripper that establishes a
  489. // MeekConn when RoundTrip is called.
  490. //
  491. // Resources are cleaned up when the response body is closed.
  492. roundTrip := func(request *http.Request) (*http.Response, error) {
  493. conn, err := DialMeek(
  494. ctx, meekConfig, meekDialConfig)
  495. if err != nil {
  496. return nil, errors.Trace(err)
  497. }
  498. response, err := conn.RoundTrip(request)
  499. if err != nil {
  500. return nil, errors.Trace(err)
  501. }
  502. // Do not read the response body into memory all at once because it may
  503. // be large. Instead allow the caller to stream the response.
  504. response.Body = newMeekHTTPResponseReadCloser(conn, response.Body)
  505. return response, nil
  506. }
  507. params := func() common.APIParameters {
  508. params := make(common.APIParameters)
  509. params["fronting_provider_id"] = frontingProviderID
  510. if meekConfig.DialAddress != "" {
  511. params["meek_dial_address"] = meekConfig.DialAddress
  512. }
  513. meekResolvedIPAddress := resolvedIPAddress.Load()
  514. if meekResolvedIPAddress != "" {
  515. params["meek_resolved_ip_address"] = meekResolvedIPAddress
  516. }
  517. if meekConfig.SNIServerName != "" {
  518. params["meek_sni_server_name"] = meekConfig.SNIServerName
  519. }
  520. if meekConfig.HostHeader != "" {
  521. params["meek_host_header"] = meekConfig.HostHeader
  522. }
  523. transformedHostName := "0"
  524. if meekTransformedHostName {
  525. transformedHostName = "1"
  526. }
  527. params["meek_transformed_host_name"] = transformedHostName
  528. if meekConfig.TLSProfile != "" {
  529. params["tls_profile"] = meekConfig.TLSProfile
  530. }
  531. if selectedUserAgent {
  532. params["user_agent"] = userAgent
  533. }
  534. if tlsVersion != "" {
  535. params["tls_version"] = getTLSVersionForMetrics(tlsVersion, meekConfig.NoDefaultTLSSessionID)
  536. }
  537. if meekConfig.TLSFragmentClientHello {
  538. params["tls_fragmented"] = "1"
  539. }
  540. return params
  541. }
  542. return &http.Client{
  543. Transport: common.NewHTTPRoundTripper(roundTrip),
  544. }, params, nil
  545. }
  546. // meekHTTPResponseReadCloser wraps an http.Response.Body received over a
  547. // MeekConn in MeekModePlaintextRoundTrip and exposes an io.ReadCloser. Close
  548. // closes the meek conn and response body.
  549. type meekHTTPResponseReadCloser struct {
  550. conn *MeekConn
  551. responseBody io.ReadCloser
  552. }
  553. // newMeekHTTPResponseReadCloser creates a meekHTTPResponseReadCloser.
  554. func newMeekHTTPResponseReadCloser(meekConn *MeekConn, responseBody io.ReadCloser) *meekHTTPResponseReadCloser {
  555. return &meekHTTPResponseReadCloser{
  556. conn: meekConn,
  557. responseBody: responseBody,
  558. }
  559. }
  560. // Read implements the io.Reader interface.
  561. func (meek *meekHTTPResponseReadCloser) Read(p []byte) (n int, err error) {
  562. return meek.responseBody.Read(p)
  563. }
  564. // Read implements the io.Closer interface.
  565. func (meek *meekHTTPResponseReadCloser) Close() error {
  566. err := meek.responseBody.Close()
  567. _ = meek.conn.Close()
  568. return err
  569. }
  570. // MakeUntunneledHTTPClient returns a net/http.Client which is configured to
  571. // use custom dialing features -- including BindToDevice, etc. A function is
  572. // returned which, if non-nil, can be called after each request made with the
  573. // net/http.Client completes to retrieve the set of API parameter values
  574. // applied to the request.
  575. //
  576. // The context is applied to underlying TCP dials. The caller is responsible
  577. // for applying the context to requests made with the returned http.Client.
  578. func MakeUntunneledHTTPClient(
  579. ctx context.Context,
  580. config *Config,
  581. untunneledDialConfig *DialConfig,
  582. skipVerify bool,
  583. disableSystemRootCAs bool,
  584. frontingSpecs parameters.FrontingSpecs,
  585. selectedFrontingProviderID func(string)) (*http.Client, func() common.APIParameters, error) {
  586. if len(frontingSpecs) > 0 {
  587. // Ignore skipVerify because it only applies when there are no
  588. // fronting specs.
  589. httpClient, getParams, err := makeFrontedHTTPClient(
  590. ctx,
  591. config,
  592. false,
  593. untunneledDialConfig,
  594. frontingSpecs,
  595. selectedFrontingProviderID,
  596. false,
  597. disableSystemRootCAs)
  598. if err != nil {
  599. return nil, nil, errors.Trace(err)
  600. }
  601. return httpClient, getParams, nil
  602. }
  603. dialer := NewTCPDialer(untunneledDialConfig)
  604. tlsConfig := &CustomTLSConfig{
  605. Parameters: config.GetParameters(),
  606. Dial: dialer,
  607. UseDialAddrSNI: true,
  608. SNIServerName: "",
  609. SkipVerify: skipVerify,
  610. DisableSystemRootCAs: disableSystemRootCAs,
  611. TrustedCACertificatesFilename: untunneledDialConfig.TrustedCACertificatesFilename,
  612. }
  613. tlsConfig.EnableClientSessionCache()
  614. tlsDialer := NewCustomTLSDialer(tlsConfig)
  615. transport := &http.Transport{
  616. Dial: func(network, addr string) (net.Conn, error) {
  617. return dialer(ctx, network, addr)
  618. },
  619. DialTLS: func(network, addr string) (net.Conn, error) {
  620. return tlsDialer(ctx, network, addr)
  621. },
  622. }
  623. httpClient := &http.Client{
  624. Transport: transport,
  625. }
  626. return httpClient, nil, nil
  627. }
  628. // MakeTunneledHTTPClient returns a net/http.Client which is
  629. // configured to use custom dialing features including tunneled
  630. // dialing and, optionally, UseTrustedCACertificatesForStockTLS.
  631. // This http.Client uses stock TLS for HTTPS.
  632. func MakeTunneledHTTPClient(
  633. ctx context.Context,
  634. config *Config,
  635. tunnel *Tunnel,
  636. skipVerify bool,
  637. disableSystemRootCAs bool,
  638. frontingSpecs parameters.FrontingSpecs,
  639. selectedFrontingProviderID func(string)) (*http.Client, func() common.APIParameters, error) {
  640. // Note: there is no dial context since SSH port forward dials cannot
  641. // be interrupted directly. Closing the tunnel will interrupt the dials.
  642. tunneledDialer := func(_, addr string) (net.Conn, error) {
  643. // Set alwaysTunneled to ensure the http.Client traffic is always tunneled,
  644. // even when split tunnel mode is enabled.
  645. conn, _, err := tunnel.DialTCPChannel(addr, true, nil)
  646. return conn, errors.Trace(err)
  647. }
  648. if len(frontingSpecs) > 0 {
  649. dialConfig := &DialConfig{
  650. TrustedCACertificatesFilename: config.TrustedCACertificatesFilename,
  651. CustomDialer: func(_ context.Context, _, addr string) (net.Conn, error) {
  652. return tunneledDialer("", addr)
  653. },
  654. }
  655. // Ignore skipVerify because it only applies when there are no
  656. // fronting specs.
  657. httpClient, getParams, err := makeFrontedHTTPClient(
  658. ctx,
  659. config,
  660. true,
  661. dialConfig,
  662. frontingSpecs,
  663. selectedFrontingProviderID,
  664. false,
  665. disableSystemRootCAs)
  666. if err != nil {
  667. return nil, nil, errors.Trace(err)
  668. }
  669. return httpClient, getParams, nil
  670. }
  671. transport := &http.Transport{
  672. Dial: tunneledDialer,
  673. }
  674. if skipVerify {
  675. transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
  676. } else if config.TrustedCACertificatesFilename != "" {
  677. rootCAs := x509.NewCertPool()
  678. certData, err := ioutil.ReadFile(config.TrustedCACertificatesFilename)
  679. if err != nil {
  680. return nil, nil, errors.Trace(err)
  681. }
  682. rootCAs.AppendCertsFromPEM(certData)
  683. transport.TLSClientConfig = &tls.Config{RootCAs: rootCAs}
  684. }
  685. return &http.Client{
  686. Transport: transport,
  687. }, nil, nil
  688. }
  689. // MakeDownloadHTTPClient is a helper that sets up a http.Client for use either
  690. // untunneled or through a tunnel. True is returned if the http.Client is setup
  691. // for use through a tunnel; otherwise it is setup for untunneled use. A
  692. // function is returned which, if non-nil, can be called after each request
  693. // made with the http.Client completes to retrieve the set of API
  694. // parameter values applied to the request.
  695. func MakeDownloadHTTPClient(
  696. ctx context.Context,
  697. config *Config,
  698. tunnel *Tunnel,
  699. untunneledDialConfig *DialConfig,
  700. skipVerify,
  701. disableSystemRootCAs bool,
  702. frontingSpecs parameters.FrontingSpecs,
  703. selectedFrontingProviderID func(string)) (*http.Client, bool, func() common.APIParameters, error) {
  704. var httpClient *http.Client
  705. var getParams func() common.APIParameters
  706. var err error
  707. tunneled := tunnel != nil
  708. if tunneled {
  709. httpClient, getParams, err = MakeTunneledHTTPClient(
  710. ctx,
  711. config,
  712. tunnel,
  713. skipVerify || disableSystemRootCAs,
  714. disableSystemRootCAs,
  715. frontingSpecs,
  716. selectedFrontingProviderID)
  717. if err != nil {
  718. return nil, false, nil, errors.Trace(err)
  719. }
  720. } else {
  721. httpClient, getParams, err = MakeUntunneledHTTPClient(
  722. ctx,
  723. config,
  724. untunneledDialConfig,
  725. skipVerify,
  726. disableSystemRootCAs,
  727. frontingSpecs,
  728. selectedFrontingProviderID)
  729. if err != nil {
  730. return nil, false, nil, errors.Trace(err)
  731. }
  732. }
  733. return httpClient, tunneled, getParams, nil
  734. }
  735. // ResumeDownload is a reusable helper that downloads requestUrl via the
  736. // httpClient, storing the result in downloadFilename when the download is
  737. // complete. Intermediate, partial downloads state is stored in
  738. // downloadFilename.part and downloadFilename.part.etag.
  739. // Any existing downloadFilename file will be overwritten.
  740. //
  741. // In the case where the remote object has changed while a partial download
  742. // is to be resumed, the partial state is reset and resumeDownload fails.
  743. // The caller must restart the download.
  744. //
  745. // When ifNoneMatchETag is specified, no download is made if the remote
  746. // object has the same ETag. ifNoneMatchETag has an effect only when no
  747. // partial download is in progress.
  748. func ResumeDownload(
  749. ctx context.Context,
  750. httpClient *http.Client,
  751. downloadURL string,
  752. userAgent string,
  753. downloadFilename string,
  754. ifNoneMatchETag string) (int64, string, error) {
  755. partialFilename := fmt.Sprintf("%s.part", downloadFilename)
  756. partialETagFilename := fmt.Sprintf("%s.part.etag", downloadFilename)
  757. file, err := os.OpenFile(partialFilename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
  758. if err != nil {
  759. return 0, "", errors.Trace(err)
  760. }
  761. defer file.Close()
  762. fileInfo, err := file.Stat()
  763. if err != nil {
  764. return 0, "", errors.Trace(err)
  765. }
  766. // A partial download should have an ETag which is to be sent with the
  767. // Range request to ensure that the source object is the same as the
  768. // one that is partially downloaded.
  769. var partialETag []byte
  770. if fileInfo.Size() > 0 {
  771. partialETag, err = ioutil.ReadFile(partialETagFilename)
  772. // When the ETag can't be loaded, delete the partial download. To keep the
  773. // code simple, there is no immediate, inline retry here, on the assumption
  774. // that the controller's upgradeDownloader will shortly call DownloadUpgrade
  775. // again.
  776. if err != nil {
  777. // On Windows, file must be closed before it can be deleted
  778. file.Close()
  779. tempErr := os.Remove(partialFilename)
  780. if tempErr != nil && !os.IsNotExist(tempErr) {
  781. NoticeWarning("reset partial download failed: %s", tempErr)
  782. }
  783. tempErr = os.Remove(partialETagFilename)
  784. if tempErr != nil && !os.IsNotExist(tempErr) {
  785. NoticeWarning("reset partial download ETag failed: %s", tempErr)
  786. }
  787. return 0, "", errors.Tracef(
  788. "failed to load partial download ETag: %s", err)
  789. }
  790. }
  791. request, err := http.NewRequest("GET", downloadURL, nil)
  792. if err != nil {
  793. return 0, "", errors.Trace(err)
  794. }
  795. request = request.WithContext(ctx)
  796. request.Header.Set("User-Agent", userAgent)
  797. request.Header.Add("Range", fmt.Sprintf("bytes=%d-", fileInfo.Size()))
  798. if partialETag != nil {
  799. // Note: not using If-Range, since not all host servers support it.
  800. // Using If-Match means we need to check for status code 412 and reset
  801. // when the ETag has changed since the last partial download.
  802. request.Header.Add("If-Match", string(partialETag))
  803. } else if ifNoneMatchETag != "" {
  804. // Can't specify both If-Match and If-None-Match. Behavior is undefined.
  805. // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
  806. // So for downloaders that store an ETag and wish to use that to prevent
  807. // redundant downloads, that ETag is sent as If-None-Match in the case
  808. // where a partial download is not in progress. When a partial download
  809. // is in progress, the partial ETag is sent as If-Match: either that's
  810. // a version that was never fully received, or it's no longer current in
  811. // which case the response will be StatusPreconditionFailed, the partial
  812. // download will be discarded, and then the next retry will use
  813. // If-None-Match.
  814. // Note: in this case, fileInfo.Size() == 0
  815. request.Header.Add("If-None-Match", ifNoneMatchETag)
  816. }
  817. response, err := httpClient.Do(request)
  818. // The resumeable download may ask for bytes past the resource range
  819. // since it doesn't store the "completed download" state. In this case,
  820. // the HTTP server returns 416. Otherwise, we expect 206. We may also
  821. // receive 412 on ETag mismatch.
  822. if err == nil &&
  823. (response.StatusCode != http.StatusPartialContent &&
  824. // Certain http servers return 200 OK where we expect 206, so accept that.
  825. response.StatusCode != http.StatusOK &&
  826. response.StatusCode != http.StatusRequestedRangeNotSatisfiable &&
  827. response.StatusCode != http.StatusPreconditionFailed &&
  828. response.StatusCode != http.StatusNotModified) {
  829. response.Body.Close()
  830. err = fmt.Errorf("unexpected response status code: %d", response.StatusCode)
  831. }
  832. if err != nil {
  833. // Redact URL from "net/http" error message.
  834. if !GetEmitNetworkParameters() {
  835. errStr := err.Error()
  836. err = std_errors.New(strings.Replace(errStr, downloadURL, "[redacted]", -1))
  837. }
  838. return 0, "", errors.Trace(err)
  839. }
  840. defer response.Body.Close()
  841. responseETag := response.Header.Get("ETag")
  842. if response.StatusCode == http.StatusPreconditionFailed {
  843. // When the ETag no longer matches, delete the partial download. As above,
  844. // simply failing and relying on the caller's retry schedule.
  845. os.Remove(partialFilename)
  846. os.Remove(partialETagFilename)
  847. return 0, "", errors.TraceNew("partial download ETag mismatch")
  848. } else if response.StatusCode == http.StatusNotModified {
  849. // This status code is possible in the "If-None-Match" case. Don't leave
  850. // any partial download in progress. Caller should check that responseETag
  851. // matches ifNoneMatchETag.
  852. os.Remove(partialFilename)
  853. os.Remove(partialETagFilename)
  854. return 0, responseETag, nil
  855. }
  856. // Not making failure to write ETag file fatal, in case the entire download
  857. // succeeds in this one request.
  858. ioutil.WriteFile(partialETagFilename, []byte(responseETag), 0600)
  859. // A partial download occurs when this copy is interrupted. The io.Copy
  860. // will fail, leaving a partial download in place (.part and .part.etag).
  861. n, err := io.Copy(NewSyncFileWriter(file), response.Body)
  862. // From this point, n bytes are indicated as downloaded, even if there is
  863. // an error; the caller may use this to report partial download progress.
  864. if err != nil {
  865. return n, "", errors.Trace(err)
  866. }
  867. // Ensure the file is flushed to disk. The deferred close
  868. // will be a noop when this succeeds.
  869. err = file.Close()
  870. if err != nil {
  871. return n, "", errors.Trace(err)
  872. }
  873. // Remove if exists, to enable rename
  874. os.Remove(downloadFilename)
  875. err = os.Rename(partialFilename, downloadFilename)
  876. if err != nil {
  877. return n, "", errors.Trace(err)
  878. }
  879. os.Remove(partialETagFilename)
  880. return n, responseETag, nil
  881. }