net.go 34 KB

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