client.go 16 KB

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