client.go 17 KB

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