mirror of
https://github.com/tailscale/tailscale.git
synced 2026-12-03 23:22:23 -08:00
Previously, the Noise control dialer preferred plaintext HTTP on port 80
and only fell back to HTTPS on port 443 for middlebox compatibility,
because Noise already encrypted the inner connection with X25519.
To protect control connections against near-term 256-bit ECC / quantum
concerns when the server supports stronger key exchange, without
sacrificing compatibility, dial in three staggered stages:
1. TLS 1.3 with post-quantum key exchange (hybrid ML-KEM), falling
back to P-384/P-521 (excluding 256-bit ECC curves X25519 and P-256)
2. Plaintext HTTP (Noise over HTTP), unless forceNoise443 is set
3. Default HTTPS using Go's default TLS settings (matching the
existing Tailscale HTTPS fallback)
Also adds clientmetric counters for the negotiated transport
(controlhttp_dial_pq_https, controlhttp_dial_p384_https,
controlhttp_dial_http, controlhttp_dial_classic_https) and a
TS_DISABLE_NOISE_PQ_HTTPS envknob to restore the legacy HTTP-first order.
Updates #21022
Updates tailscale/corp#52709
Change-Id: I9f1d264ee196a58e75857b4401be8185de4b3e3e
Signed-off-by: James Tucker <[email protected]>
(cherry picked from commit 35f4a6e55a)
712 lines
23 KiB
Go
712 lines
23 KiB
Go
// Copyright (c) Tailscale Inc & contributors
|
|
// SPDX-License-Identifier: BSD-3-Clause
|
|
|
|
//go:build !js
|
|
|
|
// Package controlhttp implements the Tailscale 2021 control protocol
|
|
// base transport over HTTP.
|
|
//
|
|
// This tunnels the Noise-encrypted protocol in control/controlbase over
|
|
// HTTP with compatibility fallbacks for handling picky or deep-inspecting
|
|
// proxies. Historically, HTTP on port 80 was preferred because this layer
|
|
// is only a dumb transport beneath ts2021 Noise, which provides the
|
|
// primary authentication and encryption, with HTTPS used only as a
|
|
// middlebox fallback.
|
|
//
|
|
// Because ts2021 Noise uses classical X25519 key exchange, we now prefer
|
|
// outer HTTPS with post-quantum TLS 1.3 (falling back to P-384/P-521) as
|
|
// an interim defense against passive harvest-now-decrypt-later attacks
|
|
// until the control protocol itself is upgraded or replaced with
|
|
// post-quantum cryptography.
|
|
//
|
|
// In the happy path, a client connects over TLS 1.3 (preferring
|
|
// post-quantum key exchange, or P-384/P-521 if PQ is unavailable), sends
|
|
// an HTTP upgrade request, receives 101 Switching Protocols, and runs the
|
|
// Noise-encrypted control base protocol inside that TLS tunnel. If that
|
|
// attempt fails or stalls (for example, the server only supports 256-bit
|
|
// ECC or TLS 1.2, or port 443 is interfered with), the client falls back
|
|
// to plaintext HTTP (Noise over HTTP), and finally to default HTTPS for
|
|
// compatibility with picky or deep-inspecting proxies.
|
|
package controlhttp
|
|
|
|
import (
|
|
"cmp"
|
|
"context"
|
|
"crypto/tls"
|
|
"encoding/base64"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"net/http/httptrace"
|
|
"net/netip"
|
|
"net/url"
|
|
"runtime"
|
|
"strings"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"tailscale.com/control/controlbase"
|
|
"tailscale.com/control/controlhttp/controlhttpcommon"
|
|
"tailscale.com/envknob"
|
|
"tailscale.com/feature"
|
|
"tailscale.com/feature/buildfeatures"
|
|
"tailscale.com/health"
|
|
"tailscale.com/net/dnscache"
|
|
"tailscale.com/net/dnsfallback"
|
|
"tailscale.com/net/netutil"
|
|
"tailscale.com/net/netx"
|
|
"tailscale.com/net/sockstats"
|
|
"tailscale.com/net/tlsdial"
|
|
"tailscale.com/syncs"
|
|
"tailscale.com/tailcfg"
|
|
"tailscale.com/tstime"
|
|
"tailscale.com/util/clientmetric"
|
|
)
|
|
|
|
var stdDialer net.Dialer
|
|
|
|
// Dial connects to the server, requests to switch to the Tailscale control
|
|
// protocol, and returns an established control protocol connection.
|
|
//
|
|
// When HTTPS is enabled, Dial tries transports in order:
|
|
// 1. TLS 1.3 with post-quantum key exchange, falling back to P-384/P-521 (Host:HTTPSPort)
|
|
// 2. Plaintext HTTP (Host:HTTPPort)
|
|
// 3. Default HTTPS using Go's default TLS settings (Host:HTTPSPort)
|
|
//
|
|
// The provided ctx is only used for the initial connection, until
|
|
// Dial returns. It does not affect the connection once established.
|
|
func (a *Dialer) Dial(ctx context.Context) (*ClientConn, error) {
|
|
if a.Hostname == "" {
|
|
return nil, errors.New("required Dialer.Hostname empty")
|
|
}
|
|
return a.dial(ctx)
|
|
}
|
|
|
|
func (a *Dialer) logf(format string, args ...any) {
|
|
if a.Logf != nil {
|
|
a.Logf(format, args...)
|
|
}
|
|
}
|
|
|
|
func (a *Dialer) getProxyFunc() func(*http.Request) (*url.URL, error) {
|
|
if a.proxyFunc != nil {
|
|
return a.proxyFunc
|
|
}
|
|
return feature.HookProxyFromEnvironment.GetOrNil()
|
|
}
|
|
|
|
// fallbackDelay is how long we wait for a dial stage to succeed or fail
|
|
// before starting the next fallback stage.
|
|
func (a *Dialer) fallbackDelay() time.Duration {
|
|
if v := a.testFallbackDelay; v != 0 {
|
|
return v
|
|
}
|
|
return 500 * time.Millisecond
|
|
}
|
|
|
|
var _ = envknob.RegisterBool("TS_USE_CONTROL_DIAL_PLAN") // to record at init time whether it's in use
|
|
|
|
func (a *Dialer) dial(ctx context.Context) (*ClientConn, error) {
|
|
|
|
a.logPort80Failure.Store(true)
|
|
|
|
// If we don't have a dial plan, just fall back to dialing the single
|
|
// host we know about.
|
|
useDialPlan := envknob.BoolDefaultTrue("TS_USE_CONTROL_DIAL_PLAN")
|
|
if !useDialPlan || a.DialPlan == nil || len(a.DialPlan.Candidates) == 0 {
|
|
return a.dialHost(ctx)
|
|
}
|
|
candidates := a.DialPlan.Candidates
|
|
|
|
// Create a context to be canceled as we return, so once we get a good connection,
|
|
// we can drop all the other ones.
|
|
ctx, cancel := context.WithCancel(ctx)
|
|
defer cancel()
|
|
|
|
// Now, for each candidate, kick off a dial in parallel.
|
|
type dialResult struct {
|
|
conn *ClientConn
|
|
err error
|
|
}
|
|
resultsCh := make(chan dialResult) // unbuffered, never closed
|
|
|
|
dialCand := func(cand tailcfg.ControlIPCandidate) (*ClientConn, error) {
|
|
if cand.ACEHost != "" {
|
|
a.logf("[v2] controlhttp: waited %.2f seconds, dialing %q via ACE %s (%s)", cand.DialStartDelaySec, a.Hostname, cand.ACEHost, cmp.Or(cand.IP.String(), "dns"))
|
|
} else {
|
|
a.logf("[v2] controlhttp: waited %.2f seconds, dialing %q @ %s", cand.DialStartDelaySec, a.Hostname, cand.IP.String())
|
|
}
|
|
|
|
ctx, cancel := context.WithTimeout(ctx, time.Duration(cand.DialTimeoutSec*float64(time.Second)))
|
|
defer cancel()
|
|
return a.dialHostOpt(ctx, cand.IP, cand.ACEHost)
|
|
}
|
|
|
|
for _, cand := range candidates {
|
|
timer := time.AfterFunc(time.Duration(cand.DialStartDelaySec*float64(time.Second)), func() {
|
|
go func() {
|
|
conn, err := dialCand(cand)
|
|
select {
|
|
case resultsCh <- dialResult{conn, err}:
|
|
if err == nil {
|
|
a.logf("[v1] controlhttp: succeeded dialing %q @ %v from dial plan", a.Hostname, cmp.Or(cand.ACEHost, cand.IP.String()))
|
|
}
|
|
case <-ctx.Done():
|
|
if conn != nil {
|
|
conn.Close()
|
|
}
|
|
}
|
|
}()
|
|
})
|
|
defer timer.Stop()
|
|
}
|
|
|
|
var errs []error
|
|
for {
|
|
select {
|
|
case res := <-resultsCh:
|
|
if res.err == nil {
|
|
return res.conn, nil
|
|
}
|
|
errs = append(errs, res.err)
|
|
if len(errs) == len(candidates) {
|
|
// If we get here, then we didn't get anywhere with our dial plan; fall back to just using DNS.
|
|
a.logf("controlhttp: failed dialing using DialPlan, falling back to DNS; errs=%s", errors.Join(errs...))
|
|
return a.dialHost(ctx)
|
|
}
|
|
case <-ctx.Done():
|
|
a.logf("controlhttp: context aborted dialing")
|
|
return nil, ctx.Err()
|
|
}
|
|
}
|
|
}
|
|
|
|
// The TS_FORCE_NOISE_443 envknob forces the controlclient noise dialer to
|
|
// always use port 443 HTTPS connections to the controlplane and not try the
|
|
// port 80 HTTP fast path.
|
|
//
|
|
// This is currently (2023-01-17) needed for Docker Desktop's "VPNKit" proxy
|
|
// that breaks port 80 for us post-Noise-handshake, causing us to never try port
|
|
// 443. Until one of Docker's proxy and/or this package's port 443 fallback is
|
|
// fixed, this is a workaround. It might also be useful for future debugging.
|
|
var forceNoise443 = envknob.RegisterBool("TS_FORCE_NOISE_443")
|
|
|
|
// disablePQHTTPS disables preferring post-quantum / P-384 HTTPS on port 443
|
|
// over plaintext HTTP on port 80, restoring the legacy HTTP-then-HTTPS dial
|
|
// order.
|
|
var disablePQHTTPS = envknob.RegisterBool("TS_DISABLE_NOISE_PQ_HTTPS")
|
|
|
|
var (
|
|
metricDialPQHTTPS = clientmetric.NewCounter("controlhttp_dial_pq_https")
|
|
metricDialP384HTTPS = clientmetric.NewCounter("controlhttp_dial_p384_https")
|
|
metricDialHTTP = clientmetric.NewCounter("controlhttp_dial_http")
|
|
metricDialClassicHTTPS = clientmetric.NewCounter("controlhttp_dial_classic_https")
|
|
)
|
|
|
|
type tlsMode uint8
|
|
|
|
const (
|
|
// tlsModeDefault leaves crypto/tls version and curve defaults untouched.
|
|
// Used for HTTP requests (where TLSClientConfig may still be used when
|
|
// dialing an HTTPS proxy) and for the fallback HTTPS attempt.
|
|
tlsModeDefault tlsMode = iota
|
|
// tlsModePQOrP384 requires TLS 1.3 with either a post-quantum key exchange
|
|
// or a P-384/P-521 key exchange (excluding 256-bit ECC curves X25519 and
|
|
// P-256).
|
|
tlsModePQOrP384
|
|
)
|
|
|
|
// pqOrP384CurvePreferences are the hybrid post-quantum key exchanges
|
|
// enabled by default in Go's crypto/tls, plus P-384 and P-521 as fallback
|
|
// when a server doesn't support PQ. 256-bit curves (X25519, P-256) are
|
|
// excluded. Note that crypto/tls ignores slice order in
|
|
// Config.CurvePreferences and always uses its internal preference order
|
|
// (which prefers all PQ hybrids before P-384 and P-521).
|
|
var pqOrP384CurvePreferences = []tls.CurveID{
|
|
tls.SecP384r1MLKEM1024,
|
|
tls.X25519MLKEM768,
|
|
tls.SecP256r1MLKEM768,
|
|
tls.CurveP521,
|
|
tls.CurveP384,
|
|
}
|
|
|
|
func isPQCurve(id tls.CurveID) bool {
|
|
switch id {
|
|
case tls.X25519MLKEM768, tls.SecP256r1MLKEM768, tls.SecP384r1MLKEM1024, tls.MLKEM1024:
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
func isP384OrHigherCurve(id tls.CurveID) bool {
|
|
return id == tls.CurveP384 || id == tls.CurveP521
|
|
}
|
|
|
|
func isPQOrP384Curve(id tls.CurveID) bool {
|
|
return isPQCurve(id) || isP384OrHigherCurve(id)
|
|
}
|
|
|
|
// forceNoise443 reports whether the controlclient noise dialer should always
|
|
// use HTTPS connections as its underlay connection (double crypto). This can
|
|
// be necessary when networks or middle boxes are messing with port 80.
|
|
func (d *Dialer) forceNoise443() bool {
|
|
if runtime.GOOS == "plan9" {
|
|
// For running demos of Plan 9 in a browser with network relays,
|
|
// we want to minimize the number of connections we're making.
|
|
// The main reason to use port 80 is to avoid double crypto
|
|
// costs server-side but the costs are tiny and number of Plan 9
|
|
// users doesn't make it worth it. Just disable this and always use
|
|
// HTTPS for Plan 9. That also reduces some log spam.
|
|
return true
|
|
}
|
|
if forceNoise443() {
|
|
return true
|
|
}
|
|
|
|
if d.HealthTracker.LastNoiseDialWasRecent() {
|
|
// If we dialed recently, assume there was a recent failure and fall
|
|
// back to HTTPS dials for the subsequent retries.
|
|
//
|
|
// This heuristic works around networks where port 80 is MITMed and
|
|
// appears to work for a bit post-Upgrade but then gets closed,
|
|
// such as seen in https://github.com/tailscale/tailscale/issues/13597.
|
|
if d.logPort80Failure.CompareAndSwap(true, false) {
|
|
d.logf("controlhttp: forcing port 443 dial due to recent noise dial")
|
|
}
|
|
return true
|
|
}
|
|
|
|
return false
|
|
}
|
|
|
|
func (d *Dialer) clock() tstime.Clock {
|
|
if d.Clock != nil {
|
|
return d.Clock
|
|
}
|
|
return tstime.StdClock{}
|
|
}
|
|
|
|
var debugNoiseDial = envknob.RegisterBool("TS_DEBUG_NOISE_DIAL")
|
|
|
|
// dialHost connects to the configured Dialer.Hostname and upgrades the
|
|
// connection into a controlbase.Conn.
|
|
func (a *Dialer) dialHost(ctx context.Context) (*ClientConn, error) {
|
|
return a.dialHostOpt(ctx,
|
|
netip.Addr{}, // no pre-resolved IP
|
|
"", // don't use ACE
|
|
)
|
|
}
|
|
|
|
// dialHostOpt connects to the configured Dialer.Hostname and upgrades the
|
|
// connection into a controlbase.Conn.
|
|
//
|
|
// If optAddr is valid, then no DNS is used and the connection will be made to the
|
|
// provided address.
|
|
func (a *Dialer) dialHostOpt(ctx context.Context, optAddr netip.Addr, optACEHost string) (*ClientConn, error) {
|
|
// Create one shared context used by all dial attempts. When one attempt
|
|
// succeeds, this deferred cancel will stop any others still in flight.
|
|
ctx, cancel := context.WithCancel(ctx)
|
|
defer cancel()
|
|
|
|
ctx = sockstats.WithSockStats(ctx, sockstats.LabelControlClientDialer, a.logf)
|
|
|
|
// u80 and u443 are the URLs we'll try to hit over HTTP or HTTPS,
|
|
// respectively, in order to do the HTTP upgrade to a net.Conn over which
|
|
// we'll speak Noise.
|
|
u80 := &url.URL{
|
|
Scheme: "http",
|
|
Host: net.JoinHostPort(a.Hostname, strDef(a.HTTPPort, "80")),
|
|
Path: serverUpgradePath,
|
|
}
|
|
u443 := &url.URL{
|
|
Scheme: "https",
|
|
Host: net.JoinHostPort(a.Hostname, strDef(a.HTTPSPort, "443")),
|
|
Path: serverUpgradePath,
|
|
}
|
|
if a.HTTPSPort == NoPort || optACEHost != "" {
|
|
u443 = nil
|
|
}
|
|
|
|
type dialAttempt struct {
|
|
name string
|
|
u *url.URL
|
|
tlsMode tlsMode
|
|
}
|
|
|
|
forceTLS := a.forceNoise443()
|
|
|
|
var attempts []dialAttempt
|
|
switch {
|
|
case u443 == nil:
|
|
attempts = []dialAttempt{
|
|
{name: "http", u: u80, tlsMode: tlsModeDefault},
|
|
}
|
|
case disablePQHTTPS():
|
|
if !forceTLS {
|
|
attempts = append(attempts, dialAttempt{name: "http", u: u80, tlsMode: tlsModeDefault})
|
|
}
|
|
attempts = append(attempts, dialAttempt{name: "https", u: u443, tlsMode: tlsModeDefault})
|
|
default:
|
|
// Prefer post-quantum HTTPS (falling back to P-384/P-521), then
|
|
// plaintext HTTP (Noise over HTTP), then default HTTPS.
|
|
attempts = append(attempts, dialAttempt{name: "pq-https", u: u443, tlsMode: tlsModePQOrP384})
|
|
if !forceTLS {
|
|
attempts = append(attempts, dialAttempt{name: "http", u: u80, tlsMode: tlsModeDefault})
|
|
}
|
|
attempts = append(attempts, dialAttempt{name: "https", u: u443, tlsMode: tlsModeDefault})
|
|
}
|
|
|
|
type tryAttemptRes struct {
|
|
idx int
|
|
conn *ClientConn // mutually exclusive with err
|
|
curveID tls.CurveID // negotiated TLS curve for HTTPS attempts, 0 for HTTP
|
|
err error
|
|
}
|
|
ch := make(chan tryAttemptRes) // must be unbuffered
|
|
try := func(idx int, att dialAttempt) {
|
|
if debugNoiseDial() {
|
|
a.logf("trying noise dial (%s, %v, %v) ...", att.name, att.u, cmp.Or(optACEHost, optAddr.String()))
|
|
}
|
|
cbConn, curveID, err := a.dialURL(ctx, att.u, optAddr, optACEHost, att.tlsMode)
|
|
if debugNoiseDial() {
|
|
a.logf("noise dial (%s, %v, %v) = (%v, curve=%v, %v)", att.name, att.u, cmp.Or(optACEHost, optAddr.String()), cbConn, curveID, err)
|
|
}
|
|
select {
|
|
case ch <- tryAttemptRes{idx, cbConn, curveID, err}:
|
|
case <-ctx.Done():
|
|
if cbConn != nil {
|
|
cbConn.Close()
|
|
}
|
|
}
|
|
}
|
|
|
|
var (
|
|
nextIdx int
|
|
timer tstime.TimerController
|
|
timerCh <-chan time.Time
|
|
)
|
|
stopTimer := func() {
|
|
if timer != nil {
|
|
timer.Stop()
|
|
timer = nil
|
|
timerCh = nil
|
|
}
|
|
}
|
|
defer stopTimer()
|
|
|
|
startNext := func() {
|
|
if nextIdx >= len(attempts) {
|
|
return
|
|
}
|
|
idx := nextIdx
|
|
nextIdx++
|
|
go try(idx, attempts[idx])
|
|
stopTimer()
|
|
if nextIdx < len(attempts) {
|
|
timer, timerCh = a.clock().NewTimer(a.fallbackDelay())
|
|
}
|
|
}
|
|
|
|
startNext()
|
|
|
|
errs := make([]error, len(attempts))
|
|
failed := 0
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return nil, fmt.Errorf("connection attempts aborted by context: %w", ctx.Err())
|
|
case <-timerCh:
|
|
startNext()
|
|
case res := <-ch:
|
|
if res.err == nil {
|
|
switch {
|
|
case attempts[res.idx].u.Scheme == "http":
|
|
metricDialHTTP.Add(1)
|
|
case isPQCurve(res.curveID):
|
|
metricDialPQHTTPS.Add(1)
|
|
case isP384OrHigherCurve(res.curveID):
|
|
metricDialP384HTTPS.Add(1)
|
|
default:
|
|
metricDialClassicHTTPS.Add(1)
|
|
}
|
|
return res.conn, nil
|
|
}
|
|
errs[res.idx] = res.err
|
|
failed++
|
|
if failed == len(attempts) {
|
|
errParts := make([]string, len(attempts))
|
|
for i, att := range attempts {
|
|
errParts[i] = fmt.Sprintf("%s: %v", att.name, errs[i])
|
|
}
|
|
return nil, fmt.Errorf("all connection attempts failed (%s)", strings.Join(errParts, ", "))
|
|
}
|
|
// If the most recently started attempt failed, advance immediately
|
|
// instead of waiting for its fallback timer.
|
|
if res.idx == nextIdx-1 {
|
|
startNext()
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// dialURL attempts to connect to the given URL.
|
|
//
|
|
// If optAddr is valid, then no DNS is used and the connection will be made to the
|
|
// provided address.
|
|
func (a *Dialer) dialURL(ctx context.Context, u *url.URL, optAddr netip.Addr, optACEHost string, mode tlsMode) (*ClientConn, tls.CurveID, error) {
|
|
init, cont, err := controlbase.ClientDeferred(a.MachineKey, a.ControlKey, a.ProtocolVersion)
|
|
if err != nil {
|
|
return nil, 0, err
|
|
}
|
|
netConn, curveID, err := a.tryURLUpgrade(ctx, u, optAddr, optACEHost, mode, init)
|
|
if err != nil {
|
|
return nil, 0, err
|
|
}
|
|
cbConn, err := cont(ctx, netConn)
|
|
if err != nil {
|
|
netConn.Close()
|
|
return nil, 0, err
|
|
}
|
|
return &ClientConn{
|
|
Conn: cbConn,
|
|
}, curveID, nil
|
|
}
|
|
|
|
// resolver returns a.DNSCache if non-nil or a new *dnscache.Resolver
|
|
// otherwise.
|
|
func (a *Dialer) resolver() *dnscache.Resolver {
|
|
if a.DNSCache != nil {
|
|
return a.DNSCache
|
|
}
|
|
|
|
return &dnscache.Resolver{
|
|
Forward: dnscache.Get().Forward,
|
|
LookupIPFallback: dnsfallback.MakeLookupFunc(a.logf, a.NetMon),
|
|
UseLastGood: true,
|
|
Logf: a.Logf, // not a.logf method; we want to propagate nil-ness
|
|
}
|
|
}
|
|
|
|
func isLoopback(a net.Addr) bool {
|
|
if ta, ok := a.(*net.TCPAddr); ok {
|
|
return ta.IP.IsLoopback()
|
|
}
|
|
return false
|
|
}
|
|
|
|
var macOSScreenTime = health.Register(&health.Warnable{
|
|
Code: "macos-screen-time",
|
|
Severity: health.SeverityHigh,
|
|
Title: "Tailscale blocked by Screen Time",
|
|
Text: func(args health.Args) string {
|
|
return "macOS Screen Time seems to be blocking Tailscale. Try disabling Screen Time in System Settings > Screen Time > Content & Privacy > Access to Web Content."
|
|
},
|
|
ImpactsConnectivity: true,
|
|
})
|
|
|
|
var HookMakeACEDialer feature.Hook[func(dialer netx.DialFunc, aceHost string, optIP netip.Addr) netx.DialFunc]
|
|
|
|
// tryURLUpgrade connects to u, and tries to upgrade it to a net.Conn.
|
|
//
|
|
// If optAddr is valid, then no DNS is used and the connection will be made to
|
|
// the provided address.
|
|
//
|
|
// Only the provided ctx is used, not a.ctx.
|
|
func (a *Dialer) tryURLUpgrade(ctx context.Context, u *url.URL, optAddr netip.Addr, optACEHost string, mode tlsMode, init []byte) (_ net.Conn, _ tls.CurveID, retErr error) {
|
|
var dns *dnscache.Resolver
|
|
|
|
// If we were provided an address to dial, then create a resolver that just
|
|
// returns that value; otherwise, fall back to DNS.
|
|
if optAddr.IsValid() {
|
|
dns = &dnscache.Resolver{
|
|
SingleHostStaticResult: []netip.Addr{optAddr},
|
|
SingleHost: u.Hostname(),
|
|
Logf: a.Logf, // not a.logf method; we want to propagate nil-ness
|
|
}
|
|
} else {
|
|
dns = a.resolver()
|
|
}
|
|
|
|
var dialer netx.DialFunc
|
|
if a.Dialer != nil {
|
|
dialer = a.Dialer
|
|
} else {
|
|
dialer = stdDialer.DialContext
|
|
}
|
|
|
|
if optACEHost != "" {
|
|
if !buildfeatures.HasACE {
|
|
return nil, 0, feature.ErrUnavailable
|
|
}
|
|
f, ok := HookMakeACEDialer.GetOk()
|
|
if !ok {
|
|
return nil, 0, feature.ErrUnavailable
|
|
}
|
|
dialer = f(dialer, optACEHost, optAddr)
|
|
}
|
|
|
|
// On macOS, see if Screen Time is blocking things.
|
|
if runtime.GOOS == "darwin" {
|
|
var proxydIntercepted atomic.Bool // intercepted by macOS webfilterproxyd
|
|
origDialer := dialer
|
|
dialer = func(ctx context.Context, network, address string) (net.Conn, error) {
|
|
c, err := origDialer(ctx, network, address)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if isLoopback(c.LocalAddr()) && isLoopback(c.RemoteAddr()) {
|
|
proxydIntercepted.Store(true)
|
|
}
|
|
return c, nil
|
|
}
|
|
defer func() {
|
|
if retErr != nil && proxydIntercepted.Load() {
|
|
a.HealthTracker.SetUnhealthy(macOSScreenTime, nil)
|
|
retErr = fmt.Errorf("macOS Screen Time is blocking network access: %w", retErr)
|
|
} else {
|
|
a.HealthTracker.SetHealthy(macOSScreenTime)
|
|
}
|
|
}()
|
|
}
|
|
|
|
tr := netutil.NewDefaultTransport()
|
|
defer tr.CloseIdleConnections()
|
|
if optACEHost != "" {
|
|
// If using ACE, we don't want to use any HTTP proxy.
|
|
// ACE is already a tunnel+proxy.
|
|
// TODO(tailscale/corp#32483): use system proxy too?
|
|
tr.Proxy = nil
|
|
tr.DialContext = dialer
|
|
} else {
|
|
if buildfeatures.HasUseProxy {
|
|
tr.Proxy = a.getProxyFunc()
|
|
if set, ok := feature.HookProxySetTransportGetProxyConnectHeader.GetOk(); ok {
|
|
set(tr)
|
|
}
|
|
}
|
|
tr.DialContext = dnscache.Dialer(dialer, dns)
|
|
}
|
|
// Disable HTTP2, since h2 can't do protocol switching.
|
|
tr.TLSClientConfig.NextProtos = []string{}
|
|
tr.TLSNextProto = map[string]func(string, *tls.Conn) http.RoundTripper{}
|
|
if a.ExtraRootCAs != nil {
|
|
tr.TLSClientConfig.RootCAs = a.ExtraRootCAs
|
|
}
|
|
tr.TLSClientConfig = tlsdial.Config(a.HealthTracker, tr.TLSClientConfig)
|
|
if !tr.TLSClientConfig.InsecureSkipVerify {
|
|
panic("unexpected") // should be set by tlsdial.Config
|
|
}
|
|
verify := tr.TLSClientConfig.VerifyConnection
|
|
if verify == nil {
|
|
panic("unexpected") // should be set by tlsdial.Config
|
|
}
|
|
if mode == tlsModePQOrP384 {
|
|
tr.TLSClientConfig.MinVersion = tls.VersionTLS13
|
|
tr.TLSClientConfig.CurvePreferences = pqOrP384CurvePreferences
|
|
}
|
|
// Demote cert verification errors to log messages. The inner Noise
|
|
// handshake authenticates the control server's static key regardless of
|
|
// the outer transport (including plaintext port 80), so tolerating cert
|
|
// errors avoids breaking behind TLS-inspecting corporate middleboxes or
|
|
// hosts with missing roots. When tlsModePQOrP384 is active, we still
|
|
// require a post-quantum or P-384/P-521 key exchange to guard against
|
|
// passive harvest-now-decrypt-later eavesdroppers; an active TLS MITM
|
|
// still only sees Noise traffic (classically authenticated and encrypted).
|
|
tr.TLSClientConfig.VerifyConnection = func(cs tls.ConnectionState) error {
|
|
if mode == tlsModePQOrP384 && !isPQOrP384Curve(cs.CurveID) {
|
|
return fmt.Errorf("TLS connection did not negotiate a post-quantum or P-384/P-521 key exchange (got %v)", cs.CurveID)
|
|
}
|
|
if err := verify(cs); err != nil && a.Logf != nil && !a.omitCertErrorLogging {
|
|
a.Logf("warning: TLS cert verification for %q failed: %v", a.Hostname, err)
|
|
}
|
|
return nil // regardless
|
|
}
|
|
|
|
tr.DialTLSContext = dnscache.TLSDialer(dialer, dns, tr.TLSClientConfig)
|
|
tr.DisableCompression = true
|
|
|
|
// (mis)use httptrace to extract the underlying net.Conn from the
|
|
// transport. The transport handles 101 Switching Protocols correctly,
|
|
// such that the Conn will not be reused or kept alive by the transport
|
|
// once the response has been handed back from RoundTrip.
|
|
//
|
|
// In theory, the machinery of net/http should make it such that
|
|
// the trace callback happens-before we get the response, but
|
|
// there's no promise of that. So, to make sure, we use a buffered
|
|
// channel as a synchronization step to avoid data races.
|
|
//
|
|
// Note that even though we're able to extract a net.Conn via this
|
|
// mechanism, we must still keep using the eventual resp.Body to
|
|
// read from, because it includes a buffer we can't get rid of. If
|
|
// the server never sends any data after sending the HTTP
|
|
// response, we could get away with it, but violating this
|
|
// assumption leads to very mysterious transport errors (lockups,
|
|
// unexpected EOFs...), and we're bound to forget someday and
|
|
// introduce a protocol optimization at a higher level that starts
|
|
// eagerly transmitting from the server.
|
|
var lastConn syncs.AtomicValue[net.Conn]
|
|
trace := httptrace.ClientTrace{
|
|
// Even though we only make a single HTTP request which should
|
|
// require a single connection, the context (with the attached
|
|
// trace configuration) might be used by our custom dialer to
|
|
// make other HTTP requests (e.g. BootstrapDNS). We only care
|
|
// about the last connection made, which should be the one to
|
|
// the control server.
|
|
GotConn: func(info httptrace.GotConnInfo) {
|
|
lastConn.Store(info.Conn)
|
|
},
|
|
}
|
|
ctx = httptrace.WithClientTrace(ctx, &trace)
|
|
req := &http.Request{
|
|
Method: "POST",
|
|
URL: u,
|
|
Header: http.Header{
|
|
"Upgrade": []string{controlhttpcommon.UpgradeHeaderValue},
|
|
"Connection": []string{"upgrade"},
|
|
controlhttpcommon.HandshakeHeaderName: []string{base64.StdEncoding.EncodeToString(init)},
|
|
},
|
|
}
|
|
req = req.WithContext(ctx)
|
|
|
|
resp, err := tr.RoundTrip(req)
|
|
if err != nil {
|
|
return nil, 0, err
|
|
}
|
|
|
|
if resp.StatusCode != http.StatusSwitchingProtocols {
|
|
resp.Body.Close()
|
|
return nil, 0, fmt.Errorf("unexpected HTTP response: %s", resp.Status)
|
|
}
|
|
|
|
var curveID tls.CurveID
|
|
if resp.TLS != nil {
|
|
curveID = resp.TLS.CurveID
|
|
}
|
|
|
|
// From here on, the underlying net.Conn is ours to use, but there
|
|
// is still a read buffer attached to it within resp.Body. So, we
|
|
// must direct I/O through resp.Body, but we can still use the
|
|
// underlying net.Conn for stuff like deadlines.
|
|
switchedConn := lastConn.Load()
|
|
if switchedConn == nil {
|
|
resp.Body.Close()
|
|
return nil, 0, fmt.Errorf("httptrace didn't provide a connection")
|
|
}
|
|
|
|
if next := resp.Header.Get("Upgrade"); next != controlhttpcommon.UpgradeHeaderValue {
|
|
resp.Body.Close()
|
|
return nil, 0, fmt.Errorf("server switched to unexpected protocol %q", next)
|
|
}
|
|
|
|
rwc, ok := resp.Body.(io.ReadWriteCloser)
|
|
if !ok {
|
|
resp.Body.Close()
|
|
return nil, 0, errors.New("http Transport did not provide a writable body")
|
|
}
|
|
|
|
return netutil.NewAltReadWriteCloserConn(rwc, switchedConn), curveID, nil
|
|
}
|