client.go 16 KB

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