diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 9b03a29..cc64ecf 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -4,6 +4,55 @@ Newest first. This file records *why* things changed, since that is the part a d does not keep. Structural decisions live in [`DESIGN.md`](../DESIGN.md) §14 and in [`docs/adr/`](adr/). +## 2026-10-03 — L1 hardening: echo the borrowed suite, correct the SNI claim + +Two distinguishers found while reading the code during the 2026-10-01 pass +(ROADMAP H4 and H5), closed together because both are about the relay's two +answer paths — local for a tagged client, spliced for everyone else — agreeing +on what they put in cleartext. + +### The relay echoes the cipher suite the site negotiates (H4) + +`buildServerHello` pinned the suite to `TLS_AES_128_GCM_SHA256`, and the profile +never recorded what the borrowed site actually chose. The cipher suite sits in +cleartext in the ServerHello, so against a site preferring AES-256 or ChaCha20 a +tagged client got `0x1301` from local state while a spliced probe got the site's +real choice — two suites from one address, separable with no decryption and no +key, exactly the shape of split the 2026-10-01 pass closed on the time axis. + +`ProfileSite` now reads the negotiated suite off the wire +(`FlightProfile.CipherSuite`) and the relay echoes it. The value names nothing +about how Warren encrypts the session — that is still ChaCha20-Poly1305 under the +derived key regardless — it only has to match what the site answers, so echoing +the measured value costs nothing. An unmeasured profile falls back to the pinned +suite, which every parroted Chrome hello offers. + +The gate now measures it: `Compare` parses both ServerHellos' suites and reports +a mismatch, and a canary (`TestCanary_CipherSuiteMismatchIsDetected`) forces the +relay onto a suite the site does not negotiate and requires the finding to fire — +because a measurement with no canary is one that can quietly stop measuring. + +### The SNI claim is corrected to match the single-site splice (H5) + +The transport package comment said an unauthenticated connection is spliced "to +the real site the ClientHello's SNI names". It is not: a relay fronts **one** +site and splices every unauthenticated connection to `FallbackAddr`, whatever SNI +the hello carried. For real traffic the two coincide — a genuine Warren client +always presents the borrowed site's SNI — and for a probe presenting some other +name the relay hands back the borrowed site anyway, which is precisely what a +real single-site server does with an unexpected SNI (its default certificate). + +Routing by SNI was considered and rejected: it would turn the relay into an open +proxy to arbitrary hosts, which is the amplification problem tracked as H7, and a +security regression rather than a fix. So the behaviour is correct and the claim +was wrong; the comment is fixed, and an `unexpected-sni` probe now asserts the +relay still matches the borrowed site under a name neither endpoint fronts — a +relay that *did* route by SNI would return a certificate for a different name and +separate itself on the leaf digest alone. + +Verified: `go build`, `go vet`, `go test ./...`, `gofmt`. Not verified locally: +`-race` (needs cgo and a C toolchain this machine lacks); CI covers it. + ## 2026-10-01 — L1 hardening: answer timing, replay freshness, and canaries on the gate Three weaknesses closed and three defects found on the way, one of which had been diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 92ca8c9..1fbe366 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -130,8 +130,6 @@ from it, not by effort. Items marked **found** came out of the hardening pass on | H1 | **Traffic shape after the handshake** (`bucket`/`cover`, DESIGN §6.4) | The largest measured gap. The machinery exists — every record carries a kind byte and filler is already discarded by the peer — so this is a policy layer over tested code, not a new wire format. Slice 2 | | H2 | **The gate stops measuring where the handshake ends** | `cmd/probe` compares handshake shape and now answer timing; it does not compare the data phase against the borrowed site's real responses. Slice 1's PASS is routinely misread as deployability because of this | | H3 | **One round trip still separates the relay's two answer paths** — *found* | The ServerHello wait equalises the site's answer time but not the TCP connect the splice additionally pays. Fix is warm upstream connections (better: keeps Warren fast) or measuring from dial (simpler: makes Warren slower). Measured and reported by `cmd/probe` today | -| H4 | **The relay hardcodes its ServerHello cipher suite** — *found* | `tls13CipherSuite` is pinned to `TLS_AES_128_GCM_SHA256`, and the profile never records what the borrowed site actually negotiated. Against a site preferring AES-256 or ChaCha20, a tagged client and a spliced probe get *different* cipher suites from the same relay. It names nothing about how Warren really encrypts, so echoing the measured value is free | -| H5 | **The splice ignores the ClientHello's SNI** — *found* | The code always dials `FallbackAddr`; the package comment and the README both say it splices to the site the SNI names. A probe presenting an unexpected SNI gets a certificate for the wrong name. Fix the behaviour or the claim, and add the probe case either way | | H6 | **No session rekey** | One ChaCha20-Poly1305 key for the whole connection, no record-count limit, no KeyUpdate equivalent. TLS 1.3 rekeys; a long-lived tunnel should too | ### Resource and failure behaviour @@ -178,6 +176,16 @@ from it, not by effort. Items marked **found** came out of the hardening pass on | H24 | **No relay operator guide** | How to choose a site to borrow, what that site's operator sees (a handshake every 30 minutes, plus a connection per probe), and what abuse handling is expected. §7.4 is logged as a requirement with nothing written against it | | H25 | **"~5,500 lines" is hardcoded in four documents** | A drift magnet. Say it once, or derive it | +### Resolved + +Closed since the 2026-10-01 pass, kept here so the numbering stays stable and +the history is legible. + +| # | Item | How it was closed | +|---|------|-------------------| +| H4 | **The relay hardcoded its ServerHello cipher suite** — *found* | ✅ `ProfileSite` now records the suite the borrowed site negotiates (`FlightProfile.CipherSuite`) and the relay echoes it rather than a pinned `TLS_AES_128_GCM_SHA256`, so a tagged client and a spliced probe see the same suite. `cmd/probe` compares the two ServerHellos' suites, guarded by a canary. It still names nothing about how Warren encrypts (ChaCha20-Poly1305 under the derived key); the echoed value only has to agree with the site | +| H5 | **The splice ignored the ClientHello's SNI** — *found* | ✅ Claim corrected rather than behaviour changed: a relay fronts **one** site and splices every unauthenticated connection to `FallbackAddr` regardless of the SNI, exactly as a real single-site server answers an unexpected SNI with its own default certificate. Routing by SNI was rejected on purpose — it would make the relay an open proxy to arbitrary hosts (see H7). The package comment is fixed and a `unexpected-sni` probe asserts the relay still matches the borrowed site | + --- ## Slice 2 — L1 breadth + client distribution ⬜ diff --git a/internal/network/probe/canary_test.go b/internal/network/probe/canary_test.go index bbed851..2aa5293 100644 --- a/internal/network/probe/canary_test.go +++ b/internal/network/probe/canary_test.go @@ -83,6 +83,35 @@ func TestCanary_AnswerLatencySplitIsDetected(t *testing.T) { } } +// TestCanary_CipherSuiteMismatchIsDetected guards the cipher-suite measurement +// (H4). The borrowed site negotiates one TLS 1.3 suite; a relay that answers a +// tagged client with a different one splits its two answer paths onto suites a +// censor can read in cleartext from the ServerHello. The measurement is new, so +// it gets a canary: force the relay to echo a suite the loopback site does not +// negotiate and require the comparison to say so. +func TestCanary_CipherSuiteMismatchIsDetected(t *testing.T) { + site := startBorrowedSite(t) + + relay, clientCfg := startRelayShaped(t, site, func(p *transport.FlightProfile) { + // The Go test site negotiates AES-128 (0x1301) on loopback hardware; + // force the relay to answer AES-256 so the two disagree. This does not + // touch Warren's own encryption, which is ChaCha20-Poly1305 under the + // derived key regardless of the suite named here. + p.CipherSuite = 0x1302 + }) + + report := captureAndCompare(t, relay, clientCfg, site) + + f := findingByName(t, report, "ServerHello cipher suite") + if f.Warren == "unparsed" || f.Real == "unparsed" { + t.Fatalf("a ServerHello did not parse, so this canary measured nothing: warren %s, real %s", f.Warren, f.Real) + } + if !f.Distinguisher { + t.Errorf("a relay answering 0x1302 where the site negotiates %s was reported as indistinguishable: warren %s, real %s", + f.Real, f.Warren, f.Real) + } +} + // TestCanary_MissingSessionTicketsAreDetected guards the post-handshake // measurement, which is the one a relay would fail a few records later than the // certificate flight if it stopped replaying what the site sends after the diff --git a/internal/network/probe/probe.go b/internal/network/probe/probe.go index 29f80a0..205fdef 100644 --- a/internal/network/probe/probe.go +++ b/internal/network/probe/probe.go @@ -60,6 +60,7 @@ func Suite() []Probe { return []Probe{ tlsHandshakeProbe(), repeatHandshakeProbe(), + unexpectedSNIProbe(), plaintextHTTPProbe(), randomJunkProbe(), truncatedHelloProbe(), @@ -149,6 +150,28 @@ func repeatHandshakeProbe() Probe { } } +// unexpectedSNIProbe connects with an SNI the relay does not front (H5). A +// Warren relay borrows one site and splices every unauthenticated connection to +// it regardless of the SNI presented — it does not route by SNI — so it must +// answer an unexpected SNI exactly as the borrowed site does: with that site's +// own default certificate. A relay that instead dialed the SNI-named host would +// return a certificate for a different name and separate itself from the site on +// the leaf digest alone. The SNI argument from the suite is deliberately ignored +// in favour of a fixed name neither endpoint is configured for. +func unexpectedSNIProbe() Probe { + const unexpected = "nonexistent.example" + return Probe{ + Name: "unexpected-sni", + Desc: "handshake with an SNI the relay does not front; it must still answer like the borrowed site", + Run: func(ctx context.Context, addr, _ string) Observation { + return runTLSHandshake(ctx, addr, unexpected) + }, + Signature: func(o Observation) string { + return fmt.Sprintf("ok=%t cert=%s err=%s", o.HandshakeOK, o.CertSHA256, o.ErrClass) + }, + } +} + func runTLSHandshake(ctx context.Context, addr, sni string) Observation { start := time.Now() raw, err := dial(ctx, addr) diff --git a/internal/network/probe/probe_test.go b/internal/network/probe/probe_test.go index f44f00e..90ce4ac 100644 --- a/internal/network/probe/probe_test.go +++ b/internal/network/probe/probe_test.go @@ -262,6 +262,45 @@ func TestProbeSuite_TLSHandshakeSeesBorrowedCertificate(t *testing.T) { } } +// TestUnexpectedSNIIsSplicedToTheBorrowedSite is H5: a relay fronts one site and +// splices every unauthenticated connection to it regardless of the SNI, so a +// probe that presents an SNI the relay does not front must still be answered by +// the borrowed site — the same certificate a real single-site server returns for +// an unexpected SNI. A relay that routed by SNI would hand back a certificate for +// a different name, which the leaf digest would expose. +func TestUnexpectedSNIIsSplicedToTheBorrowedSite(t *testing.T) { + site := startBorrowedSite(t) + relay, _ := startRelay(t, site) + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + // The probe must be in the suite — otherwise H5's guard runs nowhere. + var inSuite bool + for _, p := range Suite() { + if p.Name == "unexpected-sni" { + inSuite = true + } + } + if !inSuite { + t.Fatal("the unexpected-sni probe is not in the suite; H5's guard is not running") + } + + const unexpected = "nonexistent.example" + viaRelay := runTLSHandshake(ctx, relay, unexpected) + direct := runTLSHandshake(ctx, site, unexpected) + + // The comparison is only meaningful if both actually handshook and returned a + // certificate; "both failed identically" would pass vacuously. + if !viaRelay.HandshakeOK || viaRelay.CertSHA256 == "" { + t.Fatalf("relay did not complete a handshake and present a certificate under an unexpected SNI: %+v", viaRelay) + } + if viaRelay.CertSHA256 != direct.CertSHA256 { + t.Errorf("under an unexpected SNI the relay returned certificate %q, the borrowed site %q: a relay that routed by SNI would do exactly this", + viaRelay.CertSHA256, direct.CertSHA256) + } +} + // TestCompare_FlightMatchesRealSite is Stage A's verdict, measured rather than // asserted: a Warren session's record shape no longer separates from a real TLS // session to the same site. diff --git a/internal/network/probe/trace.go b/internal/network/probe/trace.go index d9c8348..20bdbf5 100644 --- a/internal/network/probe/trace.go +++ b/internal/network/probe/trace.go @@ -75,11 +75,22 @@ type Trace struct { // ClientHello can be replayed back at the relay (ReplayProbe) — which is // exactly the move a censor makes with one recording. ClientBytes []byte + + // ServerBytes is the head of the server->client stream, kept so the + // ServerHello's cleartext fields — the negotiated cipher suite in + // particular — can be read back off the wire. A censor needs no key to see + // them, so the harness compares them the same way. + ServerBytes []byte } // maxCapturedClientBytes bounds ClientBytes; a ClientHello record is ~1.5 KB -// and nothing beyond the first record is replayable anyway. -const maxCapturedClientBytes = 16 << 10 +// and nothing beyond the first record is replayable anyway. maxCapturedServerBytes +// matches it: a hybrid ServerHello record is ~1.2 KB and only the first record +// is parsed. +const ( + maxCapturedClientBytes = 16 << 10 + maxCapturedServerBytes = 16 << 10 +) // FirstClientRecord returns the first complete TLS record the client sent, or // nil if the capture did not contain one. @@ -94,6 +105,38 @@ func (t Trace) FirstClientRecord() []byte { return t.ClientBytes[:end] } +// ServerHelloCipherSuite reads the negotiated cipher suite out of the first +// server handshake record. It parses only the fixed prefix up to the suite — +// legacy_version, random, session_id, cipher_suite — which is all cleartext in +// a TLS 1.3 ServerHello. ok is false if the capture held no parseable +// ServerHello. +func (t Trace) ServerHelloCipherSuite() (suite uint16, ok bool) { + b := t.ServerBytes + if len(b) < 5 || b[0] != TypeHandshake { + return 0, false + } + recLen := int(b[3])<<8 | int(b[4]) + rec := b[5:] + if recLen < len(rec) { + rec = rec[:recLen] + } + // handshake: msg_type(1)=server_hello + length(3) + body + if len(rec) < 4 || rec[0] != 0x02 { + return 0, false + } + body := rec[4:] + // legacy_version(2) + random(32) + session_id_len(1) + if len(body) < 35 { + return 0, false + } + sidLen := int(body[34]) + p := body[35:] + if len(p) < sidLen+2 { + return 0, false + } + return uint16(p[sidLen])<<8 | uint16(p[sidLen+1]), true +} + func (t Trace) String() string { var b strings.Builder fmt.Fprintf(&b, "%s (%d records)\n", t.Label, len(t.Records)) @@ -126,6 +169,12 @@ func (s *scanner) Write(p []byte) (int, error) { s.out.ClientBytes = append(s.out.ClientBytes, p[:min(room, len(p))]...) } s.mu.Unlock() + } else { + s.mu.Lock() + if room := maxCapturedServerBytes - len(s.out.ServerBytes); room > 0 { + s.out.ServerBytes = append(s.out.ServerBytes, p[:min(room, len(p))]...) + } + s.mu.Unlock() } for { @@ -205,6 +254,7 @@ func Capture(ctx context.Context, label, target string, drive func(ctx context.C defer mu.Unlock() trace.Records = append([]Record(nil), trace.Records...) trace.ClientBytes = append([]byte(nil), trace.ClientBytes...) + trace.ServerBytes = append([]byte(nil), trace.ServerBytes...) sort.SliceStable(trace.Records, func(i, j int) bool { return trace.Records[i].At < trace.Records[j].At }) return trace, driveErr } @@ -374,6 +424,23 @@ func Compare(warren, real Trace) Report { Distinguisher: absDiff(wSH, rSH) > serverHelloSizeTolerance, }) + // The negotiated cipher suite, in cleartext in the ServerHello. The relay + // answers a tagged client from local state and everyone else by splicing to + // the borrowed site; if the local answer hardcodes a suite the site does not + // negotiate, the two paths to one address differ on a field a censor reads + // without a key. Only flagged when both ServerHellos parse, so a capture + // that missed one is not mistaken for a mismatch (that failure is the + // capture canary's job, not this measurement's). + wCS, wCSOK := warren.ServerHelloCipherSuite() + rCS, rCSOK := real.ServerHelloCipherSuite() + r.Findings = append(r.Findings, Finding{ + Name: "ServerHello cipher suite", + Warren: cipherSuiteName(wCS, wCSOK), + Real: cipherSuiteName(rCS, rCSOK), + Distinguisher: wCSOK && rCSOK && wCS != rCS, + Note: "the relay must echo the suite the borrowed site negotiates, not a hardcoded one", + }) + // How long the peer took to answer, which is a shape measurement on the // time axis and the cheapest one a passive observer has: it needs no // decryption, no key, and no probe of its own, just a clock. @@ -543,6 +610,25 @@ func shortType(t byte) string { } } +// cipherSuiteName renders a TLS 1.3 cipher suite for a report. The three TLS +// 1.3 suites get their names; anything else is shown as its hex code, which is +// enough to see a mismatch. +func cipherSuiteName(suite uint16, ok bool) string { + if !ok { + return "unparsed" + } + switch suite { + case 0x1301: + return "AES_128_GCM_SHA256" + case 0x1302: + return "AES_256_GCM_SHA384" + case 0x1303: + return "CHACHA20_POLY1305_SHA256" + default: + return fmt.Sprintf("0x%04x", suite) + } +} + func absDiff(a, b int) int { if a > b { return a - b diff --git a/internal/network/transport/camouflage.go b/internal/network/transport/camouflage.go index 8e965ab..69d1e92 100644 --- a/internal/network/transport/camouflage.go +++ b/internal/network/transport/camouflage.go @@ -20,9 +20,15 @@ // identity exchange (see handshake.go). Application data then flows in // records shaped like TLS application_data. // - tag invalid, absent, or replayed -> the connection is spliced -// byte-for-byte to the real site the ClientHello's SNI names. A censor's -// active probe (or any passive DPI classifier) sees a completely genuine -// handshake with the real site's real certificate, because it *is* one. +// byte-for-byte to the one site this relay borrows (Config.FallbackAddr), +// not to whatever the ClientHello's SNI names. A relay fronts a single +// site, and a genuine Warren client always carries that site's SNI +// (Config.FallbackSNI) in its hello, so for real traffic the two are the +// same; a probe presenting some other SNI is still handed the borrowed +// site, exactly as a real single-site server answers an unexpected SNI +// with its own default certificate. A censor's active probe (or any +// passive DPI classifier) sees a completely genuine handshake with that +// site's real certificate, because it *is* one. // // Known gap vs. full REALITY (xtls/xray-core's `reality` package): a genuine // Warren session's second flight is shaped like TLS 1.3 but is not a real TLS @@ -367,10 +373,19 @@ func serveConn(ctx context.Context, raw net.Conn, cfg Config, replays *replayCac // the key exchange below has to fall inside that budget rather than extend it. helloAt := time.Now() if err == nil { + // Fetch the flight before validating the tag: its measured cipher suite + // goes into the ServerHello serverAccept builds, so the relay echoes the + // suite the borrowed site negotiated rather than a hardcoded one. A nil + // or unmeasured profile leaves it zero, which buildServerHello falls back + // from; flight.Validate below is what refuses to serve on a nil profile. + flight := cfg.flight() + var cipherSuite uint16 + if flight != nil { + cipherSuite = flight.CipherSuite + } accepted, acceptErr := serverAccept( - cfg.ServerPrivateKey, hello.random, hello.sessionID, hello.share, helloAt) + cfg.ServerPrivateKey, hello.random, hello.sessionID, hello.share, helloAt, cipherSuite) - flight := cfg.flight() if acceptErr == nil && flight.Validate() == nil && replays.admit(hello.random, helloAt) { raw.SetReadDeadline(time.Now().Add(sniffTimeout + maxServerHelloDelay)) conn, err := completeHandshake(raw, br, recordLen, helloAt, accepted, flight, hello.random, hello.share) diff --git a/internal/network/transport/camouflage_test.go b/internal/network/transport/camouflage_test.go index c7023d8..4a848d2 100644 --- a/internal/network/transport/camouflage_test.go +++ b/internal/network/transport/camouflage_test.go @@ -351,11 +351,11 @@ func TestEphemeralSecretsDifferPerConnection(t *testing.T) { now := time.Now() copy(sessionID, deriveTag(first.authSS, clientRandom, first.share, tagWindowIndex(now))) - acceptA, err := serverAccept(priv, clientRandom, sessionID, first.share, now) + acceptA, err := serverAccept(priv, clientRandom, sessionID, first.share, now, 0) if err != nil { t.Fatalf("serverAccept: %v", err) } - acceptB, err := serverAccept(priv, clientRandom, sessionID, first.share, now) + acceptB, err := serverAccept(priv, clientRandom, sessionID, first.share, now, 0) if err != nil { t.Fatalf("serverAccept: %v", err) } @@ -367,7 +367,7 @@ func TestEphemeralSecretsDifferPerConnection(t *testing.T) { if err != nil { t.Fatalf("generate identity: %v", err) } - if _, err := serverAccept(otherPriv, clientRandom, sessionID, first.share, now); err == nil { + if _, err := serverAccept(otherPriv, clientRandom, sessionID, first.share, now, 0); err == nil { t.Fatal("a relay holding a different identity key validated the tag") } } diff --git a/internal/network/transport/cipher_test.go b/internal/network/transport/cipher_test.go new file mode 100644 index 0000000..5e04998 --- /dev/null +++ b/internal/network/transport/cipher_test.go @@ -0,0 +1,55 @@ +package transport + +import ( + "testing" + "time" +) + +// TestServerHelloEchoesMeasuredCipherSuite is H4 in the small. The relay has +// two answer paths: a tagged client is answered from local state, everyone else +// is spliced to the borrowed site. The cipher suite sits in cleartext in the +// ServerHello, so if the local path hardcodes TLS_AES_128_GCM_SHA256 while the +// borrowed site negotiates AES-256 or ChaCha20, the two paths hand different +// suites from one address — a distinguisher needing no decryption. serverAccept +// must echo whatever suite the profile measured. +func TestServerHelloEchoesMeasuredCipherSuite(t *testing.T) { + priv, pub, err := GenerateServerIdentity() + if err != nil { + t.Fatalf("identity: %v", err) + } + keys, err := newClientKeys(pub) + if err != nil { + t.Fatalf("client keys: %v", err) + } + + clientRandom := randomBytes(t, 32) + now := time.Now() + sessionID := make([]byte, sessionIDLen) + copy(sessionID, deriveTag(keys.authSS, clientRandom, keys.share, tagWindowIndex(now))) + + cases := []struct { + name string + suite uint16 + want uint16 + }{ + {"aes-256", 0x1302, 0x1302}, + {"chacha20", 0x1303, 0x1303}, + {"aes-128", 0x1301, 0x1301}, + {"unmeasured falls back", 0, tls13CipherSuite}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + accepted, err := serverAccept(priv, clientRandom, sessionID, keys.share, now, tc.suite) + if err != nil { + t.Fatalf("serverAccept: %v", err) + } + _, _, got, _, err := parseServerHelloParts(serverHelloBody(accepted.serverHello)) + if err != nil { + t.Fatalf("parse ServerHello: %v", err) + } + if got != tc.want { + t.Errorf("ServerHello cipher suite = 0x%04x, want 0x%04x", got, tc.want) + } + }) + } +} diff --git a/internal/network/transport/flight.go b/internal/network/transport/flight.go index f6cfc17..0cefcd9 100644 --- a/internal/network/transport/flight.go +++ b/internal/network/transport/flight.go @@ -55,6 +55,18 @@ type FlightProfile struct { Group uint16 ServerHelloLen int + // CipherSuite is the TLS 1.3 cipher suite the borrowed site selected in its + // ServerHello. The relay echoes this value in its own ServerHello rather + // than a hardcoded one: the suite sits in cleartext, so a site that prefers + // AES-256 or ChaCha20 while the relay always answered TLS_AES_128_GCM_SHA256 + // would hand a tagged client and a spliced probe different suites from the + // same address — a distinguisher on the ServerHello, with no decryption + // needed. It names nothing about how Warren actually encrypts the session + // (that is ChaCha20-Poly1305 under the derived key); it only has to agree + // with what the site answers. Zero means unmeasured, and buildServerHello + // falls back to a suite every parroted ClientHello offers. + CipherSuite uint16 + // ServerHelloDelay is how long the borrowed site took to answer a // ClientHello, measured from the relay's own vantage point: one network // round trip to the site plus whatever the site spends choosing parameters @@ -283,8 +295,9 @@ func (t *profilingTap) profile(addr, sni string) (*FlightProfile, error) { } } - if _, group, _, err := parseServerHelloParts(serverHelloBody(t.serverHello)); err == nil { + if _, group, cipherSuite, _, err := parseServerHelloParts(serverHelloBody(t.serverHello)); err == nil { p.Group = group + p.CipherSuite = cipherSuite } if len(p.ServerFlight) > maxFlightRecords { p.ServerFlight = p.ServerFlight[:maxFlightRecords] @@ -364,8 +377,8 @@ func (p *FlightProfile) TotalServerFlight() int { func (p *FlightProfile) String() string { var b strings.Builder - fmt.Fprintf(&b, "%s (%s): group 0x%04x, ServerHello %d B after %s, flight %d B in %d records", - p.Site, p.SNI, p.Group, p.ServerHelloLen, p.ServerHelloDelay.Round(time.Millisecond), + fmt.Fprintf(&b, "%s (%s): group 0x%04x, cipher 0x%04x, ServerHello %d B after %s, flight %d B in %d records", + p.Site, p.SNI, p.Group, p.CipherSuite, p.ServerHelloLen, p.ServerHelloDelay.Round(time.Millisecond), p.TotalServerFlight(), len(p.ServerFlight)) if len(p.PostClientFlight) > 0 { post := 0 diff --git a/internal/network/transport/handshake.go b/internal/network/transport/handshake.go index d0111b3..0d3a4e5 100644 --- a/internal/network/transport/handshake.go +++ b/internal/network/transport/handshake.go @@ -49,11 +49,15 @@ const ( hybridClientShareLen = mlkem.EncapsulationKeySize768 + x25519KeyLen // 1216 hybridServerShareLen = mlkem.CiphertextSize768 + x25519KeyLen // 1120 - // tls13CipherSuite is echoed in the ServerHello. Every Chrome profile - // offers TLS_AES_128_GCM_SHA256, so selecting it is always consistent - // with the ClientHello we just parroted. It names nothing about how - // Warren actually encrypts the session (that's ChaCha20-Poly1305 under - // the derived key); it only has to be a suite the client offered. + // tls13CipherSuite is the ServerHello fallback when the borrowed site's + // negotiated suite has not been measured (FlightProfile.CipherSuite == 0). + // Every Chrome profile offers TLS_AES_128_GCM_SHA256, so selecting it is + // always consistent with the ClientHello we just parroted. It names nothing + // about how Warren actually encrypts the session (that's ChaCha20-Poly1305 + // under the derived key); it only has to be a suite the client offered. When + // the profile carries the site's real choice, that is echoed instead, so a + // site preferring AES-256 or ChaCha20 does not split the relay's two answer + // paths onto different suites. tls13CipherSuite = 0x1301 extSupportedVersions = 0x002b @@ -285,8 +289,11 @@ type acceptResult struct { } // serverAccept validates a client's tag and produces everything the relay needs -// to answer. -func serverAccept(identityKey, clientRandom, sessionID, clientShare []byte, now time.Time) (*acceptResult, error) { +// to answer. cipherSuite is the suite the borrowed site negotiated (from its +// FlightProfile), echoed in the ServerHello so the relay's two answer paths — +// local for a tagged client, spliced for everyone else — agree on it; zero +// falls back to a suite every parroted ClientHello offers. +func serverAccept(identityKey, clientRandom, sessionID, clientShare []byte, now time.Time, cipherSuite uint16) (*acceptResult, error) { if len(identityKey) != x25519KeyLen { return nil, ErrIdentityMissing } @@ -341,7 +348,7 @@ func serverAccept(identityKey, clientRandom, sessionID, clientShare []byte, now return nil, err } return &acceptResult{ - serverHello: buildServerHello(sessionID, serverRandom, serverShare), + serverHello: buildServerHello(sessionID, serverRandom, serverShare, cipherSuite), sessionKey: key, serverRandom: serverRandom, serverShare: serverShare, @@ -354,8 +361,13 @@ var errTagMismatch = errors.New("transport: client hello tag mismatch") // key_share. Everything about its shape — legacy version 0x0303, the echoed // session_id, supported_versions announcing TLS 1.3, key_share carrying // ciphertext||x25519 for group X25519MLKEM768 — is what a real TLS 1.3 server -// answering our parroted ClientHello would send. -func buildServerHello(sessionIDEcho, serverRandom, serverShare []byte) []byte { +// answering our parroted ClientHello would send. cipherSuite is the suite the +// borrowed site negotiated; zero falls back to TLS_AES_128_GCM_SHA256, which +// every parroted Chrome profile offers. +func buildServerHello(sessionIDEcho, serverRandom, serverShare []byte, cipherSuite uint16) []byte { + if cipherSuite == 0 { + cipherSuite = tls13CipherSuite + } ext := make([]byte, 0, 16+len(serverShare)) ext = appendUint16(ext, extSupportedVersions) ext = appendUint16(ext, 2) @@ -372,7 +384,7 @@ func buildServerHello(sessionIDEcho, serverRandom, serverShare []byte) []byte { body = append(body, serverRandom...) body = append(body, byte(len(sessionIDEcho))) body = append(body, sessionIDEcho...) - body = appendUint16(body, tls13CipherSuite) + body = appendUint16(body, cipherSuite) body = append(body, 0x00) // legacy_compression_method body = appendUint16(body, uint16(len(ext))) body = append(body, ext...) @@ -392,7 +404,7 @@ func buildServerHello(sessionIDEcho, serverRandom, serverShare []byte) []byte { // ServerHello handshake body, rejecting anything that isn't the group Warren // hides its handshake in. func parseServerHello(body []byte) (serverRandom, serverShare []byte, err error) { - serverRandom, group, share, err := parseServerHelloParts(body) + serverRandom, group, _, share, err := parseServerHelloParts(body) if err != nil { return nil, nil, err } @@ -406,33 +418,34 @@ func parseServerHello(body []byte) (serverRandom, serverShare []byte, err error) // borrowed site: there we need to know *which* group the site actually // negotiated, because a site that doesn't offer the hybrid group cannot // plausibly be the one answering a hybrid ClientHello. -func parseServerHelloParts(body []byte) (serverRandom []byte, group uint16, share []byte, err error) { +func parseServerHelloParts(body []byte) (serverRandom []byte, group, cipherSuite uint16, share []byte, err error) { // server_hello(1) + length(3) + legacy_version(2) + random(32) + session_id_len(1) if len(body) < 39 || body[0] != 0x02 { - return nil, 0, nil, ErrBadServerHello + return nil, 0, 0, nil, ErrBadServerHello } p := body[4:] if len(p) < 35 { - return nil, 0, nil, ErrBadServerHello + return nil, 0, 0, nil, ErrBadServerHello } serverRandom = append([]byte(nil), p[2:34]...) sidLen := int(p[34]) p = p[35:] if len(p) < sidLen+2+1+2 { - return nil, 0, nil, ErrBadServerHello + return nil, 0, 0, nil, ErrBadServerHello } + cipherSuite = uint16(p[sidLen])<<8 | uint16(p[sidLen+1]) p = p[sidLen+3:] // session_id + cipher_suite(2) + compression(1) extLen := int(p[0])<<8 | int(p[1]) p = p[2:] if len(p) < extLen { - return nil, 0, nil, ErrBadServerHello + return nil, 0, 0, nil, ErrBadServerHello } for ext := p[:extLen]; len(ext) >= 4; { extType := uint16(ext[0])<<8 | uint16(ext[1]) bodyLen := int(ext[2])<<8 | int(ext[3]) if len(ext) < 4+bodyLen { - return nil, 0, nil, ErrBadServerHello + return nil, 0, 0, nil, ErrBadServerHello } payload := ext[4 : 4+bodyLen] ext = ext[4+bodyLen:] @@ -443,11 +456,11 @@ func parseServerHelloParts(body []byte) (serverRandom []byte, group uint16, shar group = uint16(payload[0])<<8 | uint16(payload[1]) shareLen := int(payload[2])<<8 | int(payload[3]) if len(payload) < 4+shareLen { - return nil, 0, nil, ErrBadServerHello + return nil, 0, 0, nil, ErrBadServerHello } - return serverRandom, group, append([]byte(nil), payload[4:4+shareLen]...), nil + return serverRandom, group, cipherSuite, append([]byte(nil), payload[4:4+shareLen]...), nil } - return nil, 0, nil, ErrBadServerHello + return nil, 0, 0, nil, ErrBadServerHello } func appendUint16(b []byte, v uint16) []byte { return append(b, byte(v>>8), byte(v)) } diff --git a/internal/network/transport/replay_test.go b/internal/network/transport/replay_test.go index 5b370fc..b8a3b1f 100644 --- a/internal/network/transport/replay_test.go +++ b/internal/network/transport/replay_test.go @@ -41,14 +41,14 @@ func TestTagStopsVerifyingOnceItsWindowPasses(t *testing.T) { minted := time.Now() copy(sessionID, deriveTag(keys.authSS, clientRandom, keys.share, tagWindowIndex(minted))) - if _, err := serverAccept(priv, clientRandom, sessionID, keys.share, minted); err != nil { + if _, err := serverAccept(priv, clientRandom, sessionID, keys.share, minted, 0); err != nil { t.Fatalf("a freshly minted tag was rejected: %v", err) } // Well past every window the relay will accept. A captured hello is now // inert on its own terms, with no cache lookup involved. late := minted.Add(tagAcceptanceSpan + 2*tagWindow) - if _, err := serverAccept(priv, clientRandom, sessionID, keys.share, late); err == nil { + if _, err := serverAccept(priv, clientRandom, sessionID, keys.share, late, 0); err == nil { t.Fatalf("a tag minted %s earlier still verified; a captured hello stays replayable forever once the cache forgets it", late.Sub(minted)) } @@ -84,7 +84,7 @@ func TestTagToleratesClockSkewWithinTheSlack(t *testing.T) { tagWindow - time.Minute, } { relayNow := base.Add(skew) - if _, err := serverAccept(priv, clientRandom, sessionID, keys.share, relayNow); err != nil { + if _, err := serverAccept(priv, clientRandom, sessionID, keys.share, relayNow, 0); err != nil { t.Errorf("a client %s out of step with the relay was refused: %v", skew, err) } }