diff --git a/control/controlhttp/client.go b/control/controlhttp/client.go index d93e19b95..a63b1ce53 100644 --- a/control/controlhttp/client.go +++ b/control/controlhttp/client.go @@ -6,17 +6,27 @@ // Package controlhttp implements the Tailscale 2021 control protocol // base transport over HTTP. // -// This tunnels the protocol in control/controlbase over HTTP with a -// variety of compatibility fallbacks for handling picky or deep -// inspecting proxies. +// 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. // -// In the happy path, a client makes a single cleartext HTTP request -// to the server, the server responds with 101 Switching Protocols, -// and the control base protocol takes place over plain TCP. +// 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 compatibility path, the client does the above over HTTPS, -// resulting in double encryption (once for the control transport, and -// once for the outer TLS layer). +// 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 ( @@ -33,6 +43,7 @@ import ( "net/netip" "net/url" "runtime" + "strings" "sync/atomic" "time" @@ -51,16 +62,18 @@ import ( "tailscale.com/syncs" "tailscale.com/tailcfg" "tailscale.com/tstime" + "tailscale.com/util/clientmetric" ) var stdDialer net.Dialer -// Dial connects to the HTTP server at this Dialer's Host:HTTPPort, requests to -// switch to the Tailscale control protocol, and returns an established control -// protocol connection. +// Dial connects to the server, requests to switch to the Tailscale control +// protocol, and returns an established control protocol connection. // -// If Dial fails to connect using HTTP, it also tries to tunnel over TLS to the -// Dialer's Host:HTTPSPort as a compatibility fallback. +// 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. @@ -84,9 +97,9 @@ func (a *Dialer) getProxyFunc() func(*http.Request) (*url.URL, error) { return feature.HookProxyFromEnvironment.GetOrNil() } -// httpsFallbackDelay is how long we'll wait for a.HTTPPort to work before -// starting to try a.HTTPSPort. -func (a *Dialer) httpsFallbackDelay() time.Duration { +// 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 } @@ -180,6 +193,62 @@ func (a *Dialer) dial(ctx context.Context) (*ClientConn, error) { // 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. @@ -237,9 +306,8 @@ func (a *Dialer) dialHost(ctx context.Context) (*ClientConn, error) { // 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 both port 80 and port 443 dials. - // If port 80 is still in flight when 443 returns, this deferred cancel - // will stop the port 80 dial. + // 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() @@ -262,22 +330,52 @@ func (a *Dialer) dialHostOpt(ctx context.Context, optAddr netip.Addr, optACEHost u443 = nil } - type tryURLRes struct { - u *url.URL // input (the URL conn+err are for/from) - conn *ClientConn // result (mutually exclusive with err) - err error + type dialAttempt struct { + name string + u *url.URL + tlsMode tlsMode } - ch := make(chan tryURLRes) // must be unbuffered - try := func(u *url.URL) { - if debugNoiseDial() { - a.logf("trying noise dial (%v, %v) ...", u, cmp.Or(optACEHost, optAddr.String())) + + forceTLS := a.forceNoise443() + + var attempts []dialAttempt + switch { + case u443 == nil: + attempts = []dialAttempt{ + {name: "http", u: u80, tlsMode: tlsModeDefault}, } - cbConn, err := a.dialURL(ctx, u, optAddr, optACEHost) + 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("noise dial (%v, %v) = (%v, %v)", u, cmp.Or(optACEHost, optAddr.String()), cbConn, err) + 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 <- tryURLRes{u, cbConn, err}: + case ch <- tryAttemptRes{idx, cbConn, curveID, err}: case <-ctx.Done(): if cbConn != nil { cbConn.Close() @@ -285,55 +383,70 @@ func (a *Dialer) dialHostOpt(ctx context.Context, optAddr netip.Addr, optACEHost } } - forceTLS := a.forceNoise443() - - // Start the plaintext HTTP attempt first, unless disabled by the envknob. - if !forceTLS || u443 == nil { - go try(u80) + var ( + nextIdx int + timer tstime.TimerController + timerCh <-chan time.Time + ) + stopTimer := func() { + if timer != nil { + timer.Stop() + timer = nil + timerCh = nil + } } + defer stopTimer() - // In case outbound port 80 blocked or MITM'ed poorly, start a backup timer - // to dial port 443 if port 80 doesn't either succeed or fail quickly. - var try443Timer tstime.TimerController - if u443 != nil { - delay := a.httpsFallbackDelay() - if forceTLS { - delay = 0 + 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()) } - try443Timer = a.clock().AfterFunc(delay, func() { try(u443) }) - defer try443Timer.Stop() } - var err80, err443 error - if forceTLS { - err80 = errors.New("TLS forced: no port 80 dialed") - } + 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 } - switch res.u { - case u80: - // Connecting over plain HTTP failed; assume it's an HTTP proxy - // being difficult and see if we can get through over HTTPS. - err80 = res.err - // Stop the fallback timer and run it immediately. We don't use - // Timer.Reset(0) here because on AfterFuncs, that can run it - // again. - if try443Timer != nil && try443Timer.Stop() { - go try(u443) - } // else we lost the race and it started already which is what we want - case u443: - err443 = res.err - default: - panic("invalid") + 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 err80 != nil && err443 != nil { - return nil, fmt.Errorf("all connection attempts failed (HTTP: %v, HTTPS: %v)", err80, err443) + // If the most recently started attempt failed, advance immediately + // instead of waiting for its fallback timer. + if res.idx == nextIdx-1 { + startNext() } } } @@ -343,23 +456,23 @@ func (a *Dialer) dialHostOpt(ctx context.Context, optAddr netip.Addr, optACEHost // // 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) (*ClientConn, error) { +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, err + return nil, 0, err } - netConn, err := a.tryURLUpgrade(ctx, u, optAddr, optACEHost, init) + netConn, curveID, err := a.tryURLUpgrade(ctx, u, optAddr, optACEHost, mode, init) if err != nil { - return nil, err + return nil, 0, err } cbConn, err := cont(ctx, netConn) if err != nil { netConn.Close() - return nil, err + return nil, 0, err } return &ClientConn{ Conn: cbConn, - }, nil + }, curveID, nil } // resolver returns a.DNSCache if non-nil or a new *dnscache.Resolver @@ -402,7 +515,7 @@ var HookMakeACEDialer feature.Hook[func(dialer netx.DialFunc, aceHost string, op // 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, init []byte) (_ net.Conn, retErr error) { +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 @@ -426,11 +539,11 @@ func (a *Dialer) tryURLUpgrade(ctx context.Context, u *url.URL, optAddr netip.Ad if optACEHost != "" { if !buildfeatures.HasACE { - return nil, feature.ErrUnavailable + return nil, 0, feature.ErrUnavailable } f, ok := HookMakeACEDialer.GetOk() if !ok { - return nil, feature.ErrUnavailable + return nil, 0, feature.ErrUnavailable } dialer = f(dialer, optACEHost, optAddr) } @@ -490,13 +603,24 @@ func (a *Dialer) tryURLUpgrade(ctx context.Context, u *url.URL, optAddr netip.Ad if verify == nil { panic("unexpected") // should be set by tlsdial.Config } - // Demote all cert verification errors to log messages. We don't actually - // care about the TLS security (because we just do the Noise crypto atop whatever - // connection we get, including HTTP port 80 plaintext) so this permits - // middleboxes to MITM their users. All they'll see is some Noise. + 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 verificication for %q failed: %v", a.Hostname, err) + a.Logf("warning: TLS cert verification for %q failed: %v", a.Hostname, err) } return nil // regardless } @@ -549,11 +673,17 @@ func (a *Dialer) tryURLUpgrade(ctx context.Context, u *url.URL, optAddr netip.Ad resp, err := tr.RoundTrip(req) if err != nil { - return nil, err + return nil, 0, err } if resp.StatusCode != http.StatusSwitchingProtocols { - return nil, fmt.Errorf("unexpected HTTP response: %s", resp.Status) + 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 @@ -563,19 +693,19 @@ func (a *Dialer) tryURLUpgrade(ctx context.Context, u *url.URL, optAddr netip.Ad switchedConn := lastConn.Load() if switchedConn == nil { resp.Body.Close() - return nil, fmt.Errorf("httptrace didn't provide a connection") + 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, fmt.Errorf("server switched to unexpected protocol %q", next) + 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, errors.New("http Transport did not provide a writable body") + return nil, 0, errors.New("http Transport did not provide a writable body") } - return netutil.NewAltReadWriteCloserConn(rwc, switchedConn), nil + return netutil.NewAltReadWriteCloserConn(rwc, switchedConn), curveID, nil } diff --git a/control/controlhttp/http_test.go b/control/controlhttp/http_test.go index 7f0203cd0..26bc926a2 100644 --- a/control/controlhttp/http_test.go +++ b/control/controlhttp/http_test.go @@ -19,6 +19,7 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "testing" "testing/synctest" "time" @@ -26,6 +27,7 @@ import ( "tailscale.com/control/controlbase" "tailscale.com/control/controlhttp/controlhttpcommon" "tailscale.com/control/controlhttp/controlhttpserver" + "tailscale.com/envknob" "tailscale.com/health" "tailscale.com/net/memnet" "tailscale.com/net/netmon" @@ -89,7 +91,7 @@ func TestControlHTTP(t *testing.T) { allowHTTP: false, }, }, - // HTTP->any (will pick HTTP) + // HTTP->any (will pick PQ HTTPS) { name: "http_to_any", proxy: &httpProxy{ @@ -116,7 +118,7 @@ func TestControlHTTP(t *testing.T) { allowHTTP: false, }, }, - // HTTPS->any (will pick HTTP) + // HTTPS->any (will pick PQ HTTPS) { name: "https_to_any", proxy: &httpProxy{ @@ -902,3 +904,373 @@ func (c *memnetTrackedConn) Close() error { c.dialer.noteClose(c.Conn) return c.Conn.Close() } + +// dropLargeClientHelloConn simulates a middlebox that blackholes TLS +// ClientHello records larger than maxFirstWrite bytes (such as post-quantum +// ClientHellos) while letting smaller classic ClientHellos pass through. +type dropLargeClientHelloConn struct { + net.Conn + maxFirstWrite int + wroteOnce bool + dropped bool +} + +func (c *dropLargeClientHelloConn) Write(p []byte) (int, error) { + if !c.wroteOnce { + c.wroteOnce = true + if len(p) > c.maxFirstWrite { + c.dropped = true + } + } + if c.dropped { + // Silently blackhole the bytes; subsequent Reads on the underlying + // memnet conn will block until deadline or Close. + return len(p), nil + } + return c.Conn.Write(p) +} + +func TestDialPreferenceOrder(t *testing.T) { + type outcome string + const ( + wantPQHTTPS outcome = "pq-https" + wantP384HTTPS outcome = "p384-https" + wantHTTP outcome = "http" + wantClassicHTTPS outcome = "classic-https" + wantErr outcome = "error" + ) + + classicCurves := []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.X25519, tls.CurveP256} + ecc256Only := []tls.CurveID{tls.X25519, tls.CurveP256} + + tests := []struct { + name string + httpsServerCurves []tls.CurveID // nil = Go default (includes PQ) + httpsServerMaxVersion uint16 // 0 = Go default (TLS 1.3) + httpsDisabled bool // set Dialer.HTTPSPort = NoPort + httpsFail bool // HTTPS returns 500 + httpFail bool // HTTP returns 500 + httpHangAfterUpgrade bool // HTTP hangs after 101 Switching Protocols + dropLargeClientHello bool // middlebox drops TLS ClientHello > 1000 bytes + forceNoise443Env bool // TS_FORCE_NOISE_443=1 + disablePQHTTPSEnv bool // TS_DISABLE_NOISE_PQ_HTTPS=1 + want outcome + wantErrContains []string + wantHTTPNotDialed bool + wantHTTPSNotDialed bool + wantNoFallbackWait bool // verify we didn't wait for fallback timeout + }{ + { + name: "pq_https_preferred", + want: wantPQHTTPS, + wantHTTPNotDialed: true, + }, + { + name: "non_pq_p384_https_preferred_over_http", + httpsServerCurves: classicCurves, + want: wantP384HTTPS, + wantHTTPNotDialed: true, + }, + { + name: "tls12_only_https_falls_back_to_http", + httpsServerCurves: classicCurves, + httpsServerMaxVersion: tls.VersionTLS12, + want: wantHTTP, + }, + { + name: "tls12_only_https_and_http_error_falls_back_to_classic_https", + httpsServerCurves: ecc256Only, + httpsServerMaxVersion: tls.VersionTLS12, + httpFail: true, + want: wantClassicHTTPS, + }, + { + name: "ecc256_only_https_falls_back_to_http", + httpsServerCurves: ecc256Only, + want: wantHTTP, + }, + { + name: "ecc256_only_https_and_http_error_falls_back_to_classic_https", + httpsServerCurves: ecc256Only, + httpFail: true, + want: wantClassicHTTPS, + }, + { + name: "ecc256_only_https_and_http_hang_falls_back_to_classic_https", + httpsServerCurves: ecc256Only, + httpHangAfterUpgrade: true, + want: wantClassicHTTPS, + }, + { + name: "large_client_hello_dropped_falls_back_to_http", + dropLargeClientHello: true, + want: wantHTTP, + }, + { + name: "force_noise_443_with_ecc256_only_server_skips_http", + httpsServerCurves: ecc256Only, + forceNoise443Env: true, + want: wantClassicHTTPS, + wantHTTPNotDialed: true, + }, + { + name: "disable_pq_https_env_prefers_http", + disablePQHTTPSEnv: true, + want: wantHTTP, + wantHTTPSNotDialed: true, + }, + { + name: "https_disabled_no_port_uses_http", + httpsDisabled: true, + want: wantHTTP, + wantHTTPSNotDialed: true, + }, + { + name: "https_disabled_no_port_fails_fast", + httpsDisabled: true, + httpFail: true, + want: wantErr, + wantErrContains: []string{"http:"}, + wantHTTPSNotDialed: true, + wantNoFallbackWait: true, + }, + { + name: "all_attempts_fail", + httpsFail: true, + httpFail: true, + want: wantErr, + wantErrContains: []string{"pq-https:", "http:", "https:"}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if tt.forceNoise443Env { + envknob.SetenvForTest(t, "TS_FORCE_NOISE_443", "1") + } + if tt.disablePQHTTPSEnv { + envknob.SetenvForTest(t, "TS_DISABLE_NOISE_PQ_HTTPS", "1") + } + + synctest.Test(t, func(t *testing.T) { + clientKey, serverKey := key.NewMachine(), key.NewMachine() + + const ( + testProtocolVersion = 1 + host = "10.0.0.2" + httpPort = "80" + httpsPort = "443" + ) + + memNetwork := &memnet.Network{} + done := make(chan struct{}) + t.Cleanup(func() { close(done) }) + var ( + httpHits atomic.Int32 + httpsHits atomic.Int32 + ) + + type connInfo struct { + isHTTPS bool + curveID tls.CurveID + } + acceptedCh := make(chan connInfo, 4) + + makeUpgradeHandler := func(isHTTPS bool) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if isHTTPS { + httpsHits.Add(1) + if tt.httpsFail { + http.Error(w, "https disabled", http.StatusInternalServerError) + return + } + } else { + httpHits.Add(1) + if tt.httpFail { + http.Error(w, "http disabled", http.StatusInternalServerError) + return + } + } + var curve tls.CurveID + if r.TLS != nil { + curve = r.TLS.CurveID + } + conn, err := controlhttpserver.AcceptHTTP(context.Background(), w, r, serverKey, nil) + if err != nil { + return + } + defer conn.Close() + acceptedCh <- connInfo{isHTTPS: isHTTPS, curveID: curve} + <-done + } + } + + var httpHandler http.Handler = makeUpgradeHandler(false) + if tt.httpHangAfterUpgrade { + httpHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + httpHits.Add(1) + w.Header().Set("Upgrade", controlhttpcommon.UpgradeHeaderValue) + w.Header().Set("Connection", "upgrade") + w.WriteHeader(http.StatusSwitchingProtocols) + w.(http.Flusher).Flush() + select { + case <-r.Context().Done(): + case <-done: + } + }) + } + + httpLn := must.Get(memNetwork.Listen("tcp", host+":"+httpPort)) + httpServer := &http.Server{Handler: httpHandler} + go httpServer.Serve(httpLn) + t.Cleanup(func() { httpServer.Close() }) + + httpsLn := must.Get(memNetwork.Listen("tcp", host+":"+httpsPort)) + srvTLS := tlsConfig(t) + srvTLS.CurvePreferences = tt.httpsServerCurves + srvTLS.MaxVersion = tt.httpsServerMaxVersion + httpsServer := &http.Server{ + Handler: makeUpgradeHandler(true), + TLSConfig: srvTLS, + ErrorLog: logger.StdLogger(logger.WithPrefix(t.Logf, "https.Server: ")), + } + go httpsServer.ServeTLS(httpsLn, "", "") + t.Cleanup(func() { httpsServer.Close() }) + + trackedDialer := &memnetDialer{ + inner: memNetwork.Dial, + t: t, + } + defer trackedDialer.waitForAllClosedSynctest() + + dialFunc := trackedDialer.Dial + if tt.dropLargeClientHello { + base := dialFunc + dialFunc = func(ctx context.Context, network, addr string) (net.Conn, error) { + c, err := base(ctx, network, addr) + if err != nil { + return nil, err + } + if _, port, _ := net.SplitHostPort(addr); port == httpsPort { + return &dropLargeClientHelloConn{ + Conn: c, + maxFirstWrite: 1000, + }, nil + } + return c, nil + } + } + + d := &Dialer{ + Hostname: host, + HTTPPort: httpPort, + HTTPSPort: httpsPort, + MachineKey: clientKey, + ControlKey: serverKey.Public(), + ProtocolVersion: testProtocolVersion, + Dialer: dialFunc, + Logf: t.Logf, + proxyFunc: func(*http.Request) (*url.URL, error) { return nil, nil }, + omitCertErrorLogging: true, + Clock: tstime.StdClock{}, + HealthTracker: health.NewTracker(eventbustest.NewBus(t)), + } + if tt.httpsDisabled { + d.HTTPSPort = NoPort + } + + pqBefore := metricDialPQHTTPS.Value() + p384Before := metricDialP384HTTPS.Value() + httpBefore := metricDialHTTP.Value() + classicBefore := metricDialClassicHTTPS.Value() + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + start := time.Now() + conn, err := d.Dial(ctx) + elapsed := time.Since(start) + + if tt.want == wantErr { + if err == nil { + conn.Close() + t.Fatalf("Dial succeeded unexpectedly, want error") + } + for _, sub := range tt.wantErrContains { + if !strings.Contains(err.Error(), sub) { + t.Errorf("Dial error = %q, want substring %q", err.Error(), sub) + } + } + if tt.wantNoFallbackWait && elapsed >= d.fallbackDelay() { + t.Errorf("Dial took %v, expected immediate failure (< %v)", elapsed, d.fallbackDelay()) + } + if tt.wantHTTPSNotDialed && httpsHits.Load() != 0 { + t.Errorf("HTTPS server received %d hits, want 0", httpsHits.Load()) + } + return + } + + if err != nil { + t.Fatalf("Dial failed: %v", err) + } + defer conn.Close() + + // Find the port we connected to. + addrPart, _, _ := strings.Cut(conn.RemoteAddr().String(), "|") + _, gotPort, err := net.SplitHostPort(addrPart) + if err != nil { + t.Fatalf("SplitHostPort(%q): %v", addrPart, err) + } + + info := <-acceptedCh + + switch tt.want { + case wantPQHTTPS: + if gotPort != httpsPort || !info.isHTTPS { + t.Errorf("connected to port %s (isHTTPS=%v), want PQ HTTPS port %s", gotPort, info.isHTTPS, httpsPort) + } + if !isPQCurve(info.curveID) { + t.Errorf("negotiated curve %v, want post-quantum curve", info.curveID) + } + if got := metricDialPQHTTPS.Value() - pqBefore; got != 1 { + t.Errorf("metricDialPQHTTPS delta = %d, want 1", got) + } + case wantP384HTTPS: + if gotPort != httpsPort || !info.isHTTPS { + t.Errorf("connected to port %s (isHTTPS=%v), want P-384 HTTPS port %s", gotPort, info.isHTTPS, httpsPort) + } + if !isP384OrHigherCurve(info.curveID) { + t.Errorf("negotiated curve %v, want P-384 or P-521", info.curveID) + } + if got := metricDialP384HTTPS.Value() - p384Before; got != 1 { + t.Errorf("metricDialP384HTTPS delta = %d, want 1", got) + } + case wantHTTP: + if gotPort != httpPort || info.isHTTPS { + t.Errorf("connected to port %s (isHTTPS=%v), want HTTP port %s", gotPort, info.isHTTPS, httpPort) + } + if got := metricDialHTTP.Value() - httpBefore; got != 1 { + t.Errorf("metricDialHTTP delta = %d, want 1", got) + } + case wantClassicHTTPS: + if gotPort != httpsPort || !info.isHTTPS { + t.Errorf("connected to port %s (isHTTPS=%v), want classic HTTPS port %s", gotPort, info.isHTTPS, httpsPort) + } + if isPQCurve(info.curveID) { + t.Errorf("negotiated curve %v, want classic (non-PQ) curve", info.curveID) + } + if got := metricDialClassicHTTPS.Value() - classicBefore; got != 1 { + t.Errorf("metricDialClassicHTTPS delta = %d, want 1", got) + } + } + + if tt.wantHTTPNotDialed && httpHits.Load() != 0 { + t.Errorf("HTTP server received %d hits, want 0", httpHits.Load()) + } + if tt.wantHTTPSNotDialed && httpsHits.Load() != 0 { + t.Errorf("HTTPS server received %d hits, want 0", httpsHits.Load()) + } + }) + }) + } +}