net.go 35 KB

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