net.go 34 KB

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