Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 3 additions & 9 deletions handshake_client_tls13.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import (
"crypto/rsa"
"crypto/subtle"
"errors"
"fmt"
"hash"
"slices"
"time"
Expand Down Expand Up @@ -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:]...)...)
Expand Down
41 changes: 41 additions & 0 deletions u_hello_retry.go
Original file line number Diff line number Diff line change
@@ -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
}
130 changes: 130 additions & 0 deletions u_hello_retry_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
}
}
10 changes: 2 additions & 8 deletions u_parrots.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down