@browsercore/tls 0.4.18 → 0.4.20

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 (69) hide show
  1. package/README.md +291 -6
  2. package/dist/certificates/ca-constraints.d.ts +43 -0
  3. package/dist/certificates/ca-constraints.d.ts.map +1 -0
  4. package/dist/certificates/ca-constraints.js +89 -0
  5. package/dist/certificates/ca-constraints.js.map +1 -0
  6. package/dist/certificates/cert-extensions.d.ts +106 -19
  7. package/dist/certificates/cert-extensions.d.ts.map +1 -1
  8. package/dist/certificates/cert-extensions.js +203 -48
  9. package/dist/certificates/cert-extensions.js.map +1 -1
  10. package/dist/certificates/certificate-path.d.ts +341 -0
  11. package/dist/certificates/certificate-path.d.ts.map +1 -0
  12. package/dist/certificates/certificate-path.js +613 -0
  13. package/dist/certificates/certificate-path.js.map +1 -0
  14. package/dist/certificates/certificates.d.ts +66 -47
  15. package/dist/certificates/certificates.d.ts.map +1 -1
  16. package/dist/certificates/certificates.js +251 -92
  17. package/dist/certificates/certificates.js.map +1 -1
  18. package/dist/certificates/der.d.ts +0 -8
  19. package/dist/certificates/der.d.ts.map +1 -1
  20. package/dist/certificates/der.js +0 -42
  21. package/dist/certificates/der.js.map +1 -1
  22. package/dist/certificates/extension-policy.d.ts +205 -0
  23. package/dist/certificates/extension-policy.d.ts.map +1 -0
  24. package/dist/certificates/extension-policy.js +357 -0
  25. package/dist/certificates/extension-policy.js.map +1 -0
  26. package/dist/certificates/extension-values.d.ts +131 -0
  27. package/dist/certificates/extension-values.d.ts.map +1 -0
  28. package/dist/certificates/extension-values.js +443 -0
  29. package/dist/certificates/extension-values.js.map +1 -0
  30. package/dist/certificates/general-names.d.ts +142 -0
  31. package/dist/certificates/general-names.d.ts.map +1 -0
  32. package/dist/certificates/general-names.js +354 -0
  33. package/dist/certificates/general-names.js.map +1 -0
  34. package/dist/certificates/name-constraints.d.ts +245 -0
  35. package/dist/certificates/name-constraints.d.ts.map +1 -0
  36. package/dist/certificates/name-constraints.js +692 -0
  37. package/dist/certificates/name-constraints.js.map +1 -0
  38. package/dist/certificates/name-match.d.ts +59 -0
  39. package/dist/certificates/name-match.d.ts.map +1 -0
  40. package/dist/certificates/name-match.js +271 -0
  41. package/dist/certificates/name-match.js.map +1 -0
  42. package/dist/certificates/signature-algorithm.d.ts +54 -0
  43. package/dist/certificates/signature-algorithm.d.ts.map +1 -0
  44. package/dist/certificates/signature-algorithm.js +359 -0
  45. package/dist/certificates/signature-algorithm.js.map +1 -0
  46. package/dist/connection/handshake-driver.d.ts +9 -6
  47. package/dist/connection/handshake-driver.d.ts.map +1 -1
  48. package/dist/connection/handshake-driver.js.map +1 -1
  49. package/dist/connection/handshake-messages.d.ts +9 -2
  50. package/dist/connection/handshake-messages.d.ts.map +1 -1
  51. package/dist/connection/handshake-messages.js +57 -23
  52. package/dist/connection/handshake-messages.js.map +1 -1
  53. package/dist/errors.d.ts +100 -0
  54. package/dist/errors.d.ts.map +1 -1
  55. package/dist/errors.js +54 -0
  56. package/dist/errors.js.map +1 -1
  57. package/dist/index.d.ts +8 -5
  58. package/dist/index.d.ts.map +1 -1
  59. package/dist/index.js +5 -3
  60. package/dist/index.js.map +1 -1
  61. package/dist/tls.d.ts +4 -3
  62. package/dist/tls.d.ts.map +1 -1
  63. package/dist/tls.js +4 -3
  64. package/dist/tls.js.map +1 -1
  65. package/dist/types.d.ts +2 -1
  66. package/dist/types.d.ts.map +1 -1
  67. package/dist/types.js +2 -1
  68. package/dist/types.js.map +1 -1
  69. package/package.json +3 -3
@@ -10,72 +10,91 @@
10
10
  * read and tested in isolation:
11
11
  * - `der.ts` — DER tag-length-value primitives (no X.509 semantics)
12
12
  * - `cert-extensions.ts` — subject/issuer names, SAN, KeyUsage, BasicConstraints
13
+ * - `ca-constraints.ts` — the path-validation delta: keyCertSign bit,
14
+ * BasicConstraints pathLenConstraint
15
+ * - `certificate-path.ts` — the pure RFC 5280 §6.1 path builder and its
16
+ * checks, plus the tls-internal ParsedCertificate /
17
+ * CertificateChain / TrustAnchor types (re-exported here
18
+ * for the stable import path)
13
19
  * - `pem.ts` — PEM container decoding (the only place that knows about
14
20
  * the BEGIN/END text wrapper; downstream code sees raw DER)
15
21
  */
16
- import type { CryptoProvider } from "@browsercore/contracts";
17
- import type { SignatureScheme } from "../types.js";
18
- /** A parsed X.509 certificate (validation-relevant fields only). */
19
- export interface Certificate {
20
- /** DER-encoded TBSCertificate bytes, needed for signature verification. */
21
- readonly tbsBytes: Uint8Array;
22
- /** DER-encoded SubjectPublicKeyInfo. */
23
- readonly subjectPublicKeyInfo: Uint8Array;
24
- /** Subject alternative DNS names (from the SAN extension), if any. */
25
- readonly subjectAltNames: readonly string[];
26
- /** Common Name from the subject DN, if present (legacy hostname match). */
27
- readonly commonName?: string;
28
- /** Not-before timestamp (epoch seconds). */
29
- readonly notBefore: number;
30
- /** Not-after timestamp (epoch seconds). */
31
- readonly notAfter: number;
32
- /** True if the certificate has the keyUsage bit for digital signature. */
33
- readonly keyUsageDigitalSignature: boolean;
34
- /** True if the certificate has the keyUsage bit for key encipherment/agreement. */
35
- readonly keyUsageKeyEncipherment: boolean;
36
- /** Signature algorithm used by the issuer over the TBSCertificate. */
37
- readonly signatureScheme: SignatureScheme;
38
- /** Raw signature value from the issuer. */
39
- readonly signatureValue: Uint8Array;
40
- /** DER-encoded SubjectPublicKeyInfo of the issuer (for chain building). */
41
- readonly issuer: string;
42
- /** True for a CA certificate. */
43
- readonly isCa: boolean;
44
- }
45
- /** An ordered certificate chain: leaf first, intermediates follow, root last. */
46
- export interface CertificateChain {
47
- readonly leaf: Certificate;
48
- readonly intermediates: readonly Certificate[];
49
- readonly root: Certificate;
50
- }
51
- /** A trust anchor: a root certificate we trust a priori. */
52
- export interface TrustAnchor {
53
- readonly subjectPublicKeyInfo: Uint8Array;
54
- readonly subject: string;
55
- }
22
+ import type { Certificate, CryptoProvider } from "@browsercore/contracts";
23
+ import { type CertificateSignatureAlgorithm } from "./signature-algorithm.js";
24
+ import { type CertificateChain, type ParsedCertificate, type TrustAnchor } from "./certificate-path.js";
25
+ export type { Certificate };
26
+ export type { CertificateChain, CertificateExtension, CertificatePath, CertificatePathFailureReason, ParsedCertificate, TrustAnchor } from "./certificate-path.js";
27
+ export { buildCertificatePath, MAX_PATH_INTERMEDIATES } from "./certificate-path.js";
56
28
  /**
57
- * Parse a single DER-encoded X.509 certificate.
29
+ * Parse a single DER-encoded X.509 certificate (contract-type boundary).
30
+ *
31
+ * Thin wrapper over {@link parseCertificateDetails}: consumers see ONLY the
32
+ * canonical contract `Certificate`; the tls-internal DN byte spans and
33
+ * path-constraint fields ride along on the same object for path building
34
+ * (ParsedCertificate extends Certificate, so this is a plain upcast).
35
+ *
36
+ * Throws {@link TlsHandshakeError} with phase "certificate" on malformed input.
37
+ */
38
+ export declare function parseCertificate(buf: Uint8Array): Certificate;
39
+ /**
40
+ * Parse a single DER-encoded X.509 certificate into the FULL tls-internal
41
+ * form ({@link ParsedCertificate}).
58
42
  *
59
43
  * Decodes the outer Certificate SEQUENCE into its TBSCertificate, signature
60
44
  * algorithm, and signature value, then extracts the validation-relevant fields.
61
45
  * `tbsBytes` is captured as the EXACT DER span of the TBSCertificate so that
62
- * signature verification over it is byte-correct.
46
+ * signature verification over it is byte-correct. The subject and issuer Name
47
+ * DER spans are captured as the candidate-filter key for path building (the
48
+ * signature check binds issuer to subject; DN equality only filters).
63
49
  *
64
50
  * Throws {@link TlsHandshakeError} with phase "certificate" on malformed input.
51
+ * A structurally valid certificate is NEVER rejected because of its signature
52
+ * algorithm — an unsupported/rejected algorithm is reported through
53
+ * {@link Certificate.signatureAlgorithm} and policed by the caller.
65
54
  */
66
- export declare function parseCertificate(buf: Uint8Array): Certificate;
55
+ export declare function parseCertificateDetails(buf: Uint8Array): ParsedCertificate;
67
56
  /**
68
57
  * Validate that a certificate is valid for the given hostname per RFC 6125.
69
58
  * (Moved to {@link ./hostname.js} — re-exported here for the stable import path.)
70
59
  */
71
60
  export { validateHostname, matchDnsName } from "./hostname.js";
72
61
  /**
73
- * Verify a certificate chain: each cert is signed by the next, the root is in
74
- * the trust anchors, and the leaf is valid for the hostname and not expired.
62
+ * Verify a certificate chain against trust anchors (RFC 5280 §6.1).
63
+ *
64
+ * The path is BUILT from the leaf: at each step the issuer is found among the
65
+ * trust anchors (preferred) and the remaining server-sent certificates — or a
66
+ * self-signed certificate matches an anchor by identity (subject DN + SPKI
67
+ * bytes), which ends the path without any signature verification. Candidates
68
+ * are searched depth-first with backtracking, and every completed candidate
69
+ * path is checked (validity window, basicConstraints/keyCertSign,
70
+ * pathLenConstraint); the first FULLY VALID path wins, so the outcome never
71
+ * depends on the order the server chose. Building IS the chain verification —
72
+ * no signature pair is verified twice. The server may omit the root (the
73
+ * normal case), send it, order intermediates arbitrarily, or add unrelated
74
+ * certificates; none of that is special-cased.
75
+ *
76
+ * Check order: hostname (always, first — the cheap, always-applicable check),
77
+ * then the no-anchors guard, then the signature-algorithm policy, then the
78
+ * builder (which runs the path checks per candidate path).
75
79
  *
76
- * Signature verification is delegated to @browsercore/crypto. Throws
77
- * {@link TlsHandshakeError} with phase "certificate" on any failure.
80
+ * Failures are typed: {@link TlsCertificateError} carries a discriminated
81
+ * `reason` ("no-anchors", "no-issuer", "bad-signature", "expired",
82
+ * "not-yet-valid", "not-a-ca", "missing-key-cert-sign", "path-too-long").
83
+ *
84
+ * Signature verification is delegated to @browsercore/crypto.
78
85
  */
79
86
  export declare function verifyChain(chain: CertificateChain, trustAnchors: readonly TrustAnchor[], hostname: string, now: number, provider: CryptoProvider): Promise<void>;
80
87
  export { pemToDer } from "./pem.js";
88
+ /** The `rejected` variant of {@link CertificateSignatureAlgorithm}. */
89
+ export type RejectedSignatureAlgorithm = Extract<CertificateSignatureAlgorithm, {
90
+ readonly kind: "rejected";
91
+ }>;
92
+ /**
93
+ * Diagnostic message for a certificate carrying a rejected signature
94
+ * algorithm. Names the certificate (chain index + issuer DN), the policy
95
+ * reason and the OID so an operator can identify the offending certificate
96
+ * without re-running the handshake. Shared by verifyChain and the
97
+ * validateCertificateChain policy sweep so the wording has one source.
98
+ */
99
+ export declare function rejectedAlgorithmMessage(index: number, cert: Certificate, rejected: RejectedSignatureAlgorithm): string;
81
100
  //# sourceMappingURL=certificates.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"certificates.d.ts","sourceRoot":"","sources":["../../src/certificates/certificates.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAmBnD,oEAAoE;AACpE,MAAM,WAAW,WAAW;IACxB,2EAA2E;IAC3E,QAAQ,CAAC,QAAQ,EAAE,UAAU,CAAC;IAC9B,wCAAwC;IACxC,QAAQ,CAAC,oBAAoB,EAAE,UAAU,CAAC;IAC1C,sEAAsE;IACtE,QAAQ,CAAC,eAAe,EAAE,SAAS,MAAM,EAAE,CAAC;IAC5C,2EAA2E;IAC3E,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B,4CAA4C;IAC5C,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,2CAA2C;IAC3C,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,0EAA0E;IAC1E,QAAQ,CAAC,wBAAwB,EAAE,OAAO,CAAC;IAC3C,mFAAmF;IACnF,QAAQ,CAAC,uBAAuB,EAAE,OAAO,CAAC;IAC1C,sEAAsE;IACtE,QAAQ,CAAC,eAAe,EAAE,eAAe,CAAC;IAC1C,2CAA2C;IAC3C,QAAQ,CAAC,cAAc,EAAE,UAAU,CAAC;IACpC,2EAA2E;IAC3E,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,iCAAiC;IACjC,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC;CAC1B;AAED,iFAAiF;AACjF,MAAM,WAAW,gBAAgB;IAC7B,QAAQ,CAAC,IAAI,EAAE,WAAW,CAAC;IAC3B,QAAQ,CAAC,aAAa,EAAE,SAAS,WAAW,EAAE,CAAC;IAC/C,QAAQ,CAAC,IAAI,EAAE,WAAW,CAAC;CAC9B;AAED,4DAA4D;AAC5D,MAAM,WAAW,WAAW;IACxB,QAAQ,CAAC,oBAAoB,EAAE,UAAU,CAAC;IAC1C,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;CAC5B;AAED;;;;;;;;;GASG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,UAAU,GAAG,WAAW,CAiK7D;AAED;;;GAGG;AACH,OAAO,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAE/D;;;;;;GAMG;AACH,wBAAgB,WAAW,CACvB,KAAK,EAAE,gBAAgB,EACvB,YAAY,EAAE,SAAS,WAAW,EAAE,EACpC,QAAQ,EAAE,MAAM,EAChB,GAAG,EAAE,MAAM,EACX,QAAQ,EAAE,cAAc,GACzB,OAAO,CAAC,IAAI,CAAC,CAmFf;AAED,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC"}
1
+ {"version":3,"file":"certificates.d.ts","sourceRoot":"","sources":["../../src/certificates/certificates.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAOH,OAAO,KAAK,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAS1E,OAAO,EAA2B,KAAK,6BAA6B,EAAE,MAAM,0BAA0B,CAAC;AAEvG,OAAO,EAEH,KAAK,gBAAgB,EAErB,KAAK,iBAAiB,EACtB,KAAK,WAAW,EACnB,MAAM,uBAAuB,CAAC;AAmC/B,YAAY,EAAE,WAAW,EAAE,CAAC;AAO5B,YAAY,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,eAAe,EAAE,4BAA4B,EAAE,iBAAiB,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACnK,OAAO,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AAErF;;;;;;;;;GASG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,UAAU,GAAG,WAAW,CAE7D;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,UAAU,GAAG,iBAAiB,CAmR1E;AAED;;;GAGG;AACH,OAAO,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAE/D;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAgB,WAAW,CACvB,KAAK,EAAE,gBAAgB,EACvB,YAAY,EAAE,SAAS,WAAW,EAAE,EACpC,QAAQ,EAAE,MAAM,EAChB,GAAG,EAAE,MAAM,EACX,QAAQ,EAAE,cAAc,GACzB,OAAO,CAAC,IAAI,CAAC,CA8Df;AAED,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAEpC,uEAAuE;AACvE,MAAM,MAAM,0BAA0B,GAAG,OAAO,CAAC,6BAA6B,EAAE;IAAE,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAA;CAAE,CAAC,CAAC;AAE/G;;;;;;GAMG;AACH,wBAAgB,wBAAwB,CACpC,KAAK,EAAE,MAAM,EACb,IAAI,EAAE,WAAW,EACjB,QAAQ,EAAE,0BAA0B,GACrC,MAAM,CAKR"}
@@ -10,25 +10,55 @@
10
10
  * read and tested in isolation:
11
11
  * - `der.ts` — DER tag-length-value primitives (no X.509 semantics)
12
12
  * - `cert-extensions.ts` — subject/issuer names, SAN, KeyUsage, BasicConstraints
13
+ * - `ca-constraints.ts` — the path-validation delta: keyCertSign bit,
14
+ * BasicConstraints pathLenConstraint
15
+ * - `certificate-path.ts` — the pure RFC 5280 §6.1 path builder and its
16
+ * checks, plus the tls-internal ParsedCertificate /
17
+ * CertificateChain / TrustAnchor types (re-exported here
18
+ * for the stable import path)
13
19
  * - `pem.ts` — PEM container decoding (the only place that knows about
14
20
  * the BEGIN/END text wrapper; downstream code sees raw DER)
15
21
  */
16
- import { TlsHandshakeError, ensureTlsError } from "../errors.js";
22
+ import { TlsHandshakeError, TlsMalformedExtensionError, TlsCertificateError, ensureTlsError } from "../errors.js";
17
23
  import { constantTimeEqual } from "../utils.js";
18
24
  import { validateHostname } from "./hostname.js";
19
- import { oidToSignatureScheme, parseAlgorithmIdentifierOid, parseTime, peekTag, readTlv, } from "./der.js";
20
- import { parseBasicConstraints, parseCommonName, parseExtensionsBlock, parseKeyUsage, parseName, parseSubjectAltNames, } from "./cert-extensions.js";
25
+ import { parseTime, peekTag, readTlv, } from "./der.js";
26
+ import { parseSignatureAlgorithm } from "./signature-algorithm.js";
27
+ import { hasKeyUsageBit, KEY_USAGE_KEY_CERT_SIGN_BIT } from "./ca-constraints.js";
28
+ import { buildCertificatePath, } from "./certificate-path.js";
29
+ import { parseBasicConstraints, parseCommonName, parseExtendedKeyUsage, parseExtensionsBlock, parseKeyUsage, parseName, parseSubjectAltNames, parseNameConstraints, BASIC_CONSTRAINTS_OID, EXTENDED_KEY_USAGE_OID, KEY_USAGE_OID, SUBJECT_ALT_NAME_OID, } from "./cert-extensions.js";
30
+ import { parseAuthorityInfoAccess, parseCertificatePolicies, parseInhibitAnyPolicy, parsePolicyConstraints, parsePolicyMappings, parseSubjectKeyIdentifier, parseAuthorityKeyIdentifier, AUTHORITY_INFO_ACCESS_OID, AUTHORITY_KEY_IDENTIFIER_OID, CERTIFICATE_POLICIES_OID, INHIBIT_ANY_POLICY_OID, NAME_CONSTRAINTS_OID, POLICY_CONSTRAINTS_OID, POLICY_MAPPINGS_OID, SUBJECT_KEY_IDENTIFIER_OID, } from "./extension-values.js";
31
+ export { buildCertificatePath, MAX_PATH_INTERMEDIATES } from "./certificate-path.js";
21
32
  /**
22
- * Parse a single DER-encoded X.509 certificate.
33
+ * Parse a single DER-encoded X.509 certificate (contract-type boundary).
34
+ *
35
+ * Thin wrapper over {@link parseCertificateDetails}: consumers see ONLY the
36
+ * canonical contract `Certificate`; the tls-internal DN byte spans and
37
+ * path-constraint fields ride along on the same object for path building
38
+ * (ParsedCertificate extends Certificate, so this is a plain upcast).
39
+ *
40
+ * Throws {@link TlsHandshakeError} with phase "certificate" on malformed input.
41
+ */
42
+ export function parseCertificate(buf) {
43
+ return parseCertificateDetails(buf);
44
+ }
45
+ /**
46
+ * Parse a single DER-encoded X.509 certificate into the FULL tls-internal
47
+ * form ({@link ParsedCertificate}).
23
48
  *
24
49
  * Decodes the outer Certificate SEQUENCE into its TBSCertificate, signature
25
50
  * algorithm, and signature value, then extracts the validation-relevant fields.
26
51
  * `tbsBytes` is captured as the EXACT DER span of the TBSCertificate so that
27
- * signature verification over it is byte-correct.
52
+ * signature verification over it is byte-correct. The subject and issuer Name
53
+ * DER spans are captured as the candidate-filter key for path building (the
54
+ * signature check binds issuer to subject; DN equality only filters).
28
55
  *
29
56
  * Throws {@link TlsHandshakeError} with phase "certificate" on malformed input.
57
+ * A structurally valid certificate is NEVER rejected because of its signature
58
+ * algorithm — an unsupported/rejected algorithm is reported through
59
+ * {@link Certificate.signatureAlgorithm} and policed by the caller.
30
60
  */
31
- export function parseCertificate(buf) {
61
+ export function parseCertificateDetails(buf) {
32
62
  // Outer Certificate SEQUENCE.
33
63
  const cert = readTlv(buf, 0);
34
64
  if (cert.tag !== 0x30) {
@@ -57,12 +87,16 @@ export function parseCertificate(buf) {
57
87
  }
58
88
  // serialNumber INTEGER — skip.
59
89
  o = readTlv(buf, o).end;
60
- // signature AlgorithmIdentifier.
61
- const signatureScheme = oidToSignatureScheme(parseAlgorithmIdentifierOid(buf, o));
90
+ // signature AlgorithmIdentifier — parsed to a supported/rejected union
91
+ // (never throws for an algorithm we merely do not accept).
92
+ const signatureAlgorithm = parseSignatureAlgorithm(buf, o);
62
93
  o = readTlv(buf, o).end;
63
- // issuer Name — skip past it but remember the span for the issuer string.
94
+ // issuer Name — parse the display string and keep the DER span (the path
95
+ // builder compares issuer↔subject DN BYTES, never the parsed strings,
96
+ // which collapse encoding differences).
64
97
  const issuerTlv = readTlv(buf, o);
65
98
  const issuer = parseName(buf, issuerTlv.start, issuerTlv.end);
99
+ const issuerDn = buf.subarray(issuerTlv.start, issuerTlv.end);
66
100
  o = issuerTlv.end;
67
101
  // validity SEQUENCE { notBefore, notAfter }.
68
102
  const validity = readTlv(buf, o);
@@ -78,8 +112,12 @@ export function parseCertificate(buf) {
78
112
  const notAfterTlv = readTlv(buf, v);
79
113
  const notAfter = parseTime(buf, notAfterTlv.valueStart, notAfterTlv.end, notAfterTlv.tag);
80
114
  o = validity.end;
81
- // subject Name — skip (we only need CN for legacy hostname match).
115
+ // subject Name — the DER span is kept for the path builder, and selfSigned
116
+ // is decided by comparing raw subject vs issuer bytes (never the parsed
117
+ // DN strings, which collapse encoding differences).
82
118
  const subjectTlv = readTlv(buf, o);
119
+ const subjectDn = buf.subarray(subjectTlv.start, subjectTlv.end);
120
+ const selfSigned = constantTimeEqual(issuerDn, subjectDn);
83
121
  o = subjectTlv.end;
84
122
  // subjectPublicKeyInfo — capture the full DER span.
85
123
  const spkiTlv = readTlv(buf, o);
@@ -95,30 +133,125 @@ export function parseCertificate(buf) {
95
133
  let subjectAltNames = [];
96
134
  let keyUsageDigitalSignature = false;
97
135
  let keyUsageKeyEncipherment = false;
136
+ // keyUsage PRESENCE is tracked separately from its bits: RFC 5280 §4.2.1.3
137
+ // makes the extension optional, and the path checker only demands
138
+ // keyCertSign when the extension is there at all.
139
+ let keyUsagePresent = false;
140
+ let keyUsageKeyCertSign = false;
141
+ // extendedKeyUsage PRESENCE is tracked separately from its OID list for
142
+ // the same reason: an EMPTY EKU sequence is "present, permitting nothing"
143
+ // and fails the SERVER_AUTH rule, while an absent extension is accepted
144
+ // (Chrome's kEkuNotPresent warning only).
145
+ let extendedKeyUsagePresent = false;
146
+ let extendedKeyUsage = [];
98
147
  let isCa = false;
148
+ let pathLenConstraint = null;
99
149
  let commonName;
150
+ // The strict parse-time VALUE checks (see the module comment of
151
+ // extension-values.ts): every extension BoringSSL's
152
+ // ParsedCertificate::Create parses — critical or not — gets its value
153
+ // validated here, in the SAME order as parsed_certificate.cc so the
154
+ // reported failure matches Chrome's when several values are malformed.
155
+ let nameConstraints = null;
156
+ let sanDetails = null;
157
+ // The full ordered extension inventory — every extension with its critical
158
+ // flag and raw extnValue contents — is what the critical-extension policy
159
+ // iterates on the built path (RFC 5280 §4.2 via BoringSSL
160
+ // VerifyNoUnconsumedCriticalExtensions).
161
+ let extensionInventory = [];
100
162
  while (o < tbs.end) {
101
163
  const tag = peekTag(buf, o);
102
164
  if (tag === 0xa3) {
103
165
  // extensions [3] EXPLICIT: a SEQUENCE OF Extension inside a [3] wrapper.
104
166
  const extWrapper = readTlv(buf, o);
105
- const extensions = parseExtensionsBlock(buf, extWrapper.valueStart, extWrapper.end);
106
- for (const ext of extensions) {
107
- switch (ext.oid) {
108
- case "2.5.29.17":
109
- subjectAltNames = parseSubjectAltNames(ext.value);
110
- break;
111
- case "2.5.29.15":
112
- ({ digitalSignature: keyUsageDigitalSignature, keyEncipherment: keyUsageKeyEncipherment } =
113
- parseKeyUsage(ext.value));
114
- break;
115
- case "2.5.29.19":
116
- isCa = parseBasicConstraints(ext.value);
117
- break;
118
- default:
119
- break;
167
+ extensionInventory = parseExtensionsBlock(buf, extWrapper.valueStart, extWrapper.end);
168
+ const byOid = new Map(extensionInventory.map((ext) => [ext.oid, ext]));
169
+ // ParsedCertificate::Create's processing order (parsed_certificate.cc
170
+ // 154-288) — the FIRST malformed value in this order is the failure
171
+ // Chrome reports, so the order is part of the parity contract.
172
+ const basicConstraintsExt = byOid.get(BASIC_CONSTRAINTS_OID);
173
+ if (basicConstraintsExt !== undefined) {
174
+ // kFailedParsingBasicConstraints — a malformed value rejects
175
+ // the certificate whether the extension is critical or not.
176
+ ({ isCa, pathLenConstraint } = parseBasicConstraints(basicConstraintsExt.value));
177
+ }
178
+ const keyUsageExt = byOid.get(KEY_USAGE_OID);
179
+ if (keyUsageExt !== undefined) {
180
+ keyUsagePresent = true;
181
+ ({ digitalSignature: keyUsageDigitalSignature, keyEncipherment: keyUsageKeyEncipherment } =
182
+ parseKeyUsage(keyUsageExt.value));
183
+ keyUsageKeyCertSign = hasKeyUsageBit(keyUsageExt.value, KEY_USAGE_KEY_CERT_SIGN_BIT);
184
+ }
185
+ const extendedKeyUsageExt = byOid.get(EXTENDED_KEY_USAGE_OID);
186
+ if (extendedKeyUsageExt !== undefined) {
187
+ // SEQUENCE OF KeyPurposeId; a malformed value throws
188
+ // here (BoringSSL kFailedParsingEku rejects the
189
+ // certificate at parse time the same way).
190
+ extendedKeyUsagePresent = true;
191
+ extendedKeyUsage = parseExtendedKeyUsage(extendedKeyUsageExt.value);
192
+ }
193
+ const subjectAltNameExt = byOid.get(SUBJECT_ALT_NAME_OID);
194
+ if (subjectAltNameExt !== undefined) {
195
+ // kFailedParsingSubjectAltName: GeneralNames::Create parses
196
+ // the value for EVERY certificate carrying the extension.
197
+ sanDetails = parseSubjectAltNames(subjectAltNameExt.value);
198
+ subjectAltNames = sanDetails.dnsNames;
199
+ // RFC 5280 §4.1.2.6 via parsed_certificate.cc:193-202 — a
200
+ // certificate whose subject is EMPTY must carry the SAN
201
+ // extension as critical ("then the subject name MUST be an
202
+ // empty sequence and the subjectAltName extension MUST be
203
+ // critical"); kSubjectAltNameNotCritical otherwise rejects.
204
+ // (An empty subject SEQUENCE is `30 00` — its content span is
205
+ // empty, i.e. valueStart === end.)
206
+ if (subjectTlv.valueStart >= subjectTlv.end && !subjectAltNameExt.critical) {
207
+ throw new TlsMalformedExtensionError(SUBJECT_ALT_NAME_OID, "subject is empty, so the subjectAltName extension MUST be critical (RFC 5280 §4.1.2.6; kSubjectAltNameNotCritical)");
120
208
  }
121
209
  }
210
+ const nameConstraintsExt = byOid.get(NAME_CONSTRAINTS_OID);
211
+ if (nameConstraintsExt !== undefined) {
212
+ // kFailedParsingNameConstraints: the value is parsed for
213
+ // EVERY certificate carrying the extension — a malformed
214
+ // nameConstraints value rejects the certificate critical or
215
+ // not (parsed_certificate.cc:206-213).
216
+ nameConstraints = parseNameConstraints(nameConstraintsExt.value, nameConstraintsExt.critical);
217
+ }
218
+ const authorityInfoAccessExt = byOid.get(AUTHORITY_INFO_ACCESS_OID);
219
+ if (authorityInfoAccessExt !== undefined) {
220
+ // kFailedParsingAia (parsed_certificate.cc:216-225).
221
+ parseAuthorityInfoAccess(authorityInfoAccessExt.value, AUTHORITY_INFO_ACCESS_OID);
222
+ }
223
+ const certificatePoliciesExt = byOid.get(CERTIFICATE_POLICIES_OID);
224
+ if (certificatePoliciesExt !== undefined) {
225
+ // kFailedParsingPolicies — parse-time mode tolerates unknown
226
+ // qualifier OIDs (fail_parsing_unknown_qualifier_oids=false)
227
+ // but still polices the exact structure.
228
+ parseCertificatePolicies(certificatePoliciesExt.value, CERTIFICATE_POLICIES_OID);
229
+ }
230
+ const policyConstraintsExt = byOid.get(POLICY_CONSTRAINTS_OID);
231
+ if (policyConstraintsExt !== undefined) {
232
+ // kFailedParsingPolicyConstraints (parsed_certificate.cc:239-246).
233
+ parsePolicyConstraints(policyConstraintsExt.value, POLICY_CONSTRAINTS_OID);
234
+ }
235
+ const policyMappingsExt = byOid.get(POLICY_MAPPINGS_OID);
236
+ if (policyMappingsExt !== undefined) {
237
+ // kFailedParsingPolicyMappings (parsed_certificate.cc:249-255).
238
+ parsePolicyMappings(policyMappingsExt.value, POLICY_MAPPINGS_OID);
239
+ }
240
+ const inhibitAnyPolicyExt = byOid.get(INHIBIT_ANY_POLICY_OID);
241
+ if (inhibitAnyPolicyExt !== undefined) {
242
+ // kFailedParsingInhibitAnyPolicy (parsed_certificate.cc:258-264).
243
+ parseInhibitAnyPolicy(inhibitAnyPolicyExt.value, INHIBIT_ANY_POLICY_OID);
244
+ }
245
+ const subjectKeyIdentifierExt = byOid.get(SUBJECT_KEY_IDENTIFIER_OID);
246
+ if (subjectKeyIdentifierExt !== undefined) {
247
+ // kFailedParsingSubjectKeyIdentifier (parsed_certificate.cc:267-275).
248
+ parseSubjectKeyIdentifier(subjectKeyIdentifierExt.value, SUBJECT_KEY_IDENTIFIER_OID);
249
+ }
250
+ const authorityKeyIdentifierExt = byOid.get(AUTHORITY_KEY_IDENTIFIER_OID);
251
+ if (authorityKeyIdentifierExt !== undefined) {
252
+ // kFailedParsingAuthorityKeyIdentifier (parsed_certificate.cc:278-287).
253
+ parseAuthorityKeyIdentifier(authorityKeyIdentifierExt.value, AUTHORITY_KEY_IDENTIFIER_OID);
254
+ }
122
255
  o = extWrapper.end;
123
256
  }
124
257
  else if (tag === 0xa1 || tag === 0xa2) {
@@ -146,25 +279,7 @@ export function parseCertificate(buf) {
146
279
  }
147
280
  // signatureValue is a BIT STRING: first content byte is the "unused bits" count.
148
281
  const signatureValue = buf.subarray(sigValueTlv.valueStart + 1, sigValueTlv.end);
149
- // Under exactOptionalPropertyTypes, an optional `?:` property must be omitted
150
- // rather than set to undefined. Only attach `commonName` when we found one.
151
- if (commonName !== undefined) {
152
- return {
153
- tbsBytes,
154
- subjectPublicKeyInfo,
155
- subjectAltNames: Object.freeze(subjectAltNames),
156
- commonName,
157
- notBefore,
158
- notAfter,
159
- keyUsageDigitalSignature,
160
- keyUsageKeyEncipherment,
161
- signatureScheme,
162
- signatureValue,
163
- issuer,
164
- isCa,
165
- };
166
- }
167
- return {
282
+ const parsed = {
168
283
  tbsBytes,
169
284
  subjectPublicKeyInfo,
170
285
  subjectAltNames: Object.freeze(subjectAltNames),
@@ -172,11 +287,37 @@ export function parseCertificate(buf) {
172
287
  notAfter,
173
288
  keyUsageDigitalSignature,
174
289
  keyUsageKeyEncipherment,
175
- signatureScheme,
290
+ keyUsagePresent,
291
+ keyUsageKeyCertSign,
292
+ extensions: extensionInventory,
293
+ extendedKeyUsagePresent,
294
+ extendedKeyUsage,
295
+ signatureAlgorithm,
296
+ selfSigned,
176
297
  signatureValue,
177
298
  issuer,
178
299
  isCa,
300
+ subjectDn,
301
+ issuerDn,
302
+ pathLenConstraint,
303
+ // The strict parse-time results the name-constraint engine consumes:
304
+ // the parsed SAN (null when the extension is absent) and the parsed
305
+ // nameConstraints (null when absent). The subject/issuer RDNSequence
306
+ // VALUEs (outer SEQUENCE tag stripped) are the DN-matching operands —
307
+ // the same form BoringSSL passes as normalized_subject() /
308
+ // directoryName constraint bytes.
309
+ sanNames: sanDetails,
310
+ nameConstraints,
311
+ subjectNameValue: buf.subarray(subjectTlv.valueStart, subjectTlv.end),
312
+ issuerNameValue: buf.subarray(issuerTlv.valueStart, issuerTlv.end),
179
313
  };
314
+ // Under exactOptionalPropertyTypes, an optional `?:` property must be
315
+ // omitted rather than set to undefined. Only attach `commonName` when we
316
+ // found one.
317
+ if (commonName !== undefined) {
318
+ return { ...parsed, commonName };
319
+ }
320
+ return parsed;
180
321
  }
181
322
  /**
182
323
  * Validate that a certificate is valid for the given hostname per RFC 6125.
@@ -184,11 +325,29 @@ export function parseCertificate(buf) {
184
325
  */
185
326
  export { validateHostname, matchDnsName } from "./hostname.js";
186
327
  /**
187
- * Verify a certificate chain: each cert is signed by the next, the root is in
188
- * the trust anchors, and the leaf is valid for the hostname and not expired.
328
+ * Verify a certificate chain against trust anchors (RFC 5280 §6.1).
329
+ *
330
+ * The path is BUILT from the leaf: at each step the issuer is found among the
331
+ * trust anchors (preferred) and the remaining server-sent certificates — or a
332
+ * self-signed certificate matches an anchor by identity (subject DN + SPKI
333
+ * bytes), which ends the path without any signature verification. Candidates
334
+ * are searched depth-first with backtracking, and every completed candidate
335
+ * path is checked (validity window, basicConstraints/keyCertSign,
336
+ * pathLenConstraint); the first FULLY VALID path wins, so the outcome never
337
+ * depends on the order the server chose. Building IS the chain verification —
338
+ * no signature pair is verified twice. The server may omit the root (the
339
+ * normal case), send it, order intermediates arbitrarily, or add unrelated
340
+ * certificates; none of that is special-cased.
189
341
  *
190
- * Signature verification is delegated to @browsercore/crypto. Throws
191
- * {@link TlsHandshakeError} with phase "certificate" on any failure.
342
+ * Check order: hostname (always, first — the cheap, always-applicable check),
343
+ * then the no-anchors guard, then the signature-algorithm policy, then the
344
+ * builder (which runs the path checks per candidate path).
345
+ *
346
+ * Failures are typed: {@link TlsCertificateError} carries a discriminated
347
+ * `reason` ("no-anchors", "no-issuer", "bad-signature", "expired",
348
+ * "not-yet-valid", "not-a-ca", "missing-key-cert-sign", "path-too-long").
349
+ *
350
+ * Signature verification is delegated to @browsercore/crypto.
192
351
  */
193
352
  export function verifyChain(chain, trustAnchors, hostname, now, provider) {
194
353
  // Not async: crypto.verifySignature returns a synchronous boolean (awaiting it
@@ -196,56 +355,45 @@ export function verifyChain(chain, trustAnchors, hostname, now, provider) {
196
355
  // promise so callers can await uniformly; the original TlsHandshakeError is
197
356
  // propagated as-is (not re-wrapped) so its type reaches the caller.
198
357
  try {
199
- const certs = [chain.leaf, ...chain.intermediates, chain.root];
200
- // 1. Validity windows: every cert must currently be valid.
201
- for (const cert of certs) {
202
- if (now < cert.notBefore || now > cert.notAfter) {
203
- throw new TlsHandshakeError("certificate", {
204
- cause: new Error(`certificate ${cert.issuer} not valid at ${now} (valid ${cert.notBefore}..${cert.notAfter})`),
205
- });
206
- }
358
+ // 1. Hostname validation against the leaf — FIRST: it is the cheap,
359
+ // always-applicable check and names the failure the caller cares
360
+ // about most.
361
+ if (!validateHostname(chain.leaf, hostname)) {
362
+ throw new TlsHandshakeError("certificate", {
363
+ cause: new Error(`hostname "${hostname}" does not match leaf certificate`),
364
+ });
207
365
  }
208
- // 2. basicConstraints CA flags: every intermediate must be a CA. The root
209
- // is authorized by the trust-anchor SPKI match (step 4), not by its own
210
- // basicConstraints, so a self-signed trust anchor need not set cA.
211
- for (const cert of chain.intermediates) {
212
- if (!cert.isCa) {
213
- throw new TlsHandshakeError("certificate", {
214
- cause: new Error(`intermediate certificate ${cert.issuer} is missing basicConstraints cA`),
215
- });
216
- }
366
+ // 2. An empty anchor list must never succeed vacuously — there is
367
+ // nothing the path could anchor to.
368
+ if (trustAnchors.length === 0) {
369
+ throw new TlsCertificateError("no-anchors", "no trust anchors supplied: the certificate path cannot be anchored");
217
370
  }
218
- // 3. For each (subject, issuer) pair, verify the signature. The issuer's
219
- // public key (SPKI) verifies the subject's signature over its TBSCertificate.
220
- const subjects = [chain.leaf, ...chain.intermediates];
221
- const issuers = [...chain.intermediates, chain.root];
222
- for (let i = 0; i < subjects.length; i++) {
223
- const subject = subjects[i];
224
- const issuer = issuers[i];
225
- if (subject === undefined || issuer === undefined) {
226
- throw new TlsHandshakeError("certificate", {
227
- cause: new Error(`certificate chain entry at index ${i} is missing`),
228
- });
371
+ // 3. Signature-algorithm policy for the direct caller (verifyChain is
372
+ // exported and must hold the same guarantee as
373
+ // validateCertificateChain's sweep without re-running it): a
374
+ // rejected algorithm fails with the shared diagnostic BEFORE any
375
+ // cryptographic operation. Self-signed certificates are exempt for
376
+ // the same reason the sweep exempts them — their signature covers
377
+ // nothing the client relies on (trust rests on the anchor match).
378
+ const sent = [chain.leaf, ...chain.intermediates];
379
+ for (const [index, cert] of sent.entries()) {
380
+ if (cert.selfSigned) {
381
+ continue;
229
382
  }
230
- const ok = provider.verifySignature(subject.signatureScheme, issuer.subjectPublicKeyInfo, subject.signatureValue, subject.tbsBytes);
231
- if (!ok) {
383
+ if (cert.signatureAlgorithm.kind === "rejected") {
232
384
  throw new TlsHandshakeError("certificate", {
233
- cause: new Error(`signature verification failed: ${subject.issuer} not signed by ${issuer.issuer}`),
385
+ cause: new Error(rejectedAlgorithmMessage(index, cert, cert.signatureAlgorithm)),
234
386
  });
235
387
  }
236
388
  }
237
- // 4. The chain root's SPKI must match one of the trust anchors.
238
- const rootTrusted = trustAnchors.some((ta) => constantTimeEqual(ta.subjectPublicKeyInfo, chain.root.subjectPublicKeyInfo));
239
- if (!rootTrusted) {
240
- throw new TlsHandshakeError("certificate", {
241
- cause: new Error(`root certificate ${chain.root.issuer} does not match any trust anchor`),
242
- });
243
- }
244
- // 5. Hostname validation against the leaf.
245
- if (!validateHostname(chain.leaf, hostname)) {
246
- throw new TlsHandshakeError("certificate", {
247
- cause: new Error(`hostname "${hostname}" does not match leaf certificate`),
248
- });
389
+ // 4. Build the path. Every signature verification inside the builder IS
390
+ // the chain verification, and the builder validates each completed
391
+ // candidate path (validity, CA flags, path length) so backtracking
392
+ // can skip routes that would fail a check — the returned path is
393
+ // the first fully valid one, never verify a pair twice.
394
+ const built = buildCertificatePath(chain, trustAnchors, provider, now);
395
+ if (built.kind === "unanchored") {
396
+ throw new TlsCertificateError(built.reason, built.message, built.details === undefined ? undefined : { details: built.details });
249
397
  }
250
398
  return Promise.resolve();
251
399
  }
@@ -260,4 +408,15 @@ export function verifyChain(chain, trustAnchors, hostname, now, provider) {
260
408
  }
261
409
  }
262
410
  export { pemToDer } from "./pem.js";
411
+ /**
412
+ * Diagnostic message for a certificate carrying a rejected signature
413
+ * algorithm. Names the certificate (chain index + issuer DN), the policy
414
+ * reason and the OID so an operator can identify the offending certificate
415
+ * without re-running the handshake. Shared by verifyChain and the
416
+ * validateCertificateChain policy sweep so the wording has one source.
417
+ */
418
+ export function rejectedAlgorithmMessage(index, cert, rejected) {
419
+ return (`certificate at index ${index} (${cert.issuer}) carries a rejected ` +
420
+ `signature algorithm: ${rejected.reason} (OID ${rejected.oid})`);
421
+ }
263
422
  //# sourceMappingURL=certificates.js.map