From 1884c595271fa145ff56dda0ba18295ccc34f867 Mon Sep 17 00:00:00 2001 From: roach Date: Thu, 22 Oct 2026 15:21:36 -0500 Subject: [PATCH] Insert the HelloRetryRequest cookie among the permutable extensions The cookie was spliced at Intn(len-2), a uniform index from zero, so about one retried handshake in the number of extensions put it ahead of the leading GREASE extension, which no browser does. On short lists the range collapsed and the cookie always went first. Pick the index between the first and last extension that is not GREASE, padding or pre_shared_key; the Chrome shuffle shares that predicate. Based on the HelloRetryRequest part of sardanioss/utls 356f21e. --- handshake_client_tls13.go | 12 +--- u_hello_retry.go | 41 ++++++++++++ u_hello_retry_test.go | 130 ++++++++++++++++++++++++++++++++++++++ u_parrots.go | 10 +-- 4 files changed, 176 insertions(+), 17 deletions(-) create mode 100644 u_hello_retry.go create mode 100644 u_hello_retry_test.go diff --git a/handshake_client_tls13.go b/handshake_client_tls13.go index 47445dd4251..cd1868a8640 100644 --- a/handshake_client_tls13.go +++ b/handshake_client_tls13.go @@ -13,7 +13,6 @@ import ( "crypto/rsa" "crypto/subtle" "errors" - "fmt" "hash" "slices" "time" @@ -410,18 +409,13 @@ func (hs *clientHandshakeStateTLS13) processHelloRetryRequest() error { } if !cookieFound { - // pick a random index where to add cookieExtension - // -2 instead of -1 is a lazy way to ensure that PSK is still a last extension + // insert the cookie among the permutable extensions, as browsers do + lo, hi := cookieSpliceRange(hs.uconn.Extensions) p, err := newPRNG() if err != nil { return err } - cookieIndex := p.Intn(len(hs.uconn.Extensions) - 2) - if cookieIndex >= len(hs.uconn.Extensions) { - // this check is for empty hs.uconn.Extensions - return fmt.Errorf("cookieIndex >= len(hs.uconn.Extensions): %v >= %v", - cookieIndex, len(hs.uconn.Extensions)) - } + cookieIndex := lo + p.Intn(hi-lo+1) hs.uconn.Extensions = append(hs.uconn.Extensions[:cookieIndex], append([]TLSExtension{&CookieExtension{Cookie: hs.serverHello.cookie}}, hs.uconn.Extensions[cookieIndex:]...)...) diff --git a/u_hello_retry.go b/u_hello_retry.go new file mode 100644 index 00000000000..f03a36aa20b --- /dev/null +++ b/u_hello_retry.go @@ -0,0 +1,41 @@ +package tls + +// positionInvariantExtension reports whether ext keeps its position when a +// browser permutes its extensions: GREASE brackets the list, padding sizes the +// record, and pre_shared_key must be last (RFC 8446, Section 4.2.11). +func positionInvariantExtension(ext TLSExtension) bool { + switch ext.(type) { + case *UtlsGREASEExtension, *UtlsPaddingExtension, PreSharedKeyExtension: + return true + default: + return false + } +} + +// cookieSpliceRange returns the inclusive range of indices at which the cookie +// echoed after a HelloRetryRequest may be inserted. BoringSSL emits the cookie +// from the same extension table as every other extension, so it lands among +// the permutable ones: after the leading pinned run (GREASE) and before the +// trailing one (GREASE, padding, pre_shared_key). +func cookieSpliceRange(exts []TLSExtension) (lo, hi int) { + first, last := -1, -1 + for i, ext := range exts { + if !positionInvariantExtension(ext) { + if first < 0 { + first = i + } + last = i + } + } + if first >= 0 { + return first, last + 1 + } + // Nothing permutable: append, but keep pre_shared_key last. + n := len(exts) + if n > 0 { + if _, ok := exts[n-1].(PreSharedKeyExtension); ok { + n-- + } + } + return n, n +} diff --git a/u_hello_retry_test.go b/u_hello_retry_test.go new file mode 100644 index 00000000000..d7ab1499eb3 --- /dev/null +++ b/u_hello_retry_test.go @@ -0,0 +1,130 @@ +package tls + +import ( + "encoding/binary" + "io" + "net" + "testing" +) + +// helloRetryWithCookie plays a server that answers the first ClientHello with a +// HelloRetryRequest carrying only a cookie, then reads the second ClientHello +// and hangs up. It returns the client's extensions as sent in that second hello. +func helloRetryWithCookie(t *testing.T, client func(net.Conn) *UConn) []TLSExtension { + t.Helper() + clientConn, serverConn := localPipe(t) + defer serverConn.Close() + uconn := client(clientConn) + done := make(chan struct{}) + go func() { + defer close(done) + uconn.Handshake() // fails once the server hangs up + }() + + readRecord := func(wantType recordType) []byte { + var hdr [recordHeaderLen]byte + if _, err := io.ReadFull(serverConn, hdr[:]); err != nil { + t.Fatalf("reading record header: %v", err) + } + body := make([]byte, binary.BigEndian.Uint16(hdr[3:])) + if _, err := io.ReadFull(serverConn, body); err != nil { + t.Fatalf("reading record body: %v", err) + } + if recordType(hdr[0]) != wantType { + t.Fatalf("record type %d, want %d", hdr[0], wantType) + } + return body + } + + var ch clientHelloMsg + if !ch.unmarshal(readRecord(recordTypeHandshake)) { + t.Fatal("malformed first ClientHello") + } + hrr, err := (&serverHelloMsg{ + vers: VersionTLS12, + random: helloRetryRequestRandom, + sessionId: ch.sessionId, + cipherSuite: TLS_AES_128_GCM_SHA256, + compressionMethod: compressionNone, + supportedVersion: VersionTLS13, + cookie: []byte("hrr-cookie"), + }).marshal() + if err != nil { + t.Fatal(err) + } + record := append([]byte{byte(recordTypeHandshake), 3, 3, 0, 0}, hrr...) + binary.BigEndian.PutUint16(record[3:], uint16(len(hrr))) + if _, err := serverConn.Write(record); err != nil { + t.Fatal(err) + } + + readRecord(recordTypeChangeCipherSpec) + if !ch.unmarshal(readRecord(recordTypeHandshake)) || string(ch.cookie) != "hrr-cookie" { + t.Fatal("second ClientHello does not echo the cookie") + } + serverConn.Close() + <-done + return uconn.Extensions +} + +func cookieIndex(t *testing.T, exts []TLSExtension) int { + t.Helper() + for i, ext := range exts { + if _, ok := ext.(*CookieExtension); ok { + return i + } + } + t.Fatal("no cookie extension in the second ClientHello") + return -1 +} + +// Browsers add the HRR cookie among the extensions they permute anyway, so it +// never precedes the leading GREASE extension or follows the trailing one. +func TestHelloRetryCookieStaysBetweenGREASE(t *testing.T) { + for range 300 { + exts := helloRetryWithCookie(t, func(c net.Conn) *UConn { + return UClient(c, &Config{ServerName: "example.com"}, HelloChrome_155) + }) + var grease []int + for i, ext := range exts { + if _, ok := ext.(*UtlsGREASEExtension); ok { + grease = append(grease, i) + } + } + if len(grease) != 2 { + t.Fatalf("want 2 GREASE extensions, got %d", len(grease)) + } + if i := cookieIndex(t, exts); i < grease[0] || i > grease[1] { + t.Fatalf("cookie at %d, outside the GREASE brackets at %d and %d", i, grease[0], grease[1]) + } + } +} + +// The old placement drew from len-2 slots, which on a short list always put +// the cookie ahead of the leading GREASE extension. +func TestHelloRetryCookieShortExtensionList(t *testing.T) { + spec := ClientHelloSpec{ + TLSVersMin: VersionTLS13, + TLSVersMax: VersionTLS13, + CipherSuites: []uint16{TLS_AES_128_GCM_SHA256}, + CompressionMethods: []uint8{compressionNone}, + Extensions: []TLSExtension{ + &UtlsGREASEExtension{}, + &SupportedVersionsExtension{Versions: []uint16{VersionTLS13}}, + &KeyShareExtension{KeyShares: []KeyShare{{Group: X25519}}}, + }, + } + for range 50 { + exts := helloRetryWithCookie(t, func(c net.Conn) *UConn { + u := UClient(c, &Config{ServerName: "example.com"}, HelloCustom) + s := spec.clone() + if err := u.ApplyPreset(s); err != nil { + t.Fatal(err) + } + return u + }) + if i := cookieIndex(t, exts); i == 0 { + t.Fatal("cookie placed ahead of the leading GREASE extension") + } + } +} diff --git a/u_parrots.go b/u_parrots.go index 41a57ba0b86..f9772fd173c 100644 --- a/u_parrots.go +++ b/u_parrots.go @@ -3020,15 +3020,9 @@ func utlsIdToSpec(id ClientHelloID) (ClientHelloSpec, error) { // // This feature was first introduced by Chrome 106. func ShuffleChromeTLSExtensions(exts []TLSExtension) []TLSExtension { - // unshufCheck checks if the exts[idx] is a GREASE/padding/pre_shared_key extension, - // and returns true on success. For these extensions are considered positionally invariant. + // GREASE, padding and pre_shared_key are positionally invariant. var skipShuf = func(idx int, exts []TLSExtension) bool { - switch exts[idx].(type) { - case *UtlsGREASEExtension, *UtlsPaddingExtension, PreSharedKeyExtension: - return true - default: - return false - } + return positionInvariantExtension(exts[idx]) } // Shuffle other extensions