net.go 35 KB

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