@blamejs/pki 0.5.23 → 0.5.25

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/lib/cmp-build.js CHANGED
@@ -34,6 +34,11 @@ var asn1 = require("./asn1-der");
34
34
  var oid = require("./oid");
35
35
  var cmp = require("./schema-cmp");
36
36
  var crmf = require("./crmf-sign");
37
+ var schemaCrmf = require("./schema-crmf");
38
+ var intrinsic = require("./guard-intrinsic");
39
+ // Own-key membership through an operation taken at load: it decides which proof-of-possession
40
+ // methods couple the message to a protocol version, and an inherited name is one no RFC defined.
41
+ var _hasOwn = intrinsic.hasOwn;
37
42
  var csr = require("./schema-csr");
38
43
  var crl = require("./schema-crl");
39
44
  var x509 = require("./schema-x509");
@@ -422,6 +427,29 @@ function _encodeKeyRecRepContent(spec, state) {
422
427
  return b.sequence(children);
423
428
  }
424
429
 
430
+ // Does a built CertReqMessages carry a proof of possession that RFC 9810 sec. 5.2.8.3 couples to
431
+ // cmp2021(3)? Stated over the RFC's pair rather than over the arms this toolkit happens to emit, so
432
+ // the coupling still holds if agreeMAC is built later.
433
+ var CMP2021_POP_METHODS = { agreeMAC: 1, encryptedKey: 1 };
434
+ function _popNeedsCmp2021(crmfDer) {
435
+ var messages;
436
+ // Re-reading a CertReqMessages this process just produced. A fault here is an internal
437
+ // inconsistency, not a caller error, so it is named in this module's namespace: a crmf/* parse code
438
+ // surfacing from cmp.build would send the operator looking at a request they wrote correctly. A
439
+ // CRMF fault raised while BUILDING that body still passes through untranslated, where it does name
440
+ // the caller's own input.
441
+ try { messages = schemaCrmf.parse(crmfDer).messages; }
442
+ catch (e) {
443
+ throw _err("cmp/bad-body", "the certificate request body this message just built did not parse back: " +
444
+ ((e && e.message) || e), e);
445
+ }
446
+ for (var i = 0; i < messages.length; i++) {
447
+ var popo = messages[i].popo;
448
+ if (popo && popo.method && _hasOwn(CMP2021_POP_METHODS, popo.method)) return true;
449
+ }
450
+ return false;
451
+ }
452
+
425
453
  // Dispatch the single-key body object to its EXPLICIT-tagged arm. Returns { bodyTLV, usesCmp2021 }.
426
454
  function _encodeBody(bodySpec, key, opts) {
427
455
  if (!bodySpec || typeof bodySpec !== "object" || Buffer.isBuffer(bodySpec)) throw _err("cmp/bad-input", "message.body must be a single-key object");
@@ -442,7 +470,13 @@ function _encodeBody(bodySpec, key, opts) {
442
470
  delete reqSpec.key;
443
471
  }
444
472
  return crmf.build(reqSpec, popKey, {}).then(function (crmfDer) {
445
- return { bodyTLV: b.explicit(tag, b.raw(crmfDer)), usesCmp2021: false };
473
+ // RFC 9810 sec. 5.2.8.3: "When using agreeMAC or encryptedKey choices, the pvno cmp2021(3)
474
+ // MUST be used." Read off the message that was actually emitted rather than off the spec that
475
+ // asked for it, so the announced version answers for the bytes on the wire. The parser
476
+ // enforces the same rule on the way in, and before this the two disagreed: a request carrying
477
+ // an encryptedKey proof went out announcing cmp2000(2), and this toolkit's own reader refused
478
+ // the message this toolkit had just built.
479
+ return { bodyTLV: b.explicit(tag, b.raw(crmfDer)), usesCmp2021: _popNeedsCmp2021(crmfDer) };
446
480
  });
447
481
  }
448
482
  var inner;
package/lib/cmp-verify.js CHANGED
@@ -339,14 +339,9 @@ function _rfc822Equal(a, b) {
339
339
  // SIGN lowercases to "k", so a host carrying it would compare EQUAL to the ASCII spelling
340
340
  // and two distinct domains would read as one identity. Fold only A-Z and leave every other
341
341
  // octet alone, so a non-ASCII host can differ from an ASCII one but never collide with it.
342
- function _lowerAsciiDomain(h) {
343
- var out = "";
344
- for (var i = 0; i < h.length; i++) {
345
- var c = _charCodeAt(h, i);
346
- out += (c >= 0x41 && c <= 0x5a) ? _fromCharCode(c + 32) : _charAt(h, i);
347
- }
348
- return out;
349
- }
342
+ // Through the toolkit's one definition of that fold, so no two name comparisons can disagree
343
+ // about which characters case-fold.
344
+ var _lowerAsciiDomain = guard.name.lowerAscii;
350
345
 
351
346
  // RFC 5280 sec. 4.2.1.6 / RFC 3986 sec. 6.2.2.1 URI comparison: the scheme and the authority host are
352
347
  // case-insensitive; every other component (userinfo, port, path, query, fragment) is byte-exact. Return
package/lib/crmf-sign.js CHANGED
@@ -33,6 +33,14 @@ var pkix = require("./schema-pkix");
33
33
  var pkiBuild = require("./pki-build");
34
34
  var frameworkError = require("./framework-error");
35
35
  var guard = require("./guard-all");
36
+ var intrinsic = require("./guard-intrinsic");
37
+ // Own-key membership through an operation taken at load: it decides which proof-of-possession
38
+ // alternative a request carries, and a name reached from the prototype is one the RFC never defined.
39
+ var _hasOwn = intrinsic.hasOwn;
40
+ var _stringify = intrinsic.stringify;
41
+ var cms = require("./schema-cms");
42
+ var cmsEncrypt = require("./cms-encrypt");
43
+ var key = require("./key");
36
44
  require("./path-validate"); // side-effect: path-validate injects its signature engine into crmf-verify at load
37
45
  var crmfVerify = require("./crmf-verify");
38
46
 
@@ -50,6 +58,28 @@ var _b = pkiBuild.makeBuilder({
50
58
  });
51
59
 
52
60
  var KNOWN_SPEC_KEYS = { certReqId: 1, certTemplate: 1, controls: 1, regInfo: 1, pop: 1 };
61
+ // spec.pop across all four ProofOfPossession arms: `type` picks the arm; `raVerified` and `sender`
62
+ // belong to the raVerified / signature arms; the rest to POPOPrivKey (RFC 4211 sec. 4.2, 4.3).
63
+ // spec.pop is a CHOICE, so the accepted key set is per ARM rather than a union of all of them. A
64
+ // single flat list would accept `{ type: 'keyEncipherment', method: 'subsequentMessage', privateKey,
65
+ // recipients, archive: true }`: a caller who believed they were sending the key that way gets a
66
+ // message that declares a later exchange instead, with the three fields they supplied read by
67
+ // nothing. `type` and `method` are what pick the arm, so they are read first and the rest is checked
68
+ // against the arm the caller chose.
69
+ var POP_KEYS_BY_ARM = {
70
+ raVerified: { type: 1, raVerified: 1 },
71
+ signature: { type: 1, sender: 1 },
72
+ subsequentMessage: { type: 1, method: 1, subsequentMessage: 1 },
73
+ encryptedKey: {
74
+ type: 1, method: 1, privateKey: 1, identifier: 1, recipients: 1, archive: 1,
75
+ contentEncryptionAlgorithm: 1,
76
+ },
77
+ // The arms that refuse before they read anything else still need a set, so the refusal a caller
78
+ // sees names the method rather than an unknown field alongside it.
79
+ agreeMAC: { type: 1, method: 1 },
80
+ thisMessage: { type: 1, method: 1 },
81
+ dhMAC: { type: 1, method: 1 },
82
+ };
53
83
  var KNOWN_BATCH_KEYS = { messages: 1 };
54
84
  var KNOWN_TEMPLATE_KEYS = { version: 1, subject: 1, publicKey: 1, validity: 1, extensions: 1, issuer: 1 };
55
85
  var REVOCATION_TEMPLATE_KEYS = { version: 1, subject: 1, publicKey: 1, validity: 1, extensions: 1, issuer: 1, serialNumber: 1 };
@@ -161,19 +191,271 @@ function _encodeCertId(id) {
161
191
  return b.sequence([_b.encodeGeneralName(id.issuer), _b.serialInteger(id.serialNumber)]);
162
192
  }
163
193
 
194
+ // The two ProofOfPossession arms a key that cannot sign has to use: keyEncipherment [2] and
195
+ // keyAgreement [3], each carrying a POPOPrivKey. Both field tags are EXPLICIT, because POPOPrivKey is
196
+ // itself a CHOICE and X.680 sec. 31.2.7 forbids implicit tagging of one. The parser states and
197
+ // enforces the same rule (schema-crmf.js), so an implicit emission here would disagree with the
198
+ // module's own reader.
199
+ var POPO_PRIVKEY_TAGS = { keyEncipherment: 2, keyAgreement: 3 };
200
+ // SubsequentMessage ::= INTEGER { encrCert (0), challengeResp (1) } (RFC 4211 sec. 4.2).
201
+ var SUBSEQUENT_MESSAGE = { encrCert: 0n, challengeResp: 1n };
202
+ // The specification deprecates two of the five alternatives in the same breath as defining them:
203
+ // thisMessage "has been deprecated in favor of encryptedKey", dhMAC "is deprecated in favor of the
204
+ // agreeMAC field" (sec. 4.2), and RFC 9810 sec. 5.2.8.3 restates both as `-- deprecated`. A reader
205
+ // still has to accept them, since a peer may send one; a producer choosing to emit one today is
206
+ // choosing the superseded encoding, so the builder names the successor instead of emitting it.
207
+ var DEPRECATED_POPO_METHOD = { thisMessage: "encryptedKey", dhMAC: "agreeMAC" };
208
+
209
+ // EncKeyWithID ::= SEQUENCE { privateKey PrivateKeyInfo,
210
+ // identifier CHOICE { string UTF8String, generalName GeneralName } OPTIONAL }
211
+ // (RFC 4211 sec. 4.2.1). `identifier` is marked OPTIONAL in the module and then made mandatory by the
212
+ // prose for this use: "This field MUST be present if the purpose is to prove possession of the private
213
+ // key." The reason is stated there too. Without it an escrow agent decrypts a key without knowing
214
+ // whose it is, so an attacker can wrap someone else's intercepted key in a request of their own and
215
+ // then ask for it back. Building a POP is that first purpose, so the caller supplies one.
216
+ function _encKeyWithID(privateKeyDer, identifier) {
217
+ var idNode;
218
+ if (typeof identifier === "string") idNode = b.utf8(identifier);
219
+ else idNode = _b.encodeGeneralName(identifier); // the GeneralName alternative of the CHOICE
220
+ return b.sequence([b.raw(privateKeyDer), idNode]);
221
+ }
222
+
223
+ // POPOPrivKey, the proof an encryption or key-agreement key gives instead of a signature (RFC 4211
224
+ // sec. 4.2 / 4.3). A key that cannot sign has no POPOSigningKey available, so without these arms the
225
+ // only reachable alternative is raVerified, an RA's assertion and not a proof at all. For a toolkit
226
+ // whose signature story is PQC-first that gap lands exactly on ML-KEM enrollment.
227
+ //
228
+ // `subsequentMessage` carries no cryptography: it declares which follow-up exchange will complete the
229
+ // proof, and the completion happens in the enrolling protocol (RFC 9810 sec. 5.2.8.3.2 / .3), not here.
230
+ // `encryptedKey` carries the private key itself to the CA, which is why it is gated twice below.
231
+ function _buildPopoPrivKey(pop, mode, template) {
232
+ var outerTag = POPO_PRIVKEY_TAGS[mode];
233
+ var method = pop && pop.method;
234
+ if (typeof method !== "string") {
235
+ throw _err("crmf/bad-popo", "a " + mode + " proof of possession requires pop.method ('subsequentMessage' or 'encryptedKey')");
236
+ }
237
+ if (_hasOwn(DEPRECATED_POPO_METHOD, method)) {
238
+ throw _err("crmf/bad-popo", "the " + method + " proof of possession is deprecated by RFC 4211 sec. 4.2 in favor of " +
239
+ DEPRECATED_POPO_METHOD[method] + "; a reader still accepts it, a new message should not carry it");
240
+ }
241
+ // sec. 4.2 lists exactly three methods for an encipherment key (the private key provided, a
242
+ // decrypted challenge, an encrypted certificate) and introduces the MAC alternatives only in
243
+ // sec. 4.3, "for keyAgreement (only)". The parser refuses a MAC arm under keyEncipherment; the
244
+ // builder refuses to produce one, so the two directions agree about the same message.
245
+ if (method === "agreeMAC" && mode === "keyEncipherment") {
246
+ throw _err("crmf/bad-popo", "keyEncipherment proof of possession cannot use the agreeMAC alternative -- " +
247
+ "it is defined for keyAgreement only (RFC 4211 sec. 4.2, sec. 4.3)");
248
+ }
249
+ if (method === "agreeMAC") {
250
+ // Conforming, and not built here. It needs the static Diffie-Hellman shared secret of RFC 2875
251
+ // sec. 3, derived between the requester's private key and a CA certificate the requester already
252
+ // holds, a classical key-agreement primitive this toolkit does not otherwise carry. It is
253
+ // reported, not approximated: verifyPop already names an inbound agreeMAC as unverified, and an
254
+ // emitted one nothing here can check would be worse than none.
255
+ throw _err("crmf/unsupported-popo", "the agreeMAC proof of possession is not built by this toolkit: it requires " +
256
+ "the RFC 2875 static Diffie-Hellman shared secret between the requester's key and a CA certificate it " +
257
+ "already holds. Use 'subsequentMessage' (encrCert or challengeResp), which every key type can produce");
258
+ }
259
+ if (method === "subsequentMessage") {
260
+ var which = pop.subsequentMessage;
261
+ if (typeof which !== "string" || !_hasOwn(SUBSEQUENT_MESSAGE, which)) {
262
+ throw _err("crmf/bad-popo", "pop.subsequentMessage must be 'encrCert' or 'challengeResp' -- " +
263
+ "SubsequentMessage ::= INTEGER { encrCert (0), challengeResp (1) } has no other value (RFC 4211 sec. 4.2)");
264
+ }
265
+ // subsequentMessage [1] IMPLICIT SubsequentMessage, inside the EXPLICIT [2]/[3] wrapper.
266
+ return b.explicit(outerTag, b.implicit(1, b.integer(SUBSEQUENT_MESSAGE[which])));
267
+ }
268
+ if (method !== "encryptedKey") {
269
+ throw _err("crmf/bad-popo", "unsupported POPOPrivKey method " + JSON.stringify(method) +
270
+ " (supported: 'subsequentMessage', 'encryptedKey')");
271
+ }
272
+ // encryptedKey is legal under BOTH outer arms, and the asymmetry with agreeMAC above is the
273
+ // specification's own. RFC 4211 sec. 4.3: key-agreement POP "is accomplished by one of four
274
+ // different methods. The first three are identical to those presented above for key encryption
275
+ // keys" -- and the first of sec. 4.2's three is "The private key can be provided to the CA/RA",
276
+ // which is this alternative. Only the fourth, the MAC, is agreement-only. The parser reads
277
+ // encryptedKey under both arms for the same reason, so gating it to keyEncipherment here would put
278
+ // the producer and the reader back into disagreement about one message.
279
+ return _buildEncryptedKeyPop(pop, outerTag, template);
280
+ }
281
+
282
+ // encryptedKey [4] EnvelopedData. RFC 9810 sec. 5.2.8.3.1: "This method SHALL only be used if archival
283
+ // of the private key is desired." Nothing in a builder can confirm that intent, so it is an explicit
284
+ // opt-in on the raVerified precedent: handing your private key to the CA should take a sentence that
285
+ // says so, not a mistyped method name.
286
+ function _buildEncryptedKeyPop(pop, outerTag, template) {
287
+ if (pop.archive !== true) {
288
+ throw _err("crmf/bad-popo", "an encryptedKey proof of possession sends the requester's private key to the CA, " +
289
+ "and RFC 9810 sec. 5.2.8.3.1 permits it only where archival is intended -- opt in with pop.archive: true");
290
+ }
291
+ if (pop.identifier == null) {
292
+ throw _err("crmf/bad-popo", "an encryptedKey proof of possession requires pop.identifier (a string or a GeneralName): " +
293
+ "RFC 4211 sec. 4.2.1 makes EncKeyWithID.identifier mandatory when the purpose is proving possession, so a " +
294
+ "decrypting agent knows whose key it holds");
295
+ }
296
+ // From here the function owns a plaintext copy of the caller's private key, so every exit clears it.
297
+ // The checks below reject a malformed PKCS#8, an empty recipient list, an AEAD algorithm and a
298
+ // template with no key, and each of those throws synchronously: cleanup attached only to the
299
+ // promise would run on none of them, leaving the copy readable exactly on the paths a caller hits
300
+ // by getting the call wrong. `wipe` tolerates the second buffer not existing yet.
301
+ var privateKeyDer = guard.bytes.snapshot(pop.privateKey, CrmfError, "crmf/bad-input", "pop.privateKey");
302
+ var encKeyWithIdDer = null;
303
+ function wipe() { guard.secret.zeroizeAll([privateKeyDer, encKeyWithIdDer], CrmfError, "crmf/bad-input", "the enclosed private key"); }
304
+ try {
305
+ return _encryptedKeyPopBody();
306
+ } catch (e) { wipe(); throw e; }
307
+
308
+ function _encryptedKeyPopBody() {
309
+ if (!privateKeyDer.length) throw _err("crmf/bad-input", "pop.privateKey must be the requester's PrivateKeyInfo (PKCS#8) DER");
310
+ // PrivateKeyInfo.version MUST be 0 (sec. 4.2.1). These are caller bytes, so the value is read rather
311
+ // than assumed; a v1 OneAsymmetricKey carries a public key the CA did not ask to be told.
312
+ var pkiKids, pkiVersion;
313
+ try { pkiKids = pkix.rootSequenceChildren(asn1.decode(privateKeyDer), 3); }
314
+ catch (e) { throw _err("crmf/bad-input", "pop.privateKey must be a PrivateKeyInfo (PKCS#8) SEQUENCE", e); }
315
+ if (!pkiKids) throw _err("crmf/bad-input", "pop.privateKey must be a PrivateKeyInfo (PKCS#8) SEQUENCE of at least three fields");
316
+ try { pkiVersion = asn1.read.integer(pkiKids[0]); }
317
+ catch (e) { throw _err("crmf/bad-input", "PrivateKeyInfo.version must be an INTEGER (RFC 4211 sec. 4.2.1)", e); }
318
+ if (pkiVersion !== 0n) {
319
+ throw _err("crmf/bad-input", "EncKeyWithID.privateKey must be a PrivateKeyInfo with version 0, got " + pkiVersion + " (RFC 4211 sec. 4.2.1)");
320
+ }
321
+ var recipients = pop.recipients;
322
+ if (!intrinsic.isArray(recipients) || recipients.length === 0) {
323
+ throw _err("crmf/bad-input", "an encryptedKey proof of possession requires pop.recipients (the CA or archive agents to envelope the key to)");
324
+ }
325
+ // The field is typed EnvelopedData, so the content-encryption algorithm has to be one that produces
326
+ // one. An AEAD algorithm yields an AuthEnvelopedData (RFC 5083), a different structure this field
327
+ // cannot carry and the parser will not read. It is refused by name, not emitted for a peer to
328
+ // reject. CBC is the default here for that reason, not as a preference between the two.
329
+ var cea = pop.contentEncryptionAlgorithm || "aes-256-cbc";
330
+ if (typeof cea !== "string") throw _err("crmf/bad-input", "pop.contentEncryptionAlgorithm must be an algorithm name");
331
+ if (/gcm|ccm|chacha/i.test(cea)) {
332
+ throw _err("crmf/bad-popo", "encryptedKey is typed EnvelopedData, and the AEAD algorithm " + cea +
333
+ " produces an AuthEnvelopedData instead (RFC 5083) -- choose a CBC content-encryption algorithm");
334
+ }
335
+ // RFC 4211 sec. 4.2: encryptedKey "contains the encrypted private key MATCHING THE PUBLIC KEY for
336
+ // which the certificate is to be issued". Without this the arm proves nothing it claims to: a
337
+ // requester could ask for a certificate over one key while enclosing an unrelated private key, and
338
+ // the CA would issue on a proof of possession of something it never certified. The signature arm
339
+ // self-verifies before returning for the same reason; this is that check for this arm.
340
+ if (template.spki == null) {
341
+ throw _err("crmf/bad-input", "an encryptedKey proof of possession requires certTemplate.publicKey -- " +
342
+ "the proof is that the enclosed private key is the one being certified (RFC 4211 sec. 4.2)");
343
+ }
344
+ // The second plaintext copy: the EncKeyWithID that carries the key into the message. This arm is
345
+ // the one place in the toolkit that deliberately holds a caller's private key in the clear, so both
346
+ // copies are cleared on every exit. The caller's own buffer stays intact, since it was copied.
347
+ encKeyWithIdDer = _encKeyWithID(privateKeyDer, pop.identifier);
348
+ // Composed, never hand-rolled: the one CMS producer emits the RecipientInfos, and the content type is
349
+ // the id-ct-encKeyWithID sec. 4.2 requires -- the same OID the parser independently checks for.
350
+ return _assertEnclosedKeyMatches(privateKeyDer, template.spki).then(function () {
351
+ // The CMS producer raises its own cms/* faults for a malformed recipient or an algorithm it does
352
+ // not carry. Those are this module's inputs, reached through a composition the caller cannot see,
353
+ // so they are re-raised in this module's namespace with the original kept as the cause -- the
354
+ // same translation the CRMF parser performs where it composes the CMS reader.
355
+ return cmsEncrypt.encrypt(encKeyWithIdDer, recipients, { contentType: "encKeyWithID", contentEncryptionAlgorithm: cea })
356
+ .then(null, function (e) {
357
+ if (e instanceof CrmfError) throw e;
358
+ throw _err("crmf/bad-input", "the encryptedKey proof of possession could not envelope the private key to " +
359
+ "pop.recipients: " + ((e && e.message) || e), e);
360
+ });
361
+ })
362
+ .then(function (contentInfo) {
363
+ // cms.encrypt returns a ContentInfo wrapping the EnvelopedData; the field carries the bare
364
+ // structure. Read back through the shipped walker rather than indexing into our own output, so a
365
+ // change in what encrypt emits is a typed error here and not a malformed message on the wire.
366
+ var inner = _bareEnvelopedData(contentInfo);
367
+ return b.explicit(outerTag, b.implicit(4, inner));
368
+ })
369
+ .then(function (out) { wipe(); return out; }, function (e) { wipe(); throw e; });
370
+ }
371
+ }
372
+
373
+ // Is the private key about to be enclosed the one the template asks to have certified? Derived through
374
+ // the toolkit's own key engine, not a second re-implementation, so every algorithm it drives (RSA, EC,
375
+ // the Edwards curves, ML-KEM, ML-DSA) answers the same way. Both values are public, so this is an
376
+ // ordinary comparison and not a secret one.
377
+ // nosemgrep: pki-non-constant-time-secret-compare
378
+ function _assertEnclosedKeyMatches(privateKeyDer, templateSpki) {
379
+ return Promise.resolve()
380
+ .then(function () { return key.publicFromPrivate(privateKeyDer); })
381
+ .then(function (derivedSpki) {
382
+ var derived = guard.bytes.view(derivedSpki, CrmfError, "crmf/bad-input", "the derived public key");
383
+ var wanted = guard.bytes.view(templateSpki, CrmfError, "crmf/bad-input", "certTemplate.publicKey");
384
+ if (!_b.samePublicKey(derived, wanted)) {
385
+ throw _err("crmf/bad-popo", "the private key enclosed in the encryptedKey proof of possession is not the " +
386
+ "private half of certTemplate.publicKey, so it proves possession of a key this request does not ask to " +
387
+ "have certified (RFC 4211 sec. 4.2)");
388
+ }
389
+ }, function (e) {
390
+ if (e instanceof CrmfError) throw e;
391
+ throw _err("crmf/bad-input", "pop.privateKey could not be read as a private key to check against " +
392
+ "certTemplate.publicKey: " + ((e && e.message) || e), e);
393
+ });
394
+ }
395
+
396
+ // The EnvelopedData SEQUENCE inside the ContentInfo cms.encrypt returns, validated on the way out.
397
+ // Every fault here comes from re-reading a composition the caller never sees. The codec's decode and
398
+ // the CMS walker each raise in their own namespace, so the whole body is translated, not the one call
399
+ // that happens to be likeliest. `pki.crmf.build` promises a typed CrmfError, and a promise with an
400
+ // exception for the paths nobody expected to take is the shape that makes it untrue exactly once.
401
+ function _bareEnvelopedData(contentInfoDer) {
402
+ try {
403
+ var kids = pkix.rootSequenceChildren(asn1.decode(contentInfoDer), 2, 2);
404
+ var wrapper = kids && kids[1];
405
+ if (!wrapper || wrapper.tagClass !== "context" || wrapper.tagNumber !== 0 || !wrapper.children || wrapper.children.length !== 1) {
406
+ throw _err("crmf/bad-popo", "the enveloped private key is not a ContentInfo carrying one [0] EXPLICIT content");
407
+ }
408
+ var env = wrapper.children[0];
409
+ cms.walkEnvelopedData(env); // typed cms/* on anything that is not a well-formed EnvelopedData
410
+ return b.raw(env.bytes);
411
+ } catch (e) {
412
+ if (e instanceof CrmfError) throw e;
413
+ throw _err("crmf/bad-popo", "the enveloped private key could not be read back as an EnvelopedData: " +
414
+ ((e && e.message) || e), e);
415
+ }
416
+ }
417
+
418
+ // Check spec.pop against the arm the caller selected, never against every arm's fields at once. Every
419
+ // opt-in below is a refusal a caller turns off by naming it, so a field that belongs to a different
420
+ // arm must not read as one this arm accepted and ignored: the caller believes they asked for
421
+ // something the message does not say. An unrecognized arm falls through with only the selector
422
+ // fields allowed, so the error names the arm rather than a field beside it.
423
+ function _assertPopArmKeys(pop, mode) {
424
+ var arm = _hasOwn(POPO_PRIVKEY_TAGS, mode) ? pop.method : mode;
425
+ var allowed = (typeof arm === "string" && _hasOwn(POP_KEYS_BY_ARM, arm))
426
+ ? POP_KEYS_BY_ARM[arm]
427
+ : { type: 1, method: 1 };
428
+ guard.identifier.assertKnownKeys(pop, allowed, _err, "crmf/bad-input", function (k) {
429
+ return "spec.pop field " + _stringify(k) + " is not read by a " +
430
+ (typeof arm === "string" ? arm : "proof") + " proof of possession";
431
+ });
432
+ }
433
+
164
434
  // ProofOfPossession. The signature arm (the default when a key is given): when the template carries both
165
435
  // subject and publicKey (complete), sign the CertRequest DER and omit poposkInput; otherwise build a
166
436
  // POPOSigningKeyInput (authInfo sender [0] GeneralName + the requested publicKey), sign its SEQUENCE, and
167
437
  // carry it as poposkInput [0] (RFC 4211 sec. 4.1). raVerified is emitted only on an explicit opt-in.
168
438
  function _buildProofOfPossession(pop, certReqDer, template, signingKey, opts) {
169
439
  if (pop != null && (typeof pop !== "object" || Buffer.isBuffer(pop))) throw _err("crmf/bad-input", "spec.pop must be an object (e.g. { type: 'signature' } or { type: 'raVerified', raVerified: true })");
440
+ // Every opt-in below is a refusal a caller turns off by naming it, so a misspelled key must not
441
+ // read as an omitted one: `archve: true` silently withholding the archival consent, or `identifer`
442
+ // silently omitting the field RFC 4211 sec. 4.2.1 makes mandatory, would each be a message built
443
+ // on the opposite of what the caller asked for.
444
+ // The arm is resolved BEFORE its fields are checked, because `type` is not the only thing that
445
+ // picks one: a spec that supplies a key and omits `type` selects the signature arm, and checking
446
+ // against an unresolved arm would refuse the `pop.sender` that arm reads.
170
447
  var mode = (pop && pop.type) || (signingKey != null ? "signature" : null);
448
+ if (pop != null) _assertPopArmKeys(pop, mode);
171
449
  if (mode == null) return null; // no POP requested and no key -> omit popo (an RA supplies it out of band)
172
450
  if (mode === "raVerified") {
173
451
  if (!(pop && pop.raVerified === true)) throw _err("crmf/bad-popo", "raVerified must be explicitly opted into (pop: { type: 'raVerified', raVerified: true }) -- a requester does not normally assert it (RFC 4211 sec. 4)");
174
452
  return b.implicit(0, b.nullValue()); // raVerified [0] IMPLICIT NULL
175
453
  }
176
- if (mode !== "signature") throw _err("crmf/bad-popo", "unsupported proof-of-possession type " + JSON.stringify(mode) + " (supported: 'signature', 'raVerified')");
454
+ if (_hasOwn(POPO_PRIVKEY_TAGS, mode)) return _buildPopoPrivKey(pop, mode, template);
455
+ if (mode !== "signature") {
456
+ throw _err("crmf/bad-popo", "unsupported proof-of-possession type " + JSON.stringify(mode) +
457
+ " (supported: 'signature', 'raVerified', 'keyEncipherment', 'keyAgreement')");
458
+ }
177
459
  if (signingKey == null) throw _err("crmf/bad-input", "a signature proof of possession requires the requester's private key");
178
460
  if (template.spki == null) throw _err("crmf/bad-input", "a signature proof of possession requires certTemplate.publicKey");
179
461
  var scheme = signScheme.resolveSignScheme(_b.certLikeFromSpki(template.spki), { combinedRsaSig: true, pss: opts.pss, digestAlgorithm: opts.digestAlgorithm }, true, _signE);
@@ -227,6 +509,27 @@ function _buildProofOfPossession(pop, certReqDer, template, signingKey, opts) {
227
509
  * PEM block with `opts.pem` (the label is required). Malformed input throws a typed `CrmfError`.
228
510
  * Certificate-request-message parsing is `pki.schema.crmf.parse`.
229
511
  *
512
+ * A key that cannot sign proves possession another way (RFC 4211 sec. 4.2, 4.3), which is the case an
513
+ * ML-KEM enrollment is in. Set `pop.type` to `keyEncipherment` or `keyAgreement` and pick a `pop.method`:
514
+ *
515
+ * - `subsequentMessage` with `pop.subsequentMessage` of `encrCert` or `challengeResp`. The proof completes
516
+ * over the enrolling protocol's next exchange (RFC 9810 sec. 5.2.8.3.2 / .3), so this message only
517
+ * declares which one. No key material leaves the requester, and every key type can produce it.
518
+ * - `encryptedKey`, which sends the requester's private key to the CA inside a CMS `EnvelopedData` whose
519
+ * content type is `id-ct-encKeyWithID`. RFC 9810 sec. 5.2.8.3.1 permits it only where archival is
520
+ * intended, so it takes `pop.archive: true`; `pop.privateKey` is the PKCS#8 DER, `pop.recipients` the CMS
521
+ * recipients to envelope it to, and `pop.identifier` (a string or GeneralName) is required, because
522
+ * sec. 4.2.1 makes it mandatory whenever the purpose is proving possession -- without it a decrypting
523
+ * agent cannot tell whose key it holds. `pop.contentEncryptionAlgorithm` defaults to `aes-256-cbc`; an
524
+ * AEAD algorithm is refused, since it would produce an `AuthEnvelopedData` this field cannot carry.
525
+ *
526
+ * The two alternatives the specification deprecates in the same breath as defining them, `thisMessage` and
527
+ * `dhMAC`, are refused with their successors named; `pki.schema.crmf.parse` still reads both, since a peer
528
+ * may send one. `agreeMAC` is not built: it needs the RFC 2875 static Diffie-Hellman shared secret between
529
+ * the requester's key and a CA certificate it already holds. Building an `encryptedKey` or `agreeMAC` proof
530
+ * inside `pki.cmp.build` raises the announced protocol version to cmp2021(3), which RFC 9810 sec. 5.2.8.3
531
+ * requires.
532
+ *
230
533
  * @opts
231
534
  * - `pem` (string) -- return a PEM block with this label instead of DER (e.g. "CERTIFICATE REQUEST MESSAGE").
232
535
  * - `pss` (boolean) -- sign an RSA key with RSASSA-PSS instead of PKCS#1 v1.5.
package/lib/guard-all.js CHANGED
@@ -51,6 +51,7 @@
51
51
  // its guard module, so a new boundary cannot re-inline the shape and forget the
52
52
  // defense.
53
53
 
54
+ var _freeze = require("./guard-intrinsic").freeze;
54
55
  var bytes = require("./guard-bytes");
55
56
  var text = require("./guard-text");
56
57
  var limits = require("./guard-limits");
@@ -74,7 +75,11 @@ var async_ = require("./guard-async");
74
75
  // live reads were never named. With one spelling, a module's own require IS the fact, and the check
75
76
  // reads it off the loaded module graph rather than guessing at the text.
76
77
 
77
- module.exports = {
78
+ // Frozen, like every module it gathers. A boundary reaches its guard as `guard.<family>.<fn>(...)`
79
+ // at the call, and the registry hands every module this same object, so one property assignment
80
+ // would replace a fail-closed check everywhere at once -- which is the substitution the family
81
+ // exists to refuse. Nothing writes to it after load.
82
+ module.exports = _freeze({
78
83
  bytes: bytes,
79
84
  text: text,
80
85
  limits: limits,
@@ -92,4 +97,4 @@ module.exports = {
92
97
  secret: secret,
93
98
  parsed: parsed,
94
99
  async: async_,
95
- };
100
+ });
@@ -46,4 +46,6 @@ function deferred(body) {
46
46
  catch (e) { return _reject(_Promise, e); }
47
47
  }
48
48
 
49
- module.exports = { deferred: deferred };
49
+ // Frozen for the reason the family header gives: a boundary reads its guard off this object at the
50
+ // call, so a writable export would let a caller replace the check rather than pass it.
51
+ module.exports = _intrinsic.freeze({ deferred: deferred });
@@ -1032,8 +1032,10 @@ function fixedCall(ErrorClass, code, args, body) {
1032
1032
  }), function () { if (handle) handle.release(); });
1033
1033
  }
1034
1034
 
1035
- module.exports = {
1035
+ // Frozen for the reason the family header gives: a boundary reads its guard off this object at the
1036
+ // call, so a writable export would let a caller replace the check rather than pass it.
1037
+ module.exports = intrinsic.freeze({
1036
1038
  view: view, source: source, snapshot: snapshot, snapshotSource: snapshotSource,
1037
1039
  isByteSource: isByteSource, lengthOf: lengthOf, outputView: outputView,
1038
1040
  snapshotDeep: snapshotDeep, fixArguments: fixArguments, fixedCall: fixedCall,
1039
- };
1041
+ });
@@ -181,4 +181,6 @@ function bounded(algorithm, stream, cap, E, codes, label) {
181
181
  // and a consumer offering an algorithm this list omits fails closed at `bounded`.
182
182
  function algorithms() { return _objectKeys(SAFE); }
183
183
 
184
- module.exports = { bounded: bounded, algorithms: algorithms };
184
+ // Frozen for the reason the family header gives: a boundary reads its guard off this object at the
185
+ // call, so a writable export would let a caller replace the check rather than pass it.
186
+ module.exports = _intrinsic.freeze({ bounded: bounded, algorithms: algorithms });
@@ -28,6 +28,7 @@
28
28
  // with unusedBits !== 0 fails closed before its bytes reach a verifier.
29
29
 
30
30
  var nodeCrypto = require("node:crypto");
31
+ var _freeze = require("./guard-intrinsic").freeze;
31
32
 
32
33
  // constantTimeEqual(a, b) -> boolean. Length-checked, then constant-time over
33
34
  // equal lengths. a and b are Buffers.
@@ -61,4 +62,6 @@ function assertOctetAligned(bitString, E, code, label) {
61
62
  return bitString;
62
63
  }
63
64
 
64
- module.exports = { constantTimeEqual: constantTimeEqual, isOctetAligned: isOctetAligned, assertOctetAligned: assertOctetAligned };
65
+ // Frozen for the reason the family header gives: a boundary reads its guard off this object at the
66
+ // call, so a writable export would let a caller replace the check rather than pass it.
67
+ module.exports = _freeze({ constantTimeEqual: constantTimeEqual, isOctetAligned: isOctetAligned, assertOctetAligned: assertOctetAligned });
package/lib/guard-der.js CHANGED
@@ -33,6 +33,7 @@
33
33
  // The byte comparison SET-OF ordering is decided by, taken at load. A replacement chooses which
34
34
  // encodings this guard calls correctly ordered. See guard-intrinsic for the whole captured set.
35
35
  var _compare = require("./guard-intrinsic").compare;
36
+ var _freeze = require("./guard-intrinsic").freeze;
36
37
  var _forEach = require("./guard-intrinsic").forEach;
37
38
  // The emptiness gate below decides whether bytes reach the decoder at all, and on a byte view
38
39
  // `length` is a replaceable accessor: one answering non-zero for an empty buffer sends nothing to
@@ -172,4 +173,6 @@ function tlv(content, E, code, label) {
172
173
  return content;
173
174
  }
174
175
 
175
- module.exports = { element: element, tlv: tlv };
176
+ // Frozen for the reason the family header gives: a boundary reads its guard off this object at the
177
+ // call, so a writable export would let a caller replace the check rather than pass it.
178
+ module.exports = _freeze({ element: element, tlv: tlv });
@@ -132,4 +132,6 @@ function hex(text, maxBytes, E, code, label) {
132
132
  return buf;
133
133
  }
134
134
 
135
- module.exports = { base64url: base64url, base64: base64, hex: hex };
135
+ // Frozen for the reason the family header gives: a boundary reads its guard off this object at the
136
+ // call, so a writable export would let a caller replace the check rather than pass it.
137
+ module.exports = _intrinsic.freeze({ base64url: base64url, base64: base64, hex: hex });
@@ -21,6 +21,7 @@ var C = require("./constants");
21
21
  // Taken at load. `byteLength` is what the RFC 5322 line limit is measured with, so a replacement
22
22
  // decides whether an over-long header line is refused. See guard-intrinsic for the whole set.
23
23
  var _byteLength = require("./guard-intrinsic").byteLength;
24
+ var _freeze = require("./guard-intrinsic").freeze;
24
25
  // The character-code read the RFC 5322 ftext and CR/LF/NUL checks are built on. One that never
25
26
  // reports a control byte is a header-injection defense that inspects nothing.
26
27
  var _charCodeAt = require("./guard-intrinsic").uncurry(String.prototype.charCodeAt);
@@ -60,4 +61,6 @@ function assertField(name, value, E, code) {
60
61
  return v;
61
62
  }
62
63
 
63
- module.exports = { assertField: assertField };
64
+ // Frozen for the reason the family header gives: a boundary reads its guard off this object at the
65
+ // call, so a writable export would let a caller replace the check rather than pass it.
66
+ module.exports = _freeze({ assertField: assertField });
@@ -851,7 +851,9 @@ function _settle(opts, E, code, label) {
851
851
  return opts;
852
852
  }
853
853
 
854
- module.exports = {
854
+ // Frozen for the reason the family header gives: a boundary reads its guard off this object at the
855
+ // call, so a writable export would let a caller replace the check rather than pass it.
856
+ module.exports = intrinsic.freeze({
855
857
  assertCanonicalOid: assertCanonicalOid,
856
858
  assertKnownKeys: assertKnownKeys,
857
859
  optionsObject: optionsObject,
@@ -864,4 +866,4 @@ module.exports = {
864
866
  // Exported for the same reason as its sibling: a caller copying an array has to reach the
865
867
  // elements a read reaches, and the own keys are not that set.
866
868
  readableIndices: readableIndices
867
- };
869
+ });
@@ -260,7 +260,12 @@ function sizeOf(value) {
260
260
  (value === null ? "null" : typeof value));
261
261
  }
262
262
 
263
- module.exports = {
263
+ // Frozen, and that is what makes the capture worth taking. A consumer binds these at load, but it
264
+ // also reads several of them as `intrinsic.<name>(...)` at the call itself, and the module registry
265
+ // hands every caller this same object: assigning one property would redirect that call in every
266
+ // module at once, which is the substitution the captures exist to refuse. Freezing costs nothing
267
+ // here because nothing writes to it after load.
268
+ module.exports = Object.freeze({
264
269
  uncurry: uncurry,
265
270
  getter: getter,
266
271
  sizeOf: sizeOf,
@@ -347,4 +352,4 @@ module.exports = {
347
352
  Set: _Set,
348
353
  Map: _Map,
349
354
  WeakMap: _WeakMap,
350
- };
355
+ });
package/lib/guard-json.js CHANGED
@@ -27,6 +27,7 @@ var text = require("./guard-text");
27
27
  // setter, and `fromCharCode` is how an escape becomes the character it names; a replacement for
28
28
  // either decides what this parser produces. See guard-intrinsic for the whole captured set.
29
29
  var _defineProperty = require("./guard-intrinsic").defineProperty;
30
+ var _freeze = require("./guard-intrinsic").freeze;
30
31
  var _fromCharCode = require("./guard-intrinsic").fromCharCode;
31
32
  // The character-code read the whole scanner is built on: whitespace, escapes and the control-byte
32
33
  // reject all consult it, so one that lies decides what this parser sees in the input.
@@ -209,4 +210,6 @@ function parse(input, ErrorClass, spec) {
209
210
  return result;
210
211
  }
211
212
 
212
- module.exports = { parse: parse };
213
+ // Frozen for the reason the family header gives: a boundary reads its guard off this object at the
214
+ // call, so a writable export would let a caller replace the check rather than pass it.
215
+ module.exports = _freeze({ parse: parse });
@@ -27,6 +27,7 @@ var constants = require("./constants");
27
27
  // one returning true admits a NaN or fractional cap, which makes the comparison it guards always
28
28
  // false. See guard-intrinsic for the whole captured set.
29
29
  var _isInteger = require("./guard-intrinsic").isInteger;
30
+ var _freeze = require("./guard-intrinsic").freeze;
30
31
  // And the size measurement, for the same reason one step further in: a cap compares against a
31
32
  // length, and on a byte view `length` is a replaceable accessor. One reporting a small number for a
32
33
  // large buffer leaves every byteCap below always-false, which is the size defense silently dead.
@@ -137,4 +138,6 @@ function byteCap(buf, max, E, code, label) {
137
138
  return buf;
138
139
  }
139
140
 
140
- module.exports = { cap: cap, depthCap: depthCap, counter: counter, byteCap: byteCap };
141
+ // Frozen for the reason the family header gives: a boundary reads its guard off this object at the
142
+ // call, so a writable export would let a caller replace the check rather than pass it.
143
+ module.exports = _freeze({ cap: cap, depthCap: depthCap, counter: counter, byteCap: byteCap });