@browsercore/tls 0.4.19 → 0.4.21

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.
Files changed (66) hide show
  1. package/README.md +140 -23
  2. package/dist/certificates/ca-constraints.d.ts +15 -13
  3. package/dist/certificates/ca-constraints.d.ts.map +1 -1
  4. package/dist/certificates/ca-constraints.js +41 -59
  5. package/dist/certificates/ca-constraints.js.map +1 -1
  6. package/dist/certificates/cert-extensions.d.ts +59 -9
  7. package/dist/certificates/cert-extensions.d.ts.map +1 -1
  8. package/dist/certificates/cert-extensions.js +104 -50
  9. package/dist/certificates/cert-extensions.js.map +1 -1
  10. package/dist/certificates/certificate-path.d.ts +66 -7
  11. package/dist/certificates/certificate-path.d.ts.map +1 -1
  12. package/dist/certificates/certificate-path.js +125 -11
  13. package/dist/certificates/certificate-path.js.map +1 -1
  14. package/dist/certificates/certificates.d.ts.map +1 -1
  15. package/dist/certificates/certificates.js +107 -29
  16. package/dist/certificates/certificates.js.map +1 -1
  17. package/dist/certificates/extension-policy.d.ts +16 -6
  18. package/dist/certificates/extension-policy.d.ts.map +1 -1
  19. package/dist/certificates/extension-policy.js +17 -6
  20. package/dist/certificates/extension-policy.js.map +1 -1
  21. package/dist/certificates/extension-values.d.ts +131 -0
  22. package/dist/certificates/extension-values.d.ts.map +1 -0
  23. package/dist/certificates/extension-values.js +443 -0
  24. package/dist/certificates/extension-values.js.map +1 -0
  25. package/dist/certificates/general-names.d.ts +142 -0
  26. package/dist/certificates/general-names.d.ts.map +1 -0
  27. package/dist/certificates/general-names.js +354 -0
  28. package/dist/certificates/general-names.js.map +1 -0
  29. package/dist/certificates/name-constraints.d.ts +245 -0
  30. package/dist/certificates/name-constraints.d.ts.map +1 -0
  31. package/dist/certificates/name-constraints.js +692 -0
  32. package/dist/certificates/name-constraints.js.map +1 -0
  33. package/dist/certificates/name-match.d.ts +59 -0
  34. package/dist/certificates/name-match.d.ts.map +1 -0
  35. package/dist/certificates/name-match.js +271 -0
  36. package/dist/certificates/name-match.js.map +1 -0
  37. package/dist/errors.d.ts +61 -1
  38. package/dist/errors.d.ts.map +1 -1
  39. package/dist/errors.js +48 -0
  40. package/dist/errors.js.map +1 -1
  41. package/dist/handshake/client-hello.d.ts +16 -2
  42. package/dist/handshake/client-hello.d.ts.map +1 -1
  43. package/dist/handshake/client-hello.js +38 -5
  44. package/dist/handshake/client-hello.js.map +1 -1
  45. package/dist/handshake/handshake.d.ts +1 -1
  46. package/dist/handshake/handshake.d.ts.map +1 -1
  47. package/dist/handshake/handshake.js.map +1 -1
  48. package/dist/index.d.ts +2 -2
  49. package/dist/index.d.ts.map +1 -1
  50. package/dist/index.js +1 -1
  51. package/dist/index.js.map +1 -1
  52. package/dist/session/binder.d.ts +76 -0
  53. package/dist/session/binder.d.ts.map +1 -0
  54. package/dist/session/binder.js +107 -0
  55. package/dist/session/binder.js.map +1 -0
  56. package/dist/session/psk-extension.d.ts +49 -0
  57. package/dist/session/psk-extension.d.ts.map +1 -0
  58. package/dist/session/psk-extension.js +96 -0
  59. package/dist/session/psk-extension.js.map +1 -0
  60. package/dist/session/psk-offer.d.ts +52 -0
  61. package/dist/session/psk-offer.d.ts.map +1 -0
  62. package/dist/session/psk-offer.js +62 -0
  63. package/dist/session/psk-offer.js.map +1 -0
  64. package/dist/types.d.ts +28 -1
  65. package/dist/types.d.ts.map +1 -1
  66. package/package.json +2 -2
@@ -0,0 +1,692 @@
1
+ /**
2
+ * nameConstraints processing (RFC 5280 §4.2.1.10), byte-for-byte the behavior
3
+ * of BoringSSL pki/name_constraints.cc at the revision Chromium 140 pins
4
+ * (0a0009998fa180695f3e2071805dc03c9a5f3124 — the file this module is a line-
5
+ * by-line twin of). Chrome never runs a different name-constraint engine for
6
+ * TLS server authentication: cert_verify_proc_builtin.cc just passes
7
+ * KeyPurpose::SERVER_AUTH to the CertPathBuilder and the pki verifier does
8
+ * the rest.
9
+ *
10
+ * Parse (NameConstraints::Parse):
11
+ * - the extnValue content is ONE SEQUENCE { permittedSubtrees [0] EXPLICIT
12
+ * GeneralSubtrees OPTIONAL, excludedSubtrees [1] EXPLICIT GeneralSubtrees
13
+ * OPTIONAL } with no trailing data;
14
+ * - both subtrees absent is a parse failure — RFC 5280: "Conforming CAs
15
+ * MUST NOT issue certificates where name constraints is an empty
16
+ * sequence" (name_constraints.cc:360-366);
17
+ * - each GeneralSubtrees SEQUENCE must hold ≥ 1 GeneralSubtree, and each
18
+ * GeneralSubtree is { base GeneralName } with NOTHING after the base:
19
+ * `if (subtree_sequence.HasMore()) { return false; }` (name_constraints.cc
20
+ * 179-181) rejects an explicit minimum [0] (even minimum=0 — the RFC's
21
+ * "the minimum MUST be zero" is implemented as "the field must be
22
+ * omitted, as DEFAULT requires in DER") and a maximum [1] alike;
23
+ * - an iPAddress base must be 8 or 32 octets with a contiguous-ones netmask
24
+ * (general_names.cc: RFC 5280 §4.2.1.10 "MUST contain eight (8) octets,
25
+ * encoded in the style of RFC 4632 (CIDR) … 32 octets"); a dNSName /
26
+ * rfc822Name base must be ASCII; an unknown tag or a non-ASCII string is
27
+ * a parse failure (kUnknownGeneralNameType / kFailedParsingGeneralName →
28
+ * kFailedParsingNameConstraints → ParsedCertificate::Create returns
29
+ * nullptr) REGARDLESS of the critical flag;
30
+ * - a constraint in a form the engine does not process (otherName,
31
+ * x400Address, ediPartyName, uniformResourceIdentifier, registeredID)
32
+ * PARSES fine and only matters when the extension is critical: Parse
33
+ * computes `constrained_name_types_ |= present_name_types & (is_critical
34
+ * ? GENERAL_NAME_ALL_TYPES : kSupportedNameTypes)` (name_constraints.cc
35
+ * 341-343, 356-358), and IsPermittedCert rejects a certificate whose SAN
36
+ * carries a name of such an unsupported-but-critically-constrained type
37
+ * (name_constraints.cc:450-454) — the RFC 5280 "MUST either process the
38
+ * constraint or reject the certificate" branch. The mask is a per-FORM
39
+ * bitfield (general_names.h gives every GeneralName CHOICE arm its own
40
+ * bit), so the check intersects forms independently: a critical URI
41
+ * constraint binds URI SANs and leaves otherName SANs untouched. NON-
42
+ * critical constraints on unsupported forms are dropped entirely.
43
+ *
44
+ * Enforcement (IsPermittedCert), on every certificate BELOW the constraint
45
+ * holder (never the holder itself — verify_certificate_chain.cc accumulates
46
+ * `name_constraints_list_` in PrepareForNextCertificate and applies it to the
47
+ * NEXT certificates: "Name constraints (RFC 5280 section 6.1.3 step b & c)…
48
+ * If certificate i is self-issued and it is not the final certificate in the
49
+ * path, skip this step for certificate i"; the root is exempt because the
50
+ * loop `continue`s after ProcessRootCertificate — "Don't do any other checks
51
+ * for root certificates" — but its constraints DO apply below it when anchor
52
+ * constraint enforcement is on, which Chromium's net/cert/
53
+ * cert_verify_proc_builtin.cc switches on for explicitly-supplied constrained
54
+ * anchors (`WithEnforceAnchorConstraints` over
55
+ * `additional_trust_anchors_with_constraints`)):
56
+ * - a DoS guard caps name × constraint combinations at 2^20
57
+ * (kMaxChecks = 1048576) — exceeding it is a HIGH-severity error, i.e. a
58
+ * failed verification, exactly like kNotPermittedByNameConstraints;
59
+ * - the subject's emailAddress attributes are constrained like
60
+ * rfc822Name SANs ONLY when the certificate has NO subjectAltName (RFC
61
+ * 5280 §4.2.1.10 legacy rule, name_constraints.cc:419-427, 493-519);
62
+ * - every SAN name is checked against its form's constraints: excluded
63
+ * subtrees first (a match = excluded), then — only when at least one
64
+ * permitted subtree of THAT form exists (`present_name_types` gate, e.g.
65
+ * name_constraints.cc:657 "If permitted subtrees are not constrained, any
66
+ * name that is not excluded is allowed") — the permitted match;
67
+ * - an rfc822Name CONSTRAINT that is itself structurally invalid (more
68
+ * than one "@", a local-part or domain with forbidden characters, an
69
+ * empty domain) resolves by Rfc822NameMatches' match-type polarity:
70
+ * "In case of parsing errors, return a value that will cause the name to
71
+ * not be permitted" — error_value is FALSE for a permitted-subtree
72
+ * constraint (the fault does not match) and TRUE for an excluded one
73
+ * (the fault MATCHES, so the certificate is REJECTED — fail closed,
74
+ * name_constraints.cc:234-236);
75
+ * - a dNSName SAN is matched case-insensitively with suffix semantics
76
+ * (DNSNameMatches): the empty constraint matches everything, a trailing
77
+ * dot is stripped from BOTH sides (once), a leading-dot constraint
78
+ * matches subdomains ONLY ("foo.bar.com matches constraint .bar.com, but
79
+ * bar.com doesn't" — name_constraints.cc:109-114), the label boundary is
80
+ * enforced ("foobar.com is not a match for bar.com" — 120-122), and
81
+ * wildcards are literal strings with one special case: "*.bar.com" is
82
+ * EXCLUDED by constraint "foo.bar.com" (any expansion could hit it —
83
+ * WILDCARD_PARTIAL_MATCH, 646-652) and PERMITTED only by a constraint
84
+ * that would match every expansion ("*.bar.com should match a constraint
85
+ * of bar.com, but not foo.bar.com" — WILDCARD_FULL_MATCH, 661-668);
86
+ * - the subject DN (and SAN directoryNames) are matched as DNs: subtree =
87
+ * prefix-of-RDNs-in-order with per-attribute normalization
88
+ * (VerifyNameInSubtree / verify_name_match.cc) — via name-match.ts;
89
+ * - iPAddress SANs match constraint ranges by netmask; a family with no
90
+ * range of its own is simply never matched, so an IPv6 SAN under
91
+ * IPv4-only permitted subtrees is NOT permitted (IPAddressMatchesWith
92
+ * Netmask returns false for differing lengths — "If they're different
93
+ * lengths, they're not in the same family");
94
+ * - the subject DN is checked against directoryName constraints even when a
95
+ * SAN is present, UNLESS the subject is empty (RFC 5280 §4.1.2.6
96
+ * empty-subject-with-SAN shape: name_constraints.cc:529-531 "only needs
97
+ * to avoid the IsPermittedDirectoryName check against an empty subject in
98
+ * such a case");
99
+ * - commonName is NEVER checked: "Note that this method does not check
100
+ * hostname or IP address in commonName, which is deprecated
101
+ * (crbug.com/308330)" (name_constraints.h:59-60) — and a certificate with
102
+ * an empty or SAN-less name set is NOT rejected for that reason alone
103
+ * (every check in IsPermittedCert iterates the names actually present).
104
+ */
105
+ import { readTlv } from "./der.js";
106
+ import { TlsMalformedExtensionError } from "../errors.js";
107
+ import { NAME_CONSTRAINTS_OID } from "./extension-policy.js";
108
+ import { GENERAL_NAME_TAGS, formatIpAddress, formatRdnSequence, ipAddressMatchesWithNetmask, parseGeneralName, } from "./general-names.js";
109
+ import { findEmailAddressesInSubject, nameInSubtree } from "./name-match.js";
110
+ /** The bit for each constrained GeneralName form (kSupportedNameTypes layout). */
111
+ const CONSTRAINABLE = {
112
+ rfc822: 1,
113
+ dns: 2,
114
+ directory: 4,
115
+ ip: 8,
116
+ };
117
+ /** The forms BoringSSL fully supports (name_constraints.cc:46-48). */
118
+ const SUPPORTED_NAME_TYPES = CONSTRAINABLE.rfc822 | CONSTRAINABLE.dns | CONSTRAINABLE.directory | CONSTRAINABLE.ip;
119
+ /** IsPermittedCert's DoS ceiling (name_constraints.cc:384): 1 << 20 combinations. */
120
+ const MAX_NAME_CONSTRAINT_CHECKS = 1048576;
121
+ const EMPTY_SUBTREES = {
122
+ dnsNames: Object.freeze([]),
123
+ rfc822Names: Object.freeze([]),
124
+ directoryNames: Object.freeze([]),
125
+ ipRanges: Object.freeze([]),
126
+ unsupportedTags: new Set(),
127
+ presentTypes: 0,
128
+ };
129
+ /**
130
+ * Throw the typed malformed-extension error — one helper so every rejection
131
+ * in this module names the extension OID uniformly
132
+ * (TlsMalformedExtensionError; BoringSSL's kFailedParsingNameConstraints).
133
+ */
134
+ function malformed(detail) {
135
+ throw new TlsMalformedExtensionError(NAME_CONSTRAINTS_OID, detail);
136
+ }
137
+ /**
138
+ * Parse the nameConstraints extnValue content (unwrapped OCTET STRING) — the
139
+ * NameConstraints::Parse twin. Throws the typed certificate-phase error on
140
+ * any fault: BoringSSL runs this for EVERY nameConstraints extension in
141
+ * ParsedCertificate::Create and `kFailedParsingNameConstraints` rejects the
142
+ * certificate ("Failed parsing name constraints"), critical or not.
143
+ */
144
+ export function parseNameConstraints(value, isCritical) {
145
+ // NameConstraints ::= SEQUENCE { permittedSubtrees [0] OPTIONAL,
146
+ // excludedSubtrees [1] OPTIONAL }
147
+ const seq = readTlv(value, 0);
148
+ if (seq.tag !== 0x30) {
149
+ malformed("expected NameConstraints SEQUENCE");
150
+ }
151
+ // "By definition the input was a single NameConstraints sequence, so
152
+ // there shouldn't be unconsumed data" (extension_parser.HasMore()).
153
+ if (seq.end !== value.length) {
154
+ malformed("trailing data after the NameConstraints SEQUENCE");
155
+ }
156
+ let o = seq.valueStart;
157
+ let permitted;
158
+ let excluded;
159
+ // ReadOptionalTag([0]) then ReadOptionalTag([1]) — each side is OPTIONAL
160
+ // and an excluded-only extension starts with [1].
161
+ if (o < seq.end) {
162
+ const tag = readTlv(value, o);
163
+ if (tag.tag === 0xa0) {
164
+ permitted = parseGeneralSubtrees(value.subarray(tag.valueStart, tag.end));
165
+ o = tag.end;
166
+ }
167
+ }
168
+ if (o < seq.end) {
169
+ const tag = readTlv(value, o);
170
+ if (tag.tag === 0xa1) {
171
+ excluded = parseGeneralSubtrees(value.subarray(tag.valueStart, tag.end));
172
+ o = tag.end;
173
+ }
174
+ }
175
+ if (o !== seq.end) {
176
+ // sequence_parser.HasMore() after both optional reads — an element
177
+ // that is neither [0] nor [1] (or an extra one) is the fault.
178
+ malformed("unexpected element (only [0] permittedSubtrees and [1] excludedSubtrees are allowed)");
179
+ }
180
+ // RFC 5280 §4.2.1.10 via name_constraints.cc:360-366: at least one side
181
+ // MUST be present.
182
+ if (permitted === undefined && excluded === undefined) {
183
+ malformed("empty sequence — RFC 5280 §4.2.1.10 requires permittedSubtrees or excludedSubtrees to be present");
184
+ }
185
+ const permittedSubtrees = permitted ?? EMPTY_SUBTREES;
186
+ const excludedSubtrees = excluded ?? EMPTY_SUBTREES;
187
+ // Parse's constrained-type computation: the four supported forms
188
+ // constrain through the match functions regardless of criticality;
189
+ // unsupported forms count ONLY when the extension is critical, and as
190
+ // their own tags (name_constraints.cc:341-343, 356-358 —
191
+ // `present_name_types & (is_critical ? GENERAL_NAME_ALL_TYPES :
192
+ // kSupportedNameTypes)` over the per-form general_names.h bits).
193
+ const constrainedTypes = (permittedSubtrees.presentTypes | excludedSubtrees.presentTypes) & SUPPORTED_NAME_TYPES;
194
+ const constrainedUnsupportedTags = isCritical
195
+ ? new Set([...permittedSubtrees.unsupportedTags, ...excludedSubtrees.unsupportedTags])
196
+ : new Set();
197
+ return { permittedSubtrees, excludedSubtrees, constrainedTypes, constrainedUnsupportedTags, isCritical };
198
+ }
199
+ /**
200
+ * Parse one GeneralSubtrees value — the CONTENT of the [0]/[1] element, which
201
+ * per RFC 5280's IMPLICIT-tagged `[0] GeneralSubtrees` IS the
202
+ * `GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree` (openssl's
203
+ * wire form, and exactly what BoringSSL's ParseGeneralSubtrees walks:
204
+ * ReadOptionalTag hands it the [0] content and
205
+ * `sequence_parser.ReadSequence(&subtree_sequence)` reads each GeneralSubtree
206
+ * SEQUENCE from it). Each GeneralSubtree is SEQUENCE { base GeneralName }
207
+ * with NO minimum/maximum/trailing element.
208
+ */
209
+ function parseGeneralSubtrees(value) {
210
+ // "The GeneralSubtrees sequence should have at least 1 element" — an
211
+ // empty [0]/[1] is a parse failure (name_constraints.cc:146-148,
212
+ // `if (!sequence_parser.HasMore()) { return false; }`).
213
+ if (value.length === 0) {
214
+ malformed("GeneralSubtrees must have at least one element");
215
+ }
216
+ const dnsNames = [];
217
+ const rfc822Names = [];
218
+ const directoryNames = [];
219
+ const ipRanges = [];
220
+ const unsupportedTags = new Set();
221
+ let presentTypes = 0;
222
+ let o = 0;
223
+ while (o < value.length) {
224
+ const subtree = readTlv(value, o);
225
+ if (subtree.tag !== 0x30) {
226
+ malformed("expected GeneralSubtree SEQUENCE");
227
+ }
228
+ let p = subtree.valueStart;
229
+ const base = readTlv(value, p);
230
+ p = base.end;
231
+ // "the minimum and maximum fields appear uncommon enough that
232
+ // implementing that isn't useful": ANY element after the base — an
233
+ // explicit minimum [0] (even the DEFAULT value 0) or a maximum [1] —
234
+ // fails the parse (name_constraints.cc:179-181).
235
+ if (p !== subtree.end) {
236
+ malformed("GeneralSubtree carries minimum/maximum — RFC 5280 §4.2.1.10 requires minimum omitted (DEFAULT 0) and maximum absent");
237
+ }
238
+ const parsed = parseGeneralName(value, base, "address-and-netmask", "nameConstraints");
239
+ if (parsed === undefined) {
240
+ // An unprocessed name form (otherName/x400/ediParty/registeredID);
241
+ // remember the tag for the critical-unsupported-form rule.
242
+ unsupportedTags.add(base.tag);
243
+ }
244
+ else {
245
+ switch (parsed.kind) {
246
+ case "dns":
247
+ dnsNames.push(parsed.value);
248
+ presentTypes |= CONSTRAINABLE.dns;
249
+ break;
250
+ case "rfc822":
251
+ rfc822Names.push(parsed.value);
252
+ presentTypes |= CONSTRAINABLE.rfc822;
253
+ break;
254
+ case "ip": {
255
+ const half = parsed.value.length / 2;
256
+ ipRanges.push({ address: parsed.value.subarray(0, half), netmask: parsed.value.subarray(half) });
257
+ presentTypes |= CONSTRAINABLE.ip;
258
+ break;
259
+ }
260
+ case "directory":
261
+ directoryNames.push(parsed.value);
262
+ presentTypes |= CONSTRAINABLE.directory;
263
+ break;
264
+ case "uri":
265
+ // uniformResourceIdentifier parses (validated ASCII) but
266
+ // is not a processed form — kSupportedNameTypes omits it.
267
+ unsupportedTags.add(GENERAL_NAME_TAGS.uniformResourceIdentifier);
268
+ break;
269
+ }
270
+ }
271
+ o = subtree.end;
272
+ }
273
+ return {
274
+ dnsNames: Object.freeze(dnsNames),
275
+ rfc822Names: Object.freeze(rfc822Names),
276
+ directoryNames: Object.freeze(directoryNames),
277
+ ipRanges: Object.freeze(ipRanges),
278
+ unsupportedTags: new Set(unsupportedTags),
279
+ presentTypes,
280
+ };
281
+ }
282
+ /**
283
+ * ASCII case-insensitive suffix test (string_util::EndsWithNoCase). Byte-wise
284
+ * comparison: names and constraints are ASCII-validated at parse time
285
+ * (kDnsNameNotAscii / kRFC822NameNotAscii), so code points are bytes here.
286
+ */
287
+ function endsWithNoCase(name, suffix) {
288
+ if (name.length < suffix.length) {
289
+ return false;
290
+ }
291
+ const offset = name.length - suffix.length;
292
+ for (let i = 0; i < suffix.length; i++) {
293
+ if (asciiLower(name.codePointAt(offset + i) ?? -1) !== asciiLower(suffix.codePointAt(i) ?? -1)) {
294
+ return false;
295
+ }
296
+ }
297
+ return true;
298
+ }
299
+ /** ASCII case-insensitive equality (string_util::IsEqualNoCase). */
300
+ function equalsNoCase(a, b) {
301
+ if (a.length !== b.length) {
302
+ return false;
303
+ }
304
+ for (let i = 0; i < a.length; i++) {
305
+ if (asciiLower(a.codePointAt(i) ?? -1) !== asciiLower(b.codePointAt(i) ?? -1)) {
306
+ return false;
307
+ }
308
+ }
309
+ return true;
310
+ }
311
+ function asciiLower(code) {
312
+ return code >= 65 && code <= 90 ? code + 32 : code;
313
+ }
314
+ /**
315
+ * DNSNameMatches: does `name` fall in the subtree of `dnsConstraint`?
316
+ *
317
+ * RFC 5280 §4.2.1.10 (quoted in the BoringSSL source): "DNS name restrictions
318
+ * are expressed as host.example.com. Any DNS name that can be constructed by
319
+ * simply adding zero or more labels to the left-hand side of the name
320
+ * satisfies the name constraint. For example, www.host.example.com would
321
+ * satisfy the constraint but host1.example.com would not."
322
+ *
323
+ * Rule by rule (name_constraints.cc:69-122):
324
+ * - the EMPTY constraint matches everything ("Everything matches the empty
325
+ * DNS name constraint");
326
+ * - ONE trailing dot is stripped from name and constraint alike
327
+ * ("Normalize absolute DNS names by removing the trailing dot, if any");
328
+ * - wildcard partial-match: a name "*.<domain>" matches a constraint whose
329
+ * own part after the first dot equals <domain> (exclusions only);
330
+ * - the suffix test is case-insensitive; equal length = exact match;
331
+ * - a constraint with a LEADING dot strips it and then only subdomains
332
+ * match ("foo.bar.com matches constraint .bar.com, but bar.com doesn't");
333
+ * - otherwise the character before the matched suffix must be a label
334
+ * boundary dot ("Trailing text matches, but not in a subtree (e.g.,
335
+ * foobar.com is not a match for bar.com)").
336
+ */
337
+ export function dnsNameMatches(name, dnsConstraint, wildcardMatching) {
338
+ // Everything matches the empty DNS name constraint.
339
+ if (dnsConstraint.length === 0) {
340
+ return true;
341
+ }
342
+ // Normalize absolute DNS names by removing the trailing dot, if any (one
343
+ // dot only — a name of just "." normalizes to the empty string, which
344
+ // then fails every non-empty constraint's suffix test).
345
+ let namePart = name;
346
+ if (namePart.length > 0 && namePart.endsWith(".")) {
347
+ namePart = namePart.slice(0, -1);
348
+ }
349
+ let constraintPart = dnsConstraint;
350
+ if (constraintPart.length > 0 && constraintPart.endsWith(".")) {
351
+ constraintPart = constraintPart.slice(0, -1);
352
+ }
353
+ // Wildcard partial-match handling ("*.bar.com" matching name constraint
354
+ // "foo.bar.com"). Only when the name starts "*." and the constraint has a
355
+ // dot: the wildcard's domain must equal the constraint's domain part.
356
+ if (wildcardMatching === "partial" && namePart.length > 2 && namePart.startsWith("*.")) {
357
+ const dotPos = constraintPart.indexOf(".");
358
+ if (dotPos !== -1) {
359
+ const constraintDomain = constraintPart.slice(dotPos + 1);
360
+ const wildcardDomain = namePart.slice(2);
361
+ if (equalsNoCase(wildcardDomain, constraintDomain)) {
362
+ return true;
363
+ }
364
+ }
365
+ }
366
+ if (!endsWithNoCase(namePart, constraintPart)) {
367
+ return false;
368
+ }
369
+ // Exact match.
370
+ if (namePart.length === constraintPart.length) {
371
+ return true;
372
+ }
373
+ // If dNSName constraint starts with a dot, only subdomains should match.
374
+ if (constraintPart.startsWith(".")) {
375
+ constraintPart = constraintPart.slice(1);
376
+ }
377
+ // Subtree match: the character before the suffix must be a dot.
378
+ if (namePart.length > constraintPart.length && namePart[namePart.length - constraintPart.length - 1] === ".") {
379
+ return true;
380
+ }
381
+ // Trailing text matches, but not in a subtree (e.g., "foobar.com" is not
382
+ // a match for "bar.com").
383
+ return false;
384
+ }
385
+ /**
386
+ * RFC 5280 §4.2.1.10 mailbox matching: constraint "root@example.com" pins one
387
+ * mailbox; ".example.com" matches every address whose domain ends with
388
+ * ".example.com"; "example.com" matches every address at that host
389
+ * (domain equality). Names with a local-part that uses characters outside the
390
+ * unquoted atext set or more than one "@" never match (IsPermittedRfc822Name's
391
+ * own structure check); CONSTRAINTS with such faults, more than one "@", or a
392
+ * domain with characters outside alnum/-/. resolve to the match-type's fault
393
+ * value (IsAllowedRfc822LocalPart / IsAllowedRfc822Domain: "we don't
394
+ * implement [RFC 2821 mailbox parsing] either, but do something a bit more
395
+ * fail-safe by rejecting any addresses that contain characters that are not
396
+ * allowed in the non-quoted formats").
397
+ */
398
+ export function rfc822NameMatches(name, rfc822Constraint, matchType, caseInsensitiveLocalPart) {
399
+ const nameComponents = name.split("@");
400
+ if (nameComponents.length !== 2) {
401
+ // IsPermittedRfc822Name: "just fail if @ appears more than once" (or
402
+ // zero times).
403
+ return false;
404
+ }
405
+ const localPart = nameComponents[0] ?? "";
406
+ const domain = nameComponents[1] ?? "";
407
+ if (!isAllowedRfc822LocalPart(localPart) || !isAllowedRfc822Domain(domain)) {
408
+ return false;
409
+ }
410
+ // "In case of parsing errors, return a value that will cause the name to
411
+ // not be permitted" (name_constraints.cc:232-235): an excluded fault
412
+ // matches — the certificate is rejected; a permitted fault does not.
413
+ const errorValue = matchType === "excluded";
414
+ const constraintComponents = rfc822Constraint.split("@");
415
+ let constraintLocalPart = "";
416
+ let constraintDomain;
417
+ if (constraintComponents.length === 1) {
418
+ constraintDomain = constraintComponents[0] ?? "";
419
+ }
420
+ else if (constraintComponents.length === 2) {
421
+ constraintLocalPart = constraintComponents[0] ?? "";
422
+ if (!isAllowedRfc822LocalPart(constraintLocalPart)) {
423
+ return errorValue;
424
+ }
425
+ constraintDomain = constraintComponents[1] ?? "";
426
+ }
427
+ else {
428
+ // "If we did the full parsing then it is possible for a @ to be in a
429
+ // quoted local-part of the name, but we don't do that, so just error
430
+ // if @ appears more than once" (name_constraints.cc:244-248).
431
+ return errorValue;
432
+ }
433
+ if (!isAllowedRfc822Domain(constraintDomain)) {
434
+ return errorValue;
435
+ }
436
+ if (constraintLocalPart.length > 0) {
437
+ return (caseInsensitiveLocalPart ? equalsNoCase(localPart, constraintLocalPart) : localPart === constraintLocalPart) &&
438
+ equalsNoCase(domain, constraintDomain);
439
+ }
440
+ if (constraintDomain.length > 0 && constraintDomain.startsWith(".")) {
441
+ return endsWithNoCase(domain, constraintDomain);
442
+ }
443
+ return equalsNoCase(domain, constraintDomain);
444
+ }
445
+ function isAlphaDigit(c) {
446
+ return (c >= "0" && c <= "9") || (c >= "a" && c <= "z") || (c >= "A" && c <= "Z");
447
+ }
448
+ function isAllowedRfc822LocalPart(localPart) {
449
+ if (localPart.length === 0) {
450
+ return false;
451
+ }
452
+ const allowed = "!#$%&'*+-/=?^_`{|}~.";
453
+ for (const c of localPart) {
454
+ if (!isAlphaDigit(c) && !allowed.includes(c)) {
455
+ return false;
456
+ }
457
+ }
458
+ return true;
459
+ }
460
+ function isAllowedRfc822Domain(domain) {
461
+ if (domain.length === 0) {
462
+ return false;
463
+ }
464
+ for (const c of domain) {
465
+ if (!isAlphaDigit(c) && c !== "-" && c !== ".") {
466
+ return false;
467
+ }
468
+ }
469
+ return true;
470
+ }
471
+ /** Human-readable form labels for diagnostics (the RFC 5280 CHOICE arm names). */
472
+ const FORM_LABELS = {
473
+ rfc822: "rfc822Name",
474
+ dns: "dNSName",
475
+ directory: "directoryName",
476
+ ip: "iPAddress",
477
+ unsupported: "unsupported name form",
478
+ };
479
+ /**
480
+ * IsPermittedCert (name_constraints.cc:375-537): is `subject` — its SANs
481
+ * (`san`, null when the extension is absent) and its subject DN (RDNSequence
482
+ * VALUE bytes) — permitted by `constraints`? `subjectIsTarget` mirrors
483
+ * BoringSSL's `is_target_cert` in the caller's self-issued exemption
484
+ * ("(!IsSelfIssued(cert) || is_target_cert)"): a self-issued NON-target
485
+ * certificate skips the check entirely.
486
+ *
487
+ * Returns undefined (permitted) or the discriminated violation.
488
+ */
489
+ export function nameConstraintViolation(constraints, san, subjectValue, subjectIsTarget, isSelfIssued) {
490
+ // RFC 5280 §6.1.3 step b & c via verify_certificate_chain.cc:1177-1178:
491
+ // "If certificate i is self-issued and it is not the final certificate in
492
+ // the path, skip this step for certificate i."
493
+ if (isSelfIssued && !subjectIsTarget) {
494
+ return undefined;
495
+ }
496
+ // DoS guard (name_constraints.cc:384-416): constraint × name combinations
497
+ // above 2^20 fail (kTooManyNameConstraintChecks, SEVERITY_HIGH). The
498
+ // SAN-less branch counts the raw subject bytes instead of names.
499
+ let nameCount;
500
+ let constraintCount;
501
+ if (san === null) {
502
+ // SAN-less branch counts the raw subject bytes instead of names
503
+ // (name_constraints.cc:405-409).
504
+ constraintCount =
505
+ constraints.excludedSubtrees.directoryNames.length + constraints.permittedSubtrees.directoryNames.length;
506
+ nameCount = subjectValue.length;
507
+ }
508
+ else {
509
+ nameCount =
510
+ san.rfc822Names.length + san.dnsNames.length + san.directoryNames.length + san.ipAddresses.length;
511
+ constraintCount =
512
+ constraints.excludedSubtrees.rfc822Names.length +
513
+ constraints.permittedSubtrees.rfc822Names.length +
514
+ constraints.excludedSubtrees.dnsNames.length +
515
+ constraints.permittedSubtrees.dnsNames.length +
516
+ constraints.excludedSubtrees.directoryNames.length +
517
+ constraints.permittedSubtrees.directoryNames.length +
518
+ constraints.excludedSubtrees.ipRanges.length +
519
+ constraints.permittedSubtrees.ipRanges.length;
520
+ }
521
+ if (constraintCount * nameCount > MAX_NAME_CONSTRAINT_CHECKS) {
522
+ return { kind: "too-many-checks" };
523
+ }
524
+ // The subject emailAddress fallback applies ONLY when there is no SAN
525
+ // extension at all (name_constraints.cc:419-427).
526
+ let subjectEmails = [];
527
+ if (san === null && (constraints.constrainedTypes & CONSTRAINABLE.rfc822) !== 0) {
528
+ const found = findEmailAddressesInSubject(subjectValue);
529
+ if (found === undefined) {
530
+ // "Error parsing |subject_rdn_sequence|" → kNotPermittedByName
531
+ // Constraints.
532
+ return { kind: "subject-email-unreadable" };
533
+ }
534
+ subjectEmails = found;
535
+ }
536
+ if (san !== null) {
537
+ // Unsupported-but-critically-constrained forms: any SAN of such a
538
+ // type rejects ("the application MUST either process the constraint
539
+ // or reject the certificate" — name_constraints.cc:450-454). The
540
+ // intersection is PER FORM (general_names.h gives every CHOICE arm
541
+ // its own bit, so `constrained_name_types() & present_name_types &
542
+ // ~kSupportedNameTypes` binds each form independently): a critical
543
+ // URI constraint must not reject an otherName SAN.
544
+ for (const tag of san.presentTags) {
545
+ if (constraints.constrainedUnsupportedTags.has(tag)) {
546
+ return {
547
+ kind: "unsupported-name-form",
548
+ form: `${FORM_LABELS.unsupported} (tag 0x${tag.toString(16)})`,
549
+ };
550
+ }
551
+ }
552
+ if ((constraints.constrainedTypes & CONSTRAINABLE.rfc822) !== 0) {
553
+ // SAN rfc822Names are matched with the case-SENSITIVE local-part
554
+ // (IsPermittedRfc822Name's case_insensitive_exclude_localpart =
555
+ // false); the subject fallback below uses case-insensitive.
556
+ for (const rfc822Name of san.rfc822Names) {
557
+ const verdict = isPermittedRfc822Name(constraints, rfc822Name, false);
558
+ if (verdict !== undefined) {
559
+ return verdict;
560
+ }
561
+ }
562
+ }
563
+ for (const dnsName of san.dnsNames) {
564
+ const verdict = isPermittedDnsName(constraints, dnsName);
565
+ if (verdict !== undefined) {
566
+ return verdict;
567
+ }
568
+ }
569
+ for (const directoryName of san.directoryNames) {
570
+ const verdict = isPermittedDirectoryName(constraints, directoryName);
571
+ if (verdict !== undefined) {
572
+ return { ...verdict, name: formatRdnSequence(directoryName) };
573
+ }
574
+ }
575
+ for (const ipAddress of san.ipAddresses) {
576
+ const verdict = isPermittedIp(constraints, ipAddress);
577
+ if (verdict !== undefined) {
578
+ return { ...verdict, name: formatIpAddress(ipAddress) };
579
+ }
580
+ }
581
+ }
582
+ // The legacy subject-emailAddress check (name_constraints.cc:493-519),
583
+ // matched with a case-INSENSITIVE local-part for exclusions ("this
584
+ // implementation will do case-insensitive match for excluded names from
585
+ // the subject to avoid potentially allowing something that wasn't
586
+ // expected" — IsPermittedRfc822Name's case_insensitive_exclude flag).
587
+ for (const rfc822Name of subjectEmails) {
588
+ const verdict = isPermittedRfc822Name(constraints, rfc822Name, true);
589
+ if (verdict !== undefined) {
590
+ return verdict;
591
+ }
592
+ }
593
+ // Subject DN vs directoryName constraints — skipped for the RFC 5280
594
+ // §4.1.2.6 empty-subject-with-SAN shape (name_constraints.cc:529-531).
595
+ if (san !== null && subjectValue.length === 0) {
596
+ return undefined;
597
+ }
598
+ const subjectVerdict = isPermittedDirectoryName(constraints, subjectValue);
599
+ if (subjectVerdict !== undefined) {
600
+ return { ...subjectVerdict, name: formatRdnSequence(subjectValue) };
601
+ }
602
+ return undefined;
603
+ }
604
+ /** IsPermittedRfc822Name (name_constraints.cc:539-643). */
605
+ function isPermittedRfc822Name(constraints, name, caseInsensitiveLocalPart) {
606
+ // Structural sanity of the NAME itself (the constraint's structure is
607
+ // checked inside rfc822NameMatches): a name with two @s or forbidden
608
+ // characters fails ("in case of parsing errors, return a value that will
609
+ // cause the name to not be permitted").
610
+ const components = name.split("@");
611
+ if (components.length !== 2) {
612
+ return { kind: "not-permitted", form: FORM_LABELS.rfc822, name };
613
+ }
614
+ if (!isAllowedRfc822LocalPart(components[0] ?? "") || !isAllowedRfc822Domain(components[1] ?? "")) {
615
+ return { kind: "not-permitted", form: FORM_LABELS.rfc822, name };
616
+ }
617
+ for (const excludedName of constraints.excludedSubtrees.rfc822Names) {
618
+ if (rfc822NameMatches(name, excludedName, "excluded", caseInsensitiveLocalPart)) {
619
+ return { kind: "excluded", form: FORM_LABELS.rfc822, name };
620
+ }
621
+ }
622
+ // "If permitted subtrees are not constrained, any name that is not
623
+ // excluded is allowed."
624
+ if ((constraints.permittedSubtrees.presentTypes & CONSTRAINABLE.rfc822) === 0) {
625
+ return undefined;
626
+ }
627
+ for (const permittedName of constraints.permittedSubtrees.rfc822Names) {
628
+ // The PERMITTED call passes /*case_insenitive_local_part=*/false
629
+ // (name_constraints.cc:634-640): the mailbox-pinning comparison is
630
+ // exact, whichever operand supplied the flag.
631
+ if (rfc822NameMatches(name, permittedName, "permitted", false)) {
632
+ return undefined;
633
+ }
634
+ }
635
+ return { kind: "not-permitted", form: FORM_LABELS.rfc822, name };
636
+ }
637
+ /** IsPermittedDNSName (name_constraints.cc:645-671). */
638
+ function isPermittedDnsName(constraints, name) {
639
+ for (const excludedName of constraints.excludedSubtrees.dnsNames) {
640
+ // "consider it a match if the constraint would match any expansion of
641
+ // the wildcard" — WILDCARD_PARTIAL_MATCH.
642
+ if (dnsNameMatches(name, excludedName, "partial")) {
643
+ return { kind: "excluded", form: FORM_LABELS.dns, name };
644
+ }
645
+ }
646
+ if ((constraints.permittedSubtrees.presentTypes & CONSTRAINABLE.dns) === 0) {
647
+ return undefined;
648
+ }
649
+ for (const permittedName of constraints.permittedSubtrees.dnsNames) {
650
+ // "consider it a match only if the constraint would match all
651
+ // expansions of the wildcard" — WILDCARD_FULL_MATCH.
652
+ if (dnsNameMatches(name, permittedName, "full")) {
653
+ return undefined;
654
+ }
655
+ }
656
+ return { kind: "not-permitted", form: FORM_LABELS.dns, name };
657
+ }
658
+ /** IsPermittedDirectoryName (name_constraints.cc:673-694). */
659
+ function isPermittedDirectoryName(constraints, nameValue) {
660
+ for (const excludedName of constraints.excludedSubtrees.directoryNames) {
661
+ if (nameInSubtree(nameValue, excludedName)) {
662
+ return { kind: "excluded", form: FORM_LABELS.directory, name: "" };
663
+ }
664
+ }
665
+ if ((constraints.permittedSubtrees.presentTypes & CONSTRAINABLE.directory) === 0) {
666
+ return undefined;
667
+ }
668
+ for (const permittedName of constraints.permittedSubtrees.directoryNames) {
669
+ if (nameInSubtree(nameValue, permittedName)) {
670
+ return undefined;
671
+ }
672
+ }
673
+ return { kind: "not-permitted", form: FORM_LABELS.directory, name: "" };
674
+ }
675
+ /** IsPermittedIP (name_constraints.cc:696-718). */
676
+ function isPermittedIp(constraints, ip) {
677
+ for (const excludedIp of constraints.excludedSubtrees.ipRanges) {
678
+ if (ipAddressMatchesWithNetmask(ip, excludedIp.address, excludedIp.netmask)) {
679
+ return { kind: "excluded", form: FORM_LABELS.ip, name: formatIpAddress(ip) };
680
+ }
681
+ }
682
+ if ((constraints.permittedSubtrees.presentTypes & CONSTRAINABLE.ip) === 0) {
683
+ return undefined;
684
+ }
685
+ for (const permittedIp of constraints.permittedSubtrees.ipRanges) {
686
+ if (ipAddressMatchesWithNetmask(ip, permittedIp.address, permittedIp.netmask)) {
687
+ return undefined;
688
+ }
689
+ }
690
+ return { kind: "not-permitted", form: FORM_LABELS.ip, name: formatIpAddress(ip) };
691
+ }
692
+ //# sourceMappingURL=name-constraints.js.map