@blamejs/pki 0.1.17 → 0.1.19

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/CHANGELOG.md CHANGED
@@ -4,7 +4,51 @@ All notable changes to `@blamejs/pki` are documented here. The format
4
4
  follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); this
5
5
  project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
- ## v0.1.17 — 2026-07-07
7
+ ## v0.1.19 — 2026-07-09
8
+
9
+ An RFC 9810 Certificate Management Protocol message parser joins the pki.schema family.
10
+
11
+ ### Added
12
+
13
+ - pki.schema.cmp.parse(input) — RFC 9810 PKIMessage parsing. It decodes a DER Buffer or PEM into { header, headerBytes, body, bodyBytes, protection, extraCerts }. The header carries pvno (1..3), validated sender / recipient GeneralNames (the anonymous NULL-DN accepted), and the optional messageTime (GeneralizedTime only), protectionAlg, senderKID / recipKID, transactionID, senderNonce / recipNonce, freeText, and generalInfo (recognized id-it values are syntax-checked). The body is { arm, tag, bytes, decoded? }: ir / cr / kur / krr / ccr decode through the CRMF parser; ip / cp / kup / ccp decode to a certificate-response structure (an encrypted certificate's EnvelopedData decodes through the CMS parser; the deprecated EncryptedValue arm and caPubs surface raw, conferring no trust); krp decodes to a key-recovery structure ({ status, newSigCert, caCerts, keyPairHist }); rr / rp, genm / genp, error, certConf (an empty confirmation is the legal reject-all), and pollReq / pollRep decode structurally; pkiconf decodes to null; every other defined arm — p10cr, the challenge-response and announcement arms, and nested (never auto-recursed) — surfaces raw. certReqId values are big integers and accept the protocol's -1 sentinel. The two cross-field coherence rules (protection bits and protectionAlg present together or absent together; a certConf hashAlg requires version cmp2021) are enforced. Protection is surfaced, not verified: headerBytes and bodyBytes are the exact wire slices, so a verifier reconstructs the protected part as a DER SEQUENCE wrapping them and checks the MAC or signature. Malformed input fails closed with a typed cmp/* or asn1/* code.
14
+ - pki.schema.cmp.pemDecode(text, label?) / pemEncode(der, label?) — PEM handling for messages that transit text channels (default label CMP).
15
+ - pki.schema.crmf.parse now surfaces every CertTemplate field, including serialNumber and the issuer/subject unique identifiers. RFC 4211's rule that a certificate request must omit the CA-assigned fields (serialNumber, signingAlg) and the deprecated unique identifiers moved from the shared CertTemplate structure to the request layer, so a request that sets them still fails closed while the same structure can identify an existing certificate — serialNumber and issuer present — inside a CMP revocation.
16
+ - The OID registry gains the CMP id-it information types and the message-protection MAC algorithm identifiers (passwordBasedMac, dhBasedMac, kemBasedMac), so a parsed message's info types and protection algorithm resolve to names.
17
+ - The error taxonomy gains CmpError, carrying a stable cmp/* code.
18
+
19
+ ### Changed
20
+
21
+ - pki.schema.tsp parsing (parse, parseTstInfo, parseToken, pemDecode) is now stable.
22
+ - The npm-publish vulnerability scan reads the committed lockfiles (the dev and build toolchain that runs during a publish) instead of the runtime SBOM, which is empty by construction because the package ships zero runtime dependencies.
23
+
24
+ ### Fixed
25
+
26
+ - Certification-path validation bounds the BasicConstraints pathLenConstraint and the PolicyConstraints / InhibitAnyPolicy skip counts before narrowing them to a number, so a certificate carrying a value past the safe-integer range is rejected rather than having the counter round silently to the wrong value (the same exact-or-rejected rule the RSASSA-PSS salt length and PKCS#12 iteration count follow).
27
+ - Certification-path validation rejects a non-empty DER NULL in an RSASSA-PSS hash AlgorithmIdentifier's parameters — a NULL must carry empty content (X.690 8.8.2), so the previous tag-only check accepted a malformed encoding it now fails closed.
28
+
29
+ ## v0.1.18 — 2026-07-08
30
+
31
+ An RFC 7292 PKCS#12 (PFX) store parser joins the pki.schema family.
32
+
33
+ ### Added
34
+
35
+ - pki.schema.pkcs12.parse(input) — RFC 7292 PFX parsing. It decodes a DER / BER Buffer or PEM into { version, integrityMode, mac, macedBytes, authSafeSigned, safeBags, encryptedSafes }. Password-integrity stores surface { kind, hashOid, hashName, hashParameters, pbmac1, macValue, macSalt, iterations } plus macedBytes — the exact value octets the HMAC covers, excluding the octet-string header, so an external verifier hashes the correct region. The RFC 9579 PBMAC1 arm is validated, not just recognized: its parameters must be present, the key-derivation function must be PBKDF2 with a keyLength, and the decoded KDF (salt, iteration count, key length, PRF) and MAC scheme surface on pbmac1. The X.690 DEFAULT rule is enforced (an explicitly encoded iterations = 1 is non-canonical and rejects). Public-key-integrity stores surface the CMS SignedData and must carry at least one signer (the signature itself is verified externally). Each safeBag carries its type, friendlyName / localKeyId (decoded, single-value and single-instance rules enforced), and all attributes: keyBags delegate to pki.schema.pkcs8.parse, shrouded key bags to parseEncrypted (algorithm surfaced, ciphertext opaque), cert / CRL / secret values stay raw and byte-exact, and safeContentsBags recurse under a depth ceiling. Encrypted and enveloped safes are validated structurally by the CMS module with ciphertext kept raw, and must declare id-data (a SafeContents) as their encrypted content type. The version-3 rule, the contradictory MacData-alongside-SignedData combination, the closed bag-type and cert/CRL-type sets, and per-list element caps all fail closed with typed pkcs12/* codes; a MacData-less id-data store is legal syntax and parses as integrityMode "none".
36
+ - pki.schema.pkcs12.pemDecode(text, label?) / pemEncode(der, label?) — PEM handling for stores that transit text channels (default label PKCS12).
37
+ - pki.asn1.decode gains an opt-in ber option accepting exactly two shapes — an indefinite length on a constructed value and a constructed OCTET STRING, whose segments reassemble into one primitive content — for formats whose content is normatively BER. The default remains strict DER; minimal-length, minimal-integer, trailing-byte, and size / depth verdicts are unchanged in both modes, an indefinite length on a primitive value still rejects, a foreign-type segment inside a constructed string rejects, and constructed-string nesting is capped (each level re-copies its payload, so deep nesting is memory amplification, not data).
38
+ - pki.schema.engine.embeddedDer(schema, bytes, ctx, opts) — the named form of the re-decode idiom: decode a fresh DER / BER blob carried inside an already-decoded value and walk it against a schema, wrapping codec failures in the caller's typed code. A shared budget option bounds how many nested blobs one parse may unwrap, so a container that chains encodings across octet-string boundaries cannot restart the depth caps from zero. The timestamp, OCSP, and certificate-request parsers now route their embedded-structure decodes through it.
39
+ - SEQUENCE OF / SET OF schemas can declare an element-count ceiling (max), so a container listing a great many tiny elements fails typed instead of amplifying memory through per-element parse products; a single attribute's value list is now capped this way across every format.
40
+ - The OID registry gains the PKCS#12 bag types, the PKCS#12 password-based encryption identifiers, the PKCS#9 certTypes / crlTypes / friendlyName / localKeyId entries, PKCS#5 PBKDF2 / PBES2 / PBMAC1, the NIST AES content-encryption arc, and the HMAC-with-SHA identifiers, so a store's algorithms resolve to names.
41
+ - The error taxonomy gains Pkcs12Error, carrying a stable pkcs12/* code.
42
+
43
+ ### Changed
44
+
45
+ - The npm-publish workflow's vulnerability scan now scans the SBOM unconditionally and the vendored-bundle directory only when it holds a real bundle, so the scan is exact in both states instead of warning on the empty directory.
46
+
47
+ ### Fixed
48
+
49
+ - Certification-path validation bounds the RSASSA-PSS saltLength and trailerField before numeric conversion, so an oversized value rejects with path/unsupported-algorithm instead of rounding silently on its way to the verifier — the same exact-or-rejected rule the PKCS#12 MAC parameters follow.
50
+
51
+ ## v0.1.17 — 2026-07-06
8
52
 
9
53
  An RFC 4211 certificate-request-message parser joins the pki.schema family.
10
54
 
package/README.md CHANGED
@@ -200,10 +200,12 @@ is callable today; nothing below is a stub.
200
200
  | `pki.schema.tsp` | Parse DER / PEM RFC 3161 timestamp responses and tokens — the TSTInfo payload (imprint, genTime with sub-second precision, serial, nonce, accuracy), the status-to-token coupling, and the token wrapper composed over CMS with the single-signer rule, fail-closed — `parse`, `parseTstInfo`, `parseToken`, `pemDecode` |
201
201
  | `pki.schema.attrcert` | Parse DER / PEM RFC 5755 attribute certificates — the holder and issuer identities (validated GeneralNames), the validity window (real `Date`s), the privilege attributes (role / group / clearance) and extensions, with the raw signed region for a verifier; the obsolete v1 form is recognized and deferred, fail-closed — `parse`, `pemDecode` |
202
202
  | `pki.schema.crmf` | Parse DER / PEM RFC 4211 certificate request messages (CertReqMessages — the CMP / EST enrollment body) — the requested-certificate template (subject, public key, validity, extensions), proof-of-possession, and registration controls, with the raw `CertRequest` region a POP verifier hashes; names dual-accepted (IMPLICIT and EXPLICIT), fail-closed — `parse`, `pemDecode` |
203
- | `pki.schema.engine` | The declarative ASN.1 structure-schema engine every format parser composes — `walk` plus the schema combinators |
203
+ | `pki.schema.pkcs12` | Parse DER / BER / PEM RFC 7292 PKCS#12 (PFX) stores key bags via the PKCS#8 parser, shrouded keys (algorithm surfaced, ciphertext opaque), cert / CRL / secret bags raw and byte-exact, encrypted and enveloped safes structurally via CMS, `friendlyName` / `localKeyId` decoded, and the exact MAC byte range (`macedBytes`) plus RFC 9579 PBMAC1 recognition for external verification; BER accepted exactly where §4.1 requires it, fail-closed — `parse`, `pemDecode`, `pemEncode` |
204
+ | `pki.schema.cmp` | Parse DER / PEM RFC 9810 Certificate Management Protocol messages (PKIMessage) — the header (version, sender / recipient incl. the anonymous NULL-DN, nonces, transaction id, general info), the 27-arm body (certificate requests via the CRMF parser, an encrypted certificate's EnvelopedData via CMS, response / revocation / confirmation / error / support / polling arms structural, the rest raw), and the exact `headerBytes` / `bodyBytes` slices an external verifier reconstructs the protected part from; the CMP-before-OCSP dispatch order is enforced, fail-closed — `parse`, `pemDecode`, `pemEncode` |
205
+ | `pki.schema.engine` | The declarative ASN.1 structure-schema engine every format parser composes — `walk` / `encode` / `embeddedDer` plus the schema combinators |
204
206
  | `pki.path` | RFC 5280 §6 certification-path validation — `validate` runs the §6.1 state machine (signature chaining, validity windows, name chaining, basic constraints and path length, key usage, name constraints, the certificate-policy tree) over an ordered path and a trust anchor, returning a structured verdict with per-check reason codes; `crlChecker` supplies CRL-based revocation. Pure and re-entrant, fail-closed — `validate`, `crlChecker` |
205
207
  | `pki.C` / `pki.constants` | Version-stable constants — functional scale helpers (`C.TIME.*`, `C.BYTES.*`), codec `LIMITS`, `version` |
206
- | `pki.errors` | The `PkiError` taxonomy — `defineClass` plus `ConstantsError` / `Asn1Error` / `OidError` / `PemError` / `CertificateError` / `CrlError` / `CsrError` / `Pkcs8Error` / `CmsError` / `OcspError` / `TspError` / `AttrCertError` / `CrmfError` / `PathError`, each carrying a stable `code` in `domain/reason` form |
208
+ | `pki.errors` | The `PkiError` taxonomy — `defineClass` plus `ConstantsError` / `Asn1Error` / `OidError` / `PemError` / `CertificateError` / `CrlError` / `CsrError` / `Pkcs8Error` / `CmsError` / `OcspError` / `TspError` / `AttrCertError` / `CrmfError` / `Pkcs12Error` / `CmpError` / `PathError`, each carrying a stable `code` in `domain/reason` form |
207
209
  | `pki` CLI | `pki version`, `pki oid <dotted\|name>`, `pki parse <cert>` |
208
210
 
209
211
  ### CLI
@@ -217,11 +219,11 @@ pki parse cert.pem # structured JSON summary of a certific
217
219
 
218
220
  ### What's coming
219
221
 
220
- Certificate build/sign/verify, certification-path
221
- validation, CMS (SignedData / EnvelopedData / EncryptedData / AuthenticatedData),
222
- OCSP, RFC 3161 timestamping, PKCS#8 decryption (PBES2) / SPKI / PKCS#12, and the
223
- post-quantum certificate and CMS surface (ML-DSA / ML-KEM / SLH-DSA and hybrid
224
- composites) are on the roadmap and ride this same core. See
222
+ Certificate build/sign/verify, CMS AuthenticatedData /
223
+ AuthEnvelopedData, PKCS#8 decryption (PBES2) / SPKI, PKCS#12 MAC verification
224
+ and bag decryption, and the post-quantum certificate and CMS surface (ML-DSA /
225
+ ML-KEM / SLH-DSA and hybrid composites) are on the roadmap and ride this same
226
+ core. See
225
227
  [ROADMAP.md](ROADMAP.md) for the full plan and current status of each area, and
226
228
  [CHANGELOG.md](CHANGELOG.md) for what has landed.
227
229
 
package/lib/asn1-der.js CHANGED
@@ -127,10 +127,19 @@ function _asBuffer(input, who) {
127
127
  * after the top-level value (unless `allowTrailing`), or exceeding the
128
128
  * size / depth caps.
129
129
  *
130
+ * `ber: true` is a scoped relaxation for formats whose content regions are
131
+ * normatively BER (RFC 7292 PKCS#12): it accepts an indefinite length on a
132
+ * constructed value and a constructed OCTET STRING, whose segments are
133
+ * reassembled into one primitive `content`. Nothing else is relaxed —
134
+ * definite lengths stay minimal, an indefinite length on a primitive value
135
+ * and a foreign-type segment still reject, and the size / depth caps hold.
136
+ *
130
137
  * @opts
131
138
  * maxBytes: number, // default: C.LIMITS.DER_MAX_BYTES (16 MiB)
132
139
  * maxDepth: number, // default: C.LIMITS.DER_MAX_DEPTH (64)
133
140
  * allowTrailing: boolean, // default: false — allow bytes after the top TLV
141
+ * ber: boolean, // default: false — accept indefinite lengths +
142
+ * // constructed OCTET STRINGs (BER content regions)
134
143
  *
135
144
  * @example
136
145
  * var node = pki.asn1.decode(der);
@@ -144,14 +153,14 @@ function decode(input, opts) {
144
153
  if (buf.length > maxBytes) {
145
154
  throw new Asn1Error("asn1/too-large", "input " + buf.length + " bytes exceeds cap " + maxBytes);
146
155
  }
147
- var r = _decodeTLV(buf, 0, buf.length, 0, maxDepth);
156
+ var r = _decodeTLV(buf, 0, buf.length, 0, maxDepth, opts.ber === true);
148
157
  if (!opts.allowTrailing && r.end !== buf.length) {
149
158
  throw new Asn1Error("asn1/trailing-bytes", (buf.length - r.end) + " trailing byte(s) after the top-level value");
150
159
  }
151
160
  return r.node;
152
161
  }
153
162
 
154
- function _decodeTLV(buf, start, limit, depth, maxDepth) {
163
+ function _decodeTLV(buf, start, limit, depth, maxDepth, ber, strDepth) {
155
164
  if (depth > maxDepth) {
156
165
  throw new Asn1Error("asn1/too-deep", "nesting exceeds depth cap " + maxDepth);
157
166
  }
@@ -195,8 +204,20 @@ function _decodeTLV(buf, start, limit, depth, maxDepth) {
195
204
  // encoded constructed is not valid DER. Without this a constructed string
196
205
  // tag decodes to a childless node that later paths (an X.509 DN attribute
197
206
  // value) would hex-render or dereference instead of failing closed.
207
+ // The ber mode licenses exactly one constructed primitive-only type — the
208
+ // OCTET STRING (the streamed content carrier RFC 7292 §4.1 permits); its
209
+ // segments are reassembled below. Every other primitive-only type stays
210
+ // primitive even in BER. Reassembly re-copies each nesting level's payload,
211
+ // so nesting is capped on the way down: real producers segment one level
212
+ // deep, and a deep chain multiplies transient memory without carrying data.
198
213
  if (tagClassBits === CLASS_UNIVERSAL && constructed && PRIMITIVE_ONLY_UNIVERSAL_TAGS[tagNumber]) {
199
- throw new Asn1Error("asn1/constructed-primitive-type", "a universal primitive-only type must be encoded primitive in DER");
214
+ if (!(ber && tagNumber === TAGS.OCTET_STRING)) {
215
+ throw new Asn1Error("asn1/constructed-primitive-type", "a universal primitive-only type must be encoded primitive in DER");
216
+ }
217
+ strDepth = (strDepth || 0) + 1;
218
+ if (strDepth > constants.LIMITS.BER_MAX_STRING_NESTING) {
219
+ throw new Asn1Error("asn1/bad-constructed-string", "constructed OCTET STRING nesting exceeds the cap " + constants.LIMITS.BER_MAX_STRING_NESTING);
220
+ }
200
221
  }
201
222
 
202
223
  if (p >= limit) throw new Asn1Error("asn1/truncated", "expected a length octet");
@@ -205,7 +226,12 @@ function _decodeTLV(buf, start, limit, depth, maxDepth) {
205
226
  if (lenByte < 0x80) {
206
227
  length = lenByte;
207
228
  } else if (lenByte === 0x80) {
208
- throw new Asn1Error("asn1/indefinite-length", "indefinite length is not valid DER");
229
+ // X.690 §8.1.3.6 indefinite length is only defined for a constructed
230
+ // encoding; the value runs to the end-of-contents octets.
231
+ if (!ber || !constructed) {
232
+ throw new Asn1Error("asn1/indefinite-length", "indefinite length is not valid DER");
233
+ }
234
+ length = -1;
209
235
  } else {
210
236
  var numLenBytes = lenByte & 0x7f;
211
237
  if (numLenBytes > 6) throw new Asn1Error("asn1/length-too-large", "length uses more than 6 octets");
@@ -218,34 +244,79 @@ function _decodeTLV(buf, start, limit, depth, maxDepth) {
218
244
  }
219
245
 
220
246
  var contentStart = p;
221
- var contentEnd = contentStart + length;
222
- if (contentEnd > limit) throw new Asn1Error("asn1/truncated", "content length overruns the buffer");
247
+ var indefinite = length === -1;
248
+ var contentEnd = indefinite ? -1 : contentStart + length;
249
+ if (!indefinite && contentEnd > limit) throw new Asn1Error("asn1/truncated", "content length overruns the buffer");
250
+
251
+ var children = null;
252
+ var content = null;
253
+ var child;
254
+ var end;
255
+ if (constructed) {
256
+ children = [];
257
+ var cp = contentStart;
258
+ if (indefinite) {
259
+ for (;;) {
260
+ if (cp + 2 > limit) throw new Asn1Error("asn1/truncated", "indefinite-length value is missing its end-of-contents octets");
261
+ if (buf[cp] === 0x00 && buf[cp + 1] === 0x00) break;
262
+ child = _decodeTLV(buf, cp, limit, depth + 1, maxDepth, ber, strDepth);
263
+ children.push(child.node);
264
+ cp = child.end;
265
+ }
266
+ contentEnd = cp;
267
+ end = cp + 2;
268
+ } else {
269
+ while (cp < contentEnd) {
270
+ child = _decodeTLV(buf, cp, contentEnd, depth + 1, maxDepth, ber, strDepth);
271
+ children.push(child.node);
272
+ cp = child.end;
273
+ }
274
+ end = contentEnd;
275
+ }
276
+ } else {
277
+ content = buf.subarray(contentStart, contentEnd);
278
+ end = contentEnd;
279
+ }
223
280
 
224
281
  var node = {
225
282
  tagClass: _className(tagClassBits),
226
283
  constructed: constructed,
227
284
  tagNumber: tagNumber,
228
- length: length,
285
+ length: contentEnd - contentStart,
229
286
  header: { start: start, end: contentStart },
230
287
  contentStart: contentStart,
231
288
  contentEnd: contentEnd,
232
- content: null,
233
- children: null,
234
- bytes: buf.subarray(start, contentEnd),
289
+ content: content,
290
+ children: children,
291
+ bytes: buf.subarray(start, end),
235
292
  };
236
293
 
237
- if (constructed) {
238
- node.children = [];
239
- var cp = contentStart;
240
- while (cp < contentEnd) {
241
- var child = _decodeTLV(buf, cp, contentEnd, depth + 1, maxDepth);
242
- node.children.push(child.node);
243
- cp = child.end;
294
+ // BER reassembly: a constructed OCTET STRING's segments concatenate into
295
+ // one primitive content, so every downstream reader sees the value a
296
+ // single-segment encoding would carry; `bytes` keeps the original wire
297
+ // range for raw round-trip surfaces. Nested constructed segments arrive
298
+ // already reassembled by the recursion (their nesting depth is capped on
299
+ // the way down — see the strDepth check above).
300
+ if (ber && constructed && tagClassBits === CLASS_UNIVERSAL && tagNumber === TAGS.OCTET_STRING) {
301
+ var segments = [];
302
+ for (var s = 0; s < children.length; s++) {
303
+ if (children[s].tagClass !== "universal" || children[s].tagNumber !== TAGS.OCTET_STRING) {
304
+ throw new Asn1Error("asn1/bad-constructed-string", "a constructed OCTET STRING segment must itself be an OCTET STRING");
305
+ }
306
+ segments.push(children[s].content);
244
307
  }
245
- } else {
246
- node.content = buf.subarray(contentStart, contentEnd);
308
+ node.content = Buffer.concat(segments);
309
+ node.constructed = false;
310
+ node.children = null;
247
311
  }
248
- return { node: node, end: contentEnd };
312
+ // A context-tagged constructed node from a ber decode may be an IMPLICIT
313
+ // streamed string (the tag hides the underlying type), which only the
314
+ // schema-driven typed reader can identify — mark it so readers reassemble
315
+ // exactly those nodes and a strict decode's verdicts never change.
316
+ if (ber && constructed && tagClassBits === CLASS_CONTEXT && node.children) {
317
+ node.ber = true;
318
+ }
319
+ return { node: node, end: end };
249
320
  }
250
321
 
251
322
  // ---- Node assertions ------------------------------------------------
@@ -375,13 +446,29 @@ function readOctetString(node) {
375
446
  // Read a [tag] IMPLICIT OCTET STRING — a context-class PRIMITIVE node whose
376
447
  // content is the octet-string body (the IMPLICIT tag replaces the universal one,
377
448
  // so there is no inner universal node). Primitive-only, like its universal
378
- // counterpart, so the BER constructed/streamed form is rejected. Used for the CMS
379
- // SignerIdentifier subjectKeyIdentifier [0] (RFC 5652 §5.3).
449
+ // counterpart, so a strict decode's constructed/streamed form is rejected.
450
+ // A node from a ber decode (the `ber` marker) may carry the streamed form —
451
+ // the context tag hides the underlying type from the decoder, so THIS reader
452
+ // is where a [tag] IMPLICIT OCTET STRING's segments reassemble (the shape CMS
453
+ // ciphertext streams as). Used for the CMS SignerIdentifier
454
+ // subjectKeyIdentifier [0] (RFC 5652 §5.3) and EncryptedContentInfo
455
+ // encryptedContent [0] (§6.1).
380
456
  function readOctetStringImplicit(node, tag) {
381
457
  if (node.tagClass !== "context" || node.tagNumber !== tag) {
382
458
  throw new Asn1Error("asn1/unexpected-tag", "readOctetStringImplicit: expected context tag [" + tag +
383
459
  "], got " + node.tagClass + "/" + node.tagNumber);
384
460
  }
461
+ if (node.constructed && node.ber === true) {
462
+ var segments = [];
463
+ for (var s = 0; s < node.children.length; s++) {
464
+ var seg = node.children[s];
465
+ if (seg.tagClass !== "universal" || seg.tagNumber !== TAGS.OCTET_STRING || seg.constructed || !seg.content) {
466
+ throw new Asn1Error("asn1/bad-constructed-string", "a constructed OCTET STRING segment must itself be an OCTET STRING");
467
+ }
468
+ segments.push(seg.content);
469
+ }
470
+ return Buffer.concat(segments);
471
+ }
385
472
  _expectPrimitive(node, "readOctetStringImplicit");
386
473
  return node.content;
387
474
  }
package/lib/constants.js CHANGED
@@ -121,6 +121,22 @@ var LIMITS = {
121
121
  // work on an untrusted certificate bundle (a real chain is well under this;
122
122
  // the operator may override via opts.maxPathCerts).
123
123
  PATH_MAX_CERTS: 100,
124
+ // PKCS#12 container ceilings. A PFX carries lists at three altitudes
125
+ // (ContentInfos per AuthenticatedSafe, SafeBags per SafeContents,
126
+ // attributes per bag) and can chain fresh DER blobs inside OCTET STRINGs,
127
+ // where every re-decode would otherwise restart the depth cap from zero.
128
+ // A real keystore holds a handful of keys and certificates; thousands of
129
+ // elements or dozens of chained re-decodes is hostile input, not a store.
130
+ PKCS12_MAX_ELEMENTS: 1024,
131
+ PKCS12_MAX_REDECODES: 64,
132
+ PKCS12_MAX_BAG_DEPTH: 16,
133
+ // BER constructed-string reassembly copies each nesting level's payload, so
134
+ // nesting multiplies transient memory. Real producers segment one level
135
+ // deep; nesting past this cap is amplification, not a store.
136
+ BER_MAX_STRING_NESTING: 8,
137
+ // A single attribute's value SET — no deployed attribute carries more than
138
+ // a handful of values; a list at this scale is amplification.
139
+ ATTRIBUTE_MAX_VALUES: 256,
124
140
  };
125
141
 
126
142
  // Single-sourced from the package manifest so the reported version can
@@ -160,6 +160,18 @@ var AttrCertError = defineClass("AttrCertError", { withCause: true });
160
160
  // `.cause`.
161
161
  var CrmfError = defineClass("CrmfError", { withCause: true });
162
162
 
163
+ // Pkcs12Error — a byte sequence that is not a well-formed RFC 7292 PFX
164
+ // (AuthenticatedSafe / SafeContents / SafeBag), or a PFX violating a §4
165
+ // coherence rule (version, integrity mode, bag dispatch, MacData). Carries
166
+ // the underlying leaf fault as `.cause`.
167
+ var Pkcs12Error = defineClass("Pkcs12Error", { withCause: true });
168
+
169
+ // CmpError — a byte sequence that is not a well-formed RFC 9810 PKIMessage
170
+ // (PKIHeader / PKIBody / protection / extraCerts), or one violating a §5
171
+ // coherence rule (protection⇔protectionAlg, certConf-hashAlg⇔pvno). Carries
172
+ // the underlying leaf fault as `.cause`.
173
+ var CmpError = defineClass("CmpError", { withCause: true });
174
+
163
175
  // PathError — a certification path that fails RFC 5280 §6 validation, or a
164
176
  // malformed input handed to the validator (an extension value that does not
165
177
  // decode, an empty path, an unsupported signature algorithm). Carries the
@@ -184,5 +196,7 @@ module.exports = {
184
196
  TspError: TspError,
185
197
  AttrCertError: AttrCertError,
186
198
  CrmfError: CrmfError,
199
+ Pkcs12Error: Pkcs12Error,
200
+ CmpError: CmpError,
187
201
  PathError: PathError,
188
202
  };
package/lib/oid.js CHANGED
@@ -128,10 +128,50 @@ var FAMILIES = {
128
128
  data: 1, signedData: 2, envelopedData: 3, signedAndEnvelopedData: 4,
129
129
  digestedData: 5, encryptedData: 6 } },
130
130
 
131
- // PKCS#9 attribute types — incl. the CMS signed-attribute OIDs (RFC 5652 §11).
131
+ // PKCS#9 attribute types — incl. the CMS signed-attribute OIDs (RFC 5652 §11)
132
+ // and the PKCS#12 bag attributes friendlyName / localKeyId (RFC 7292 §4.2).
132
133
  pkcs9: { base: [1, 2, 840, 113549, 1, 9], of: {
133
134
  emailAddress: 1, contentType: 3, messageDigest: 4, signingTime: 5,
134
- challengePassword: 7, extensionRequest: 14 } },
135
+ challengePassword: 7, extensionRequest: 14, friendlyName: 20, localKeyId: 21 } },
136
+
137
+ // PKCS#9 CertBag / CRLBag value discriminators (RFC 7292 §4.2.3-§4.2.4).
138
+ pkcs9CertTypes: { base: [1, 2, 840, 113549, 1, 9, 22], of: { x509Certificate: 1, sdsiCertificate: 2 } },
139
+ pkcs9CrlTypes: { base: [1, 2, 840, 113549, 1, 9, 23], of: { x509CRL: 1 } },
140
+
141
+ // PKCS#5 password-based schemes (RFC 8018) + the PBMAC1 MacData arm (RFC 9579).
142
+ pkcs5: { base: [1, 2, 840, 113549, 1, 5], of: { pbkdf2: 12, pbes2: 13, pbmac1: 14 } },
143
+
144
+ // CMP InfoTypeAndValue types — id-it under id-pkix (RFC 9810 §5.3.19; the
145
+ // PKIXCMP-2023 module assigns these leaves, 8/9 unassigned).
146
+ idIt: { base: [1, 3, 6, 1, 5, 5, 7, 4], of: {
147
+ caProtEncCert: 1, signKeyPairTypes: 2, encKeyPairTypes: 3, preferredSymmAlg: 4,
148
+ caKeyUpdateInfo: 5, currentCRL: 6, unsupportedOIDs: 7, keyPairParamReq: 10,
149
+ keyPairParamRep: 11, revPassphrase: 12, implicitConfirm: 13, confirmWaitTime: 14,
150
+ origPKIMessage: 15, suppLangTags: 16, caCerts: 17, rootCaKeyUpdate: 18,
151
+ certReqTemplate: 19, rootCaCert: 20, certProfile: 21, crlStatusList: 22,
152
+ crls: 23, kemCiphertextInfo: 24 } },
153
+
154
+ // CMP message-protection MAC algorithms on the Entrust arc (RFC 9810
155
+ // §5.1.3.1/.2/.4; RFC 9481 §6.1.1).
156
+ entrustAlg: { base: [1, 2, 840, 113533, 7, 66], of: {
157
+ passwordBasedMac: 13, kemBasedMac: 16, dhBasedMac: 30 } },
158
+
159
+ // PKCS#12 bag types (RFC 7292 §4.2, Appendix D).
160
+ pkcs12BagTypes: { base: [1, 2, 840, 113549, 1, 12, 10, 1], of: {
161
+ keyBag: 1, pkcs8ShroudedKeyBag: 2, certBag: 3, crlBag: 4, secretBag: 5, safeContentsBag: 6 } },
162
+
163
+ // PKCS#12 password-based encryption schemes (RFC 7292 Appendix C) — legacy
164
+ // PBE identifiers still emitted by deployed exporters; recognized so a
165
+ // shrouded bag's algorithm resolves to a name, never decrypted here.
166
+ pkcs12Pbe: { base: [1, 2, 840, 113549, 1, 12, 1], of: {
167
+ pbeWithSHAAnd128BitRC4: 1, pbeWithSHAAnd40BitRC4: 2,
168
+ "pbeWithSHAAnd3-KeyTripleDES-CBC": 3, "pbeWithSHAAnd2-KeyTripleDES-CBC": 4,
169
+ "pbeWithSHAAnd128BitRC2-CBC": 5, "pbeWithSHAAnd40BitRC2-CBC": 6 } },
170
+
171
+ // RSADSI digest / HMAC algorithms (RFC 8018 §B.1) — the PBKDF2 / PBMAC1 PRFs.
172
+ rsadsiDigest: { base: [1, 2, 840, 113549, 2], of: {
173
+ hmacWithSHA1: 7, hmacWithSHA224: 8, hmacWithSHA256: 9,
174
+ hmacWithSHA384: 10, hmacWithSHA512: 11 } },
135
175
 
136
176
  // S/MIME content types on the PKCS#9 smime arc (RFC 5652, RFC 3161): id-ct.
137
177
  smimeCt: { base: [1, 2, 840, 113549, 1, 9, 16, 1], of: { authData: 2, tSTInfo: 4, encKeyWithID: 21 } },
@@ -157,6 +197,12 @@ var FAMILIES = {
157
197
  // nistHash covers only SHA-256 and above.
158
198
  oiwSecsig: { base: [1, 3, 14, 3, 2], of: { sha1: 26 } },
159
199
 
200
+ // NIST AES content-encryption algorithms (arc 2.16.840.1.101.3.4.1) — the
201
+ // modern PBES2 / CMS content ciphers a PKCS#12 or EnvelopedData names.
202
+ nistAes: { base: [2, 16, 840, 1, 101, 3, 4, 1], of: {
203
+ "aes128-CBC": 2, "aes128-GCM": 6, "aes192-CBC": 22, "aes192-GCM": 26,
204
+ "aes256-CBC": 42, "aes256-GCM": 46 } },
205
+
160
206
  // NIST hash functions (SHA-2, SHA-3, SHAKE).
161
207
  nistHash: { base: [2, 16, 840, 1, 101, 3, 4, 2], of: {
162
208
  sha256: 1, sha384: 2, sha512: 3, "sha3-256": 8, "sha3-512": 10, shake256: 12 } },
@@ -144,6 +144,10 @@ function hashAlgOid(seq) {
144
144
  if (seq.children.length === 2) {
145
145
  var p = seq.children[1];
146
146
  if (p.tagClass !== "universal" || p.tagNumber !== asn1.TAGS.NULL) throw E("path/unsupported-algorithm", "hash AlgorithmIdentifier parameters must be NULL or absent (RFC 4055)");
147
+ // A NULL is well-formed only with empty content (X.690 §8.8.2); the tag check
148
+ // alone would accept a non-empty NULL as valid parameters.
149
+ try { asn1.read.nullValue(p); }
150
+ catch (e) { throw E("path/unsupported-algorithm", "hash AlgorithmIdentifier NULL parameters must have empty content (RFC 4055)", e); }
147
151
  }
148
152
  return o;
149
153
  }
@@ -193,10 +197,18 @@ function resolveRsaPss(paramsBytes) {
193
197
  // A negative saltLength must be rejected: the OpenSSL-backed verify shim
194
198
  // reads -1/-2/-3 as RSA_PSS_SALTLEN_DIGEST/AUTO/MAX, and AUTO (-2) accepts
195
199
  // a signature of ANY salt length — defeating the salt-length binding.
196
- if (sl < 0n) throw E("path/unsupported-algorithm", "RSASSA-PSS saltLength must be non-negative");
200
+ // The upper bound keeps the value exact through Number conversion: the
201
+ // verifier binds to the salt length the certificate states, so a value
202
+ // that would round is not verifiable material (no real salt exceeds the
203
+ // modulus size, let alone this).
204
+ if (sl < 0n || sl > 2147483647n) throw E("path/unsupported-algorithm", "RSASSA-PSS saltLength must be a non-negative integer within the salt-length range");
197
205
  saltLength = Number(sl);
198
206
  } else if (f.tagNumber === 3) {
199
- trailer = Number(asn1.read.integer(f.children[0]));
207
+ // Compared for equality with 1 below — bound before conversion so an
208
+ // oversized value cannot round on its way to the comparison.
209
+ var tf = asn1.read.integer(f.children[0]);
210
+ if (tf < 0n || tf > 2147483647n) throw E("path/unsupported-algorithm", "unsupported RSASSA-PSS trailerField " + tf.toString());
211
+ trailer = Number(tf);
200
212
  }
201
213
  });
202
214
  if (hash === null) throw E("path/unsupported-algorithm", "RSASSA-PSS hashAlgorithm must be stated explicitly (the SHA-1 default is rejected)");
package/lib/schema-all.js CHANGED
@@ -11,9 +11,9 @@
11
11
  *
12
12
  * @intro
13
13
  * The schema family: a declarative ASN.1 structure-schema engine and the
14
- * per-format parsers built on it. Every format (X.509 certificates, CRLs,
15
- * PKCS#10 certification requests, PKCS#8 private keys, and CMS SignedData) is a
16
- * member that COMPOSES the
14
+ * per-format parsers built on it. Every format — from X.509 certificates
15
+ * and CRLs through CMS, OCSP, timestamps, and PKCS#12 stores; `all()`
16
+ * enumerates the registered set — is a member that COMPOSES the
17
17
  * shared engine and the shared PKIX sub-schemas (AlgorithmIdentifier, Name,
18
18
  * Extension), so a structural rule — bounds-checked positional reads,
19
19
  * optional / tagged field ordering, SET-OF uniqueness, fail-closed typed
@@ -36,10 +36,12 @@ var x509 = require("./schema-x509");
36
36
  var crl = require("./schema-crl");
37
37
  var csr = require("./schema-csr");
38
38
  var pkcs8 = require("./schema-pkcs8");
39
+ var pkcs12 = require("./schema-pkcs12");
39
40
  var cms = require("./schema-cms");
40
41
  var ocsp = require("./schema-ocsp");
41
42
  var tsp = require("./schema-tsp");
42
43
  var crmf = require("./schema-crmf");
44
+ var cmp = require("./schema-cmp");
43
45
  var attrcert = require("./schema-attrcert");
44
46
  var frameworkError = require("./framework-error");
45
47
 
@@ -47,9 +49,12 @@ var SchemaError = frameworkError.SchemaError;
47
49
  var PemError = frameworkError.PemError;
48
50
 
49
51
  // The shared parse-entry opts for the orchestrator: label-agnostic PEM unwrap
50
- // (any block type routes), the schema/* error family. Detection needs DER, so
51
- // the coerced DER is what gets routed to the matched format.
52
- var ENTRY = { pemLabel: null, PemError: PemError, ErrorClass: SchemaError, prefix: "schema", what: "input" };
52
+ // (any block type routes), the schema/* error family. Detection needs a decoded
53
+ // root, so the coerced bytes are what gets routed to the matched format. The
54
+ // ber mode lets a BER-encoded PFX (the dominant real-world .p12 shape) decode
55
+ // far enough to detect; a BER input matching a strict-DER-only format still
56
+ // fails typed inside that format's own parse.
57
+ var ENTRY = { pemLabel: null, PemError: PemError, ErrorClass: SchemaError, prefix: "schema", what: "input", ber: true };
53
58
 
54
59
  // REGISTRY — each format is declarative data: a name, a `detect(root)` that
55
60
  // recognizes the decoded DER root as this format's outer structure, and the
@@ -97,12 +102,28 @@ var FORMATS = [
97
102
  detect: crmf.matches,
98
103
  parse: function (input) { return crmf.parse(input); },
99
104
  },
105
+ {
106
+ // PKIMessage ::= SEQUENCE { header PKIHeader, body PKIBody [0..26],
107
+ // protection [0]?, extraCerts [1]? } (RFC 9810 §5.1) — a SEQUENCE of 2-4
108
+ // whose first child is a >=3-child SEQUENCE leading with a bare INTEGER
109
+ // (pvno) and whose second child is context-constructed [0..26]. ORDER IS
110
+ // LOAD-BEARING here: a 2-child PKIMessage whose body is ir [0] also
111
+ // satisfies the shallow ocsp-request probe below (k[0] SEQUENCE +
112
+ // k[1] context-[0]), while no OCSPRequest satisfies this detector (its
113
+ // tbsRequest never leads with a bare INTEGER) — so cmp MUST sit ahead of
114
+ // ocsp-request for the pair to dispatch deterministically.
115
+ name: "cmp",
116
+ module: cmp,
117
+ detect: cmp.matches,
118
+ parse: function (input) { return cmp.parse(input); },
119
+ },
100
120
  {
101
121
  // OCSPRequest ::= SEQUENCE { tbsRequest SEQUENCE, optionalSignature [0] EXPLICIT
102
122
  // OPTIONAL } — a SEQUENCE of 1-2 whose first child is the tbsRequest SEQUENCE.
103
123
  // Leads with a SEQUENCE like the signed-envelope trio, but is excluded by arity
104
124
  // (the trio is EXACTLY 3 children; an OCSPRequest is 1-2). Checked AFTER tsp,
105
- // whose detector is a strict refinement (RFC 6960 §4.1.1).
125
+ // whose detector is a strict refinement (RFC 6960 §4.1.1), and AFTER cmp,
126
+ // whose 2-child ir-body shape this probe would otherwise shadow.
106
127
  name: "ocsp-request",
107
128
  module: ocsp,
108
129
  detect: ocsp.matchesRequest,
@@ -117,6 +138,20 @@ var FORMATS = [
117
138
  detect: ocsp.matchesResponse,
118
139
  parse: function (input) { return ocsp.parseResponse(input); },
119
140
  },
141
+ {
142
+ // PKCS#12 PFX ::= SEQUENCE { version INTEGER, authSafe ContentInfo, macData
143
+ // OPTIONAL } — INTEGER-first like pkcs8, so the discriminators are deeper:
144
+ // children[1] is a ContentInfo (SEQUENCE of exactly 2: OID + [0] constructed —
145
+ // a shape a PrivateKeyInfo's AlgorithmIdentifier never presents) and
146
+ // children[2] is a MacData SEQUENCE or absent (pkcs8 requires an OCTET STRING
147
+ // there). Shape-disjoint from pkcs8, and registered ahead of it as the more
148
+ // specific probe (RFC 7292 §4). A BER-encoded PFX detects through the
149
+ // orchestrator's BER decode fallback and routes here.
150
+ name: "pkcs12",
151
+ module: pkcs12,
152
+ detect: pkcs12.matches,
153
+ parse: function (input) { return pkcs12.parse(input); },
154
+ },
120
155
  {
121
156
  // PKCS#8 PrivateKeyInfo / OneAsymmetricKey — SEQUENCE whose first child is an
122
157
  // INTEGER (version) and third an OCTET STRING (privateKey); disjoint from the
@@ -193,7 +228,7 @@ var FORMATS = [
193
228
  * The names of every registered format, in detection order.
194
229
  *
195
230
  * @example
196
- * pki.schema.all(); // → ["cms", "tsp", "crmf", "ocsp-request", "ocsp-response", "pkcs8", "csr", "attrcert", "attrcert-v1", "crl", "x509"]
231
+ * pki.schema.all(); // → ["cms", "tsp", "crmf", "cmp", "ocsp-request", "ocsp-response", "pkcs12", "pkcs8", "csr", "attrcert", "attrcert-v1", "crl", "x509"]
197
232
  */
198
233
  function all() { return FORMATS.map(function (f) { return f.name; }); }
199
234
 
@@ -235,10 +270,12 @@ module.exports = {
235
270
  crl: { parse: crl.parse, pemDecode: crl.pemDecode },
236
271
  csr: { parse: csr.parse, pemDecode: csr.pemDecode, pemEncode: csr.pemEncode },
237
272
  pkcs8: { parse: pkcs8.parse, parseEncrypted: pkcs8.parseEncrypted, pemDecode: pkcs8.pemDecode, pemEncode: pkcs8.pemEncode },
273
+ pkcs12: { parse: pkcs12.parse, pemDecode: pkcs12.pemDecode, pemEncode: pkcs12.pemEncode },
238
274
  cms: { parse: cms.parse, pemDecode: cms.pemDecode, pemEncode: cms.pemEncode },
239
275
  ocsp: { parseRequest: ocsp.parseRequest, parseResponse: ocsp.parseResponse, pemDecode: ocsp.pemDecode },
240
276
  tsp: { parse: tsp.parse, parseTstInfo: tsp.parseTstInfo, parseToken: tsp.parseToken, pemDecode: tsp.pemDecode },
241
277
  crmf: { parse: crmf.parse, pemDecode: crmf.pemDecode },
278
+ cmp: { parse: cmp.parse, pemDecode: cmp.pemDecode, pemEncode: cmp.pemEncode },
242
279
  attrcert: { parse: attrcert.parse, pemDecode: attrcert.pemDecode },
243
280
  all: all,
244
281
  parse: parse,
@@ -353,11 +353,11 @@ function matches(root) {
353
353
  if (!acinfo) return false;
354
354
  var k = acinfo.children;
355
355
  if (!k || k.length < 7) return false;
356
- if (!(k[0].tagClass === "universal" && k[0].tagNumber === TAGS.INTEGER)) return false;
357
- if (!(k[1].tagClass === "universal" && k[1].tagNumber === TAGS.SEQUENCE && k[1].children)) return false;
356
+ if (!schema.isUniversal(k[0], TAGS.INTEGER)) return false;
357
+ if (!(schema.isUniversal(k[1], TAGS.SEQUENCE) && k[1].children)) return false;
358
358
  var v = k[5];
359
- if (!(v && v.tagClass === "universal" && v.tagNumber === TAGS.SEQUENCE && v.children && v.children.length === 2)) return false;
360
- return v.children.every(function (t) { return t.tagClass === "universal" && t.tagNumber === TAGS.GENERALIZED_TIME; });
359
+ if (!(schema.isUniversal(v, TAGS.SEQUENCE) && v.children && v.children.length === 2)) return false;
360
+ return v.children.every(function (t) { return schema.isUniversal(t, TAGS.GENERALIZED_TIME); });
361
361
  }
362
362
 
363
363
  // matchesV1(root): the obsolete AttributeCertificateV1 — its acInfo (version DEFAULT
@@ -370,8 +370,8 @@ function matchesV1(root) {
370
370
  if (!acinfo) return false;
371
371
  var k = acinfo.children;
372
372
  if (!k || k.length < 6) return false;
373
- if (!(k[0].tagClass === "context" && (k[0].tagNumber === 0 || k[0].tagNumber === 1) && k[0].children)) return false;
374
- return !!k[1] && k[1].tagClass === "universal" && k[1].tagNumber === TAGS.SEQUENCE;
373
+ if (!(schema.isContextOneOf(k[0], [0, 1]) && k[0].children)) return false;
374
+ return schema.isUniversal(k[1], TAGS.SEQUENCE);
375
375
  }
376
376
 
377
377
  module.exports = {