@blamejs/pki 0.5.24 → 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/CHANGELOG.md +24 -0
- package/README.md +1 -1
- package/lib/cmp-build.js +35 -1
- package/lib/crmf-sign.js +304 -1
- package/lib/pki-build.js +29 -0
- package/package.json +1 -1
- package/sbom.cdx.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,30 @@ 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.5.25 — 2026-08-21
|
|
8
|
+
|
|
9
|
+
A key that cannot sign can now prove possession, so an ML-KEM certificate request has a proof to carry instead of no option at all.
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- `pki.crmf.build` emits a `POPOPrivKey` proof of possession under `pop.type` of `keyEncipherment` or `keyAgreement`. `pop.method: 'subsequentMessage'` with `pop.subsequentMessage` of `encrCert` or `challengeResp` declares which follow-up exchange completes the proof (RFC 9810 sec. 5.2.8.3.2 and sec. 5.2.8.3.3); no key material leaves the requester and every key type can produce it. `pop.method: 'encryptedKey'` encloses the requester's private key for the certification authority in a CMS `EnvelopedData` whose content type is `id-ct-encKeyWithID`, taking `pop.privateKey`, `pop.recipients`, `pop.identifier`, and `pop.archive: true`. `pki.cmp.build` carries either in an `ir`, `cr`, or `kur` body.
|
|
14
|
+
- The requested version follows what the message carries: a CMP request whose proof of possession uses `encryptedKey` or `agreeMAC` announces cmp2021(3), which RFC 9810 sec. 5.2.8.3 requires. Before this a request carrying an `encryptedKey` proof went out announcing cmp2000(2), and this toolkit's own reader refused the message it had just built.
|
|
15
|
+
|
|
16
|
+
### Changed
|
|
17
|
+
|
|
18
|
+
- `spec.pop` refuses a field it does not recognize. Each rule below is one a caller turns off by naming it, so a misspelled key must not read as an omitted one: `archve: true` would have withheld the archival consent while appearing to give it.
|
|
19
|
+
|
|
20
|
+
### Security
|
|
21
|
+
|
|
22
|
+
- An `encryptedKey` proof must enclose the private half of `certTemplate.publicKey`. RFC 4211 sec. 4.2 defines the field as "the encrypted private key matching the public key for which the certificate is to be issued"; enclosing any other key proves possession of something the request never asked to have certified, while every structural check still passes. The public key is derived from the supplied private key through the toolkit's own key engine and compared before the message is built.
|
|
23
|
+
- An `encryptedKey` proof requires `pop.identifier`. The ASN.1 marks `EncKeyWithID.identifier` OPTIONAL and RFC 4211 sec. 4.2.1 then makes it mandatory whenever the purpose is proving possession, for a reason the section states: without it a decrypting agent holds a key it cannot attribute, so an intercepted key can be wrapped in someone else's request and recovered.
|
|
24
|
+
- The two alternatives RFC 4211 sec. 4.2 deprecates as it defines them, `thisMessage` and `dhMAC`, are refused with their successors named. `pki.schema.crmf.parse` still reads both, since a peer may send one.
|
|
25
|
+
- A `keyEncipherment` proof cannot carry a MAC alternative. RFC 4211 sec. 4.2 lists three methods for an encipherment key and introduces the MAC alternatives only in sec. 4.3, "for keyAgreement (only)". The parser already refused such a message; the builder no longer produces one.
|
|
26
|
+
|
|
27
|
+
### Notes
|
|
28
|
+
|
|
29
|
+
- The `agreeMAC` proof is not built. It requires the RFC 2875 static Diffie-Hellman shared secret between the requester's key and a certification authority certificate the requester already holds, a classical key-agreement primitive this toolkit does not otherwise carry. `pki.crmf.verifyPop` continues to report an inbound `agreeMAC` as unverified, naming the arm. Use `subsequentMessage`, which any key type can produce.
|
|
30
|
+
|
|
7
31
|
## v0.5.24 — 2026-08-21
|
|
8
32
|
|
|
9
33
|
An ACME certificate download is now bound to the order that asked for it, so a certificate for another key or another name is refused instead of returned as the issued one.
|
package/README.md
CHANGED
|
@@ -232,7 +232,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
|
|
|
232
232
|
| `pki.x509` | Certificate issuance (RFC 5280 §4). `sign(spec, issuer, opts)` builds and signs a certificate from a `spec` of subject (a common-name string, an array of RDNs, or raw Name DER), the public key being certified, the validity window, an optional serial, and an optional `extensions` object. The `issuer` is a key alone (self-signed: issuer equals subject, signed with that key), a name plus public key plus key, or an issuing certificate plus key. The signature algorithm is resolved from the signing key through the shared registry, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA P-256/384/521, Ed25519, Ed448, ML-DSA-44/65/87, the twelve SLH-DSA sets, and the composite arms all issue without a per-algorithm branch. It encodes basic constraints, key usage, extended key usage, subject and authority key identifiers (the SKI derived by SHA-1 of the subject key), subject alternative names, and certificate policies from the spec, taking any other extension as pre-encoded DER. It derives the version from the field set and enforces the serial bounds, the UTCTime/GeneralizedTime cutover, the DER default omissions, and the CA cross-field rules; a violation throws a typed `CertificateError`. Returns DER, or a PEM `CERTIFICATE` with `opts.pem`. Every arm is independently verified by OpenSSL. Parsing stays at `pki.schema.x509.parse` — `sign` |
|
|
233
233
|
| `pki.csr` | PKCS#10 certification-request issuance (RFC 2986 / RFC 2985). `sign(spec, key, opts)` builds and signs a `CertificationRequest` from a `spec` of subject (which may be empty), the public key being certified, an optional `extensionRequest` carrying the requested v3 extensions a CA copies into the issued certificate (subject alternative names, key usage, extended key usage, basic constraints, certificate policies, subject key identifier, or an array of pre-encoded Extension DER), and an optional `challengePassword`. `key` (or `{ key }`) is the subject's own private key: the request is self-signed to prove possession of the private half of `subjectPublicKey`, and that proof is verified before the request is returned, which is what `openssl req -verify` checks. The signature algorithm is resolved from the subject key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. Returns DER, or a PEM `CERTIFICATE REQUEST` with `opts.pem`; malformed input throws a typed `CsrError`. `verify(request)` asks the same question of a request someone else produced, over its exact signed `certificationRequestInfo` bytes under the `subjectPKInfo` inside them, through the one path-validation signature engine. It answers `{ verified, subject, subjectPublicKeyInfo, attributes, certificationRequestInfoBytes }`, all re-derived from the signed bytes, so a CA issues from the fields the signature covers rather than from the object it passed in. A `verified: true` says the producer held that private key and that the subject and requested extensions are the ones they signed; who they are is the enrollment protocol's question, not this one. Parsing stays at `pki.schema.csr.parse` — `sign`, `verify` |
|
|
234
234
|
| `pki.attrcert` | Attribute-certificate issuance (RFC 5755). `sign(spec, issuer, opts)` builds and signs an `AttributeCertificate` as an Attribute Authority: a `spec` of `holder` (exactly one of an entity name, a `baseCertificateID` reference, a `fromCertificate` binding, or an object digest), the validity window as GeneralizedTime, an optional serial (positive, at most 20 octets, randomly generated when omitted), the `attributes` (role, clearance, group, chargingIdentity, accessIdentity, authenticationInfo, or pre-encoded Attribute DER), and optional `extensions` (auditIdentity, targetInformation, noRevAvail, aaControls, acProxying, authorityKeyIdentifier, or pre-encoded Extension DER) each with its RFC 5755 criticality. An attribute certificate is never self-signed, so the `issuer` is the signing AA, supplied as `{ cert, key }` or `{ name, publicKey, key }`. The signature algorithm is resolved from the AA key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch, and the signature is verified under the AA public key before the certificate is returned. Returns DER, or a PEM `ATTRIBUTE CERTIFICATE` with `opts.pem`; malformed input throws a typed `AttrCertError`. `verify(ac, issuer, opts)` is the receiving side, performing the RFC 5755 sec. 5 checks an attribute certificate and a named issuer can settle between them: the signature over the exact `AttributeCertificateInfo` bytes through the one path-validation signature engine, the AC naming the issuer this verifier trusts (compared as a distinguished name), the evaluation instant lying within the validity with equality at either bound succeeding as the section states, the sec. 4.3.2 targeting rule, and rejection of any critical extension this verb does not process (section 5 defines support as parsing the value AND rejecting where the value would reject, so `aaControls` and `acProxying`, whose constraints it does not evaluate, are refused when critical). It answers `{ verified, signatureValid, validityChecked, targetingChecked, holderBindingChecked, issuerPathChecked, holder, issuer, attributes, extensions, notBefore, notAfter, serialNumberHex, reason }` with the fields re-derived from the signed bytes; the holder's own certificate chain and the AC issuer's chain need certificates the verb is not given, so those slots report `false` rather than letting their absence read as a pass. Parsing stays at `pki.schema.attrcert.parse` — `sign`, `verify` |
|
|
235
|
-
| `pki.crmf` | Certificate-request-message issuance (RFC 4211). `build(spec, key, opts)` assembles a `CertReqMessages` from a `spec` of `certReqId` (default 0, with the RFC 9483 `-1` sentinel allowed), a `certTemplate` of the requested fields (`subject`, `publicKey` as the SPKI DER of the key being certified, `validity`, requested `extensions`, an optional `version` 2), optional `controls` and `regInfo` (regToken, authenticator, utf8Pairs, oldCertID, protocolEncrKey, or pre-encoded `AttributeTypeAndValue` DER), and an optional `pop` selector. `key` (or `{ key }`) is the requester's private key: the message carries a `POPOSigningKey` proof of possession signed with the private half of `certTemplate.publicKey` and verified before the message is returned, exactly as a PKCS#10 CSR proves possession. A complete template signs the `CertRequest`; an incomplete one signs a `POPOSigningKeyInput`. The signature algorithm is resolved from the requested public key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. `key` is optional for a `raVerified` proof. Pass an array of specs for a batch; the CA-assigned template fields are never emitted. Returns DER, or a PEM block with `opts.pem`; malformed input throws a typed `CrmfError`. `verifyPop(messages)` is the receiving side: for each `CertReqMsg` it verifies the `POPOSigningKey` signature over the bytes RFC 4211 sec. 4.1 names — the DER of `poposkInput` when present, of `certReq` when not — through the one path-validation signature engine, and answers `{ verified, messages: [{ verified, method, cryptographicallyVerified, certReqId, subject, subjectBound, publicKey, reason }] }` with the fields re-derived from the message's own bytes. Each verdict reports only what its preimage covers: `publicKey` is the key possession was proven for, and `subject` is the requested name when the `certReq` was signed. A `poposkInput` preimage covers the key and the sender alone, so any subject beside it is unsigned and is withheld with `subjectBound: false`. A `raVerified` proof is an RA's out-of-band assertion and a `keyEncipherment` or `keyAgreement` proof completes over a later exchange, so each is reported unverified with its `method` named instead of guessed. Parsing stays at `pki.schema.crmf.parse` — `build`, `verifyPop` |
|
|
235
|
+
| `pki.crmf` | Certificate-request-message issuance (RFC 4211). `build(spec, key, opts)` assembles a `CertReqMessages` from a `spec` of `certReqId` (default 0, with the RFC 9483 `-1` sentinel allowed), a `certTemplate` of the requested fields (`subject`, `publicKey` as the SPKI DER of the key being certified, `validity`, requested `extensions`, an optional `version` 2), optional `controls` and `regInfo` (regToken, authenticator, utf8Pairs, oldCertID, protocolEncrKey, or pre-encoded `AttributeTypeAndValue` DER), and an optional `pop` selector. `key` (or `{ key }`) is the requester's private key: the message carries a `POPOSigningKey` proof of possession signed with the private half of `certTemplate.publicKey` and verified before the message is returned, exactly as a PKCS#10 CSR proves possession. A complete template signs the `CertRequest`; an incomplete one signs a `POPOSigningKeyInput`. The signature algorithm is resolved from the requested public key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. `key` is optional for a `raVerified` proof. A key that cannot sign, which is where an ML-KEM enrollment sits, takes a `POPOPrivKey` proof instead (RFC 4211 sec. 4.2, sec. 4.3): `pop.type` of `keyEncipherment` or `keyAgreement` with `pop.method: 'subsequentMessage'` declares whether an encrypted certificate (`encrCert`) or a challenge (`challengeResp`) completes the proof over the enrolling protocol's next exchange, and `pop.method: 'encryptedKey'` encloses the requester's private key for the CA in a CMS `EnvelopedData` under `id-ct-encKeyWithID`, requiring `pop.privateKey`, `pop.recipients`, the `pop.identifier` sec. 4.2.1 makes mandatory, and `pop.archive: true` because RFC 9810 sec. 5.2.8.3.1 permits the method only where archival is intended. The enclosed key must be the private half of `certTemplate.publicKey`, or the proof demonstrates possession of a key the request never asked to have certified. The `thisMessage` and `dhMAC` alternatives the specification deprecates are refused with their successors named, and `agreeMAC` is not built, since it needs the RFC 2875 static Diffie-Hellman secret against a CA certificate the requester already holds. Pass an array of specs for a batch; the CA-assigned template fields are never emitted. Returns DER, or a PEM block with `opts.pem`; malformed input throws a typed `CrmfError`. `verifyPop(messages)` is the receiving side: for each `CertReqMsg` it verifies the `POPOSigningKey` signature over the bytes RFC 4211 sec. 4.1 names — the DER of `poposkInput` when present, of `certReq` when not — through the one path-validation signature engine, and answers `{ verified, messages: [{ verified, method, cryptographicallyVerified, certReqId, subject, subjectBound, publicKey, reason }] }` with the fields re-derived from the message's own bytes. Each verdict reports only what its preimage covers: `publicKey` is the key possession was proven for, and `subject` is the requested name when the `certReq` was signed. A `poposkInput` preimage covers the key and the sender alone, so any subject beside it is unsigned and is withheld with `subjectBound: false`. A `raVerified` proof is an RA's out-of-band assertion and a `keyEncipherment` or `keyAgreement` proof completes over a later exchange, so each is reported unverified with its `method` named instead of guessed. Parsing stays at `pki.schema.crmf.parse` — `build`, `verifyPop` |
|
|
236
236
|
| `pki.cmp` | CMP message building, transfer, and verification (RFC 9810). `build(message, opts)` assembles a protected `PKIMessage`. `message.header` carries the `sender` and `recipient` GeneralNames (including the anonymous NULL-DN) plus optional transaction metadata; `message.body` is a single-key object naming the arm — request-side `ir`, `cr`, `kur`, `p10cr`, `certConf`, `pollReq`, `genm`, `rr`, and responder-side `ip`, `cp`, `kup`, `ccp`, `rp`, `genp`, `error`, `pollRep`, `krp`, `pkiconf`. Protection is exactly one of `opts.{ key, cert }`, a signature under the sender key with the algorithm resolved from the signer certificate so RSA (PKCS#1 v1.5 / PSS), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch, or `opts.mac`, a PBMAC1 shared-secret HMAC (RFC 9481 / 9579, PBKDF2-derived). Protection covers the exact DER of the virtual `ProtectedPart` and is self-verified before the message is returned, and `protectionAlg` is derived rather than caller-set, so the message the parser accepts is coherent by construction. `transfer(url, message, opts)` carries a built message to a CMP endpoint over `pki.transport` (RFC 9811): one POST of the DER PKIMessage, with the response classified fail-closed — 200 only for success, a non-200 2xx or an un-followed 3xx refused, a 4xx or 5xx carrying a CMP error PKIMessage forwarded as the integrity-protected verdict — and protection surfaced rather than verified. `wellKnownUrl(base, opts)` builds the §3.4 `/.well-known/cmp` request-URIs. `verify(message, opts)` checks the protection on an incoming message, either a signature through the same certification-path engine `pki.crl.verify` and `pki.ocsp.verify` use, with the EdDSA low-order-point and algorithm-confusion gates, or a PBMAC1 MAC recomputed from `opts.sharedSecret` and the message's own PBKDF2 parameters and constant-time compared, over the exact `ProtectedPart` reconstructed from the parser's raw slices. It is fail-closed on an unprotected message, a legacy or KEM MAC algorithm, an omitted keyLength, or a SHA-1 PRF, and returns a `{ valid, trusted, protectionType, signer, ... }` verdict. With `opts.trustAnchors` the signer certificate is fully path-validated (RFC 5280 §6.1 plus the RFC 9483 §3.2 `keyUsage.digitalSignature` gate) at a trusted current time, or an explicit `opts.time` for historical verification and never the message's self-asserted `messageTime`, before it is reported trusted; without one the verdict is crypto-only and the signer certificate is surfaced to anchor. `session(opts)` returns a stateful enrollment session whose `enroll(request)` drives a full `ir` / `cr` / `kur` / `p10cr` transaction over the shared transport, composing `build`, `transfer`, and `verify`. Every response is protection-verified, signer-trusted, and bound to the exchange (a stable `transactionID`, a fresh-`senderNonce` and echoed-`recipNonce` chain) before its body is read, with a bounded `pollReq` / `pollRep` loop for a `waiting` status and a `certConf` / `pkiConf` (or implicit) confirmation carrying an explicit `hashAlg` for a signature algorithm that does not convey its hash. It returns a terminal `{ outcome, certificate, chain, status, trusted, confirmed, implicitConfirm, transactionID, polls, transcript }`. The signature flavor requires `opts.trustAnchors` to authenticate the CA; a verified rejection or error and an exhausted poll budget are terminal verdicts, while a tampered, untrusted, or desynchronized response is a typed throw. Returns DER, or a PEM `CMP` block with `opts.pem`; malformed input throws a typed `CmpError`. Parsing stays at `pki.schema.cmp.parse` — `build`, `transfer`, `wellKnownUrl`, `verify`, `session` |
|
|
237
237
|
| `pki.crl` | CRL issuance and verification (RFC 5280 §5). `sign(spec, issuer, opts)` builds and signs a `CertificateList` from a `spec` of `thisUpdate` and `nextUpdate`, an optional `crlNumber`, a `revoked` array (each entry a `serialNumber` and `revocationDate` with an optional `reason` or `invalidityDate`), and an optional `extensions` object (authority key identifier, issuing distribution point, delta-CRL indicator, freshest CRL, authority information access) or an array of pre-encoded Extension DER, with an `issuer` of `{ cert, key }` or `{ name, publicKey, key }`. The signature algorithm is resolved from the issuer key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. The version is derived from the extension set (v2 when any CRL or entry extension is present, else v1), the outer `signatureAlgorithm` matches `tbsCertList.signature`, an empty revocation list omits the field rather than emitting an empty SEQUENCE, `reasonCode` is an ENUMERATED and `invalidityDate` is always GeneralizedTime, the RFC fixes per-extension criticality, and the produced signature is verified under the issuer key before return. `verify(crl, issuer)` checks a CRL signature through the one path-validation signature engine, algorithm-confusion and EdDSA low-order gates included; handed a certificate rather than a bare key it also asks what only a certificate can answer — that the certificate is the issuer the CRL names, and that its `keyUsage`, when present, asserts `cRLSign` — so a CRL minted under an end-entity certificate of the same CA does not verify as that CA's. `isRevoked(crl, serialNumber, opts)` looks a serial up, and first checks that the CRL is one a serial can be looked up in at all — it is handed a serial and nothing else, so a CRL that speaks for part of its issuer's certificates is refused rather than answered from. A delta CRL lists changes since a base, so an entry recording a release reads as a revocation when read alone; an indirect CRL carries other issuers' entries, whose serials are unrelated to yours; and any other `issuingDistributionPoint` narrows the CRL to one distribution point, one kind of certificate, or a subset of revocation reasons, none of which a serial can be matched against. A CRL speaks for a span as well as a set, so `opts.time` states the instant the question is asked at and a list that has stopped speaking for it — `nextUpdate` passed, `thisUpdate` later, or no `nextUpdate` stated at all — is refused rather than read as a clean bill of health; without `opts.time` the lookup is structural and an absent serial means only that it is not on that list. `pki.path.crlChecker` is the verb for all of them: it is handed the certificate, merges a delta with its base, performs the §6.3.3 correspondence, and decides currency against the material it fetched. Returns DER, or a PEM `X509 CRL` with `opts.pem`; malformed input throws a typed `CrlError`. Parsing stays at `pki.schema.crl.parse` — `sign`, `verify`, `isRevoked` |
|
|
238
238
|
| `pki.key` | Key-material lifecycle (RFC 5958 / RFC 8018). `encrypt(privateKey, password, opts)` wraps a PKCS#8 private key (DER, PEM, or an extractable `CryptoKey`) into an `EncryptedPrivateKeyInfo` under PBES2 (PBKDF2 with AES-CBC-Pad), where `opts` selects the `cipher` (`aes-256-cbc` default, `aes-192-cbc`, `aes-128-cbc`), the `prf` (`hmacWithSHA256` default, SHA-384/512, SHA-1), the `iterations` (default 600000), and the `salt`. The plaintext is validated as PKCS#8 before encryption, a default `prf` and `keyLength` are omitted so the parameters are byte-exact with OpenSSL, and the output is re-parsed before return. `decrypt(encrypted, password, opts)` recovers the inner `PrivateKeyInfo`, re-validated through `pki.schema.pkcs8.parse`: only PBES2 / PBKDF2 / AES-CBC is accepted (PBES1, PBMAC1, and scrypt are refused), the salt and iteration count are bounded before any derivation (`opts.maxIterations` lowers the cap), and a malformed parameter set or wrong-length IV is a distinct typed error. Because a MAC-less PBES2-CBC decrypt must not become a padding oracle (RFC 8018 §8), a wrong password and a valid-pad-but-not-a-key both surface the one uniform `key/decrypt-failed`. `export(key, opts)` and `import(input, opts)` move a private key as PKCS#8 or a public key as SubjectPublicKeyInfo. The key may come from the platform's WebCrypto or from a separately installed copy of this toolkit, and is exported through whichever holds its material; a non-extractable key, or one whose implementation keeps its material out of reach, is refused with that as the reason. Encoding is delegated to WebCrypto, so RSA carries an explicit NULL, EC a named curve, and Ed25519/Ed448/X25519/X448 omit parameters, and an ambiguous RSA or EC import requires `opts.algorithm`. `generate(algorithm, opts)` produces a key pair over RSA, ECDSA/ECDH, the Edwards and Montgomery curves, and the FIPS post-quantum ML-DSA and ML-KEM; `publicFromPrivate(privateKey)` derives the public key. Returns DER or PEM, with a typed `KeyError` on failure. Parsing stays at `pki.schema.pkcs8.parse` — `encrypt`, `decrypt`, `export`, `import`, `generate`, `publicFromPrivate` |
|
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
|
-
|
|
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/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 (
|
|
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/pki-build.js
CHANGED
|
@@ -18,9 +18,16 @@ var intrinsic = require("./guard-intrinsic");
|
|
|
18
18
|
// Each of these doors refuses a caller argument that is not a list. Read live, a replacement
|
|
19
19
|
// answering true lets a non-list through the check written to stop it.
|
|
20
20
|
var _isArray = intrinsic.isArray;
|
|
21
|
+
// Taken at load for the reason every capture here is: the question "do these two encodings name the
|
|
22
|
+
// same key" decides whether a proof of possession is accepted, and a caller who replaces the copy or
|
|
23
|
+
// the comparison afterwards decides it instead.
|
|
24
|
+
var _bufferFrom = intrinsic.bufferFrom;
|
|
25
|
+
var _bufferEquals = intrinsic.bufferEquals;
|
|
21
26
|
var oid = require("./oid");
|
|
22
27
|
var ipUtils = require("./ip-utils");
|
|
23
28
|
var nodeCrypto = require("crypto");
|
|
29
|
+
// The key-material comparison, taken at load like every other operation a decision here rests on.
|
|
30
|
+
var _keyEquals = intrinsic.uncurry(nodeCrypto.KeyObject.prototype.equals);
|
|
24
31
|
|
|
25
32
|
var b = asn1.build;
|
|
26
33
|
|
|
@@ -402,6 +409,27 @@ function makeBuilder(ctx) {
|
|
|
402
409
|
if (!ok) throw E("bad-input", "the signing key does not correspond to the public key -- the signature would not verify");
|
|
403
410
|
}
|
|
404
411
|
|
|
412
|
+
// Do two SubjectPublicKeyInfo encodings name the same key? Bytes first, because that is the answer
|
|
413
|
+
// almost always and it costs nothing. When they differ the question is still open, since one key has
|
|
414
|
+
// more than one legal SPKI: an EC point may be carried compressed or uncompressed, so a P-256 key
|
|
415
|
+
// written the compressed way is byte-unequal to the same key written the other. Comparing the DER
|
|
416
|
+
// alone would refuse a proof of possession over a key the requester genuinely holds, while the
|
|
417
|
+
// sibling arms of the same verb accept that template. The fallback asks the key layer, which
|
|
418
|
+
// compares key material and still answers false for a different key, a different curve, or a
|
|
419
|
+
// different algorithm. A key neither side can import is equal to nothing, so the refusal stands.
|
|
420
|
+
function samePublicKey(spkiA, spkiB) {
|
|
421
|
+
var a = _bufferFrom(spkiA), bb = _bufferFrom(spkiB);
|
|
422
|
+
if (_bufferEquals(a, bb)) return true;
|
|
423
|
+
var ka, kb;
|
|
424
|
+
// allow:swallow-unverified an SPKI the key layer cannot import matches nothing, which is the
|
|
425
|
+
// refusal the caller wants; the caller raises its own typed error on the false.
|
|
426
|
+
try {
|
|
427
|
+
ka = nodeCrypto.createPublicKey({ key: a, format: "der", type: "spki" });
|
|
428
|
+
kb = nodeCrypto.createPublicKey({ key: bb, format: "der", type: "spki" });
|
|
429
|
+
} catch (_e) { return false; }
|
|
430
|
+
return _keyEquals(ka, kb) === true;
|
|
431
|
+
}
|
|
432
|
+
|
|
405
433
|
return {
|
|
406
434
|
E: E, code: code, KU_BIT: KU_BIT,
|
|
407
435
|
encodeName: encodeName, isEmptyName: isEmptyName, encodeGeneralName: encodeGeneralName,
|
|
@@ -413,6 +441,7 @@ function makeBuilder(ctx) {
|
|
|
413
441
|
spkiKeyId: spkiKeyId, skiKeyId: skiKeyId,
|
|
414
442
|
reqDer: reqDer, assertValidSpki: assertValidSpki, assertValidExtension: assertValidExtension,
|
|
415
443
|
certLikeFromSpki: certLikeFromSpki, assertSignatureVerifies: assertSignatureVerifies,
|
|
444
|
+
samePublicKey: samePublicKey,
|
|
416
445
|
};
|
|
417
446
|
}
|
|
418
447
|
|
package/package.json
CHANGED
package/sbom.cdx.json
CHANGED
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
"$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json",
|
|
3
3
|
"bomFormat": "CycloneDX",
|
|
4
4
|
"specVersion": "1.5",
|
|
5
|
-
"serialNumber": "urn:uuid:
|
|
5
|
+
"serialNumber": "urn:uuid:119ff1fc-7d17-4f0b-8f84-06c75f1e6ac1",
|
|
6
6
|
"version": 1,
|
|
7
7
|
"metadata": {
|
|
8
|
-
"timestamp": "2026-08-
|
|
8
|
+
"timestamp": "2026-08-21T13:36:35.267Z",
|
|
9
9
|
"lifecycles": [
|
|
10
10
|
{
|
|
11
11
|
"phase": "build"
|
|
@@ -19,14 +19,14 @@
|
|
|
19
19
|
}
|
|
20
20
|
],
|
|
21
21
|
"component": {
|
|
22
|
-
"bom-ref": "@blamejs/pki@0.5.
|
|
22
|
+
"bom-ref": "@blamejs/pki@0.5.25",
|
|
23
23
|
"type": "application",
|
|
24
24
|
"name": "pki",
|
|
25
|
-
"version": "0.5.
|
|
25
|
+
"version": "0.5.25",
|
|
26
26
|
"scope": "required",
|
|
27
27
|
"author": "blamejs contributors",
|
|
28
28
|
"description": "Pure-JavaScript PKI toolkit that owns its stack — X.509, ASN.1/DER, CMS, PQC-first.",
|
|
29
|
-
"purl": "pkg:npm/%40blamejs/pki@0.5.
|
|
29
|
+
"purl": "pkg:npm/%40blamejs/pki@0.5.25",
|
|
30
30
|
"properties": [],
|
|
31
31
|
"externalReferences": [
|
|
32
32
|
{
|
|
@@ -54,7 +54,7 @@
|
|
|
54
54
|
"components": [],
|
|
55
55
|
"dependencies": [
|
|
56
56
|
{
|
|
57
|
-
"ref": "@blamejs/pki@0.5.
|
|
57
|
+
"ref": "@blamejs/pki@0.5.25",
|
|
58
58
|
"dependsOn": []
|
|
59
59
|
}
|
|
60
60
|
]
|