diff --git a/common.go b/common.go index 868c725e07..396dc844ae 100644 --- a/common.go +++ b/common.go @@ -426,6 +426,12 @@ type ClientSessionCache interface { type SignatureScheme uint16 const ( + // ML-DSA signature scheme identifiers for ClientHello fingerprints. This fork + // does not implement ML-DSA CertificateVerify. + MLDSA44 SignatureScheme = 0x0904 + MLDSA65 SignatureScheme = 0x0905 + MLDSA87 SignatureScheme = 0x0906 + // RSASSA-PKCS1-v1_5 algorithms. PKCS1WithSHA256 SignatureScheme = 0x0401 PKCS1WithSHA384 SignatureScheme = 0x0501 diff --git a/dicttls/exttype_values.go b/dicttls/exttype_values.go index cb0ef403fc..30cbea8938 100644 --- a/dicttls/exttype_values.go +++ b/dicttls/exttype_values.go @@ -67,11 +67,12 @@ const ( // Not IANA assigned const ( - ExtType_next_protocol_negotiation uint16 = 13172 // https://datatracker.ietf.org/doc/html/draft-agl-tls-nextprotoneg-04 - ExtType_application_settings uint16 = 17513 // https://www.ietf.org/archive/id/draft-vvv-tls-alps-01.html - ExtType_application_settings_new uint16 = 17613 // https://www.ietf.org/archive/id/draft-vvv-tls-alps-01.html - ExtType_channel_id_old uint16 = 30031 // https://datatracker.ietf.org/doc/html/draft-balfanz-tls-channelid-01 - ExtType_channel_id uint16 = 30032 // https://datatracker.ietf.org/doc/html/draft-balfanz-tls-channelid-01 + ExtType_next_protocol_negotiation uint16 = 13172 // https://datatracker.ietf.org/doc/html/draft-agl-tls-nextprotoneg-04 + ExtType_application_settings uint16 = 17513 // https://www.ietf.org/archive/id/draft-vvv-tls-alps-01.html + ExtType_application_settings_new uint16 = 17613 // https://www.ietf.org/archive/id/draft-vvv-tls-alps-01.html + ExtType_channel_id_old uint16 = 30031 // https://datatracker.ietf.org/doc/html/draft-balfanz-tls-channelid-01 + ExtType_channel_id uint16 = 30032 // https://datatracker.ietf.org/doc/html/draft-balfanz-tls-channelid-01 + ExtType_trust_anchors uint16 = 0xca34 // draft-ietf-tls-trust-anchor-ids ) var DictExtTypeValueIndexed = map[uint16]string{ @@ -135,11 +136,12 @@ var DictExtTypeValueIndexed = map[uint16]string{ 59: "dnssec_chain", 65281: "renegotiation_info", - 13172: "next_protocol_negotiation", - 17513: "application_settings", - 17613: "application_settings_new", - 30031: "channel_id_old", - 30032: "channel_id", + 13172: "next_protocol_negotiation", + 17513: "application_settings", + 17613: "application_settings_new", + 30031: "channel_id_old", + 30032: "channel_id", + 0xca34: "trust_anchors", } var DictExtTypeNameIndexed = map[string]uint16{ @@ -209,4 +211,5 @@ var DictExtTypeNameIndexed = map[string]uint16{ "application_settings_new": 17613, "channel_id_old": 30031, "channel_id": 30032, + "trust_anchors": 0xca34, } diff --git a/dicttls/signaturescheme.go b/dicttls/signaturescheme.go index d0b9803f8e..70e5e3dc50 100644 --- a/dicttls/signaturescheme.go +++ b/dicttls/signaturescheme.go @@ -38,6 +38,9 @@ const ( SigScheme_ecdsa_brainpoolP256r1tls13_sha256 uint16 = 0x081A SigScheme_ecdsa_brainpoolP384r1tls13_sha384 uint16 = 0x081B SigScheme_ecdsa_brainpoolP512r1tls13_sha512 uint16 = 0x081C + SigScheme_mldsa44 uint16 = 0x0904 + SigScheme_mldsa65 uint16 = 0x0905 + SigScheme_mldsa87 uint16 = 0x0906 ) var DictSignatureSchemeValueIndexed = map[uint16]string{ @@ -75,6 +78,9 @@ var DictSignatureSchemeValueIndexed = map[uint16]string{ 0x081A: "ecdsa_brainpoolP256r1tls13_sha256", 0x081B: "ecdsa_brainpoolP384r1tls13_sha384", 0x081C: "ecdsa_brainpoolP512r1tls13_sha512", + 0x0904: "mldsa44", + 0x0905: "mldsa65", + 0x0906: "mldsa87", } var DictSignatureSchemeNameIndexed = map[string]uint16{ @@ -113,4 +119,7 @@ var DictSignatureSchemeNameIndexed = map[string]uint16{ "ecdsa_brainpoolP256r1tls13_sha256": 0x081A, "ecdsa_brainpoolP384r1tls13_sha384": 0x081B, "ecdsa_brainpoolP512r1tls13_sha512": 0x081C, + "mldsa44": 0x0904, + "mldsa65": 0x0905, + "mldsa87": 0x0906, } diff --git a/testdata/chrome158_clienthello.hex b/testdata/chrome158_clienthello.hex new file mode 100644 index 0000000000..342999a9ae --- /dev/null +++ b/testdata/chrome158_clienthello.hex @@ -0,0 +1 @@ +16030107e1010007dd030348e79bda9f595ee8ff4eb3beb8718ee7e46e97ff3cf90bb87d0ad022dfddd3c120afa25c61a3a222942d3bf31436aa3b4bad732d67a562175dd8e3aa44e4be51660020aaaa130113021303c02bc02fc02cc030cca9cca8c013c014009c009d002f0035010007749a9a000000050005010000000044cd00050003026832000b0002010000170000001b0003020002000a000c000aeaea11ec001d0017001800000011000f00000c636170747572652e74657374000d001a00184a4a09040905090604030804040105030805050108060601002d00020101002b000706fafa030403030023000000120000ca3400ba00b80582df1302010582df1302060582df13020d0582df13020e0582df13020f0582df1302120582df1302130582df13021408839a648c9b2d010708839a648c9b2d010808839a648c9b2d010908839a648c9b2d010a08839a648c9b2d010b08839a648c9b2d010c08839a648c9b2d010d08839a648c9b2d011208839a648c9b2d011304d679090104d679090404d679090504d679090604d679090704d679090804d679090a04d679090b04d679090c04d679090d04d679090ffe0d011a0000010001e300204d69015977434dc24a9fd0bd97c636114db6e30eb2e06d3a87df259f4ef3d66000f037cc4bc95cf716c604cb81b6dfc6a56957ec64640de326781efba4e130ac26fb22b20d5ad6140a6105599e0d362f5719b0f81f1dd23a6329930e51232a3f0dfb183870a7ce5fd042d0219400f2827023b2a75543ab56c2cec7ab0732928cd39b9122fc3fef2da6f9db4b92823b49c1e746fd5bf7a4b224a978c97906e4cc0050f031f341e5bc309cc1d68f64d133adb52d339842a0ef98e071d8c457e47370ef320fb6665903d6baad67930a9dd2463ec67972a281a288daedfb31ea01d7596f994542e97eb92f9838cf7d20370d724f92e44ec0553f03ebeec2370c3b1be2a114a1486a59295d2517dc119f6f7311f6ff010001000010000e000c02683208687474702f312e3112e000020000003304ef04edeaea00010011ec04c0c4b11dd8c72f6a93749a34b8a848264029a5217ac0537678b18b73243c1642ea3dbd322241175c98f73d3b6b4e4eca9d0b7c42b4aaacc0d600bdd20be8a6a1c160a3d560751d063e7a7493da0c7b28e428a5665ad082b93af842e8d0797e4567ab047cf8cac7244ac81a5524a1e60f6c49c889602cb9066f62b9b222fb8ada304fdde6be3e4b78132a45166661a6d76f4dd1599ad80ed0506697634ac2874bdd22bf30bb71c646c909f83694f47956c465e8e9b7bdc5593ee22d28db23ae95acf818af83851615798e5580241e4a38c37a44e667201e44485ea746ef22a4feb614118b6687e20bcd7917ae63b1935134c4d9ac772842fd42546346a393ea20a007c523dc2a4337ae02856129c405e60a51a1dab4ac292a644645ee1b96597c354e004877814af122751e538a0c851e246663cca60b7d59462e0cc27e7643b5b71a8f626a3d8265793c9461d853458715d4fc58f1f65ff2cb5a22dbc4b9848c30b90e27d5377c89c024709f68ba75fc94671a6b7e7ed367cba51c09dc008bc2a56ce216ec758e4a4a99d8db38270578fe242ce3ec41e06676a8961900bac5537a8da5bb3310c012e6538df8f6cf590ca54f748615c779336abcf0d53216260228e53b27a2a20a5939a873a2da75a7c2372e44a71f5228556c20410ec61d57fb2906da4a10f203f5f18542932f9a62bf344a3e08127c37e5c75e565126090cc2e08466da5423d4c1f44845664594d7fc343f325b6de50bc1d10d803131040516cebb8e29248852840cf118302fd768ba8677b0dcccce209ed2c31441bc0e6379c4c1b65ef17283aa36368df64b95c0701d626295eb0eae343098f1284ce0cde2b63da75b014dd418ea53a9f408822c8710a8c35ec5d91bdec5428d11c6c7191961525d76a4a80f9a9394fcca0278ac73844a46dbb878b98f99cb672710719d9b918c6ba1063a3bcff28b3f79051931494b52394255b1f3e94a49eb296b020cde561caea6bbcc6a64c41a9e1b8a528675bb86267cd0c9906d756e395837c680c0583357e5cacbd0f6291be1a1368c8bf494051040aa4657ac225857c5254bc47b9fd1949d3b38481579a42f24b9ff6519cc8c2d734012be278aa924c7c82125cd2a86d96860125a4d8ba6546ae00674031d069019cbf39bf72cb7b01084f3271113638822a380ece5420d609d191b8e9ee49f8b02428c5ac3cddcbaddc32aec746419cca796039bd7c38131898483485208540b85c34bcf66029aabb3ca244d0fd6c2ee2aa383ba344529593fcb6c3675cfa5216efac55d602260e6fc6ab98073bae400a42a37258164b799671c5080e8dc5cbacc0a028cc0ee607d75063a62b70c5ddc739cb18fd4f33cc4d81e3333ba5d384c0e8b98dc9208b1c368c4ea89b54640fb2b1b7315ac5e9bc6ef7b9e59ab2c808040a4fcc2f28776fb5ac12f61bf9b3acb919c71aba47bf82897195849ed75164ec50f79a697c7a31562acc29dd369cb85457545ae46fb11aecc80773aa2e4c11b4a34057c03530a9919e91c699a3bb472d9bc0f50a60ae99b3d065421f001e7b92b7f5aa57631a795c46f1b5cb72ee566c7b53c4040c314c149de73746bf714ec818a7fc470fe3a25dbe2cdaec18537f606bba22bc17598b2220e792f14851f2f6a147bb768bc0698990799bd58506b138a94fc2a9b38685c0fe4d01c4cc3e4746aaca75a1dfaa0a72429ddba406c001d0020b242d39bbb360c21fb06e4995ebf90a18a074670d423b5866e36140da1215520caca000100 diff --git a/testdata/chrome158_clienthello.md b/testdata/chrome158_clienthello.md new file mode 100644 index 0000000000..e9c31435fa --- /dev/null +++ b/testdata/chrome158_clienthello.md @@ -0,0 +1,9 @@ +# Chrome 158 ClientHello + +The fixture is the first TLS record sent by Chrome for Testing Stable 158.0.8127.88 for Windows x64 to `https://capture.test`. The browser ran headless with a fresh user-data directory, a loopback host resolver rule and no proxy. Three independently launched profiles offered the same ordered capabilities and extension bodies after normalization. The TLS record contains only the public ClientHello. + +The regression test compares the entire ClientHello, allowing fresh randomness, GREASE values, ephemeral keys, GREASE ECH payload sizes, and shuffled extension order. A fresh connection from installed Google Chrome 158.0.8127.37 on the same host matched the other capabilities but omitted the experimental server padding request (0x12e0). Trust anchor IDs are a snapshot of the browser's root store. + +Select `HelloChrome_158` explicitly. This fork advertises the browser's ML-DSA scheme IDs in this profile and verifies conventional certificate signatures. If a server selects ML-DSA for CertificateVerify the handshake fails. The profile does not install Chrome's trust roots. + +[Chrome for Testing build](https://googlechromelabs.github.io/chrome-for-testing/known-good-versions-with-downloads.json) ยท [Upstream Chrome 155 implementation](https://github.com/refraction-networking/utls/commit/6ebdceb2607e8c72942805af16ed4b8f052ee509) diff --git a/u_chrome158.go b/u_chrome158.go new file mode 100644 index 0000000000..699b0074c0 --- /dev/null +++ b/u_chrome158.go @@ -0,0 +1,38 @@ +package tls + +// chrome158TrustAnchorIDs returns the Chrome Root Store IDs advertised by a fresh +// Google Chrome 158.0.8127.88 (Windows x64) connection. Chrome encodes the IDs in +// lexicographic order. Return fresh slices because ClientHelloSpec is mutable. +// Source: https://chromium.googlesource.com/chromium/src/+/refs/tags/158.0.8127.88/net/data/ssl/chrome_root_store/root_store.textproto +func chrome158TrustAnchorIDs() [][]byte { + return [][]byte{ + {0x82, 0xdf, 0x13, 0x02, 0x01}, + {0x82, 0xdf, 0x13, 0x02, 0x06}, + {0x82, 0xdf, 0x13, 0x02, 0x0d}, + {0x82, 0xdf, 0x13, 0x02, 0x0e}, + {0x82, 0xdf, 0x13, 0x02, 0x0f}, + {0x82, 0xdf, 0x13, 0x02, 0x12}, + {0x82, 0xdf, 0x13, 0x02, 0x13}, + {0x82, 0xdf, 0x13, 0x02, 0x14}, + {0x83, 0x9a, 0x64, 0x8c, 0x9b, 0x2d, 0x01, 0x07}, + {0x83, 0x9a, 0x64, 0x8c, 0x9b, 0x2d, 0x01, 0x08}, + {0x83, 0x9a, 0x64, 0x8c, 0x9b, 0x2d, 0x01, 0x09}, + {0x83, 0x9a, 0x64, 0x8c, 0x9b, 0x2d, 0x01, 0x0a}, + {0x83, 0x9a, 0x64, 0x8c, 0x9b, 0x2d, 0x01, 0x0b}, + {0x83, 0x9a, 0x64, 0x8c, 0x9b, 0x2d, 0x01, 0x0c}, + {0x83, 0x9a, 0x64, 0x8c, 0x9b, 0x2d, 0x01, 0x0d}, + {0x83, 0x9a, 0x64, 0x8c, 0x9b, 0x2d, 0x01, 0x12}, + {0x83, 0x9a, 0x64, 0x8c, 0x9b, 0x2d, 0x01, 0x13}, + {0xd6, 0x79, 0x09, 0x01}, + {0xd6, 0x79, 0x09, 0x04}, + {0xd6, 0x79, 0x09, 0x05}, + {0xd6, 0x79, 0x09, 0x06}, + {0xd6, 0x79, 0x09, 0x07}, + {0xd6, 0x79, 0x09, 0x08}, + {0xd6, 0x79, 0x09, 0x0a}, + {0xd6, 0x79, 0x09, 0x0b}, + {0xd6, 0x79, 0x09, 0x0c}, + {0xd6, 0x79, 0x09, 0x0d}, + {0xd6, 0x79, 0x09, 0x0f}, + } +} diff --git a/u_chrome158_test.go b/u_chrome158_test.go new file mode 100644 index 0000000000..74c442dbb8 --- /dev/null +++ b/u_chrome158_test.go @@ -0,0 +1,384 @@ +// Copyright 2026 The uTLS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package tls + +import ( + "bytes" + "encoding/hex" + "fmt" + + "io" + "net" + "os" + "reflect" + "sort" + "strings" + "testing" + + "golang.org/x/exp/slices" +) + +// This parser is deliberately independent of Fingerprinter: comparing the +// captured browser bytes against generated bytes must not hide a parser bug. +// Only extension permutation, GREASE codepoints, ephemeral public keys, and +// GREASE ECH randomness are normalized. Ordered capability lists and trust +// anchor IDs retain their original order and bytes. +type chrome158WireHello struct { + Version uint16 + RandomLength int + SessionIDLength int + CipherSuites []uint16 + CompressionMethods []byte + Extensions map[uint16][]string +} + +type chrome158Reader struct { + t *testing.T + b []byte + label string +} + +func (r *chrome158Reader) take(n int) []byte { + r.t.Helper() + if n < 0 || n > len(r.b) { + r.t.Fatalf("%s: truncated field: need %d bytes, have %d", r.label, n, len(r.b)) + } + b := r.b[:n] + r.b = r.b[n:] + return b +} + +func (r *chrome158Reader) number(n int) int { + r.t.Helper() + v := 0 + for _, b := range r.take(n) { + v = v<<8 | int(b) + } + return v +} + +func (r *chrome158Reader) vector(n int) []byte { + r.t.Helper() + return r.take(r.number(n)) +} + +func (r *chrome158Reader) end() { + r.t.Helper() + if len(r.b) != 0 { + r.t.Fatalf("%s: %d trailing bytes", r.label, len(r.b)) + } +} + +func chrome158NormalizeGREASE(v uint16) uint16 { + if isGREASEUint16(v) { + return GREASE_PLACEHOLDER + } + return v +} + +func chrome158Uint16s(t *testing.T, b []byte) []uint16 { + t.Helper() + if len(b)%2 != 0 { + t.Fatalf("odd uint16 vector length: %d", len(b)) + } + out := make([]uint16, len(b)/2) + for i := range out { + out[i] = chrome158NormalizeGREASE(uint16(b[2*i])<<8 | uint16(b[2*i+1])) + } + return out +} + +func chrome158NormalizeExtension(t *testing.T, id uint16, body []byte) string { + t.Helper() + r := chrome158Reader{t, body, fmt.Sprintf("extension %#04x", id)} + var value string + switch id { + case 10, 13: // supported_groups, signature_algorithms + value = fmt.Sprint(chrome158Uint16s(t, r.vector(2))) + case 43: // supported_versions + value = fmt.Sprint(chrome158Uint16s(t, r.vector(1))) + case 51: // key_share + shares := chrome158Reader{t, r.vector(2), "key_share entries"} + var entries []string + for len(shares.b) > 0 { + group := uint16(shares.number(2)) + key := shares.vector(2) + entry := fmt.Sprintf("%04x/%d", chrome158NormalizeGREASE(group), len(key)) + if isGREASEUint16(group) { + entry += "/" + hex.EncodeToString(key) + } + entries = append(entries, entry) + } + value = strings.Join(entries, ",") + case 0xfe0d: // GREASE encrypted_client_hello + outer, kdf, aead := r.number(1), r.number(2), r.number(2) + r.take(1) // randomized config_id + enc, payload := r.vector(2), r.vector(2) + if outer != 0 || !slices.Contains([]int{144, 176, 208, 240}, len(payload)) { + t.Fatalf("unexpected GREASE ECH shape: outer=%d, payload length=%d", outer, len(payload)) + } + value = fmt.Sprintf("%d/%d/%d/enc=%d/payload=144,176,208,240", outer, kdf, aead, len(enc)) + case 0xca34: // trust_anchors + ids := chrome158Reader{t, r.vector(2), "trust anchor IDs"} + for len(ids.b) > 0 { + if len(ids.vector(1)) == 0 { + t.Fatal("empty trust anchor ID in fixture") + } + } + value = hex.EncodeToString(body) + default: + value = hex.EncodeToString(r.take(len(r.b))) + } + r.end() + return value +} + +func chrome158ParseWire(t *testing.T, data []byte) (chrome158WireHello, []uint16, map[uint16][]byte) { + t.Helper() + r := chrome158Reader{t, data, "ClientHello"} + if len(data) > 0 && data[0] == byte(recordTypeHandshake) { + if r.number(1) != int(recordTypeHandshake) || r.number(2) != int(VersionTLS10) { + t.Fatal("unexpected ClientHello TLS record header") + } + record := r.vector(2) + r.end() + r = chrome158Reader{t, record, "ClientHello handshake"} + } + if r.number(1) != 1 { + t.Fatal("fixture is not a ClientHello") + } + body := r.vector(3) + r.end() + r = chrome158Reader{t, body, "ClientHello body"} + version := uint16(r.number(2)) + random := r.take(32) + sid := r.vector(1) + ciphers := chrome158Uint16s(t, r.vector(2)) + compression := bytes.Clone(r.vector(1)) + extensions := r.vector(2) + r.end() + out := chrome158WireHello{version, len(random), len(sid), ciphers, compression, make(map[uint16][]string)} + r = chrome158Reader{t, extensions, "ClientHello extensions"} + seen, raw := make(map[uint16]bool), make(map[uint16][]byte) + var order []uint16 + for len(r.b) > 0 { + id := uint16(r.number(2)) + body := r.vector(2) + if seen[id] { + t.Fatalf("duplicate extension %#04x", id) + } + seen[id] = true + raw[id] = bytes.Clone(body) + normalizedID := chrome158NormalizeGREASE(id) + order = append(order, normalizedID) + out.Extensions[normalizedID] = append(out.Extensions[normalizedID], chrome158NormalizeExtension(t, id, body)) + } + for _, values := range out.Extensions { + sort.Strings(values) // distinguish the two GREASE bodies independently of their values + } + return out, order, raw +} + +func chrome158Fixture(t *testing.T) []byte { + t.Helper() + text, err := os.ReadFile("testdata/chrome158_clienthello.hex") + if err != nil { + t.Fatal(err) + } + data, err := hex.DecodeString(strings.Join(strings.Fields(string(text)), "")) + if err != nil { + t.Fatal(err) + } + return data +} + +func chrome158FixtureServerName(t *testing.T, raw map[uint16][]byte) string { + t.Helper() + r := chrome158Reader{t, raw[0], "server_name"} + names := chrome158Reader{t, r.vector(2), "server_name list"} + r.end() + if names.number(1) != 0 { + t.Fatal("fixture SNI is not a host name") + } + name := string(names.vector(2)) + names.end() + return name +} + +func chrome158Build(t *testing.T, id ClientHelloID, serverName string, spec *ClientHelloSpec) *UConn { + t.Helper() + client := UClient(&net.TCPConn{}, &Config{ServerName: serverName, ClientSessionCache: nil}, id) + if spec != nil { + if err := client.ApplyPreset(spec); err != nil { + t.Fatal(err) + } + } + if err := client.BuildHandshakeState(); err != nil { + t.Fatal(err) + } + return client +} + +func chrome158CompareWire(t *testing.T, want, got chrome158WireHello) { + t.Helper() + if !reflect.DeepEqual(got, want) { + t.Errorf("generated ClientHello differs from fresh Chrome 158 capture:\n got: %+v\nwant: %+v", got, want) + } +} + +func TestChrome158CapturedClientHello(t *testing.T) { + if HelloChrome_Auto != HelloChrome_133 { + t.Fatalf("HelloChrome_Auto = %s, want %s", HelloChrome_Auto.Str(), HelloChrome_133.Str()) + } + want, _, captured := chrome158ParseWire(t, chrome158Fixture(t)) + client := chrome158Build(t, HelloChrome_158, chrome158FixtureServerName(t, captured), nil) + got, _, generated := chrome158ParseWire(t, client.HandshakeState.Hello.Raw) + chrome158CompareWire(t, want, got) + if ticket, ok := generated[35]; !ok || len(ticket) != 0 { + t.Fatal("fresh profile must advertise an empty session_ticket extension") + } + if _, ok := generated[41]; ok { + t.Fatal("fresh profile unexpectedly offers pre_shared_key") + } +} + +func TestChrome158DefaultFingerprintRoundTrip(t *testing.T) { + fixture := chrome158Fixture(t) + want, wantOrder, raw := chrome158ParseWire(t, fixture) + spec, err := (&Fingerprinter{}).FingerprintClientHello(fixture) + if err != nil { + t.Fatalf("default Fingerprinter must parse captured Chrome 158 ClientHello: %v", err) + } + client := chrome158Build(t, HelloCustom, chrome158FixtureServerName(t, raw), spec) + got, gotOrder, _ := chrome158ParseWire(t, client.HandshakeState.Hello.Raw) + chrome158CompareWire(t, want, got) + if !slices.Equal(gotOrder, wantOrder) { + t.Errorf("fingerprint roundtrip reordered extensions: got %x, want %x", gotOrder, wantOrder) + } + if chrome158TrustAnchors(t, spec.Extensions) == nil { + t.Fatal("fingerprinted trust anchors must use the typed extension") + } +} + +func chrome158TrustAnchors(t *testing.T, extensions []TLSExtension) *TrustAnchorsExtension { + t.Helper() + for _, extension := range extensions { + if anchors, ok := extension.(*TrustAnchorsExtension); ok { + return anchors + } + } + t.Fatal("missing typed trust_anchors extension") + return nil +} + +func TestChrome158PresetOwnership(t *testing.T) { + spec, err := UTLSIdToSpec(HelloChrome_158) + if err != nil { + t.Fatal(err) + } + before := spec.clone() + first := chrome158Build(t, HelloCustom, "example.com", &spec) + second := chrome158Build(t, HelloCustom, "example.com", &spec) + if !reflect.DeepEqual(&spec, before) { + t.Fatal("ApplyPreset mutated the reusable Chrome 158 preset") + } + anchors := chrome158TrustAnchors(t, first.Extensions) + if len(anchors.TrustAnchorIDs) == 0 || len(anchors.TrustAnchorIDs[0]) == 0 { + t.Fatal("Chrome 158 capture must contain trust anchor IDs") + } + anchors.TrustAnchorIDs[0][0] ^= 0xff + for _, extension := range first.Extensions { + switch extension := extension.(type) { + case *SignatureAlgorithmsExtension: + extension.SupportedSignatureAlgorithms[0] = PKCS1WithSHA1 + case *SupportedCurvesExtension: + extension.Curves[0] = CurveP384 + } + } + first.HandshakeState.Hello.CipherSuites[0] = TLS_RSA_WITH_AES_256_CBC_SHA + if !reflect.DeepEqual(&spec, before) { + t.Fatal("connection mutations leaked into the reusable Chrome 158 preset") + } + wantAnchors := chrome158TrustAnchors(t, before.Extensions).TrustAnchorIDs + if !reflect.DeepEqual(chrome158TrustAnchors(t, second.Extensions).TrustAnchorIDs, wantAnchors) { + t.Fatal("nested trust anchor mutations leaked between connections") + } + later, err := UTLSIdToSpec(HelloChrome_158) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(chrome158TrustAnchors(t, later.Extensions).TrustAnchorIDs, wantAnchors) { + t.Fatal("trust anchor mutations leaked into future preset instances") + } +} + +func TestChrome158SignatureGREASESeed(t *testing.T) { + client := UClient(&net.TCPConn{}, &Config{ + ServerName: "example.com", + Rand: bytes.NewReader(bytes.Repeat([]byte{0xa1}, 8192)), + }, HelloChrome_158) + if err := client.BuildHandshakeState(); err != nil { + t.Fatal(err) + } + // BoringSSL reserves seed slot 7 for signature algorithms, independently + // of the cipher, group, extension, and version GREASE slots. + const signatureSeedSlot = 7 + seed := client.greaseSeed[signatureSeedSlot] + want := (seed & 0xf0) | 0x0a + want |= want << 8 + if want == GREASE_PLACEHOLDER { + t.Fatal("deterministic test seed must distinguish generated GREASE from the placeholder") + } + _, _, raw := chrome158ParseWire(t, client.HandshakeState.Hello.Raw) + r := chrome158Reader{t, raw[13], "signature_algorithms"} + signatures := chrome158Reader{t, r.vector(2), "signature schemes"} + r.end() + got := uint16(signatures.number(2)) + if got != want || got == GREASE_PLACEHOLDER { + t.Fatalf("signature GREASE = %#04x, want %#04x from BoringSSL seed slot 7", got, want) + } + if gotState := uint16(client.HandshakeState.Hello.SupportedSignatureAlgorithms[0]); gotState != want { + t.Fatalf("signature GREASE in handshake state = %#04x, want %#04x", gotState, want) + } +} + +func TestChrome133CapabilitiesPreserved(t *testing.T) { + client := chrome158Build(t, HelloChrome_133, "example.com", nil) + _, _, raw := chrome158ParseWire(t, client.HandshakeState.Hello.Raw) + r := chrome158Reader{t, raw[13], "Chrome 133 signature_algorithms"} + got := chrome158Uint16s(t, r.vector(2)) + r.end() + want := []uint16{ + uint16(ECDSAWithP256AndSHA256), uint16(PSSWithSHA256), uint16(PKCS1WithSHA256), + uint16(ECDSAWithP384AndSHA384), uint16(PSSWithSHA384), uint16(PKCS1WithSHA384), + uint16(PSSWithSHA512), uint16(PKCS1WithSHA512), + } + if !slices.Equal(got, want) { + t.Fatalf("Chrome 133 signature schemes changed: got %x, want original classical schemes %x", got, want) + } + if _, ok := raw[0xca34]; ok { + t.Fatal("Chrome 158 trust anchor IDs leaked into the Chrome 133 profile") + } +} + +func TestServerPaddingRequest(t *testing.T) { + ext := &FakeServerPaddingExtension{} + for _, body := range [][]byte{nil, {0}, {0, 1, 2}} { + if _, err := ext.Write(body); err == nil { + t.Fatalf("accepted malformed server padding request %x", body) + } + } + if _, err := ext.Write([]byte{0x12, 0x34}); err != nil { + t.Fatal(err) + } + if _, err := ext.Read(make([]byte, ext.Len()-1)); err != io.ErrShortBuffer { + t.Fatalf("short buffer: %v", err) + } + got := make([]byte, ext.Len()) + n, err := ext.Read(got) + if err != io.EOF || n != len(got) || !bytes.Equal(got, []byte{0x12, 0xe0, 0, 2, 0x12, 0x34}) { + t.Fatalf("server padding encoding: %x, %d, %v", got, n, err) + } +} diff --git a/u_common.go b/u_common.go index 770507c6a1..ab778f3b97 100644 --- a/u_common.go +++ b/u_common.go @@ -41,6 +41,8 @@ const ( utlsFakeExtensionCustom uint16 = 1234 // not IANA assigned, for ALPS utlsExtensionECH uint16 = 0xfe0d // draft-ietf-tls-esni-17 utlsExtensionECHOuterExtensions uint16 = 0xfd00 // draft-ietf-tls-esni-17 + utlsExtensionTrustAnchors uint16 = 0xca34 // draft-ietf-tls-trust-anchor-ids + utlsExtensionServerPadding uint16 = 0x12e0 // BoringSSL server handshake padding experiment // extensions with 'fake' prefix break connection, if server echoes them back fakeExtensionEncryptThenMAC uint16 = 22 @@ -645,6 +647,9 @@ var ( HelloChrome_131 = ClientHelloID{helloChrome, "131", nil, nil} // Chrome w/ New ALPS codepoint HelloChrome_133 = ClientHelloID{helloChrome, "133", nil, nil} + // Chrome 158.0.8127.88 on Windows x64, with ML-DSA signatures and a snapshot of + // the Chrome Root Store trust anchor IDs. See testdata/chrome158_clienthello.md. + HelloChrome_158 = ClientHelloID{helloChrome, "158", nil, nil} HelloIOS_Auto = HelloIOS_14 HelloIOS_11_1 = ClientHelloID{helloIOS, "111", nil, nil} // legacy "111" means 11.1 diff --git a/u_conn.go b/u_conn.go index 08c044d6b2..3a3b34255a 100644 --- a/u_conn.go +++ b/u_conn.go @@ -38,7 +38,7 @@ type UConn struct { HandshakeState PubClientHandshakeState - greaseSeed [ssl_grease_last_index]uint16 + greaseSeed [ssl_grease_seed_count]uint16 omitSNIExtension bool diff --git a/u_grease_api_test.go b/u_grease_api_test.go new file mode 100644 index 0000000000..d2088bb628 --- /dev/null +++ b/u_grease_api_test.go @@ -0,0 +1,21 @@ +package tls_test + +import ( + "testing" + + tls "github.com/metacubex/utls" +) + +// The public helper's five-element array remains source-compatible when the +// internal GREASE seed gains slots for additional ClientHello fields. +var _ func([5]uint16, int) uint16 = tls.GetBoringGREASEValue + +func TestBoringGREASEPublicAPI(t *testing.T) { + seed := [5]uint16{0x0000, 0x0012, 0x0080, 0x00f0, 0xffe1} + want := [5]uint16{0x0a0a, 0x1a1a, 0x8a8a, 0xfafa, 0xeaea} + for i, expected := range want { + if got := tls.GetBoringGREASEValue(seed, i); got != expected { + t.Fatalf("GREASE index %d = %#04x; want %#04x", i, got, expected) + } + } +} diff --git a/u_mldsa_json_test.go b/u_mldsa_json_test.go new file mode 100644 index 0000000000..235d89e1db --- /dev/null +++ b/u_mldsa_json_test.go @@ -0,0 +1,56 @@ +package tls + +import ( + "encoding/json" + "fmt" + + "testing" + + "golang.org/x/exp/slices" + + "github.com/metacubex/utls/dicttls" +) + +func TestMLDSASignatureSchemeJSON(t *testing.T) { + for _, tc := range []struct { + name string + scheme SignatureScheme + }{ + {"mldsa44", MLDSA44}, + {"mldsa65", MLDSA65}, + {"mldsa87", MLDSA87}, + } { + if got := dicttls.DictSignatureSchemeNameIndexed[tc.name]; got != uint16(tc.scheme) { + t.Fatalf("signature scheme %s = %#04x, want %#04x", tc.name, got, tc.scheme) + } + if got := dicttls.DictSignatureSchemeValueIndexed[uint16(tc.scheme)]; got != tc.name { + t.Fatalf("signature scheme %#04x = %s, want %s", tc.scheme, got, tc.name) + } + } + for _, name := range []string{"signature_algorithms", "signature_algorithms_cert"} { + t.Run(name, func(t *testing.T) { + data := fmt.Sprintf(`[{"name":%q,"supported_signature_algorithms":["GREASE","mldsa44","mldsa65","mldsa87"]}]`, name) + var extensions TLSExtensionsJSONUnmarshaler + if err := json.Unmarshal([]byte(data), &extensions); err != nil { + t.Fatal(err) + } + exts := extensions.Extensions() + if len(exts) != 1 { + t.Fatalf("parsed %d extensions, want 1", len(exts)) + } + var got []SignatureScheme + switch ext := exts[0].(type) { + case *SignatureAlgorithmsExtension: + got = ext.SupportedSignatureAlgorithms + case *SignatureAlgorithmsCertExtension: + got = ext.SupportedSignatureAlgorithms + default: + t.Fatalf("unexpected extension type %T", ext) + } + want := []SignatureScheme{GREASE_PLACEHOLDER, MLDSA44, MLDSA65, MLDSA87} + if !slices.Equal(got, want) { + t.Fatalf("signature algorithms = %x, want %x", got, want) + } + }) + } +} diff --git a/u_parrots.go b/u_parrots.go index 425ab6ddda..4e8f951690 100644 --- a/u_parrots.go +++ b/u_parrots.go @@ -964,6 +964,85 @@ func utlsIdToSpec(id ClientHelloID) (ClientHelloSpec, error) { &UtlsGREASEExtension{}, }), }, nil + case HelloChrome_158: + return ClientHelloSpec{ + CipherSuites: []uint16{ + GREASE_PLACEHOLDER, + TLS_AES_128_GCM_SHA256, + TLS_AES_256_GCM_SHA384, + TLS_CHACHA20_POLY1305_SHA256, + TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, + TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, + TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, + TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, + TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, + TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, + TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, + TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, + TLS_RSA_WITH_AES_128_GCM_SHA256, + TLS_RSA_WITH_AES_256_GCM_SHA384, + TLS_RSA_WITH_AES_128_CBC_SHA, + TLS_RSA_WITH_AES_256_CBC_SHA, + }, + CompressionMethods: []byte{ + 0x00, // compressionNone + }, + Extensions: ShuffleChromeTLSExtensions([]TLSExtension{ + &UtlsGREASEExtension{}, + &SNIExtension{}, + &ExtendedMasterSecretExtension{}, + &RenegotiationInfoExtension{Renegotiation: RenegotiateOnceAsClient}, + &SupportedCurvesExtension{[]CurveID{ + GREASE_PLACEHOLDER, + X25519MLKEM768, + X25519, + CurveP256, + CurveP384, + }}, + &SupportedPointsExtension{SupportedPoints: []byte{ + 0x00, // pointFormatUncompressed + }}, + &SessionTicketExtension{}, + &ALPNExtension{AlpnProtocols: []string{"h2", "http/1.1"}}, + &StatusRequestExtension{}, + &SignatureAlgorithmsExtension{SupportedSignatureAlgorithms: []SignatureScheme{ + GREASE_PLACEHOLDER, + MLDSA44, + MLDSA65, + MLDSA87, + ECDSAWithP256AndSHA256, + PSSWithSHA256, + PKCS1WithSHA256, + ECDSAWithP384AndSHA384, + PSSWithSHA384, + PKCS1WithSHA384, + PSSWithSHA512, + PKCS1WithSHA512, + }}, + &SCTExtension{}, + &KeyShareExtension{[]KeyShare{ + {Group: CurveID(GREASE_PLACEHOLDER), Data: []byte{0}}, + {Group: X25519MLKEM768}, + {Group: X25519}, + }}, + &PSKKeyExchangeModesExtension{[]uint8{ + PskModeDHE, + }}, + &SupportedVersionsExtension{[]uint16{ + GREASE_PLACEHOLDER, + VersionTLS13, + VersionTLS12, + }}, + &UtlsCompressCertExtension{[]CertCompressionAlgo{ + CertCompressionBrotli, + }}, + &ApplicationSettingsExtensionNew{SupportedProtocols: []string{"h2"}}, + &TrustAnchorsExtension{TrustAnchorIDs: chrome158TrustAnchorIDs()}, + &FakeServerPaddingExtension{}, + BoringGREASEECH(), + &UtlsGREASEExtension{}, + }), + }, nil case HelloFirefox_55, HelloFirefox_56: return ClientHelloSpec{ TLSVersMax: VersionTLS12, @@ -3064,7 +3143,7 @@ func (uconn *UConn) ApplyPreset(p *ClientHelloSpec) error { } // Currently, GREASE is assumed to come from BoringSSL - grease_bytes := make([]byte, 2*ssl_grease_last_index) + grease_bytes := make([]byte, 2*ssl_grease_seed_count) grease_extensions_seen := 0 _, err = io.ReadFull(uconn.config.rand(), grease_bytes) if err != nil { @@ -3073,7 +3152,7 @@ func (uconn *UConn) ApplyPreset(p *ClientHelloSpec) error { for i := range uconn.greaseSeed { uconn.greaseSeed[i] = binary.LittleEndian.Uint16(grease_bytes[2*i : 2*i+2]) } - if GetBoringGREASEValue(uconn.greaseSeed, ssl_grease_extension1) == GetBoringGREASEValue(uconn.greaseSeed, ssl_grease_extension2) { + if getBoringGREASEValue(uconn.greaseSeed[:], ssl_grease_extension1) == getBoringGREASEValue(uconn.greaseSeed[:], ssl_grease_extension2) { uconn.greaseSeed[ssl_grease_extension2] ^= 0x1010 } @@ -3081,7 +3160,7 @@ func (uconn *UConn) ApplyPreset(p *ClientHelloSpec) error { copy(hello.CipherSuites, p.CipherSuites) for i := range hello.CipherSuites { if isGREASEUint16(hello.CipherSuites[i]) { // just in case the user set a GREASE value instead of unGREASEd - hello.CipherSuites[i] = GetBoringGREASEValue(uconn.greaseSeed, ssl_grease_cipher) + hello.CipherSuites[i] = getBoringGREASEValue(uconn.greaseSeed[:], ssl_grease_cipher) } } @@ -3117,9 +3196,9 @@ func (uconn *UConn) ApplyPreset(p *ClientHelloSpec) error { case *UtlsGREASEExtension: switch grease_extensions_seen { case 0: - ext.Value = GetBoringGREASEValue(uconn.greaseSeed, ssl_grease_extension1) + ext.Value = getBoringGREASEValue(uconn.greaseSeed[:], ssl_grease_extension1) case 1: - ext.Value = GetBoringGREASEValue(uconn.greaseSeed, ssl_grease_extension2) + ext.Value = getBoringGREASEValue(uconn.greaseSeed[:], ssl_grease_extension2) ext.Body = []byte{0} default: return errors.New("at most 2 grease extensions are supported") @@ -3128,7 +3207,13 @@ func (uconn *UConn) ApplyPreset(p *ClientHelloSpec) error { case *SupportedCurvesExtension: for i := range ext.Curves { if isGREASEUint16(uint16(ext.Curves[i])) { - ext.Curves[i] = CurveID(GetBoringGREASEValue(uconn.greaseSeed, ssl_grease_group)) + ext.Curves[i] = CurveID(getBoringGREASEValue(uconn.greaseSeed[:], ssl_grease_group)) + } + } + case *SignatureAlgorithmsExtension: + for i, scheme := range ext.SupportedSignatureAlgorithms { + if isGREASEUint16(uint16(scheme)) { + ext.SupportedSignatureAlgorithms[i] = SignatureScheme(getBoringGREASEValue(uconn.greaseSeed[:], ssl_grease_signature_algorithm)) } } case *KeyShareExtension: @@ -3137,7 +3222,7 @@ func (uconn *UConn) ApplyPreset(p *ClientHelloSpec) error { for i := range ext.KeyShares { curveID := ext.KeyShares[i].Group if isGREASEUint16(uint16(curveID)) { // just in case the user set a GREASE value instead of unGREASEd - ext.KeyShares[i].Group = CurveID(GetBoringGREASEValue(uconn.greaseSeed, ssl_grease_group)) + ext.KeyShares[i].Group = CurveID(getBoringGREASEValue(uconn.greaseSeed[:], ssl_grease_group)) continue } if len(ext.KeyShares[i].Data) > 1 { @@ -3224,7 +3309,7 @@ func (uconn *UConn) ApplyPreset(p *ClientHelloSpec) error { case *SupportedVersionsExtension: for i := range ext.Versions { if isGREASEUint16(ext.Versions[i]) { // just in case the user set a GREASE value instead of unGREASEd - ext.Versions[i] = GetBoringGREASEValue(uconn.greaseSeed, ssl_grease_version) + ext.Versions[i] = getBoringGREASEValue(uconn.greaseSeed[:], ssl_grease_version) } } case *NPNExtension: diff --git a/u_tls_extensions.go b/u_tls_extensions.go index 77ee10ce68..731751b233 100644 --- a/u_tls_extensions.go +++ b/u_tls_extensions.go @@ -79,6 +79,10 @@ func ExtensionFromID(id uint16) TLSExtension { return &FakeChannelIDExtension{} case utlsExtensionECH: return &GREASEEncryptedClientHelloExtension{} + case utlsExtensionTrustAnchors: + return &TrustAnchorsExtension{} + case utlsExtensionServerPadding: + return &FakeServerPaddingExtension{} case extensionRenegotiationInfo: return &RenegotiationInfoExtension{} default: @@ -877,6 +881,33 @@ type GenericExtension struct { Data []byte } +// FakeServerPaddingExtension sends BoringSSL's experimental two-byte padding request. +// Chrome 158.0.8127.88 sends a zero on fresh connections in the reference capture. +type FakeServerPaddingExtension struct { + PaddingLen uint16 `json:"padding_len"` +} + +func (*FakeServerPaddingExtension) writeToUConn(*UConn) error { return nil } +func (*FakeServerPaddingExtension) Len() int { return 6 } + +func (e *FakeServerPaddingExtension) Read(b []byte) (int, error) { + if len(b) < e.Len() { + return 0, io.ErrShortBuffer + } + b[0], b[1] = byte(utlsExtensionServerPadding>>8), byte(utlsExtensionServerPadding&0xff) + b[2], b[3] = 0, 2 + b[4], b[5] = byte(e.PaddingLen>>8), byte(e.PaddingLen) + return e.Len(), io.EOF +} + +func (e *FakeServerPaddingExtension) Write(b []byte) (int, error) { + if len(b) != 2 { + return 0, errors.New("server padding request must contain two bytes") + } + e.PaddingLen = uint16(b[0])<<8 | uint16(b[1]) + return len(b), nil +} + func (e *GenericExtension) writeToUConn(uc *UConn) error { return nil } @@ -966,9 +997,14 @@ const ( ssl_grease_extension2 ssl_grease_version ssl_grease_ticket_extension - ssl_grease_last_index = ssl_grease_ticket_extension + ssl_grease_ech_config_id + ssl_grease_signature_algorithm + ssl_grease_seed_count ) +// Preserve the array size accepted by the exported GetBoringGREASEValue helper. +const ssl_grease_last_index = ssl_grease_ticket_extension + // it is responsibility of user not to generate multiple grease extensions with same value type UtlsGREASEExtension struct { Value uint16 @@ -981,6 +1017,10 @@ func (e *UtlsGREASEExtension) writeToUConn(uc *UConn) error { // will panic if ssl_grease_last_index[index] is out of bounds. func GetBoringGREASEValue(greaseSeed [ssl_grease_last_index]uint16, index int) uint16 { + return getBoringGREASEValue(greaseSeed[:], index) +} + +func getBoringGREASEValue(greaseSeed []uint16, index int) uint16 { // GREASE value is back from deterministic to random. // https://github.com/google/boringssl/blob/a365138ac60f38b64bfc608b493e0f879845cb88/ssl/handshake_client.c#L530 ret := uint16(greaseSeed[index]) diff --git a/u_trust_anchors.go b/u_trust_anchors.go new file mode 100644 index 0000000000..4fc9fb4e98 --- /dev/null +++ b/u_trust_anchors.go @@ -0,0 +1,103 @@ +package tls + +import ( + "encoding/json" + "errors" + "fmt" + "io" + + "golang.org/x/crypto/cryptobyte" +) + +// TrustAnchorsExtension implements the draft trust_anchors ClientHello extension +// (0xca34). Each TrustAnchorID contains 1 to 255 bytes; an empty list is valid. +// The IDs are advertised to the server and do not change Config.RootCAs. +type TrustAnchorsExtension struct { + TrustAnchorIDs [][]byte `json:"trust_anchor_ids"` +} + +func (e *TrustAnchorsExtension) writeToUConn(_ *UConn) error { + return nil +} + +func (e *TrustAnchorsExtension) Len() int { + n := 6 // Extension header and RequestedTrustAnchorList length. + for _, id := range e.TrustAnchorIDs { + n += 1 + len(id) + } + return n +} + +func (e *TrustAnchorsExtension) validate() error { + listLen := 0 + for _, id := range e.TrustAnchorIDs { + if len(id) == 0 || len(id) > 255 { + return fmt.Errorf("tls: trust anchor ID length %d is outside 1..255", len(id)) + } + listLen += 1 + len(id) + // The extension_data length also includes the two-byte list length. + if listLen > (1<<16)-3 { + return errors.New("tls: trust anchors extension data exceeds 65535 bytes") + } + } + return nil +} + +func (e *TrustAnchorsExtension) Read(b []byte) (int, error) { + if err := e.validate(); err != nil { + return 0, err + } + if len(b) < e.Len() { + return 0, io.ErrShortBuffer + } + listLen := e.Len() - 6 + b[0] = byte(utlsExtensionTrustAnchors >> 8) + b[1] = byte(utlsExtensionTrustAnchors & 0xff) + b[2] = byte((2 + listLen) >> 8) + b[3] = byte(2 + listLen) + b[4] = byte(listLen >> 8) + b[5] = byte(listLen) + offset := 6 + for _, id := range e.TrustAnchorIDs { + b[offset] = byte(len(id)) + offset++ + offset += copy(b[offset:], id) + } + return offset, io.EOF +} + +func (e *TrustAnchorsExtension) Write(b []byte) (int, error) { + if len(b) > (1<<16)-1 { + return 0, errors.New("tls: trust anchors extension data exceeds 65535 bytes") + } + extData := cryptobyte.String(b) + var list cryptobyte.String + if !extData.ReadUint16LengthPrefixed(&list) || !extData.Empty() { + return 0, errors.New("tls: unable to read trust anchors extension data") + } + ids := make([][]byte, 0) + for !list.Empty() { + var id cryptobyte.String + if !list.ReadUint8LengthPrefixed(&id) || id.Empty() { + return 0, errors.New("tls: unable to read trust anchor ID") + } + ids = append(ids, append([]byte(nil), id...)) + } + e.TrustAnchorIDs = ids + return len(b), nil +} + +func (e *TrustAnchorsExtension) UnmarshalJSON(data []byte) error { + var value struct { + TrustAnchorIDs [][]byte `json:"trust_anchor_ids"` + } + if err := json.Unmarshal(data, &value); err != nil { + return err + } + parsed := TrustAnchorsExtension{TrustAnchorIDs: value.TrustAnchorIDs} + if err := parsed.validate(); err != nil { + return err + } + e.TrustAnchorIDs = parsed.TrustAnchorIDs + return nil +} diff --git a/u_trust_anchors_test.go b/u_trust_anchors_test.go new file mode 100644 index 0000000000..e1271fb130 --- /dev/null +++ b/u_trust_anchors_test.go @@ -0,0 +1,173 @@ +package tls + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "reflect" + "testing" +) + +func TestTrustAnchorsExtensionRoundTrip(t *testing.T) { + for _, tc := range []struct { + name string + ids [][]byte + wire []byte + }{ + {"empty", nil, []byte{0xca, 0x34, 0, 2, 0, 0}}, + {"single", [][]byte{{0x42}}, []byte{0xca, 0x34, 0, 4, 0, 2, 1, 0x42}}, + {"multiple", [][]byte{{1, 2}, {3}}, []byte{0xca, 0x34, 0, 7, 0, 5, 2, 1, 2, 1, 3}}, + {"maximum ID", [][]byte{bytes.Repeat([]byte{0x81}, 255)}, nil}, + } { + t.Run(tc.name, func(t *testing.T) { + ext := &TrustAnchorsExtension{TrustAnchorIDs: tc.ids} + wire := make([]byte, ext.Len()) + if n, err := ext.Read(wire); n != len(wire) || err != io.EOF { + t.Fatalf("Read = %d, %v; want %d, EOF", n, err, len(wire)) + } + if tc.wire != nil && !bytes.Equal(wire, tc.wire) { + t.Fatalf("wire = %x; want %x", wire, tc.wire) + } + parsed, ok := ExtensionFromID(utlsExtensionTrustAnchors).(*TrustAnchorsExtension) + if !ok { + t.Fatal("trust_anchors is not registered with the fingerprint parser") + } + if n, err := parsed.Write(wire[4:]); n != len(wire)-4 || err != nil { + t.Fatalf("Write = %d, %v; want %d, nil", n, err, len(wire)-4) + } + if len(parsed.TrustAnchorIDs) != len(tc.ids) { + t.Fatalf("parsed %d IDs; want %d", len(parsed.TrustAnchorIDs), len(tc.ids)) + } + for i, id := range tc.ids { + if !bytes.Equal(parsed.TrustAnchorIDs[i], id) { + t.Fatalf("ID %d = %x; want %x", i, parsed.TrustAnchorIDs[i], id) + } + } + encoded := make([]byte, parsed.Len()) + if _, err := parsed.Read(encoded); err != io.EOF { + t.Fatal(err) + } + if !bytes.Equal(encoded, wire) { + t.Fatalf("roundtrip changed wire: %x != %x", encoded, wire) + } + }) + } +} + +func TestTrustAnchorsExtensionParseDoesNotAliasInput(t *testing.T) { + data := []byte{0, 5, 2, 1, 2, 1, 3} + ext := &TrustAnchorsExtension{} + if _, err := ext.Write(data); err != nil { + t.Fatal(err) + } + data[3] = 0xff + if ext.TrustAnchorIDs[0][0] != 1 { + t.Fatal("parsed ID aliases input") + } + ext.TrustAnchorIDs[1][0] = 0xfe + if data[6] != 3 { + t.Fatal("input aliases parsed ID") + } +} + +func TestTrustAnchorsExtensionRejectsMalformedData(t *testing.T) { + for _, data := range [][]byte{ + nil, + {0}, // Truncated list length. + {0, 1}, // Truncated list. + {0, 3, 1, 1}, // List length exceeds available data. + {0, 1, 0}, // Empty ID. + {0, 2, 2, 1}, // Truncated ID. + {0, 0, 1}, // Trailing bytes after the list. + {0, 2, 1, 1, 2}, // Trailing bytes after a nonempty list. + } { + t.Run(fmt.Sprintf("%x", data), func(t *testing.T) { + ext := &TrustAnchorsExtension{TrustAnchorIDs: [][]byte{{0x42}}} + if n, err := ext.Write(data); n != 0 || err == nil { + t.Fatalf("Write = %d, %v; want 0, error", n, err) + } + if !reflect.DeepEqual(ext.TrustAnchorIDs, [][]byte{{0x42}}) { + t.Fatal("failed parsing modified existing IDs") + } + }) + } +} + +func TestTrustAnchorsExtensionEncodingLimits(t *testing.T) { + ids := make([][]byte, 256) + for i := range ids[:255] { + ids[i] = bytes.Repeat([]byte{byte(i)}, 255) + } + ids[255] = bytes.Repeat([]byte{0xff}, 252) + ext := &TrustAnchorsExtension{TrustAnchorIDs: ids} + wire := make([]byte, ext.Len()) + if _, err := ext.Read(wire); err != io.EOF { + t.Fatalf("maximum extension_data failed: %v", err) + } + if len(wire)-4 != 65535 || wire[2] != 0xff || wire[3] != 0xff { + t.Fatalf("maximum extension_data length = %d; header = %x", len(wire)-4, wire[:4]) + } + parsed := &TrustAnchorsExtension{} + if _, err := parsed.Write(wire[4:]); err != nil { + t.Fatalf("maximum extension_data parsing failed: %v", err) + } + for _, ids := range [][][]byte{ + {nil}, + {{}}, + {make([]byte, 256)}, + append(ids[:255:255], make([]byte, 253)), // One byte over the extension_data limit. + } { + ext := &TrustAnchorsExtension{TrustAnchorIDs: ids} + if n, err := ext.Read(make([]byte, ext.Len())); n != 0 || err == nil { + t.Fatalf("invalid IDs Read = %d, %v; want 0, error", n, err) + } + } + if n, err := parsed.Write(make([]byte, 65536)); n != 0 || err == nil { + t.Fatalf("oversize input Write = %d, %v; want 0, error", n, err) + } + if n, err := ext.Read(make([]byte, ext.Len()-1)); n != 0 || err != io.ErrShortBuffer { + t.Fatalf("short buffer Read = %d, %v; want 0, ErrShortBuffer", n, err) + } +} + +func TestTrustAnchorsExtensionJSON(t *testing.T) { + var extensions TLSExtensionsJSONUnmarshaler + if err := json.Unmarshal([]byte(`[{"name":"trust_anchors","trust_anchor_ids":["AQI=","/w=="]}]`), &extensions); err != nil { + t.Fatal(err) + } + exts := extensions.Extensions() + if len(exts) != 1 { + t.Fatalf("parsed %d extensions; want 1", len(exts)) + } + ext, ok := exts[0].(*TrustAnchorsExtension) + if !ok || !reflect.DeepEqual(ext.TrustAnchorIDs, [][]byte{{1, 2}, {0xff}}) { + t.Fatalf("JSON extension = %#v", exts[0]) + } + encoded, err := json.Marshal(ext) + if err != nil { + t.Fatal(err) + } + var roundtrip TrustAnchorsExtension + if err := json.Unmarshal(encoded, &roundtrip); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(roundtrip.TrustAnchorIDs, ext.TrustAnchorIDs) { + t.Fatalf("JSON roundtrip changed IDs: got %x, want %x", roundtrip.TrustAnchorIDs, ext.TrustAnchorIDs) + } + for _, data := range []string{ + `{"trust_anchor_ids":[""]}`, + `{"trust_anchor_ids":[null]}`, + `{"trust_anchor_ids":["invalid base64"]}`, + } { + if err := json.Unmarshal([]byte(data), ext); err == nil { + t.Fatalf("invalid JSON accepted: %s", data) + } + if !reflect.DeepEqual(ext.TrustAnchorIDs, [][]byte{{1, 2}, {0xff}}) { + t.Fatal("failed JSON parsing modified existing IDs") + } + } + if err := json.Unmarshal([]byte(`{"trust_anchor_ids":[]}`), ext); err != nil || len(ext.TrustAnchorIDs) != 0 { + t.Fatalf("empty JSON list = %#v, %v", ext.TrustAnchorIDs, err) + } +}