client.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. //go:build !js
  4. // Package controlhttp implements the Tailscale 2021 control protocol
  5. // base transport over HTTP.
  6. //
  7. // This tunnels the protocol in control/controlbase over HTTP with a
  8. // variety of compatibility fallbacks for handling picky or deep
  9. // inspecting proxies.
  10. //
  11. // In the happy path, a client makes a single cleartext HTTP request
  12. // to the server, the server responds with 101 Switching Protocols,
  13. // and the control base protocol takes place over plain TCP.
  14. //
  15. // In the compatibility path, the client does the above over HTTPS,
  16. // resulting in double encryption (once for the control transport, and
  17. // once for the outer TLS layer).
  18. package controlhttp
  19. import (
  20. "context"
  21. "crypto/tls"
  22. "encoding/base64"
  23. "errors"
  24. "fmt"
  25. "io"
  26. "math"
  27. "net"
  28. "net/http"
  29. "net/http/httptrace"
  30. "net/netip"
  31. "net/url"
  32. "runtime"
  33. "sort"
  34. "sync/atomic"
  35. "time"
  36. "tailscale.com/control/controlbase"
  37. "tailscale.com/envknob"
  38. "tailscale.com/health"
  39. "tailscale.com/net/dnscache"
  40. "tailscale.com/net/dnsfallback"
  41. "tailscale.com/net/netutil"
  42. "tailscale.com/net/sockstats"
  43. "tailscale.com/net/tlsdial"
  44. "tailscale.com/net/tshttpproxy"
  45. "tailscale.com/tailcfg"
  46. "tailscale.com/tstime"
  47. "tailscale.com/util/multierr"
  48. )
  49. var stdDialer net.Dialer
  50. // Dial connects to the HTTP server at this Dialer's Host:HTTPPort, requests to
  51. // switch to the Tailscale control protocol, and returns an established control
  52. // protocol connection.
  53. //
  54. // If Dial fails to connect using HTTP, it also tries to tunnel over TLS to the
  55. // Dialer's Host:HTTPSPort as a compatibility fallback.
  56. //
  57. // The provided ctx is only used for the initial connection, until
  58. // Dial returns. It does not affect the connection once established.
  59. func (a *Dialer) Dial(ctx context.Context) (*ClientConn, error) {
  60. if a.Hostname == "" {
  61. return nil, errors.New("required Dialer.Hostname empty")
  62. }
  63. return a.dial(ctx)
  64. }
  65. func (a *Dialer) logf(format string, args ...any) {
  66. if a.Logf != nil {
  67. a.Logf(format, args...)
  68. }
  69. }
  70. func (a *Dialer) getProxyFunc() func(*http.Request) (*url.URL, error) {
  71. if a.proxyFunc != nil {
  72. return a.proxyFunc
  73. }
  74. return tshttpproxy.ProxyFromEnvironment
  75. }
  76. // httpsFallbackDelay is how long we'll wait for a.HTTPPort to work before
  77. // starting to try a.HTTPSPort.
  78. func (a *Dialer) httpsFallbackDelay() time.Duration {
  79. if forceNoise443() {
  80. return time.Nanosecond
  81. }
  82. if v := a.testFallbackDelay; v != 0 {
  83. return v
  84. }
  85. return 500 * time.Millisecond
  86. }
  87. var _ = envknob.RegisterBool("TS_USE_CONTROL_DIAL_PLAN") // to record at init time whether it's in use
  88. func (a *Dialer) dial(ctx context.Context) (*ClientConn, error) {
  89. // If we don't have a dial plan, just fall back to dialing the single
  90. // host we know about.
  91. useDialPlan := envknob.BoolDefaultTrue("TS_USE_CONTROL_DIAL_PLAN")
  92. if !useDialPlan || a.DialPlan == nil || len(a.DialPlan.Candidates) == 0 {
  93. return a.dialHost(ctx, netip.Addr{})
  94. }
  95. candidates := a.DialPlan.Candidates
  96. // Otherwise, we try dialing per the plan. Store the highest priority
  97. // in the list, so that if we get a connection to one of those
  98. // candidates we can return quickly.
  99. var highestPriority int = math.MinInt
  100. for _, c := range candidates {
  101. if c.Priority > highestPriority {
  102. highestPriority = c.Priority
  103. }
  104. }
  105. // This context allows us to cancel in-flight connections if we get a
  106. // highest-priority connection before we're all done.
  107. ctx, cancel := context.WithCancel(ctx)
  108. defer cancel()
  109. // Now, for each candidate, kick off a dial in parallel.
  110. type dialResult struct {
  111. conn *ClientConn
  112. err error
  113. addr netip.Addr
  114. priority int
  115. }
  116. resultsCh := make(chan dialResult, len(candidates))
  117. var pending atomic.Int32
  118. pending.Store(int32(len(candidates)))
  119. for _, c := range candidates {
  120. go func(ctx context.Context, c tailcfg.ControlIPCandidate) {
  121. var (
  122. conn *ClientConn
  123. err error
  124. )
  125. // Always send results back to our channel.
  126. defer func() {
  127. resultsCh <- dialResult{conn, err, c.IP, c.Priority}
  128. if pending.Add(-1) == 0 {
  129. close(resultsCh)
  130. }
  131. }()
  132. // If non-zero, wait the configured start timeout
  133. // before we do anything.
  134. if c.DialStartDelaySec > 0 {
  135. a.logf("[v2] controlhttp: waiting %.2f seconds before dialing %q @ %v", c.DialStartDelaySec, a.Hostname, c.IP)
  136. if a.Clock == nil {
  137. a.Clock = tstime.StdClock{}
  138. }
  139. tmr, tmrChannel := a.Clock.NewTimer(time.Duration(c.DialStartDelaySec * float64(time.Second)))
  140. defer tmr.Stop()
  141. select {
  142. case <-ctx.Done():
  143. err = ctx.Err()
  144. return
  145. case <-tmrChannel:
  146. }
  147. }
  148. // Now, create a sub-context with the given timeout and
  149. // try dialing the provided host.
  150. ctx, cancel := context.WithTimeout(ctx, time.Duration(c.DialTimeoutSec*float64(time.Second)))
  151. defer cancel()
  152. // This will dial, and the defer above sends it back to our parent.
  153. a.logf("[v2] controlhttp: trying to dial %q @ %v", a.Hostname, c.IP)
  154. conn, err = a.dialHost(ctx, c.IP)
  155. }(ctx, c)
  156. }
  157. var results []dialResult
  158. for res := range resultsCh {
  159. // If we get a response that has the highest priority, we don't
  160. // need to wait for any of the other connections to finish; we
  161. // can just return this connection.
  162. //
  163. // TODO(andrew): we could make this better by keeping track of
  164. // the highest remaining priority dynamically, instead of just
  165. // checking for the highest total
  166. if res.priority == highestPriority && res.conn != nil {
  167. a.logf("[v1] controlhttp: high-priority success dialing %q @ %v from dial plan", a.Hostname, res.addr)
  168. // Drain the channel and any existing connections in
  169. // the background.
  170. go func() {
  171. for _, res := range results {
  172. if res.conn != nil {
  173. res.conn.Close()
  174. }
  175. }
  176. for res := range resultsCh {
  177. if res.conn != nil {
  178. res.conn.Close()
  179. }
  180. }
  181. if a.drainFinished != nil {
  182. close(a.drainFinished)
  183. }
  184. }()
  185. return res.conn, nil
  186. }
  187. // This isn't a highest-priority result, so just store it until
  188. // we're done.
  189. results = append(results, res)
  190. }
  191. // After we finish this function, close any remaining open connections.
  192. defer func() {
  193. for _, result := range results {
  194. // Note: below, we nil out the returned connection (if
  195. // any) in the slice so we don't close it.
  196. if result.conn != nil {
  197. result.conn.Close()
  198. }
  199. }
  200. // We don't drain asynchronously after this point, so notify our
  201. // channel when we return.
  202. if a.drainFinished != nil {
  203. close(a.drainFinished)
  204. }
  205. }()
  206. // Sort by priority, then take the first non-error response.
  207. sort.Slice(results, func(i, j int) bool {
  208. // NOTE: intentionally inverted so that the highest priority
  209. // item comes first
  210. return results[i].priority > results[j].priority
  211. })
  212. var (
  213. conn *ClientConn
  214. errs []error
  215. )
  216. for i, result := range results {
  217. if result.err != nil {
  218. errs = append(errs, result.err)
  219. continue
  220. }
  221. a.logf("[v1] controlhttp: succeeded dialing %q @ %v from dial plan", a.Hostname, result.addr)
  222. conn = result.conn
  223. results[i].conn = nil // so we don't close it in the defer
  224. return conn, nil
  225. }
  226. merr := multierr.New(errs...)
  227. // If we get here, then we didn't get anywhere with our dial plan; fall back to just using DNS.
  228. a.logf("controlhttp: failed dialing using DialPlan, falling back to DNS; errs=%s", merr.Error())
  229. return a.dialHost(ctx, netip.Addr{})
  230. }
  231. // The TS_FORCE_NOISE_443 envknob forces the controlclient noise dialer to
  232. // always use port 443 HTTPS connections to the controlplane and not try the
  233. // port 80 HTTP fast path.
  234. //
  235. // This is currently (2023-01-17) needed for Docker Desktop's "VPNKit" proxy
  236. // that breaks port 80 for us post-Noise-handshake, causing us to never try port
  237. // 443. Until one of Docker's proxy and/or this package's port 443 fallback is
  238. // fixed, this is a workaround. It might also be useful for future debugging.
  239. var forceNoise443 = envknob.RegisterBool("TS_FORCE_NOISE_443")
  240. var debugNoiseDial = envknob.RegisterBool("TS_DEBUG_NOISE_DIAL")
  241. // dialHost connects to the configured Dialer.Hostname and upgrades the
  242. // connection into a controlbase.Conn. If addr is valid, then no DNS is used
  243. // and the connection will be made to the provided address.
  244. func (a *Dialer) dialHost(ctx context.Context, addr netip.Addr) (*ClientConn, error) {
  245. // Create one shared context used by both port 80 and port 443 dials.
  246. // If port 80 is still in flight when 443 returns, this deferred cancel
  247. // will stop the port 80 dial.
  248. ctx, cancel := context.WithCancel(ctx)
  249. defer cancel()
  250. ctx = sockstats.WithSockStats(ctx, sockstats.LabelControlClientDialer, a.logf)
  251. // u80 and u443 are the URLs we'll try to hit over HTTP or HTTPS,
  252. // respectively, in order to do the HTTP upgrade to a net.Conn over which
  253. // we'll speak Noise.
  254. u80 := &url.URL{
  255. Scheme: "http",
  256. Host: net.JoinHostPort(a.Hostname, strDef(a.HTTPPort, "80")),
  257. Path: serverUpgradePath,
  258. }
  259. u443 := &url.URL{
  260. Scheme: "https",
  261. Host: net.JoinHostPort(a.Hostname, strDef(a.HTTPSPort, "443")),
  262. Path: serverUpgradePath,
  263. }
  264. type tryURLRes struct {
  265. u *url.URL // input (the URL conn+err are for/from)
  266. conn *ClientConn // result (mutually exclusive with err)
  267. err error
  268. }
  269. ch := make(chan tryURLRes) // must be unbuffered
  270. try := func(u *url.URL) {
  271. if debugNoiseDial() {
  272. a.logf("trying noise dial (%v, %v) ...", u, addr)
  273. }
  274. cbConn, err := a.dialURL(ctx, u, addr)
  275. if debugNoiseDial() {
  276. a.logf("noise dial (%v, %v) = (%v, %v)", u, addr, cbConn, err)
  277. }
  278. select {
  279. case ch <- tryURLRes{u, cbConn, err}:
  280. case <-ctx.Done():
  281. if cbConn != nil {
  282. cbConn.Close()
  283. }
  284. }
  285. }
  286. // Start the plaintext HTTP attempt first, unless disabled by the envknob.
  287. if !forceNoise443() {
  288. go try(u80)
  289. }
  290. // In case outbound port 80 blocked or MITM'ed poorly, start a backup timer
  291. // to dial port 443 if port 80 doesn't either succeed or fail quickly.
  292. if a.Clock == nil {
  293. a.Clock = tstime.StdClock{}
  294. }
  295. try443Timer := a.Clock.AfterFunc(a.httpsFallbackDelay(), func() { try(u443) })
  296. defer try443Timer.Stop()
  297. var err80, err443 error
  298. for {
  299. select {
  300. case <-ctx.Done():
  301. return nil, fmt.Errorf("connection attempts aborted by context: %w", ctx.Err())
  302. case res := <-ch:
  303. if res.err == nil {
  304. return res.conn, nil
  305. }
  306. switch res.u {
  307. case u80:
  308. // Connecting over plain HTTP failed; assume it's an HTTP proxy
  309. // being difficult and see if we can get through over HTTPS.
  310. err80 = res.err
  311. // Stop the fallback timer and run it immediately. We don't use
  312. // Timer.Reset(0) here because on AfterFuncs, that can run it
  313. // again.
  314. if try443Timer.Stop() {
  315. go try(u443)
  316. } // else we lost the race and it started already which is what we want
  317. case u443:
  318. err443 = res.err
  319. default:
  320. panic("invalid")
  321. }
  322. if err80 != nil && err443 != nil {
  323. return nil, fmt.Errorf("all connection attempts failed (HTTP: %v, HTTPS: %v)", err80, err443)
  324. }
  325. }
  326. }
  327. }
  328. // dialURL attempts to connect to the given URL.
  329. func (a *Dialer) dialURL(ctx context.Context, u *url.URL, addr netip.Addr) (*ClientConn, error) {
  330. init, cont, err := controlbase.ClientDeferred(a.MachineKey, a.ControlKey, a.ProtocolVersion)
  331. if err != nil {
  332. return nil, err
  333. }
  334. netConn, err := a.tryURLUpgrade(ctx, u, addr, init)
  335. if err != nil {
  336. return nil, err
  337. }
  338. cbConn, err := cont(ctx, netConn)
  339. if err != nil {
  340. netConn.Close()
  341. return nil, err
  342. }
  343. return &ClientConn{
  344. Conn: cbConn,
  345. }, nil
  346. }
  347. // resolver returns a.DNSCache if non-nil or a new *dnscache.Resolver
  348. // otherwise.
  349. func (a *Dialer) resolver() *dnscache.Resolver {
  350. if a.DNSCache != nil {
  351. return a.DNSCache
  352. }
  353. return &dnscache.Resolver{
  354. Forward: dnscache.Get().Forward,
  355. LookupIPFallback: dnsfallback.MakeLookupFunc(a.logf, a.NetMon),
  356. UseLastGood: true,
  357. Logf: a.Logf, // not a.logf method; we want to propagate nil-ness
  358. }
  359. }
  360. func isLoopback(a net.Addr) bool {
  361. if ta, ok := a.(*net.TCPAddr); ok {
  362. return ta.IP.IsLoopback()
  363. }
  364. return false
  365. }
  366. var macOSScreenTime = health.Register(&health.Warnable{
  367. Code: "macos-screen-time",
  368. Severity: health.SeverityHigh,
  369. Title: "Tailscale blocked by Screen Time",
  370. Text: func(args health.Args) string {
  371. return "macOS Screen Time seems to be blocking Tailscale. Try disabling Screen Time in System Settings > Screen Time > Content & Privacy > Access to Web Content."
  372. },
  373. ImpactsConnectivity: true,
  374. })
  375. // tryURLUpgrade connects to u, and tries to upgrade it to a net.Conn. If addr
  376. // is valid, then no DNS is used and the connection will be made to the
  377. // provided address.
  378. //
  379. // Only the provided ctx is used, not a.ctx.
  380. func (a *Dialer) tryURLUpgrade(ctx context.Context, u *url.URL, addr netip.Addr, init []byte) (_ net.Conn, retErr error) {
  381. var dns *dnscache.Resolver
  382. // If we were provided an address to dial, then create a resolver that just
  383. // returns that value; otherwise, fall back to DNS.
  384. if addr.IsValid() {
  385. dns = &dnscache.Resolver{
  386. SingleHostStaticResult: []netip.Addr{addr},
  387. SingleHost: u.Hostname(),
  388. Logf: a.Logf, // not a.logf method; we want to propagate nil-ness
  389. }
  390. } else {
  391. dns = a.resolver()
  392. }
  393. var dialer dnscache.DialContextFunc
  394. if a.Dialer != nil {
  395. dialer = a.Dialer
  396. } else {
  397. dialer = stdDialer.DialContext
  398. }
  399. // On macOS, see if Screen Time is blocking things.
  400. if runtime.GOOS == "darwin" {
  401. var proxydIntercepted atomic.Bool // intercepted by macOS webfilterproxyd
  402. origDialer := dialer
  403. dialer = func(ctx context.Context, network, address string) (net.Conn, error) {
  404. c, err := origDialer(ctx, network, address)
  405. if err != nil {
  406. return nil, err
  407. }
  408. if isLoopback(c.LocalAddr()) && isLoopback(c.RemoteAddr()) {
  409. proxydIntercepted.Store(true)
  410. }
  411. return c, nil
  412. }
  413. defer func() {
  414. if retErr != nil && proxydIntercepted.Load() {
  415. a.HealthTracker.SetUnhealthy(macOSScreenTime, nil)
  416. retErr = fmt.Errorf("macOS Screen Time is blocking network access: %w", retErr)
  417. } else {
  418. a.HealthTracker.SetHealthy(macOSScreenTime)
  419. }
  420. }()
  421. }
  422. tr := http.DefaultTransport.(*http.Transport).Clone()
  423. defer tr.CloseIdleConnections()
  424. tr.Proxy = a.getProxyFunc()
  425. tshttpproxy.SetTransportGetProxyConnectHeader(tr)
  426. tr.DialContext = dnscache.Dialer(dialer, dns)
  427. // Disable HTTP2, since h2 can't do protocol switching.
  428. tr.TLSClientConfig.NextProtos = []string{}
  429. tr.TLSNextProto = map[string]func(string, *tls.Conn) http.RoundTripper{}
  430. tr.TLSClientConfig = tlsdial.Config(a.Hostname, a.HealthTracker, tr.TLSClientConfig)
  431. if !tr.TLSClientConfig.InsecureSkipVerify {
  432. panic("unexpected") // should be set by tlsdial.Config
  433. }
  434. verify := tr.TLSClientConfig.VerifyConnection
  435. if verify == nil {
  436. panic("unexpected") // should be set by tlsdial.Config
  437. }
  438. // Demote all cert verification errors to log messages. We don't actually
  439. // care about the TLS security (because we just do the Noise crypto atop whatever
  440. // connection we get, including HTTP port 80 plaintext) so this permits
  441. // middleboxes to MITM their users. All they'll see is some Noise.
  442. tr.TLSClientConfig.VerifyConnection = func(cs tls.ConnectionState) error {
  443. if err := verify(cs); err != nil && a.Logf != nil && !a.omitCertErrorLogging {
  444. a.Logf("warning: TLS cert verificication for %q failed: %v", a.Hostname, err)
  445. }
  446. return nil // regardless
  447. }
  448. tr.DialTLSContext = dnscache.TLSDialer(dialer, dns, tr.TLSClientConfig)
  449. tr.DisableCompression = true
  450. // (mis)use httptrace to extract the underlying net.Conn from the
  451. // transport. We make exactly 1 request using this transport, so
  452. // there will be exactly 1 GotConn call. Additionally, the
  453. // transport handles 101 Switching Protocols correctly, such that
  454. // the Conn will not be reused or kept alive by the transport once
  455. // the response has been handed back from RoundTrip.
  456. //
  457. // In theory, the machinery of net/http should make it such that
  458. // the trace callback happens-before we get the response, but
  459. // there's no promise of that. So, to make sure, we use a buffered
  460. // channel as a synchronization step to avoid data races.
  461. //
  462. // Note that even though we're able to extract a net.Conn via this
  463. // mechanism, we must still keep using the eventual resp.Body to
  464. // read from, because it includes a buffer we can't get rid of. If
  465. // the server never sends any data after sending the HTTP
  466. // response, we could get away with it, but violating this
  467. // assumption leads to very mysterious transport errors (lockups,
  468. // unexpected EOFs...), and we're bound to forget someday and
  469. // introduce a protocol optimization at a higher level that starts
  470. // eagerly transmitting from the server.
  471. connCh := make(chan net.Conn, 1)
  472. trace := httptrace.ClientTrace{
  473. GotConn: func(info httptrace.GotConnInfo) {
  474. connCh <- info.Conn
  475. },
  476. }
  477. ctx = httptrace.WithClientTrace(ctx, &trace)
  478. req := &http.Request{
  479. Method: "POST",
  480. URL: u,
  481. Header: http.Header{
  482. "Upgrade": []string{upgradeHeaderValue},
  483. "Connection": []string{"upgrade"},
  484. handshakeHeaderName: []string{base64.StdEncoding.EncodeToString(init)},
  485. },
  486. }
  487. req = req.WithContext(ctx)
  488. resp, err := tr.RoundTrip(req)
  489. if err != nil {
  490. return nil, err
  491. }
  492. if resp.StatusCode != http.StatusSwitchingProtocols {
  493. return nil, fmt.Errorf("unexpected HTTP response: %s", resp.Status)
  494. }
  495. // From here on, the underlying net.Conn is ours to use, but there
  496. // is still a read buffer attached to it within resp.Body. So, we
  497. // must direct I/O through resp.Body, but we can still use the
  498. // underlying net.Conn for stuff like deadlines.
  499. var switchedConn net.Conn
  500. select {
  501. case switchedConn = <-connCh:
  502. default:
  503. }
  504. if switchedConn == nil {
  505. resp.Body.Close()
  506. return nil, fmt.Errorf("httptrace didn't provide a connection")
  507. }
  508. if next := resp.Header.Get("Upgrade"); next != upgradeHeaderValue {
  509. resp.Body.Close()
  510. return nil, fmt.Errorf("server switched to unexpected protocol %q", next)
  511. }
  512. rwc, ok := resp.Body.(io.ReadWriteCloser)
  513. if !ok {
  514. resp.Body.Close()
  515. return nil, errors.New("http Transport did not provide a writable body")
  516. }
  517. return netutil.NewAltReadWriteCloserConn(rwc, switchedConn), nil
  518. }