@browsercore/tls 0.4.3 → 0.4.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -5
- package/dist/connection/handshake-driver.d.ts +29 -0
- package/dist/connection/handshake-driver.d.ts.map +1 -1
- package/dist/connection/handshake-driver.js +116 -14
- package/dist/connection/handshake-driver.js.map +1 -1
- package/dist/connection/handshake-messages.d.ts +51 -1
- package/dist/connection/handshake-messages.d.ts.map +1 -1
- package/dist/connection/handshake-messages.js +154 -12
- package/dist/connection/handshake-messages.js.map +1 -1
- package/dist/connection/index.d.ts +2 -1
- package/dist/connection/index.d.ts.map +1 -1
- package/dist/connection/index.js +2 -1
- package/dist/connection/index.js.map +1 -1
- package/dist/connection/lifecycle.d.ts +18 -5
- package/dist/connection/lifecycle.d.ts.map +1 -1
- package/dist/connection/lifecycle.js +20 -7
- package/dist/connection/lifecycle.js.map +1 -1
- package/dist/connection/record-layer.d.ts +5 -5
- package/dist/connection/record-layer.d.ts.map +1 -1
- package/dist/connection/record-layer.js +19 -12
- package/dist/connection/record-layer.js.map +1 -1
- package/dist/crypto/keySchedule.d.ts +18 -2
- package/dist/crypto/keySchedule.d.ts.map +1 -1
- package/dist/crypto/keySchedule.js +13 -1
- package/dist/crypto/keySchedule.js.map +1 -1
- package/dist/errors.d.ts +31 -2
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +20 -0
- package/dist/errors.js.map +1 -1
- package/dist/handshake/client-hello.d.ts +1 -1
- package/dist/handshake/client-hello.d.ts.map +1 -1
- package/dist/handshake/client-hello.js +23 -3
- package/dist/handshake/client-hello.js.map +1 -1
- package/dist/handshake/handshake.d.ts +1 -0
- package/dist/handshake/handshake.d.ts.map +1 -1
- package/dist/handshake/handshake.js +1 -0
- package/dist/handshake/handshake.js.map +1 -1
- package/dist/handshake/hello-retry-request.d.ts +89 -0
- package/dist/handshake/hello-retry-request.d.ts.map +1 -0
- package/dist/handshake/hello-retry-request.js +152 -0
- package/dist/handshake/hello-retry-request.js.map +1 -0
- package/dist/handshake/server-hello.d.ts.map +1 -1
- package/dist/handshake/server-hello.js +34 -0
- package/dist/handshake/server-hello.js.map +1 -1
- package/dist/tls.d.ts +56 -2
- package/dist/tls.d.ts.map +1 -1
- package/dist/tls.js +176 -14
- package/dist/tls.js.map +1 -1
- package/dist/types.d.ts +8 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HelloRetryRequest handling (RFC 8446 §4.1.3, §4.2.2, §4.4.1).
|
|
3
|
+
*
|
|
4
|
+
* A HelloRetryRequest (HRR) is a special ServerHello: it has the same wire
|
|
5
|
+
* format but carries the sentinel value `CF21AD74…` in its `random` field. The
|
|
6
|
+
* server sends it when the client's initial ClientHello is unacceptable (e.g.
|
|
7
|
+
* the key-share group was not in the server's preference list). On receiving an
|
|
8
|
+
* HRR the client must:
|
|
9
|
+
*
|
|
10
|
+
* 1. Replace the transcript prefix with a synthetic `message_hash` message
|
|
11
|
+
* (§4.4.1): `Hash(ClientHello_1)` wrapped in a handshake header.
|
|
12
|
+
* 2. Parse the HRR extensions — `key_share` carries only `selected_group`
|
|
13
|
+
* (2 bytes, no key-exchange data), and `cookie` is an opaque anti-DoS blob.
|
|
14
|
+
* 3. Generate a fresh key share for `selected_group`.
|
|
15
|
+
* 4. Rebuild the ClientHello with the new key share and the echoed cookie.
|
|
16
|
+
* 5. Read the *real* ServerHello that follows.
|
|
17
|
+
*
|
|
18
|
+
* The transcript hash after HRR is:
|
|
19
|
+
*
|
|
20
|
+
* ```
|
|
21
|
+
* Transcript-Hash(ClientHello1, HelloRetryRequest, … Mn) =
|
|
22
|
+
* Hash(message_hash || 00 00 Hash.length || Hash(ClientHello1) ||
|
|
23
|
+
* HelloRetryRequest || … || Mn)
|
|
24
|
+
* ```
|
|
25
|
+
*
|
|
26
|
+
* This module owns the sentinel constant, the detection predicate, the HRR
|
|
27
|
+
* extension parser, and the synthetic `message_hash` message builder — all pure
|
|
28
|
+
* functions over their inputs, so they are independently unit-testable.
|
|
29
|
+
*/
|
|
30
|
+
import { TlsHandshakeError } from "../errors.js";
|
|
31
|
+
import { ExtensionType, findExtension, parseExtensions, wireToNamedGroup } from "../extensions/extensions.js";
|
|
32
|
+
import { HandshakeType } from "./handshake-types.js";
|
|
33
|
+
import { constantTimeEqual } from "../utils.js";
|
|
34
|
+
/**
|
|
35
|
+
* The 32-byte sentinel that distinguishes a HelloRetryRequest from a regular
|
|
36
|
+
* ServerHello (RFC 8446 §4.1.3). A server MUST NOT send this value as the
|
|
37
|
+
* `random` field of a genuine ServerHello.
|
|
38
|
+
*/
|
|
39
|
+
export const HELLO_RETRY_REQUEST_RANDOM = new Uint8Array([
|
|
40
|
+
0xcf, 0x21, 0xad, 0x74, 0xe5, 0x9a, 0x61, 0x11,
|
|
41
|
+
0xbe, 0x1d, 0x8c, 0x02, 0x1e, 0x65, 0xb8, 0x91,
|
|
42
|
+
0xc2, 0xa2, 0x11, 0x16, 0x7a, 0xbb, 0x8c, 0x5e,
|
|
43
|
+
0x07, 0x9e, 0x09, 0xe2, 0xc8, 0xa8, 0x33, 0x9c,
|
|
44
|
+
]);
|
|
45
|
+
/**
|
|
46
|
+
* Test whether a ServerHello `random` field is the HRR sentinel.
|
|
47
|
+
*
|
|
48
|
+
* Uses constant-time comparison so a timing oracle cannot distinguish HRR
|
|
49
|
+
* detection from a normal ServerHello — matching the security posture of the
|
|
50
|
+
* downgrade sentinel check in `server-hello.ts`.
|
|
51
|
+
*/
|
|
52
|
+
export function isHelloRetryRequest(random) {
|
|
53
|
+
return constantTimeEqual(random, HELLO_RETRY_REQUEST_RANDOM);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Parse the extensions from an HRR ServerHello.
|
|
57
|
+
*
|
|
58
|
+
* The input is the raw extensions block (including the 2-byte length prefix)
|
|
59
|
+
* from the parsed ServerHello — the same `extensions` field the caller already
|
|
60
|
+
* has from `parseServerHello`.
|
|
61
|
+
*
|
|
62
|
+
* Throws {@link TlsHandshakeError} with phase `"server_hello"` if the required
|
|
63
|
+
* `key_share` extension with `selected_group` is missing or malformed.
|
|
64
|
+
*/
|
|
65
|
+
export function parseHelloRetryRequestExtensions(extensions) {
|
|
66
|
+
const parsed = parseExtensions(extensions);
|
|
67
|
+
// key_share in HRR: exactly 2 bytes — the selected_group (no key data).
|
|
68
|
+
const keyShare = findExtension(parsed, ExtensionType.KEY_SHARE);
|
|
69
|
+
if (keyShare === undefined) {
|
|
70
|
+
throw new TlsHandshakeError("server_hello", {
|
|
71
|
+
cause: new Error("HelloRetryRequest missing required key_share extension"),
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
if (keyShare.data.length !== 2) {
|
|
75
|
+
throw new TlsHandshakeError("server_hello", {
|
|
76
|
+
cause: new Error(`HelloRetryRequest key_share extension must be exactly 2 bytes (selected_group), got ${keyShare.data.length}`),
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
const groupHi = keyShare.data[0];
|
|
80
|
+
const groupLo = keyShare.data[1];
|
|
81
|
+
if (groupHi === undefined || groupLo === undefined) {
|
|
82
|
+
throw new TlsHandshakeError("server_hello", {
|
|
83
|
+
cause: new Error("HelloRetryRequest key_share data truncated"),
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
const selectedGroup = wireToNamedGroup((groupHi << 8) | groupLo);
|
|
87
|
+
// cookie extension is optional (RFC 8446 §4.2.2).
|
|
88
|
+
const cookieExt = findExtension(parsed, ExtensionType.COOKIE);
|
|
89
|
+
if (cookieExt !== undefined) {
|
|
90
|
+
// cookie body: cookie_length(2) || cookie. Extract the raw cookie bytes
|
|
91
|
+
// so the client can echo them in the new ClientHello without re-parsing.
|
|
92
|
+
const cookie = extractCookieValue(cookieExt.data);
|
|
93
|
+
return { selectedGroup, cookie };
|
|
94
|
+
}
|
|
95
|
+
return { selectedGroup };
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Extract the raw cookie bytes from a cookie extension body.
|
|
99
|
+
*
|
|
100
|
+
* The wire layout is `cookie_length(2) || cookie` (RFC 8446 §4.2.2). The
|
|
101
|
+
* returned slice is what the client must echo in its new ClientHello's cookie
|
|
102
|
+
* extension body (which has the same `cookie_length(2) || cookie` layout).
|
|
103
|
+
*/
|
|
104
|
+
function extractCookieValue(cookieBody) {
|
|
105
|
+
if (cookieBody.length < 2) {
|
|
106
|
+
throw new TlsHandshakeError("server_hello", {
|
|
107
|
+
cause: new Error("HelloRetryRequest cookie extension too short for length prefix"),
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
const lenHi = cookieBody[0];
|
|
111
|
+
const lenLo = cookieBody[1];
|
|
112
|
+
if (lenHi === undefined || lenLo === undefined) {
|
|
113
|
+
throw new TlsHandshakeError("server_hello", {
|
|
114
|
+
cause: new Error("HelloRetryRequest cookie length prefix truncated"),
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
const cookieLen = (lenHi << 8) | lenLo;
|
|
118
|
+
if (2 + cookieLen !== cookieBody.length) {
|
|
119
|
+
throw new TlsHandshakeError("server_hello", {
|
|
120
|
+
cause: new Error("HelloRetryRequest cookie length does not match extension body size"),
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
return cookieBody.subarray(2, 2 + cookieLen);
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Build the synthetic `message_hash` handshake message for the transcript
|
|
127
|
+
* (RFC 8446 §4.4.1).
|
|
128
|
+
*
|
|
129
|
+
* When an HRR is received, the transcript is rewritten to start with:
|
|
130
|
+
*
|
|
131
|
+
* ```
|
|
132
|
+
* HandshakeType.message_hash(254) || length(3) || Hash(ClientHello_1)
|
|
133
|
+
* ```
|
|
134
|
+
*
|
|
135
|
+
* This replaces `ClientHello_1` itself in the transcript — the original message
|
|
136
|
+
* bytes are no longer hashed directly; only their hash is. This is what makes
|
|
137
|
+
* the transcript hash after HRR different from the no-HRR case, and getting it
|
|
138
|
+
* byte-exact is critical for the key schedule.
|
|
139
|
+
*
|
|
140
|
+
* @param hashValue `Hash(ClientHello_1)` — the transcript hash of the original
|
|
141
|
+
* ClientHello, computed with the negotiated cipher's hash.
|
|
142
|
+
*/
|
|
143
|
+
export function buildMessageHashMessage(hashValue) {
|
|
144
|
+
const message = new Uint8Array(4 + hashValue.length);
|
|
145
|
+
message[0] = HandshakeType.MESSAGE_HASH; // 254
|
|
146
|
+
message[1] = (hashValue.length >> 16) & 0xff;
|
|
147
|
+
message[2] = (hashValue.length >> 8) & 0xff;
|
|
148
|
+
message[3] = hashValue.length & 0xff;
|
|
149
|
+
message.set(hashValue, 4);
|
|
150
|
+
return message;
|
|
151
|
+
}
|
|
152
|
+
//# sourceMappingURL=hello-retry-request.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hello-retry-request.js","sourceRoot":"","sources":["../../src/handshake/hello-retry-request.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAGH,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACjD,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAC9G,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAEhD;;;;GAIG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG,IAAI,UAAU,CAAC;IACrD,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI;IAC9C,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI;IAC9C,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI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,CAAC,CAAC,EAAE,CAAC,GAAG,SAAS,CAAC,CAAC;AACjD,CAAC;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,UAAU,uBAAuB,CAAC,SAAqB;IACzD,MAAM,OAAO,GAAG,IAAI,UAAU,CAAC,CAAC,GAAG,SAAS,CAAC,MAAM,CAAC,CAAC;IACrD,OAAO,CAAC,CAAC,CAAC,GAAG,aAAa,CAAC,YAAY,CAAC,CAAC,MAAM;IAC/C,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,SAAS,CAAC,MAAM,IAAI,EAAE,CAAC,GAAG,IAAI,CAAC;IAC7C,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,SAAS,CAAC,MAAM,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC;IAC5C,OAAO,CAAC,CAAC,CAAC,GAAG,SAAS,CAAC,MAAM,GAAG,IAAI,CAAC;IACrC,OAAO,CAAC,GAAG,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC;IAC1B,OAAO,OAAO,CAAC;AACnB,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-hello.d.ts","sourceRoot":"","sources":["../../src/handshake/server-hello.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"server-hello.d.ts","sourceRoot":"","sources":["../../src/handshake/server-hello.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAKhE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAExD;;;;GAIG;AACH,MAAM,WAAW,qBAAqB;IAClC,iEAAiE;IACjE,QAAQ,CAAC,YAAY,EAAE,SAAS,WAAW,EAAE,CAAC;IAC9C,sEAAsE;IACtE,QAAQ,CAAC,iBAAiB,EAAE,SAAS,eAAe,EAAE,CAAC;CAC1D;AAgGD;;;;;;;;;GASG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,UAAU,EAAE,OAAO,EAAE,qBAAqB,GAAG,WAAW,CA8D7F"}
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
import { TlsHandshakeError } from "../errors.js";
|
|
10
10
|
import { ExtensionType, findExtension, parseExtensions } from "../extensions/extensions.js";
|
|
11
11
|
import { assertCipherSuiteOffered, assertVersionSupported } from "../crypto/keySchedule.js";
|
|
12
|
+
import { constantTimeEqual } from "../utils.js";
|
|
12
13
|
/**
|
|
13
14
|
* Common TLS 1.2 cipher suites (IANA registry). The client only speaks TLS 1.3,
|
|
14
15
|
* so a server negotiating any of these is a protocol downgrade. Stored as a Set
|
|
@@ -22,6 +23,35 @@ const TLS12_CIPHER_SUITES = new Set([
|
|
|
22
23
|
0xc02b, 0xc02c, 0xc02f, 0xc030, 0xcca8, 0xcca9,
|
|
23
24
|
0xccaa, 0x0004, 0x0005, 0x000a, 0x0009, 0x0016,
|
|
24
25
|
]);
|
|
26
|
+
/**
|
|
27
|
+
* Downgrade sentinels in the last 8 bytes of ServerHello.random (RFC 8446
|
|
28
|
+
* §4.1.3). A TLS 1.3 server MUST NOT set these; their presence means the
|
|
29
|
+
* negotiating peer is a TLS 1.2 (or earlier) implementation that intentionally
|
|
30
|
+
* inserted the sentinel to prevent downgrade attacks. If a client negotiating
|
|
31
|
+
* TLS 1.3 sees them, it MUST abort with {@link TlsHandshakeError} — the server
|
|
32
|
+
* is either buggy or malicious.
|
|
33
|
+
*
|
|
34
|
+
* - `DOWNGRD\x01` (`44 4F 57 4E 47 52 44 01`): TLS 1.2 downgrade sentinel
|
|
35
|
+
* - `DOWNGRD\x00` (`44 4F 57 4E 47 52 44 00`): TLS 1.1 or below downgrade sentinel
|
|
36
|
+
*/
|
|
37
|
+
const DOWNGRADE_SENTINEL_TLS12 = new Uint8Array([0x44, 0x4f, 0x57, 0x4e, 0x47, 0x52, 0x44, 0x01]);
|
|
38
|
+
const DOWNGRADE_SENTINEL_TLS11 = new Uint8Array([0x44, 0x4f, 0x57, 0x4e, 0x47, 0x52, 0x44, 0x00]);
|
|
39
|
+
/**
|
|
40
|
+
* Check the last 8 bytes of ServerHello.random for a downgrade sentinel
|
|
41
|
+
* (RFC 8446 §4.1.3). Throws {@link TlsHandshakeError} with phase "server_hello"
|
|
42
|
+
* if either sentinel is present — the client MUST abort with `illegal_parameter`.
|
|
43
|
+
*/
|
|
44
|
+
function checkDowngradeSentinel(random) {
|
|
45
|
+
const tail = random.subarray(24, 32);
|
|
46
|
+
if (constantTimeEqual(tail, DOWNGRADE_SENTINEL_TLS12) ||
|
|
47
|
+
constantTimeEqual(tail, DOWNGRADE_SENTINEL_TLS11)) {
|
|
48
|
+
throw new TlsHandshakeError("server_hello", {
|
|
49
|
+
cause: new Error("ServerHello.random contains a downgrade sentinel — the server is " +
|
|
50
|
+
"attempting to negotiate TLS 1.2 or below in a TLS 1.3 handshake " +
|
|
51
|
+
"(RFC 8446 §4.1.3 requires the client to abort with illegal_parameter)"),
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
}
|
|
25
55
|
/** Invert the cipher-suite wire values; throws on unknown values. */
|
|
26
56
|
function wireToCipherSuite(wire) {
|
|
27
57
|
switch (wire) {
|
|
@@ -97,6 +127,10 @@ export function parseServerHello(buf, offered) {
|
|
|
97
127
|
const protocolVersion = (readByte() << 8) | readByte();
|
|
98
128
|
const random = buf.subarray(o, o + 32);
|
|
99
129
|
o += 32;
|
|
130
|
+
// RFC 8446 §4.1.3: check the last 8 bytes of ServerHello.random for a
|
|
131
|
+
// downgrade sentinel. A TLS 1.3 server MUST NOT set these — their presence
|
|
132
|
+
// means the peer is actually TLS 1.2 or below, and the client MUST abort.
|
|
133
|
+
checkDowngradeSentinel(random);
|
|
100
134
|
const sessionIdLen = readByte();
|
|
101
135
|
expect(sessionIdLen);
|
|
102
136
|
const sessionId = buf.subarray(o, o + sessionIdLen);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-hello.js","sourceRoot":"","sources":["../../src/handshake/server-hello.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAGH,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACjD,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC5F,OAAO,EAAE,wBAAwB,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;
|
|
1
|
+
{"version":3,"file":"server-hello.js","sourceRoot":"","sources":["../../src/handshake/server-hello.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAGH,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACjD,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC5F,OAAO,EAAE,wBAAwB,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAC5F,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAehD;;;;;GAKG;AACH,MAAM,mBAAmB,GAAwB,IAAI,GAAG,CAAC;IACrD,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAC9C,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAC9C,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAC9C,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAC9C,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;CACjD,CAAC,CAAC;AAEH;;;;;;;;;;GAUG;AACH,MAAM,wBAAwB,GAAG,IAAI,UAAU,CAAC,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,E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SAAS,EAAE,CAAC;QACvC,MAAM,IAAI,iBAAiB,CAAC,cAAc,EAAE;YACxC,KAAK,EAAE,IAAI,KAAK,CAAC,6CAA6C,CAAC;SAClE,CAAC,CAAC;IACP,CAAC;IACD,MAAM,IAAI,GAAG,CAAC,EAAE,IAAI,CAAC,CAAC,GAAG,EAAE,CAAC;IAC5B,MAAM,QAAQ,GAAG,aAAa,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;IAC9C,sBAAsB,CAAC,QAAQ,CAAC,CAAC;IACjC,OAAO,QAAQ,CAAC;AACpB,CAAC"}
|
package/dist/tls.d.ts
CHANGED
|
@@ -22,10 +22,10 @@
|
|
|
22
22
|
import type { CryptoProvider, HashId } from "@browsercore/crypto";
|
|
23
23
|
import type { Transport } from "@browsercore/transport";
|
|
24
24
|
import { type ApplicationData, type CipherSuite, type CloseReason, type KeyPair, type ProtocolVersion, type TlsConnection, type TlsOptions, type TlsSessionId, type TlsState, type TrafficSecrets } from "./types.js";
|
|
25
|
-
import { type TlsError } from "./errors.js";
|
|
25
|
+
import { type AlertLevel, type HandshakePhase, type TlsError } from "./errors.js";
|
|
26
26
|
import { type encryptRecord } from "./record/record.js";
|
|
27
|
+
import { type ServerHello } from "./handshake/handshake.js";
|
|
27
28
|
import type { Certificate } from "./certificates/certificates.js";
|
|
28
|
-
import type { ServerHello } from "./handshake/handshake.js";
|
|
29
29
|
import { type HandshakeContext } from "./connection/index.js";
|
|
30
30
|
/**
|
|
31
31
|
* Establish a TLS 1.3 connection over the given transport.
|
|
@@ -75,6 +75,18 @@ export declare class TlsConnectionImpl implements TlsConnection, HandshakeContex
|
|
|
75
75
|
masterSecret: Uint8Array;
|
|
76
76
|
clientHsSeq: number;
|
|
77
77
|
serverHsSeq: number;
|
|
78
|
+
/**
|
|
79
|
+
* Raw application traffic secrets, retained for KeyUpdate key rotation
|
|
80
|
+
* (RFC 8446 §4.6.3). Set by the driver when application secrets are derived.
|
|
81
|
+
*/
|
|
82
|
+
clientAppSecret: Uint8Array;
|
|
83
|
+
serverAppSecret: Uint8Array;
|
|
84
|
+
/** True once handshake traffic keys are derived — gates sendAlert during handshake. */
|
|
85
|
+
hsTrafficReady: boolean;
|
|
86
|
+
/** Mutable: current handshake phase, updated by the driver for timeout attribution. */
|
|
87
|
+
currentPhase: HandshakePhase;
|
|
88
|
+
/** Optional debug trace callback, set from TlsOptions.onDebug. */
|
|
89
|
+
onDebug: ((msg: string) => void) | undefined;
|
|
78
90
|
private applicationSecrets;
|
|
79
91
|
private clientAppSeq;
|
|
80
92
|
private serverAppSeq;
|
|
@@ -115,10 +127,52 @@ export declare class TlsConnectionImpl implements TlsConnection, HandshakeContex
|
|
|
115
127
|
* HandshakeContext fields and returns the derived application secrets, which
|
|
116
128
|
* we store for read()/write(). `now` is read here (in the orchestrator) so
|
|
117
129
|
* certificate validation stays pure and testable.
|
|
130
|
+
*
|
|
131
|
+
* Error cleanup (RFC 8446 §6): on any failure the method sends a fatal
|
|
132
|
+
* alert (best-effort), closes the transport to prevent socket leaks, and
|
|
133
|
+
* transitions to the `closed` terminal state before re-throwing.
|
|
118
134
|
*/
|
|
119
135
|
private performHandshake;
|
|
136
|
+
/**
|
|
137
|
+
* Send a TLS alert (RFC 8446 §6) to the peer.
|
|
138
|
+
*
|
|
139
|
+
* Best-effort: if the traffic keys are not yet derived (early handshake
|
|
140
|
+
* failure), or the transport write fails, the alert is silently dropped.
|
|
141
|
+
* The caller's error-handling path (transport close) is the fallback.
|
|
142
|
+
*
|
|
143
|
+
* During the handshake, the alert is sent under the client handshake traffic
|
|
144
|
+
* key; after the handshake, under the client application traffic key.
|
|
145
|
+
*/
|
|
146
|
+
sendAlert(level: AlertLevel, description: number): Promise<void>;
|
|
147
|
+
/**
|
|
148
|
+
* Map a typed TLS error to the appropriate alert description for sending
|
|
149
|
+
* before connection teardown (RFC 8446 §6).
|
|
150
|
+
*
|
|
151
|
+
* - `handshake_failure` (40): bad cipher suite / version negotiation
|
|
152
|
+
* - `bad_certificate` (42): certificate chain or hostname validation failure
|
|
153
|
+
* - `decrypt_error` (51): signature verification or Finished verify_data mismatch
|
|
154
|
+
* - `illegal_parameter` (47): downgrade sentinel, unexpected message
|
|
155
|
+
* - `internal_error` (80): anything not covered above
|
|
156
|
+
*/
|
|
157
|
+
private errorToAlertDescription;
|
|
120
158
|
/** Handle a non-application record encountered while reading application data. */
|
|
121
159
|
private handlePostHandshakeRecord;
|
|
160
|
+
/**
|
|
161
|
+
* Split a decrypted post-handshake handshake record into individual messages
|
|
162
|
+
* and dispatch each by type. KeyUpdate rotates traffic keys; all other types
|
|
163
|
+
* (NewSessionTicket, post-handshake CertificateRequest) are silently ignored.
|
|
164
|
+
*/
|
|
165
|
+
private handlePostHandshakeMessage;
|
|
166
|
+
/**
|
|
167
|
+
* Handle a received KeyUpdate (RFC 8446 §4.6.3).
|
|
168
|
+
*
|
|
169
|
+
* Upon receiving KeyUpdate, the receiver MUST immediately update its
|
|
170
|
+
* *receiving* keys (the keys for reading records from the sender) and reset
|
|
171
|
+
* the corresponding sequence counter to zero. If `request_update` is
|
|
172
|
+
* `update_requested` (1), the receiver MUST send its own KeyUpdate (with
|
|
173
|
+
* `update_not_requested`) and then update its *sending* keys.
|
|
174
|
+
*/
|
|
175
|
+
private handleKeyUpdate;
|
|
122
176
|
private transition;
|
|
123
177
|
}
|
|
124
178
|
//# sourceMappingURL=tls.d.ts.map
|
package/dist/tls.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tls.d.ts","sourceRoot":"","sources":["../src/tls.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAGH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAClE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,EAGH,KAAK,eAAe,EAEpB,KAAK,WAAW,EAEhB,KAAK,WAAW,EAEhB,KAAK,OAA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ACW,gBAAgB;IAuC9B;;;;;;;;;OASG;IACU,SAAS,CAAC,KAAK,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAiC5E;IAED;;;;;;;;;OASG;IACH,OAAO,CAAC,uBAAuB;IAuB/B,kFAAkF;YACpE,yBAAyB;IA6BvC;;;;OAIG;YACW,0BAA0B;IAaxC;;;;;;;;OAQG;YACW,eAAe;IA+C7B,OAAO,CAAC,UAAU;CAGrB"}
|
package/dist/tls.js
CHANGED
|
@@ -20,10 +20,11 @@
|
|
|
20
20
|
* this file focused on the public surface.
|
|
21
21
|
*/
|
|
22
22
|
import { systemClock, TLS_1_3, } from "./types.js";
|
|
23
|
-
import { TlsHandshakeError, ensureTlsError } from "./errors.js";
|
|
23
|
+
import { TlsHandshakeError, TlsDecryptError, AlertDescription, ensureTlsError } from "./errors.js";
|
|
24
24
|
import { createId } from "./utils.js";
|
|
25
25
|
import { ContentType } from "./record/record.js";
|
|
26
|
-
import {
|
|
26
|
+
import { HandshakeType } from "./handshake/handshake.js";
|
|
27
|
+
import { ensureOpen, handleAlert as handleAlertRecord, withTimeout, readEncryptedRecord, writeEncryptedRecord, runHandshake, splitHandshakeMessages, updateTrafficSecrets, } from "./connection/index.js";
|
|
27
28
|
/** Default handshake timeout in milliseconds. */
|
|
28
29
|
const DEFAULT_HANDSHAKE_TIMEOUT_MS = 10_000;
|
|
29
30
|
/**
|
|
@@ -127,6 +128,18 @@ export class TlsConnectionImpl {
|
|
|
127
128
|
masterSecret;
|
|
128
129
|
clientHsSeq = 0;
|
|
129
130
|
serverHsSeq = 0;
|
|
131
|
+
/**
|
|
132
|
+
* Raw application traffic secrets, retained for KeyUpdate key rotation
|
|
133
|
+
* (RFC 8446 §4.6.3). Set by the driver when application secrets are derived.
|
|
134
|
+
*/
|
|
135
|
+
clientAppSecret;
|
|
136
|
+
serverAppSecret;
|
|
137
|
+
/** True once handshake traffic keys are derived — gates sendAlert during handshake. */
|
|
138
|
+
hsTrafficReady = false;
|
|
139
|
+
/** Mutable: current handshake phase, updated by the driver for timeout attribution. */
|
|
140
|
+
currentPhase = "init";
|
|
141
|
+
/** Optional debug trace callback, set from TlsOptions.onDebug. */
|
|
142
|
+
onDebug;
|
|
130
143
|
applicationSecrets;
|
|
131
144
|
clientAppSeq = 0;
|
|
132
145
|
serverAppSeq = 0;
|
|
@@ -163,6 +176,7 @@ export class TlsConnectionImpl {
|
|
|
163
176
|
this.transport = options.transport;
|
|
164
177
|
this.serverName = options.serverName;
|
|
165
178
|
this.trustAnchors = options.trustAnchors ?? [];
|
|
179
|
+
this.onDebug = options.onDebug;
|
|
166
180
|
// An explicit alpnProtocols option overrides whatever the profile says.
|
|
167
181
|
this.profile =
|
|
168
182
|
options.alpnProtocols !== undefined && options.alpnProtocols.length > 0
|
|
@@ -213,7 +227,7 @@ export class TlsConnectionImpl {
|
|
|
213
227
|
if (this.state.state === "open") {
|
|
214
228
|
return;
|
|
215
229
|
}
|
|
216
|
-
await withTimeout(timeoutMs, () => this.performHandshake(), this.clock);
|
|
230
|
+
await withTimeout(timeoutMs, () => this.performHandshake(), this.clock, () => this.currentPhase);
|
|
217
231
|
}
|
|
218
232
|
/**
|
|
219
233
|
* Read the next chunk of decrypted application data. Blocks until a record
|
|
@@ -227,7 +241,7 @@ export class TlsConnectionImpl {
|
|
|
227
241
|
if (payload === undefined) {
|
|
228
242
|
// Length was just checked; this is unreachable but required so the
|
|
229
243
|
// non-null assertion can be dropped under noUncheckedIndexedAccess.
|
|
230
|
-
throw new TlsHandshakeError("
|
|
244
|
+
throw new TlsHandshakeError("application", {
|
|
231
245
|
cause: new Error("application data queue emptied between check and shift"),
|
|
232
246
|
});
|
|
233
247
|
}
|
|
@@ -239,13 +253,14 @@ export class TlsConnectionImpl {
|
|
|
239
253
|
// serverAppSeq and may early-return on APPLICATION_DATA; records must
|
|
240
254
|
// be processed in order, so the read cannot be parallelized.
|
|
241
255
|
// eslint-disable-next-line no-await-in-loop
|
|
242
|
-
const { innerType, content, readBuffer } = await readEncryptedRecord(this.readBuffer, this.transport, this.aead, this.applicationSecrets.server, this.serverAppSeq, this.crypto);
|
|
256
|
+
const { innerType, content, readBuffer } = await readEncryptedRecord(this.readBuffer, this.transport, this.aead, this.applicationSecrets.server, this.serverAppSeq, this.crypto, this.onDebug);
|
|
243
257
|
this.readBuffer = readBuffer;
|
|
244
258
|
this.serverAppSeq++;
|
|
245
259
|
if (innerType === ContentType.APPLICATION_DATA) {
|
|
246
260
|
return { payload: content };
|
|
247
261
|
}
|
|
248
|
-
|
|
262
|
+
// eslint-disable-next-line no-await-in-loop
|
|
263
|
+
await this.handlePostHandshakeRecord(innerType, content);
|
|
249
264
|
}
|
|
250
265
|
}
|
|
251
266
|
async write(data) {
|
|
@@ -258,7 +273,7 @@ export class TlsConnectionImpl {
|
|
|
258
273
|
// Sequential by necessity: each record carries a monotonically
|
|
259
274
|
// increasing sequence number, so the writes cannot be parallelized.
|
|
260
275
|
// eslint-disable-next-line no-await-in-loop
|
|
261
|
-
await writeEncryptedRecord(this.transport, this.aead, traffic, ContentType.APPLICATION_DATA, fragment, this.clientAppSeq, this.crypto);
|
|
276
|
+
await writeEncryptedRecord(this.transport, this.aead, traffic, ContentType.APPLICATION_DATA, fragment, this.clientAppSeq, this.crypto, this.onDebug);
|
|
262
277
|
this.clientAppSeq++;
|
|
263
278
|
}
|
|
264
279
|
}
|
|
@@ -276,7 +291,7 @@ export class TlsConnectionImpl {
|
|
|
276
291
|
if (this.state.state === "open") {
|
|
277
292
|
try {
|
|
278
293
|
const alert = new Uint8Array([0x01, 0x00]); // warning / close_notify
|
|
279
|
-
await writeEncryptedRecord(this.transport, this.aead, this.applicationSecrets.client, ContentType.ALERT, alert, this.clientAppSeq, this.crypto);
|
|
294
|
+
await writeEncryptedRecord(this.transport, this.aead, this.applicationSecrets.client, ContentType.ALERT, alert, this.clientAppSeq, this.crypto, this.onDebug);
|
|
280
295
|
}
|
|
281
296
|
catch {
|
|
282
297
|
// ignore — we are closing anyway
|
|
@@ -296,11 +311,31 @@ export class TlsConnectionImpl {
|
|
|
296
311
|
* HandshakeContext fields and returns the derived application secrets, which
|
|
297
312
|
* we store for read()/write(). `now` is read here (in the orchestrator) so
|
|
298
313
|
* certificate validation stays pure and testable.
|
|
314
|
+
*
|
|
315
|
+
* Error cleanup (RFC 8446 §6): on any failure the method sends a fatal
|
|
316
|
+
* alert (best-effort), closes the transport to prevent socket leaks, and
|
|
317
|
+
* transitions to the `closed` terminal state before re-throwing.
|
|
299
318
|
*/
|
|
300
319
|
async performHandshake() {
|
|
301
320
|
this.state = { state: "handshaking" };
|
|
302
321
|
const now = Math.floor(this.clock.now() / 1000);
|
|
303
|
-
|
|
322
|
+
try {
|
|
323
|
+
this.applicationSecrets = await runHandshake(this, this.profile, this.serverName, this.trustAnchors, (groups) => generateKeyShares(groups, this.crypto), now);
|
|
324
|
+
}
|
|
325
|
+
catch (cause) {
|
|
326
|
+
// Best-effort: send a fatal alert mapped to the error type, then
|
|
327
|
+
// close the transport. Never let cleanup failures mask the original.
|
|
328
|
+
const error = ensureTlsError(cause);
|
|
329
|
+
await this.sendAlert("fatal", this.errorToAlertDescription(error));
|
|
330
|
+
try {
|
|
331
|
+
await this.transport.close();
|
|
332
|
+
}
|
|
333
|
+
catch {
|
|
334
|
+
// Best-effort — the transport may already be broken.
|
|
335
|
+
}
|
|
336
|
+
this.transition({ state: "closed", reason: { kind: "error", error } });
|
|
337
|
+
throw cause;
|
|
338
|
+
}
|
|
304
339
|
// Expose the negotiated parameters the driver wrote onto the context.
|
|
305
340
|
this.protocolVersion = this.serverHello.selectedVersion;
|
|
306
341
|
// Transition to the open state. Under exactOptionalPropertyTypes,
|
|
@@ -313,8 +348,68 @@ export class TlsConnectionImpl {
|
|
|
313
348
|
...(this.alpnProtocol === undefined ? {} : { alpnProtocol: this.alpnProtocol }),
|
|
314
349
|
});
|
|
315
350
|
}
|
|
351
|
+
/**
|
|
352
|
+
* Send a TLS alert (RFC 8446 §6) to the peer.
|
|
353
|
+
*
|
|
354
|
+
* Best-effort: if the traffic keys are not yet derived (early handshake
|
|
355
|
+
* failure), or the transport write fails, the alert is silently dropped.
|
|
356
|
+
* The caller's error-handling path (transport close) is the fallback.
|
|
357
|
+
*
|
|
358
|
+
* During the handshake, the alert is sent under the client handshake traffic
|
|
359
|
+
* key; after the handshake, under the client application traffic key.
|
|
360
|
+
*/
|
|
361
|
+
async sendAlert(level, description) {
|
|
362
|
+
try {
|
|
363
|
+
const alertBody = new Uint8Array([level === "fatal" ? 0x02 : 0x01, description]);
|
|
364
|
+
if (this.state.state === "handshaking" && this.hsTrafficReady) {
|
|
365
|
+
await writeEncryptedRecord(this.transport, this.aead, this.clientHsTraffic, ContentType.ALERT, alertBody, this.clientHsSeq, this.crypto, this.onDebug);
|
|
366
|
+
this.clientHsSeq++;
|
|
367
|
+
}
|
|
368
|
+
else if (this.state.state === "open") {
|
|
369
|
+
await writeEncryptedRecord(this.transport, this.aead, this.applicationSecrets.client, ContentType.ALERT, alertBody, this.clientAppSeq, this.crypto, this.onDebug);
|
|
370
|
+
this.clientAppSeq++;
|
|
371
|
+
}
|
|
372
|
+
// If neither condition holds (e.g. connecting state, before keys
|
|
373
|
+
// derived), we cannot encrypt — skip silently. Best-effort by design.
|
|
374
|
+
}
|
|
375
|
+
catch {
|
|
376
|
+
// Never let an alert-sending failure mask the original error.
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
/**
|
|
380
|
+
* Map a typed TLS error to the appropriate alert description for sending
|
|
381
|
+
* before connection teardown (RFC 8446 §6).
|
|
382
|
+
*
|
|
383
|
+
* - `handshake_failure` (40): bad cipher suite / version negotiation
|
|
384
|
+
* - `bad_certificate` (42): certificate chain or hostname validation failure
|
|
385
|
+
* - `decrypt_error` (51): signature verification or Finished verify_data mismatch
|
|
386
|
+
* - `illegal_parameter` (47): downgrade sentinel, unexpected message
|
|
387
|
+
* - `internal_error` (80): anything not covered above
|
|
388
|
+
*/
|
|
389
|
+
errorToAlertDescription(error) {
|
|
390
|
+
// ensureTlsError wraps non-TlsError exceptions (TlsHandshakeError,
|
|
391
|
+
// TlsDecryptError) in a TlsError with the original as .cause.
|
|
392
|
+
const cause = error.cause;
|
|
393
|
+
if (cause instanceof TlsHandshakeError) {
|
|
394
|
+
const message = cause.cause?.message ?? "";
|
|
395
|
+
if (message.includes("downgrade") || message.includes("illegal")) {
|
|
396
|
+
return AlertDescription.ILLEGAL_PARAMETER;
|
|
397
|
+
}
|
|
398
|
+
if (cause.phase === "certificate") {
|
|
399
|
+
return AlertDescription.BAD_CERTIFICATE;
|
|
400
|
+
}
|
|
401
|
+
if (cause.phase === "certificate_verify" || cause.phase === "finished") {
|
|
402
|
+
return AlertDescription.DECRYPT_ERROR;
|
|
403
|
+
}
|
|
404
|
+
return AlertDescription.HANDSHAKE_FAILURE;
|
|
405
|
+
}
|
|
406
|
+
if (cause instanceof TlsDecryptError) {
|
|
407
|
+
return AlertDescription.DECRYPT_ERROR;
|
|
408
|
+
}
|
|
409
|
+
return AlertDescription.INTERNAL_ERROR;
|
|
410
|
+
}
|
|
316
411
|
/** Handle a non-application record encountered while reading application data. */
|
|
317
|
-
handlePostHandshakeRecord(innerType, content) {
|
|
412
|
+
async handlePostHandshakeRecord(innerType, content) {
|
|
318
413
|
if (innerType === ContentType.ALERT) {
|
|
319
414
|
// Alerts need connection-specific handling (state transition + error
|
|
320
415
|
// emission) that the shared dispatcher does not own.
|
|
@@ -330,10 +425,77 @@ export class TlsConnectionImpl {
|
|
|
330
425
|
}
|
|
331
426
|
return;
|
|
332
427
|
}
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
428
|
+
if (innerType === ContentType.HANDSHAKE) {
|
|
429
|
+
// Post-handshake handshake messages: KeyUpdate (RFC 8446 §4.6.3)
|
|
430
|
+
// rotates traffic keys; NewSessionTicket and others are ignored for now.
|
|
431
|
+
await this.handlePostHandshakeMessage(content);
|
|
432
|
+
return;
|
|
433
|
+
}
|
|
434
|
+
// CHANGE_CIPHER_SPEC or APPLICATION_DATA inside an encrypted record:
|
|
435
|
+
// neither is valid post-handshake. Reject typed.
|
|
436
|
+
throw new TlsHandshakeError("application", {
|
|
437
|
+
cause: new Error(`unexpected post-handshake record type ${innerType}`),
|
|
438
|
+
});
|
|
439
|
+
}
|
|
440
|
+
/**
|
|
441
|
+
* Split a decrypted post-handshake handshake record into individual messages
|
|
442
|
+
* and dispatch each by type. KeyUpdate rotates traffic keys; all other types
|
|
443
|
+
* (NewSessionTicket, post-handshake CertificateRequest) are silently ignored.
|
|
444
|
+
*/
|
|
445
|
+
async handlePostHandshakeMessage(content) {
|
|
446
|
+
const messages = splitHandshakeMessages(content);
|
|
447
|
+
for (const msg of messages) {
|
|
448
|
+
const typeByte = msg[0];
|
|
449
|
+
if (typeByte === HandshakeType.KEY_UPDATE) {
|
|
450
|
+
// eslint-disable-next-line no-await-in-loop
|
|
451
|
+
await this.handleKeyUpdate(msg.subarray(4));
|
|
452
|
+
}
|
|
453
|
+
// Other post-handshake message types are ignored — they do not
|
|
454
|
+
// affect the connection's traffic keys or state.
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* Handle a received KeyUpdate (RFC 8446 §4.6.3).
|
|
459
|
+
*
|
|
460
|
+
* Upon receiving KeyUpdate, the receiver MUST immediately update its
|
|
461
|
+
* *receiving* keys (the keys for reading records from the sender) and reset
|
|
462
|
+
* the corresponding sequence counter to zero. If `request_update` is
|
|
463
|
+
* `update_requested` (1), the receiver MUST send its own KeyUpdate (with
|
|
464
|
+
* `update_not_requested`) and then update its *sending* keys.
|
|
465
|
+
*/
|
|
466
|
+
async handleKeyUpdate(body) {
|
|
467
|
+
if (body.length === 0) {
|
|
468
|
+
throw new TlsHandshakeError("application", {
|
|
469
|
+
cause: new Error("KeyUpdate message body too short for request_update byte"),
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
const requestUpdate = body[0];
|
|
473
|
+
if (requestUpdate === undefined || requestUpdate > 1) {
|
|
474
|
+
throw new TlsHandshakeError("application", {
|
|
475
|
+
cause: new Error(`invalid KeyUpdate request_update value: ${requestUpdate}`),
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
// Update receiving (server) keys immediately (RFC 8446 §4.6.3).
|
|
479
|
+
const serverUpdate = updateTrafficSecrets(this.serverAppSecret, this.cipherSuite, this.crypto);
|
|
480
|
+
this.applicationSecrets = { ...this.applicationSecrets, server: serverUpdate.traffic };
|
|
481
|
+
this.serverAppSecret = serverUpdate.secret;
|
|
482
|
+
this.serverAppSeq = 0;
|
|
483
|
+
this.onDebug?.(`KeyUpdate: server (read) keys rotated, serverAppSeq reset to 0`);
|
|
484
|
+
// If the server requested an update, send our KeyUpdate and then rotate
|
|
485
|
+
// our sending (client) keys. The KeyUpdate is sent under the OLD client
|
|
486
|
+
// keys; the new keys apply to all subsequent writes.
|
|
487
|
+
if (requestUpdate === 1) {
|
|
488
|
+
// Build KeyUpdate message: type(KEY_UPDATE=24) || length(3) || request_update(0).
|
|
489
|
+
const keyUpdateMsg = new Uint8Array([HandshakeType.KEY_UPDATE, 0, 0, 1, 0]);
|
|
490
|
+
await writeEncryptedRecord(this.transport, this.aead, this.applicationSecrets.client, ContentType.HANDSHAKE, keyUpdateMsg, this.clientAppSeq, this.crypto, this.onDebug);
|
|
491
|
+
this.clientAppSeq++;
|
|
492
|
+
// Now rotate the client sending keys.
|
|
493
|
+
const clientUpdate = updateTrafficSecrets(this.clientAppSecret, this.cipherSuite, this.crypto);
|
|
494
|
+
this.applicationSecrets = { ...this.applicationSecrets, client: clientUpdate.traffic };
|
|
495
|
+
this.clientAppSecret = clientUpdate.secret;
|
|
496
|
+
this.clientAppSeq = 0;
|
|
497
|
+
this.onDebug?.(`KeyUpdate: client (write) keys rotated, clientAppSeq reset to 0`);
|
|
498
|
+
}
|
|
337
499
|
}
|
|
338
500
|
transition(next) {
|
|
339
501
|
this.state = next;
|