net.go 34 KB

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