net.go 34 KB

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