net.go 35 KB

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