@browsercore/tls 0.1.3 → 0.2.0
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 +104 -4
- package/dist/certificates/cert-extensions.d.ts +46 -0
- package/dist/certificates/cert-extensions.d.ts.map +1 -0
- package/dist/certificates/cert-extensions.js +203 -0
- package/dist/certificates/cert-extensions.js.map +1 -0
- package/dist/certificates/certificates.d.ts +11 -9
- package/dist/certificates/certificates.d.ts.map +1 -1
- package/dist/certificates/certificates.js +75 -503
- package/dist/certificates/certificates.js.map +1 -1
- package/dist/certificates/der.d.ts +43 -0
- package/dist/certificates/der.d.ts.map +1 -0
- package/dist/certificates/der.js +204 -0
- package/dist/certificates/der.js.map +1 -0
- package/dist/certificates/hostname.d.ts +21 -0
- package/dist/certificates/hostname.d.ts.map +1 -0
- package/dist/certificates/hostname.js +46 -0
- package/dist/certificates/hostname.js.map +1 -0
- package/dist/certificates/pem.d.ts +11 -0
- package/dist/certificates/pem.d.ts.map +1 -0
- package/dist/certificates/pem.js +69 -0
- package/dist/certificates/pem.js.map +1 -0
- package/dist/connection/handshake-driver.d.ts +59 -0
- package/dist/connection/handshake-driver.d.ts.map +1 -0
- package/dist/connection/handshake-driver.js +137 -0
- package/dist/connection/handshake-driver.js.map +1 -0
- package/dist/connection/handshake-messages.d.ts +45 -0
- package/dist/connection/handshake-messages.d.ts.map +1 -0
- package/dist/connection/handshake-messages.js +170 -0
- package/dist/connection/handshake-messages.js.map +1 -0
- package/dist/connection/index.d.ts +19 -0
- package/dist/connection/index.d.ts.map +1 -0
- package/dist/connection/index.js +19 -0
- package/dist/connection/index.js.map +1 -0
- package/dist/connection/key-exchange.d.ts +24 -0
- package/dist/connection/key-exchange.d.ts.map +1 -0
- package/dist/connection/key-exchange.js +104 -0
- package/dist/connection/key-exchange.js.map +1 -0
- package/dist/connection/lifecycle.d.ts +38 -0
- package/dist/connection/lifecycle.d.ts.map +1 -0
- package/dist/connection/lifecycle.js +101 -0
- package/dist/connection/lifecycle.js.map +1 -0
- package/dist/connection/record-layer.d.ts +65 -0
- package/dist/connection/record-layer.d.ts.map +1 -0
- package/dist/connection/record-layer.js +140 -0
- package/dist/connection/record-layer.js.map +1 -0
- package/dist/crypto/keySchedule.d.ts +18 -3
- package/dist/crypto/keySchedule.d.ts.map +1 -1
- package/dist/crypto/keySchedule.js +82 -11
- package/dist/crypto/keySchedule.js.map +1 -1
- package/dist/errors.d.ts +43 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +60 -2
- package/dist/errors.js.map +1 -1
- package/dist/extensions/extensions.d.ts +26 -25
- package/dist/extensions/extensions.d.ts.map +1 -1
- package/dist/extensions/extensions.js +92 -49
- package/dist/extensions/extensions.js.map +1 -1
- package/dist/handshake/client-hello.d.ts +30 -0
- package/dist/handshake/client-hello.d.ts.map +1 -0
- package/dist/handshake/client-hello.js +464 -0
- package/dist/handshake/client-hello.js.map +1 -0
- package/dist/handshake/grease.d.ts +70 -0
- package/dist/handshake/grease.d.ts.map +1 -0
- package/dist/handshake/grease.js +293 -0
- package/dist/handshake/grease.js.map +1 -0
- package/dist/handshake/handshake-types.d.ts +84 -0
- package/dist/handshake/handshake-types.d.ts.map +1 -0
- package/dist/handshake/handshake-types.js +31 -0
- package/dist/handshake/handshake-types.js.map +1 -0
- package/dist/handshake/handshake.d.ts +19 -118
- package/dist/handshake/handshake.d.ts.map +1 -1
- package/dist/handshake/handshake.js +19 -412
- package/dist/handshake/handshake.js.map +1 -1
- package/dist/handshake/server-hello.d.ts +33 -0
- package/dist/handshake/server-hello.d.ts.map +1 -0
- package/dist/handshake/server-hello.js +134 -0
- package/dist/handshake/server-hello.js.map +1 -0
- package/dist/handshake/state-machine.d.ts +34 -0
- package/dist/handshake/state-machine.d.ts.map +1 -0
- package/dist/handshake/state-machine.js +105 -0
- package/dist/handshake/state-machine.js.map +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/profiles/profiles.d.ts +12 -2
- package/dist/profiles/profiles.d.ts.map +1 -1
- package/dist/profiles/profiles.js +22 -7
- package/dist/profiles/profiles.js.map +1 -1
- package/dist/record/record.d.ts +18 -1
- package/dist/record/record.d.ts.map +1 -1
- package/dist/record/record.js +79 -11
- package/dist/record/record.js.map +1 -1
- package/dist/tls.d.ts +62 -101
- package/dist/tls.d.ts.map +1 -1
- package/dist/tls.js +166 -566
- package/dist/tls.js.map +1 -1
- package/dist/types.d.ts +40 -6
- package/dist/types.d.ts.map +1 -1
- package/dist/utils.d.ts +7 -0
- package/dist/utils.d.ts.map +1 -1
- package/dist/utils.js +23 -0
- package/dist/utils.js.map +1 -1
- package/package.json +53 -48
|
@@ -4,186 +4,21 @@
|
|
|
4
4
|
* Parses DER-encoded certificates, validates hostnames against SAN/CN, and
|
|
5
5
|
* verifies certificate chains against trust anchors. The cryptographic
|
|
6
6
|
* signature verification itself is delegated to @browsercore/crypto — this module
|
|
7
|
-
* owns
|
|
7
|
+
* owns validation policy and the top-level parse/verify orchestration only.
|
|
8
|
+
*
|
|
9
|
+
* The byte-level ASN.1 decoding lives in focused submodules so each layer can be
|
|
10
|
+
* read and tested in isolation:
|
|
11
|
+
* - `der.ts` — DER tag-length-value primitives (no X.509 semantics)
|
|
12
|
+
* - `cert-extensions.ts` — subject/issuer names, SAN, KeyUsage, BasicConstraints
|
|
13
|
+
* - `pem.ts` — PEM container decoding (the only place that knows about
|
|
14
|
+
* the BEGIN/END text wrapper; downstream code sees raw DER)
|
|
8
15
|
*/
|
|
9
16
|
import { crypto } from "@browsercore/crypto";
|
|
10
|
-
import { TlsHandshakeError } from "../errors.js";
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
cause: new Error(`DER truncated at offset ${pos}`),
|
|
16
|
-
});
|
|
17
|
-
}
|
|
18
|
-
const start = pos;
|
|
19
|
-
const tagByte = buf[pos++];
|
|
20
|
-
// We only handle single-byte tags (tag number < 31); X.509 never uses the
|
|
21
|
-
// long form for the tags we care about.
|
|
22
|
-
if ((tagByte & 0x1f) === 0x1f) {
|
|
23
|
-
throw new TlsHandshakeError("certificate", {
|
|
24
|
-
cause: new Error("multi-byte DER tags are not supported"),
|
|
25
|
-
});
|
|
26
|
-
}
|
|
27
|
-
const constructed = (tagByte & 0x20) !== 0;
|
|
28
|
-
if (pos >= buf.length) {
|
|
29
|
-
throw new TlsHandshakeError("certificate", {
|
|
30
|
-
cause: new Error(`DER length truncated at offset ${pos}`),
|
|
31
|
-
});
|
|
32
|
-
}
|
|
33
|
-
const lengthByte = buf[pos++];
|
|
34
|
-
let valueStart;
|
|
35
|
-
let length;
|
|
36
|
-
if ((lengthByte & 0x80) === 0) {
|
|
37
|
-
// Short form: single-byte length.
|
|
38
|
-
length = lengthByte;
|
|
39
|
-
valueStart = pos;
|
|
40
|
-
}
|
|
41
|
-
else {
|
|
42
|
-
// Long form: the low 7 bits give the number of length bytes.
|
|
43
|
-
const numBytes = lengthByte & 0x7f;
|
|
44
|
-
if (numBytes === 0) {
|
|
45
|
-
throw new TlsHandshakeError("certificate", {
|
|
46
|
-
cause: new Error("indefinite-length DER encoding is not supported"),
|
|
47
|
-
});
|
|
48
|
-
}
|
|
49
|
-
if (numBytes > 4 || pos + numBytes > buf.length) {
|
|
50
|
-
throw new TlsHandshakeError("certificate", {
|
|
51
|
-
cause: new Error(`DER length field overflow at offset ${pos}`),
|
|
52
|
-
});
|
|
53
|
-
}
|
|
54
|
-
length = 0;
|
|
55
|
-
for (let i = 0; i < numBytes; i++) {
|
|
56
|
-
length = (length << 8) | buf[pos++];
|
|
57
|
-
}
|
|
58
|
-
valueStart = pos;
|
|
59
|
-
}
|
|
60
|
-
const end = valueStart + length;
|
|
61
|
-
if (end > buf.length) {
|
|
62
|
-
throw new TlsHandshakeError("certificate", {
|
|
63
|
-
cause: new Error(`DER value truncated: need ${length} bytes at ${valueStart}, have ${buf.length - valueStart}`),
|
|
64
|
-
});
|
|
65
|
-
}
|
|
66
|
-
return { tag: tagByte, constructed, start, valueStart, end };
|
|
67
|
-
}
|
|
68
|
-
/** Peek the tag byte at `pos` without consuming it. */
|
|
69
|
-
function peekTag(buf, pos) {
|
|
70
|
-
if (pos >= buf.length) {
|
|
71
|
-
throw new TlsHandshakeError("certificate", {
|
|
72
|
-
cause: new Error(`DER truncated while peeking tag at offset ${pos}`),
|
|
73
|
-
});
|
|
74
|
-
}
|
|
75
|
-
return buf[pos];
|
|
76
|
-
}
|
|
77
|
-
/** Parse a DER OID (without its tag/length) into its dotted-arc string. */
|
|
78
|
-
function parseOid(buf, start, end) {
|
|
79
|
-
if (start >= end) {
|
|
80
|
-
throw new TlsHandshakeError("certificate", {
|
|
81
|
-
cause: new Error("empty OID"),
|
|
82
|
-
});
|
|
83
|
-
}
|
|
84
|
-
// The first byte encodes the first two arcs: floor(first / 40), first % 40.
|
|
85
|
-
const first = buf[start];
|
|
86
|
-
const arcs = [Math.floor(first / 40), first % 40];
|
|
87
|
-
let i = start + 1;
|
|
88
|
-
while (i < end) {
|
|
89
|
-
// Subsequent arcs are base-128 with the high bit as a continuation flag.
|
|
90
|
-
let value = 0;
|
|
91
|
-
let b;
|
|
92
|
-
do {
|
|
93
|
-
if (i >= end) {
|
|
94
|
-
throw new TlsHandshakeError("certificate", {
|
|
95
|
-
cause: new Error("OID arc truncated"),
|
|
96
|
-
});
|
|
97
|
-
}
|
|
98
|
-
b = buf[i++];
|
|
99
|
-
// Guard against overflow on absurdly long arcs.
|
|
100
|
-
value = (value << 7) | (b & 0x7f);
|
|
101
|
-
} while ((b & 0x80) !== 0);
|
|
102
|
-
arcs.push(value);
|
|
103
|
-
}
|
|
104
|
-
return arcs.join(".");
|
|
105
|
-
}
|
|
106
|
-
/** Parse a DER AlgorithmIdentifier (SEQUENCE { OID, parameters? }) into its OID string. */
|
|
107
|
-
function parseAlgorithmIdentifierOid(buf, start) {
|
|
108
|
-
const seq = readTlv(buf, start);
|
|
109
|
-
if (seq.tag !== 0x30) {
|
|
110
|
-
throw new TlsHandshakeError("certificate", {
|
|
111
|
-
cause: new Error(`expected AlgorithmIdentifier SEQUENCE, got tag 0x${seq.tag.toString(16)}`),
|
|
112
|
-
});
|
|
113
|
-
}
|
|
114
|
-
if (seq.valueStart >= seq.end) {
|
|
115
|
-
throw new TlsHandshakeError("certificate", {
|
|
116
|
-
cause: new Error("empty AlgorithmIdentifier"),
|
|
117
|
-
});
|
|
118
|
-
}
|
|
119
|
-
const oidTlv = readTlv(buf, seq.valueStart);
|
|
120
|
-
if (oidTlv.tag !== 0x06) {
|
|
121
|
-
throw new TlsHandshakeError("certificate", {
|
|
122
|
-
cause: new Error(`expected OID in AlgorithmIdentifier, got tag 0x${oidTlv.tag.toString(16)}`),
|
|
123
|
-
});
|
|
124
|
-
}
|
|
125
|
-
return parseOid(buf, oidTlv.valueStart, oidTlv.end);
|
|
126
|
-
}
|
|
127
|
-
/**
|
|
128
|
-
* Parse a DER ASN.1 TIME (UTCTime 0x17 or GeneralizedTime 0x18) into epoch
|
|
129
|
-
* seconds. Handles the "...Z" UTC suffix; fractional seconds are ignored.
|
|
130
|
-
*/
|
|
131
|
-
function parseTime(buf, start, end, tag) {
|
|
132
|
-
const textDecoder = new TextDecoder();
|
|
133
|
-
const str = textDecoder.decode(buf.subarray(start, end)).trim();
|
|
134
|
-
// UTCTime: YYMMDDHHMMSSZ. GeneralizedTime: YYYYMMDDHHMMSS[.fff]Z.
|
|
135
|
-
const isUtc = tag === 0x17;
|
|
136
|
-
if (str.length < (isUtc ? 11 : 13)) {
|
|
137
|
-
throw new TlsHandshakeError("certificate", {
|
|
138
|
-
cause: new Error(`ASN.1 TIME too short: "${str}"`),
|
|
139
|
-
});
|
|
140
|
-
}
|
|
141
|
-
const yearStr = str.slice(0, isUtc ? 2 : 4);
|
|
142
|
-
let year = Number.parseInt(yearStr, 10);
|
|
143
|
-
if (Number.isNaN(year)) {
|
|
144
|
-
throw new TlsHandshakeError("certificate", {
|
|
145
|
-
cause: new Error(`invalid year in ASN.1 TIME: "${str}"`),
|
|
146
|
-
});
|
|
147
|
-
}
|
|
148
|
-
if (isUtc) {
|
|
149
|
-
// RFC 5280: UTCTime years 50..99 => 1950..1999; 00..49 => 2000..2049.
|
|
150
|
-
year += year >= 50 ? 1900 : 2000;
|
|
151
|
-
}
|
|
152
|
-
const month = Number.parseInt(str.slice(isUtc ? 2 : 4, isUtc ? 4 : 6), 10) - 1;
|
|
153
|
-
const day = Number.parseInt(str.slice(isUtc ? 4 : 6, isUtc ? 6 : 8), 10);
|
|
154
|
-
const hour = Number.parseInt(str.slice(isUtc ? 6 : 8, isUtc ? 8 : 10), 10);
|
|
155
|
-
const minute = Number.parseInt(str.slice(isUtc ? 8 : 10, isUtc ? 10 : 12), 10);
|
|
156
|
-
const second = Number.parseInt(str.slice(isUtc ? 10 : 12, isUtc ? 12 : 14), 10);
|
|
157
|
-
// Date.UTC returns ms since epoch in UTC.
|
|
158
|
-
const ms = Date.UTC(year, month, day, hour, minute, second);
|
|
159
|
-
if (Number.isNaN(ms)) {
|
|
160
|
-
throw new TlsHandshakeError("certificate", {
|
|
161
|
-
cause: new Error(`invalid ASN.1 TIME: "${str}"`),
|
|
162
|
-
});
|
|
163
|
-
}
|
|
164
|
-
return Math.floor(ms / 1000);
|
|
165
|
-
}
|
|
166
|
-
/**
|
|
167
|
-
* Map an issuer signature-algorithm OID to our {@link SignatureScheme} union.
|
|
168
|
-
* Only the schemes we advertise are recognized; anything else throws.
|
|
169
|
-
*/
|
|
170
|
-
function oidToSignatureScheme(oid) {
|
|
171
|
-
switch (oid) {
|
|
172
|
-
case "1.2.840.10045.4.3.2":
|
|
173
|
-
return "ecdsa_secp256r1_sha256";
|
|
174
|
-
case "1.2.840.10045.4.3.3":
|
|
175
|
-
return "ecdsa_secp384r1_sha384";
|
|
176
|
-
case "1.2.840.113549.1.1.11":
|
|
177
|
-
return "rsa_pkcs1_sha256";
|
|
178
|
-
case "1.2.840.113549.1.1.10":
|
|
179
|
-
// id-RSASSA-PSS: the hash is in the parameters; default to sha256.
|
|
180
|
-
return "rsa_pss_rsae_sha256";
|
|
181
|
-
default:
|
|
182
|
-
throw new TlsHandshakeError("certificate", {
|
|
183
|
-
cause: new Error(`unsupported signature algorithm OID: ${oid}`),
|
|
184
|
-
});
|
|
185
|
-
}
|
|
186
|
-
}
|
|
17
|
+
import { TlsHandshakeError, ensureTlsError } from "../errors.js";
|
|
18
|
+
import { constantTimeEqual } from "../utils.js";
|
|
19
|
+
import { validateHostname } from "./hostname.js";
|
|
20
|
+
import { oidToSignatureScheme, parseAlgorithmIdentifierOid, parseTime, peekTag, readTlv, } from "./der.js";
|
|
21
|
+
import { parseBasicConstraints, parseCommonName, parseExtensionsBlock, parseKeyUsage, parseName, parseSubjectAltNames, } from "./cert-extensions.js";
|
|
187
22
|
/**
|
|
188
23
|
* Parse a single DER-encoded X.509 certificate.
|
|
189
24
|
*
|
|
@@ -281,7 +116,6 @@ export function parseCertificate(buf) {
|
|
|
281
116
|
case "2.5.29.19":
|
|
282
117
|
isCa = parseBasicConstraints(ext.value);
|
|
283
118
|
break;
|
|
284
|
-
case "2.5.29.35":
|
|
285
119
|
default:
|
|
286
120
|
break;
|
|
287
121
|
}
|
|
@@ -345,229 +179,11 @@ export function parseCertificate(buf) {
|
|
|
345
179
|
isCa,
|
|
346
180
|
};
|
|
347
181
|
}
|
|
348
|
-
/**
|
|
349
|
-
* Parse the subject Name and return a readable DN string (RFC 2253-ish).
|
|
350
|
-
* Used only for the `issuer` field and debug-friendliness.
|
|
351
|
-
*/
|
|
352
|
-
function parseName(buf, start, _end) {
|
|
353
|
-
void _end;
|
|
354
|
-
const seq = readTlv(buf, start);
|
|
355
|
-
if (seq.tag !== 0x30) {
|
|
356
|
-
return "";
|
|
357
|
-
}
|
|
358
|
-
const rdnParts = [];
|
|
359
|
-
let o = seq.valueStart;
|
|
360
|
-
const textDecoder = new TextDecoder();
|
|
361
|
-
while (o < seq.end) {
|
|
362
|
-
// Each RelativeDistinguishedName is a SET of AttributeTypeAndValue.
|
|
363
|
-
const setTlv = readTlv(buf, o);
|
|
364
|
-
if (setTlv.tag !== 0x31) {
|
|
365
|
-
break;
|
|
366
|
-
}
|
|
367
|
-
let p = setTlv.valueStart;
|
|
368
|
-
if (p >= setTlv.end) {
|
|
369
|
-
o = setTlv.end;
|
|
370
|
-
continue;
|
|
371
|
-
}
|
|
372
|
-
const atv = readTlv(buf, p);
|
|
373
|
-
if (atv.tag !== 0x30) {
|
|
374
|
-
o = setTlv.end;
|
|
375
|
-
continue;
|
|
376
|
-
}
|
|
377
|
-
const oidTlv = readTlv(buf, atv.valueStart);
|
|
378
|
-
const oid = parseOid(buf, oidTlv.valueStart, oidTlv.end);
|
|
379
|
-
const valueTlv = readTlv(buf, oidTlv.end);
|
|
380
|
-
const value = textDecoder.decode(buf.subarray(valueTlv.valueStart, valueTlv.end));
|
|
381
|
-
rdnParts.push(`${oid}=${value}`);
|
|
382
|
-
o = setTlv.end;
|
|
383
|
-
}
|
|
384
|
-
return rdnParts.join(", ");
|
|
385
|
-
}
|
|
386
|
-
/** Extract the CN (OID 2.5.4.3) from a subject Name, if present. */
|
|
387
|
-
function parseCommonName(buf, start, _end) {
|
|
388
|
-
void _end;
|
|
389
|
-
const seq = readTlv(buf, start);
|
|
390
|
-
if (seq.tag !== 0x30) {
|
|
391
|
-
return undefined;
|
|
392
|
-
}
|
|
393
|
-
let o = seq.valueStart;
|
|
394
|
-
const textDecoder = new TextDecoder();
|
|
395
|
-
while (o < seq.end) {
|
|
396
|
-
const setTlv = readTlv(buf, o);
|
|
397
|
-
if (setTlv.tag !== 0x31) {
|
|
398
|
-
break;
|
|
399
|
-
}
|
|
400
|
-
let p = setTlv.valueStart;
|
|
401
|
-
while (p < setTlv.end) {
|
|
402
|
-
const atv = readTlv(buf, p);
|
|
403
|
-
if (atv.tag !== 0x30) {
|
|
404
|
-
break;
|
|
405
|
-
}
|
|
406
|
-
const oidTlv = readTlv(buf, atv.valueStart);
|
|
407
|
-
const oid = parseOid(buf, oidTlv.valueStart, oidTlv.end);
|
|
408
|
-
if (oid === "2.5.4.3") {
|
|
409
|
-
const valueTlv = readTlv(buf, oidTlv.end);
|
|
410
|
-
return textDecoder.decode(buf.subarray(valueTlv.valueStart, valueTlv.end));
|
|
411
|
-
}
|
|
412
|
-
p = atv.end;
|
|
413
|
-
}
|
|
414
|
-
o = setTlv.end;
|
|
415
|
-
}
|
|
416
|
-
return undefined;
|
|
417
|
-
}
|
|
418
|
-
/**
|
|
419
|
-
* Parse the extensions block (SEQUENCE OF Extension) between `start` and `end`.
|
|
420
|
-
* Each extension is SEQUENCE { extnID OID, critical BOOLEAN?, extnValue OCTET STRING }.
|
|
421
|
-
*/
|
|
422
|
-
function parseExtensionsBlock(buf, start, _end) {
|
|
423
|
-
void _end;
|
|
424
|
-
const seq = readTlv(buf, start);
|
|
425
|
-
if (seq.tag !== 0x30) {
|
|
426
|
-
throw new TlsHandshakeError("certificate", {
|
|
427
|
-
cause: new Error(`expected extensions SEQUENCE, got tag 0x${seq.tag.toString(16)}`),
|
|
428
|
-
});
|
|
429
|
-
}
|
|
430
|
-
const extensions = [];
|
|
431
|
-
let o = seq.valueStart;
|
|
432
|
-
while (o < seq.end) {
|
|
433
|
-
const ext = readTlv(buf, o);
|
|
434
|
-
if (ext.tag !== 0x30) {
|
|
435
|
-
break;
|
|
436
|
-
}
|
|
437
|
-
let p = ext.valueStart;
|
|
438
|
-
const oidTlv = readTlv(buf, p);
|
|
439
|
-
const oid = parseOid(buf, oidTlv.valueStart, oidTlv.end);
|
|
440
|
-
p = oidTlv.end;
|
|
441
|
-
// Optional critical BOOLEAN.
|
|
442
|
-
if (peekTag(buf, p) === 0x01) {
|
|
443
|
-
p = readTlv(buf, p).end;
|
|
444
|
-
}
|
|
445
|
-
const valueTlv = readTlv(buf, p);
|
|
446
|
-
if (valueTlv.tag !== 0x04) {
|
|
447
|
-
throw new TlsHandshakeError("certificate", {
|
|
448
|
-
cause: new Error(`expected extnValue OCTET STRING, got tag 0x${valueTlv.tag.toString(16)}`),
|
|
449
|
-
});
|
|
450
|
-
}
|
|
451
|
-
// The extnValue OCTET STRING *contains* the DER-encoded extension value.
|
|
452
|
-
extensions.push({ oid, value: buf.subarray(valueTlv.valueStart, valueTlv.end) });
|
|
453
|
-
o = ext.end;
|
|
454
|
-
}
|
|
455
|
-
return extensions;
|
|
456
|
-
}
|
|
457
|
-
/**
|
|
458
|
-
* Parse the SAN extension value (already unwrapped from its OCTET STRING).
|
|
459
|
-
* The value is a SEQUENCE OF GeneralName; we only extract dNSName entries
|
|
460
|
-
* (context tag [2]).
|
|
461
|
-
*/
|
|
462
|
-
function parseSubjectAltNames(value) {
|
|
463
|
-
const seq = readTlv(value, 0);
|
|
464
|
-
if (seq.tag !== 0x30) {
|
|
465
|
-
return Object.freeze([]);
|
|
466
|
-
}
|
|
467
|
-
const names = [];
|
|
468
|
-
const textDecoder = new TextDecoder();
|
|
469
|
-
let o = seq.valueStart;
|
|
470
|
-
while (o < seq.end) {
|
|
471
|
-
const tlv = readTlv(value, o);
|
|
472
|
-
// GeneralName: context-specific tag. dNSName is [2] (0x82), iPAddress [7].
|
|
473
|
-
const tag = tlv.tag;
|
|
474
|
-
const tagClass = tag & 0xc0;
|
|
475
|
-
const tagNumber = tag & 0x1f;
|
|
476
|
-
if (tagClass === 0x80 && tagNumber === 2) {
|
|
477
|
-
names.push(textDecoder.decode(value.subarray(tlv.valueStart, tlv.end)));
|
|
478
|
-
}
|
|
479
|
-
o = tlv.end;
|
|
480
|
-
}
|
|
481
|
-
return Object.freeze(names);
|
|
482
|
-
}
|
|
483
|
-
/**
|
|
484
|
-
* Parse the KeyUsage extension value (unwrapped OCTET STRING holding a BIT
|
|
485
|
-
* STRING). Returns the digitalSignature (bit 0) and keyEncipherment (bit 2)
|
|
486
|
-
* flags.
|
|
487
|
-
*/
|
|
488
|
-
function parseKeyUsage(value) {
|
|
489
|
-
const bitString = readTlv(value, 0);
|
|
490
|
-
if (bitString.tag !== 0x03) {
|
|
491
|
-
return { digitalSignature: false, keyEncipherment: false };
|
|
492
|
-
}
|
|
493
|
-
// BIT STRING content: first byte = number of unused bits; then the bits.
|
|
494
|
-
const content = value.subarray(bitString.valueStart, bitString.end);
|
|
495
|
-
if (content.length < 2) {
|
|
496
|
-
return { digitalSignature: false, keyEncipherment: false };
|
|
497
|
-
}
|
|
498
|
-
// Pack the used bits into an integer (big-endian bit order).
|
|
499
|
-
const usedBytes = content.subarray(1); // skip the unused-bits count.
|
|
500
|
-
let bits = 0;
|
|
501
|
-
for (const byte of usedBytes) {
|
|
502
|
-
bits = (bits << 8) | byte;
|
|
503
|
-
}
|
|
504
|
-
// The bits are left-aligned; the real bit 0 is the most significant bit of
|
|
505
|
-
// the first used byte. digitalSignature = bit 0, keyEncipherment = bit 2.
|
|
506
|
-
const totalBits = usedBytes.length * 8;
|
|
507
|
-
const bitPosition = (bitIndex) => totalBits - 1 - bitIndex;
|
|
508
|
-
const getBit = (index) => {
|
|
509
|
-
const pos = bitPosition(index);
|
|
510
|
-
const byteIndex = Math.floor(pos / 8);
|
|
511
|
-
const bitInByte = pos % 8;
|
|
512
|
-
return (usedBytes[byteIndex] & (1 << (7 - bitInByte))) !== 0;
|
|
513
|
-
};
|
|
514
|
-
return {
|
|
515
|
-
digitalSignature: getBit(0),
|
|
516
|
-
keyEncipherment: getBit(2),
|
|
517
|
-
};
|
|
518
|
-
}
|
|
519
|
-
/**
|
|
520
|
-
* Parse the BasicConstraints extension value (unwrapped OCTET STRING holding a
|
|
521
|
-
* SEQUENCE { cA BOOLEAN DEFAULT FALSE, pathLenConstraint INTEGER? }).
|
|
522
|
-
*/
|
|
523
|
-
function parseBasicConstraints(value) {
|
|
524
|
-
const seq = readTlv(value, 0);
|
|
525
|
-
if (seq.tag !== 0x30 || seq.valueStart >= seq.end) {
|
|
526
|
-
return false;
|
|
527
|
-
}
|
|
528
|
-
if (peekTag(value, seq.valueStart) !== 0x01) {
|
|
529
|
-
return false;
|
|
530
|
-
}
|
|
531
|
-
const boolTlv = readTlv(value, seq.valueStart);
|
|
532
|
-
return value[boolTlv.valueStart] !== 0;
|
|
533
|
-
}
|
|
534
182
|
/**
|
|
535
183
|
* Validate that a certificate is valid for the given hostname per RFC 6125.
|
|
536
|
-
*
|
|
537
|
-
* If the cert carries SAN DNS names, one must match (wildcard-aware, matching
|
|
538
|
-
* a single left-most label and NOT crossing dots). Otherwise we fall back to
|
|
539
|
-
* the legacy CommonName. IP-literal SANs are not matched here (server certs
|
|
540
|
-
* virtually always use DNS names).
|
|
184
|
+
* (Moved to {@link ./hostname.js} — re-exported here for the stable import path.)
|
|
541
185
|
*/
|
|
542
|
-
export
|
|
543
|
-
const names = cert.subjectAltNames;
|
|
544
|
-
if (names.length > 0) {
|
|
545
|
-
return names.some((name) => matchDnsName(name, hostname));
|
|
546
|
-
}
|
|
547
|
-
if (cert.commonName !== undefined) {
|
|
548
|
-
return matchDnsName(cert.commonName, hostname);
|
|
549
|
-
}
|
|
550
|
-
return false;
|
|
551
|
-
}
|
|
552
|
-
/** Match a DNS name (possibly wildcard) against a concrete hostname (RFC 6125 §6.4.3). */
|
|
553
|
-
function matchDnsName(pattern, hostname) {
|
|
554
|
-
const p = pattern.trim().toLowerCase();
|
|
555
|
-
const h = hostname.trim().toLowerCase();
|
|
556
|
-
if (p.length === 0 || h.length === 0) {
|
|
557
|
-
return false;
|
|
558
|
-
}
|
|
559
|
-
// Wildcard: only a leading "*." matches a single non-empty left label.
|
|
560
|
-
if (p.startsWith("*.")) {
|
|
561
|
-
const suffix = p.slice(1); // e.g. ".example.com"
|
|
562
|
-
// The prefix before the suffix must be exactly one label (no dots).
|
|
563
|
-
const prefix = h.slice(0, h.length - suffix.length);
|
|
564
|
-
if (!h.endsWith(suffix)) {
|
|
565
|
-
return false;
|
|
566
|
-
}
|
|
567
|
-
return prefix.length > 0 && !prefix.includes(".");
|
|
568
|
-
}
|
|
569
|
-
return p === h;
|
|
570
|
-
}
|
|
186
|
+
export { validateHostname, matchDnsName } from "./hostname.js";
|
|
571
187
|
/**
|
|
572
188
|
* Verify a certificate chain: each cert is signed by the next, the root is in
|
|
573
189
|
* the trust anchors, and the leaf is valid for the hostname and not expired.
|
|
@@ -575,118 +191,74 @@ function matchDnsName(pattern, hostname) {
|
|
|
575
191
|
* Signature verification is delegated to @browsercore/crypto. Throws
|
|
576
192
|
* {@link TlsHandshakeError} with phase "certificate" on any failure.
|
|
577
193
|
*/
|
|
578
|
-
export
|
|
579
|
-
|
|
580
|
-
//
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
194
|
+
export function verifyChain(chain, trustAnchors, hostname, now) {
|
|
195
|
+
// Not async: crypto.verifySignature returns a synchronous boolean (awaiting it
|
|
196
|
+
// would be an error). Synchronous throws are caught and returned as a rejected
|
|
197
|
+
// promise so callers can await uniformly; the original TlsHandshakeError is
|
|
198
|
+
// propagated as-is (not re-wrapped) so its type reaches the caller.
|
|
199
|
+
try {
|
|
200
|
+
const certs = [chain.leaf, ...chain.intermediates, chain.root];
|
|
201
|
+
// 1. Validity windows: every cert must currently be valid.
|
|
202
|
+
for (const cert of certs) {
|
|
203
|
+
if (now < cert.notBefore || now > cert.notAfter) {
|
|
204
|
+
throw new TlsHandshakeError("certificate", {
|
|
205
|
+
cause: new Error(`certificate ${cert.issuer} not valid at ${now} (valid ${cert.notBefore}..${cert.notAfter})`),
|
|
206
|
+
});
|
|
207
|
+
}
|
|
586
208
|
}
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
209
|
+
// 2. basicConstraints CA flags: every intermediate must be a CA. The root
|
|
210
|
+
// is authorized by the trust-anchor SPKI match (step 4), not by its own
|
|
211
|
+
// basicConstraints, so a self-signed trust anchor need not set cA.
|
|
212
|
+
for (const cert of chain.intermediates) {
|
|
213
|
+
if (!cert.isCa) {
|
|
214
|
+
throw new TlsHandshakeError("certificate", {
|
|
215
|
+
cause: new Error(`intermediate certificate ${cert.issuer} is missing basicConstraints cA`),
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
// 3. For each (subject, issuer) pair, verify the signature. The issuer's
|
|
220
|
+
// public key (SPKI) verifies the subject's signature over its TBSCertificate.
|
|
221
|
+
const subjects = [chain.leaf, ...chain.intermediates];
|
|
222
|
+
const issuers = [...chain.intermediates, chain.root];
|
|
223
|
+
for (let i = 0; i < subjects.length; i++) {
|
|
224
|
+
const subject = subjects[i];
|
|
225
|
+
const issuer = issuers[i];
|
|
226
|
+
if (subject === undefined || issuer === undefined) {
|
|
227
|
+
throw new TlsHandshakeError("certificate", {
|
|
228
|
+
cause: new Error(`certificate chain entry at index ${i} is missing`),
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
const ok = crypto.verifySignature(subject.signatureScheme, issuer.subjectPublicKeyInfo, subject.signatureValue, subject.tbsBytes);
|
|
232
|
+
if (!ok) {
|
|
233
|
+
throw new TlsHandshakeError("certificate", {
|
|
234
|
+
cause: new Error(`signature verification failed: ${subject.issuer} not signed by ${issuer.issuer}`),
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
// 4. The chain root's SPKI must match one of the trust anchors.
|
|
239
|
+
const rootTrusted = trustAnchors.some((ta) => constantTimeEqual(ta.subjectPublicKeyInfo, chain.root.subjectPublicKeyInfo));
|
|
240
|
+
if (!rootTrusted) {
|
|
593
241
|
throw new TlsHandshakeError("certificate", {
|
|
594
|
-
cause: new Error(`
|
|
242
|
+
cause: new Error(`root certificate ${chain.root.issuer} does not match any trust anchor`),
|
|
595
243
|
});
|
|
596
244
|
}
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
// public key (SPKI) verifies the subject's signature over its TBSCertificate.
|
|
600
|
-
const subjects = [chain.leaf, ...chain.intermediates];
|
|
601
|
-
const issuers = [...chain.intermediates, chain.root];
|
|
602
|
-
for (let i = 0; i < subjects.length; i++) {
|
|
603
|
-
const subject = subjects[i];
|
|
604
|
-
const issuer = issuers[i];
|
|
605
|
-
const ok = await crypto.verifySignature(subject.signatureScheme, issuer.subjectPublicKeyInfo, subject.signatureValue, subject.tbsBytes);
|
|
606
|
-
if (!ok) {
|
|
245
|
+
// 5. Hostname validation against the leaf.
|
|
246
|
+
if (!validateHostname(chain.leaf, hostname)) {
|
|
607
247
|
throw new TlsHandshakeError("certificate", {
|
|
608
|
-
cause: new Error(`
|
|
248
|
+
cause: new Error(`hostname "${hostname}" does not match leaf certificate`),
|
|
609
249
|
});
|
|
610
250
|
}
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
// 5. Hostname validation against the leaf.
|
|
620
|
-
if (!validateHostname(chain.leaf, hostname)) {
|
|
621
|
-
throw new TlsHandshakeError("certificate", {
|
|
622
|
-
cause: new Error(`hostname "${hostname}" does not match leaf certificate`),
|
|
623
|
-
});
|
|
624
|
-
}
|
|
625
|
-
}
|
|
626
|
-
/** Parse a PEM block (base64 between BEGIN/END CERTIFICATE) into DER bytes. */
|
|
627
|
-
export function pemToDer(pem) {
|
|
628
|
-
const beginMarker = "-----BEGIN CERTIFICATE-----";
|
|
629
|
-
const endMarker = "-----END CERTIFICATE-----";
|
|
630
|
-
const begin = pem.indexOf(beginMarker);
|
|
631
|
-
const end = pem.indexOf(endMarker);
|
|
632
|
-
if (begin === -1 || end === -1 || end <= begin) {
|
|
633
|
-
throw new Error("pemToDer: missing BEGIN/END CERTIFICATE markers");
|
|
634
|
-
}
|
|
635
|
-
const body = pem.slice(begin + beginMarker.length, end);
|
|
636
|
-
// Strip all whitespace (newlines, spaces) and base64-decode.
|
|
637
|
-
const cleaned = body.replace(/\s+/g, "");
|
|
638
|
-
const binary = base64Decode(cleaned);
|
|
639
|
-
return new Uint8Array(binary);
|
|
640
|
-
}
|
|
641
|
-
// ---------------------------------------------------------------------------
|
|
642
|
-
// Small byte helpers.
|
|
643
|
-
// ---------------------------------------------------------------------------
|
|
644
|
-
/** Constant-time byte comparison (length-equal only; leaks length, not contents). */
|
|
645
|
-
function constantTimeEqual(a, b) {
|
|
646
|
-
if (a.length !== b.length) {
|
|
647
|
-
return false;
|
|
648
|
-
}
|
|
649
|
-
let diff = 0;
|
|
650
|
-
for (let i = 0; i < a.length; i++) {
|
|
651
|
-
diff |= a[i] ^ b[i];
|
|
652
|
-
}
|
|
653
|
-
return diff === 0;
|
|
654
|
-
}
|
|
655
|
-
/** Base64-decode a string into bytes (no node:crypto dependency). */
|
|
656
|
-
function base64Decode(input) {
|
|
657
|
-
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
658
|
-
const decodeTable = new Int16Array(128).fill(-1);
|
|
659
|
-
for (let i = 0; i < alphabet.length; i++) {
|
|
660
|
-
decodeTable[alphabet.charCodeAt(i)] = i;
|
|
661
|
-
}
|
|
662
|
-
// Strip padding to compute output length.
|
|
663
|
-
let padding = 0;
|
|
664
|
-
for (let i = input.length - 1; i >= 0; i--) {
|
|
665
|
-
if (input[i] === "=") {
|
|
666
|
-
padding++;
|
|
667
|
-
}
|
|
668
|
-
else {
|
|
669
|
-
break;
|
|
670
|
-
}
|
|
671
|
-
}
|
|
672
|
-
const cleanLen = input.length - padding;
|
|
673
|
-
const outLen = Math.floor((cleanLen * 6) / 8);
|
|
674
|
-
const out = new Uint8Array(outLen);
|
|
675
|
-
let buffer = 0;
|
|
676
|
-
let bitsCollected = 0;
|
|
677
|
-
let outIndex = 0;
|
|
678
|
-
for (let i = 0; i < cleanLen; i++) {
|
|
679
|
-
const value = decodeTable[input.charCodeAt(i)];
|
|
680
|
-
if (value < 0) {
|
|
681
|
-
continue; // skip any non-alphabet char (shouldn't happen post-clean)
|
|
682
|
-
}
|
|
683
|
-
buffer = (buffer << 6) | value;
|
|
684
|
-
bitsCollected += 6;
|
|
685
|
-
if (bitsCollected >= 8) {
|
|
686
|
-
bitsCollected -= 8;
|
|
687
|
-
out[outIndex++] = (buffer >> bitsCollected) & 0xff;
|
|
251
|
+
return Promise.resolve();
|
|
252
|
+
}
|
|
253
|
+
catch (cause) {
|
|
254
|
+
// Every throw in the body is a TlsHandshakeError (an Error); keep the
|
|
255
|
+
// original rejection so its type reaches the caller. Only fall back to a
|
|
256
|
+
// generic TlsError if a non-Error somehow escapes.
|
|
257
|
+
if (cause instanceof Error) {
|
|
258
|
+
return Promise.reject(cause);
|
|
688
259
|
}
|
|
260
|
+
return Promise.reject(ensureTlsError(cause));
|
|
689
261
|
}
|
|
690
|
-
return out;
|
|
691
262
|
}
|
|
263
|
+
export { pemToDer } from "./pem.js";
|
|
692
264
|
//# sourceMappingURL=certificates.js.map
|