@blamejs/pki 0.6.46 → 0.6.48
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 +28 -0
- package/README.md +2 -2
- package/lib/cmc-build.js +175 -4
- package/lib/cmc-verify.js +80 -19
- package/lib/cmp-session.js +422 -16
- package/lib/cmp-verify.js +2 -1
- package/lib/constants.js +2 -0
- package/package.json +1 -1
- package/sbom.cdx.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,34 @@ 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.6.48 — 2026-09-07
|
|
8
|
+
|
|
9
|
+
A CMC enrollment request can be authenticated by a shared secret instead of a signature.
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- pki.cmc.build(spec, { mac: { identifier, secret } }) carries a Full PKI Request in a CMS AuthenticatedData rather than a SignedData (RFC 5272 section 3.2). The recipient is the PasswordRecipientInfo that section requires, the MAC key is generated for the message, and the encapsulated content type stays id-cct-PKIData. The secret is taken as a string or as bytes. The request carries the identifier in an Identification control, since a PasswordRecipientInfo names no recipient and that control is what lets an authority holding secrets for many clients find the right one (RFC 5272 section 6.2.3). A name given anywhere else in the same request, through spec.identityProof.identity or an Identification control written into spec.controls, must be that same name: one request names one client, so a second name is refused rather than chosen between, and a control the caller already wrote is kept rather than duplicated. Because carrying that control also changes how an Identity Proof witness is derived, from the secret alone to the secret and the identity together (RFC 5272 section 6.2.3), a request that carries both derives the witness with the name it carries, whichever of the three places named it. A request also carries one secret: the one its MAC is keyed from and the one its Identity Proof is computed from are the same, and two different ones are refused. Naming a signature and a shared secret in the same call is refused: a request has one carrier, and a client with a key to sign with does not need the other. A renewal cannot use the shared-secret carrier at all, because a renewal carries no Identification or Identity Proof control and its identity comes instead from being signed with the certificate being renewed (RFC 5272 section 3.2(a)); a shared secret names no certificate, so that request would assert an identity by nothing. Every copy the toolkit makes of the secret and of the derived key is wiped once the message is built.
|
|
14
|
+
- The key is derived from the identifier encoded as UTF-8 followed by the shared secret (RFC 5272 section 3.2(c)), and pki.cmc.verify applies the same derivation to an opts.recipient given as { identifier, secret }. An implementation that derived the key itself still passes raw key material and is read as before. Deriving it in one place is what keeps a request this toolkit builds and a response it authenticates agreeing about the key: the secret alone is not it, and neither is the identifier alone.
|
|
15
|
+
|
|
16
|
+
### Changed
|
|
17
|
+
|
|
18
|
+
- An AuthenticatedData Full PKI Request this toolkit emits is read by OpenSSL: the interop suite checks that openssl cms accepts the message and that openssl names the AuthenticatedData carrier, the id-cct-PKIData content type and the password recipient's key-encryption algorithm from its own tables.
|
|
19
|
+
|
|
20
|
+
## v0.6.47 — 2026-09-06
|
|
21
|
+
|
|
22
|
+
A CMP enrollment left waiting can be picked up by a later process instead of started again.
|
|
23
|
+
|
|
24
|
+
### Added
|
|
25
|
+
|
|
26
|
+
- A pki.cmp.session poll-timeout verdict carries resumeToken, and session.resumePoll(token) continues that transaction in a later process. The authority's polling interval is waited out before the first resumed request, while the resuming session's own maxTotalWait still bounds it: a remainder longer than that budget times out immediately and hands the same due time on. A further timeout returns another token, so a wait can span any number of processes, and the polls each one spent accumulate across them. Each timeout reports the waiting status, whether or not that process read a certificate response of its own, so a wait split across processes reads the same as one held in a single process. The authority's own statusString and failInfo are not reproduced from the token, so a verdict never presents text as the authority's that it did not send in that exchange. A session that has already run a transaction refuses to resume one, since RFC 9810 section 5.1.1 gives each transaction its own identifier.
|
|
27
|
+
- The token is plain JSON, so it survives being written to disk and read back. It names the transaction identifier the exchange is keyed by, the nonce the next request must echo (RFC 9810 section 5.1.1), which request is being polled as a decimal string so an identifier of any width survives, the response arm its grant arrives on, whether the request that opened the transaction asked for implicit confirmation, the polls already spent, the public key the granted certificate must certify, the signer identity the first process authenticated and, separately, the certificate it currently verifies a response with when that response omits its extraCerts, the certificates the authority had already sent including any it delivered only on a waiting leg, and the instant its own checkAfter allows the next poll. It carries no secret, because the protection material, the trust anchors and the endpoint come from the session the caller builds to resume with.
|
|
28
|
+
- A resumed poll grants nothing the first process would not have accepted. It protection-verifies and nonce-binds every response before reading it, holds every response to the signer identity the token names, refuses a granted certificate that certifies a different key, and confirms the grant with the same certConf handshake. Those fields are what the resumed session holds the exchange to, so a token is integrity-sensitive and belongs in storage the caller controls: someone who can rewrite it can widen what the resumed session accepts, up to the limit of that session's own trust anchors and the authority's protection, which a rewritten token cannot reach past. Store it where the enrollment's own state is stored, and read it back into a session configured the way the first one was. The token carries what the transaction established and the session supplies the rest, so the protection material, the trust anchors, the endpoint and a sender pinned with opts.expectedSender are all given again: a resumed poll accepts and refuses exactly what an uninterrupted one in the same session would, which means it also refuses a response that session has no way to authenticate.
|
|
29
|
+
- A token that cannot carry the transaction is refused with cmp/bad-input before any request is sent, so stored state that cannot be used never spends the nonce the token is the only copy of. That covers a value that is not an object, one that names no transaction, a non-hex transaction identifier or non-canonical base64 nonce, a transaction identifier that is not the 128 bits a first message opens one with or a nonce shorter than the 128 bits a response must carry (RFC 9483 section 3.1 and 3.5), both of which name state no exchange could have produced, a request identifier written in any spelling other than the decimal one a session writes, a response arm that is not an enrollment arm, an unknown field, a key that is not a SubjectPublicKeyInfo, a field that names a certificate and is not one, and more certificates than the list it restores can hold. The two fields that bind the transaction are required rather than optional, since a token lives in storage where it can be edited and dropping a field must not drop the check it feeds: the key the grant is held to, and, for a signature session, the identity every response is held to. A shared-secret session pins no certificate, and its secret is the binding instead. The token also names how the transaction authenticates, and a session that authenticates the other way is refused: a signature transaction is bound by the pinned signer identity and a shared-secret one by the secret, so neither resumes the other's. A token trimmed of that field is read from its own contents, never from the session reading it, since a signature transaction pins the signer it authenticated and a shared-secret one has none to pin. How the grant is confirmed comes from the token rather than from the resuming session's own opts.implicitConfirm, since it was negotiated in the request the token continues: a session that never set the option still confirms an implicitly confirmed grant without a certConf, and one that sets it cannot make a transaction whose request never asked for it accept an implicit-confirm indication. A token that omits the field resumes as though the request asked for nothing. A token that asked for it is refused by a session carrying opts.acceptCert, the same pairing the constructor refuses, since an implicitly confirmed grant leaves no certConf leg for a policy to reject on.
|
|
30
|
+
|
|
31
|
+
### Changed
|
|
32
|
+
|
|
33
|
+
- pki.cmp.session refuses an opts.maxResponseBytes that is not a whole number of bytes between 1 and the 24 MiB transport ceiling, at construction, with cmp/bad-input. It is the bound the response reads and the restored certificate pools are measured against, and pki.acme.client already held the option to the same range. A session that passed a fractional or out-of-range value previously carried it as far as the first read.
|
|
34
|
+
|
|
7
35
|
## v0.6.46 — 2026-09-06
|
|
8
36
|
|
|
9
37
|
A Sigstore bundle can be checked against the certificate-transparency logs that recorded the signing certificate.
|
package/README.md
CHANGED
|
@@ -227,7 +227,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
|
|
|
227
227
|
| `pki.jose` | Flattened JWS (RFC 7515) and JWK thumbprints (RFC 7638). `sign` and `verify` run a Flattened JWS against declarative profiles (ACME outer, EAB inner, keyChange inner) that carry the required and forbidden header rules as data. `base64url` is the strict RFC 4648 §5 codec, rejecting padding, non-alphabet characters, and non-canonical trailing bits. `parseJson` is a bounded reader that refuses duplicate members at any depth. `thumbprint` is the RFC 7638 / 8037 / 9964 canonical digest. The algorithm registry binds each `alg` to its key type (ES/RS/PS/EdDSA/ML-DSA), leaving no code path for `alg:none`, an RS256→HS256 key confusion, or an all-zero ECDSA signature; `assertPublicJwk` refuses a JWK carrying private material, so an exported private key is never published. `opts.key` names the key a message must be signed under and governs: where the profile also permits an embedded header `jwk`, the two must be the same key — compared as RFC 7638 thumbprints, so member order cannot make equal keys differ — and a disagreement is refused rather than resolved in the message's favor. `keySource` reports which key answered, since a signature checked against a key you named is a different claim from one checked against the key the message carried — `sign`, `verify`, `base64url`, `parseJson`, `thumbprint`, `assertPublicJwk` |
|
|
228
228
|
| `pki.acme` | ACME (RFC 8555 / 8737 / 8738 / 9773). `client(directoryUrl, opts)` is a stateful client driving a live CA directory over `pki.transport`: `newAccount`, `newOrder`, `newAuthz`, `getOrder`, `getAuthorization`, `getChallenge`, `respondToChallenge`, `finalize`, `pollOrder`, `pollAuthorization`, and `downloadCertificate` walk the issuance flow, with `newAuthz` pre-authorizing a single identifier (§7.4.1) and `downloadCertificate` binding the issued certificate to the order — its key, its identifiers, or both; at least one is required by default and the result reports `boundToKey` / `boundToIdentifiers` — before choosing among alternate chains (`Link rel="alternate"`, §7.4.2, via a `selectChain` predicate bounded by `maxAlternates`). `revokeCert` (account-key or certificate-key signed), `keyChange`, `updateAccount` (change the account contacts, §7.3.2), `listOrders` (the account's orders list, following the §7.1.2.1 `Link rel="next"` pagination bounded by a page cap and confined to the orders origin), `deactivateAccount`, `deactivateAuthorization`, `renewalInfo` (ARI), `renewalWindow` (the RFC 9773 §4.2/4.3 renewal decision), and `scheduleRenewal` (the §4.1 auto-sleeping renewal loop that sleeps until the selected instant and refetches until it is time to renew, stopping at the certificate's notAfter) complete the lifecycle. Every URL is HTTPS only, an explicit trust anchor is required, each request carries a fresh single-use nonce with a bounded badNonce retry (and, when `opts.resignKeys` supplies caller-approved alternative account-key algorithms, a bounded RFC 8555 §6.2 badSignatureAlgorithm re-sign that the CA's advertised list can only filter, never widen, so it cannot force a weaker algorithm), reads are POST-as-GET, polling is bounded and sleeps on a Retry-After via an injectable sleeper capped by a poll count and a total-wait budget, and every response body is size-capped. The transport is injectable via `opts.transport`. Over the message layer it composes resource-object validators (closed status enums, conditional-required fields, unknown fields ignored), the three §7.1.6 state machines, the request builders (newAccount with External Account Binding, newOrder with `replaces`, finalize with a CSR identifier-set match and account-key-reuse rejection, challenge responses, deactivation, revokeCert in both key modes, the keyChange nested JWS, POST-as-GET), the http-01 / dns-01 / tls-alpn-01 challenge computations, the dns and ip identifier validators, and the ARI certID with serial sign-padding preserved — `client`, `validate`, `identify`, `assertTransition`, the builders, `keyAuthorization`, `http01`, `dns01`, `tlsAlpn01Extension`, `verifyTlsAlpn01`, `ariCertId` |
|
|
229
229
|
| `pki.schema.smime` | S/MIME ESS signed-attribute values (RFC 5035 / RFC 8551). `parseSigningCertificate` and `parseSigningCertificateV2` bind a signature to its signing certificate (cert hash, hash algorithm, issuer `GeneralNames` and serial); `parseSmimeCapabilities` decodes the ordered capability list; `decodeAttribute` dispatches a CMS attribute by OID, enforcing the single-value rule and deferring on unknown types. A companion decoder for CMS signed attributes rather than an auto-routed format — `parseSigningCertificate`, `parseSigningCertificateV2`, `parseSmimeCapabilities`, `decodeAttribute` |
|
|
230
|
-
| `pki.cmc` | Build and interpret CMC messages (RFC 5272). `build(spec, signer)` assembles a Full PKI Request across all three request arms (PKCS#10, CRMF, other) and signs it through `pki.cms.sign` under `id-cct-PKIData`. A PKCS#10 (`tcr`) request is verified against its own proof-of-possession before signing, so a request whose self-signature does not verify under its subject public key is refused rather than signed into a message a CA would reject. Body-part identifiers are unique across the whole message and never the reserved 0; a caller's clash is refused rather than renumbered, since a control may already reference it. An Identity Proof V2 witness is computed over the `reqSequence` bytes exactly as emitted (§6.2.1 step 1) rather than a re-serialization, a POP Link Witness is emitted only alongside the POP Link Random control §6.3.1.1 requires beside it, and a renewal carries neither Identification nor Identity Proof in either version. `verify(response, sent)` takes what the CA returned plus the state the client retained and reduces it to one terminal outcome: `issued`, `pending`, `confirm-required`, `pop-required`, or `rejected`. It binds the exchange first — Transaction Identifier, the Sender and Recipient Nonce echo compared in constant time and by full value so a truncation cannot match, and the Data Return echo — with each check applying only if the client sent that half, and, once sent, an absent or differing echo being a refusal, which is the replay defense. `bodyPartIDs` extends the same rule to what the response is about: a status reporting on a body part the request never sent is refused, which the transaction and nonce cannot catch, because a server can echo both correctly while answering about a different message. Several status controls are permitted and the worst governs, so a failure cannot hide behind an earlier success; the absence of any status control is success, per §6.1.2. The carrier's signature must verify (§3.2.1.3.4): a conforming SignedData carries its own signer certificate, so the ordinary build-then-verify flow needs nothing extra and the verdict reports `signatureVerified: true`. Where the signer is found nowhere the posture is fail-closed with a named opt-out — supply `certs` with the responder's certificate, or `allowUnverified: true`, in which case the verdict reports `signatureVerified: false`. Doing neither is refused, the opt-out never excuses a signature that is present and wrong, and a carrier with no signer at all is refused outright. The response's own `cmsSequence` and `otherMsgs` come back raw, since a request whose only arm was the other-message form has no certificate to return and §4.1 puts its answer there. Nothing is trusted: issued certificates are read from the CMS certificate bag (§4.2) and surfaced raw for `pki.path.validate`, and a Publish Trust Anchors control is surfaced with `trusted: false` rather than added to a store — `build`, `verify` |
|
|
230
|
+
| `pki.cmc` | Build and interpret CMC messages (RFC 5272). `build(spec, signer)` assembles a Full PKI Request across all three request arms (PKCS#10, CRMF, other) and carries it either way RFC 5272 §3.2 allows: `{ cert, key }` signs it, while `{ mac: { identifier, secret } }` authenticates it under a shared secret for a client that holds no key yet, using the PasswordRecipientInfo that section requires and deriving the key from the identifier followed by the secret. A signed request goes through `pki.cms.sign` under `id-cct-PKIData`. A PKCS#10 (`tcr`) request is verified against its own proof-of-possession before signing, so a request whose self-signature does not verify under its subject public key is refused rather than signed into a message a CA would reject. Body-part identifiers are unique across the whole message and never the reserved 0; a caller's clash is refused rather than renumbered, since a control may already reference it. An Identity Proof V2 witness is computed over the `reqSequence` bytes exactly as emitted (§6.2.1 step 1) rather than a re-serialization, a POP Link Witness is emitted only alongside the POP Link Random control §6.3.1.1 requires beside it, and a renewal carries neither Identification nor Identity Proof in either version. `verify(response, sent)` takes what the CA returned plus the state the client retained and reduces it to one terminal outcome: `issued`, `pending`, `confirm-required`, `pop-required`, or `rejected`. It binds the exchange first — Transaction Identifier, the Sender and Recipient Nonce echo compared in constant time and by full value so a truncation cannot match, and the Data Return echo — with each check applying only if the client sent that half, and, once sent, an absent or differing echo being a refusal, which is the replay defense. `bodyPartIDs` extends the same rule to what the response is about: a status reporting on a body part the request never sent is refused, which the transaction and nonce cannot catch, because a server can echo both correctly while answering about a different message. Several status controls are permitted and the worst governs, so a failure cannot hide behind an earlier success; the absence of any status control is success, per §6.1.2. The carrier's signature must verify (§3.2.1.3.4): a conforming SignedData carries its own signer certificate, so the ordinary build-then-verify flow needs nothing extra and the verdict reports `signatureVerified: true`. Where the signer is found nowhere the posture is fail-closed with a named opt-out — supply `certs` with the responder's certificate, or `allowUnverified: true`, in which case the verdict reports `signatureVerified: false`. Doing neither is refused, the opt-out never excuses a signature that is present and wrong, and a carrier with no signer at all is refused outright. The response's own `cmsSequence` and `otherMsgs` come back raw, since a request whose only arm was the other-message form has no certificate to return and §4.1 puts its answer there. Nothing is trusted: issued certificates are read from the CMS certificate bag (§4.2) and surfaced raw for `pki.path.validate`, and a Publish Trust Anchors control is surfaced with `trusted: false` rather than added to a store — `build`, `verify` |
|
|
231
231
|
| `pki.schema.cmc` | Decode CMC messages (RFC 5272 as updated by RFC 6402): a Full PKI Request (`PKIData`) or Full PKI Response (`PKIResponse`) riding inside a CMS SignedData, reached by the encapsulated content type (`id-cct-PKIData` / `id-cct-PKIResponse`). Controls are surfaced in wire order with their values raw, so an unrecognized one is data rather than a fault. Tagged requests decode across all three arms. The status verdicts (`CMCStatusInfo` v1 and `CMCStatusInfoV2`) are collected as an ordered list, and the RFC 6402 two-module `OtherStatusInfo` ambiguity — `pendInfo` and `extendedFailInfo` are both untagged SEQUENCEs in the 1988 module, told apart only by their first element — is resolved by inspection and refused when it cannot be told apart. Body-part identity is unique across the whole message rather than per sequence, 0 is reserved as the reference to the enclosing PKIData, and the `reqSequence` bytes are surfaced exactly as they appeared so an Identity Proof witness is computed over the wire bytes. A companion decoder for CMS content rather than an auto-routed format — `parse`, `parsePkiData`, `parsePkiResponse` |
|
|
232
232
|
| `pki.schema.engine` | The declarative ASN.1 structure-schema engine every format parser composes — `walk`, `encode`, `embeddedDer`, and the schema combinators |
|
|
233
233
|
| `pki.path` | Certification-path validation (RFC 5280 §6). `validate` runs the §6.1 state machine over an ordered path and a trust anchor: signature chaining across RSA, ECDSA, EdDSA, ML-DSA, SLH-DSA and hybrid composite ML-DSA (a composite is accepted only when both its post-quantum and traditional components verify), validity windows, name chaining, basic constraints and path length, key usage, name constraints, and the certificate-policy tree. It returns a structured verdict with per-check reason codes and enforces a `pki.trust` anchor's per-purpose distrust-after dates and delegator purposes through `checkPurpose` — an anchor that carries either one with no purpose named to select by is refused as a configuration fault rather than validated as though it carried none. The verdict says what was established. `revocationChecked` takes the weakest outcome on the path: `false` with no checker supplied, `"determined"` when every certificate got an explicit good or revoked answer, `"waived"` when `softFail` turned an undetermined one into a pass, and `"undetermined"` when one could not be answered at all — which includes a checker that throws, a fault `softFail` does not waive because `softFail` opts into an undetermined answer, not into a broken checker. `anchorConstraints` names the purpose the anchor was judged under and whether each of its two constraints applied. `crlChecker` supplies CRL-based revocation, covering partitioned and sharded CRLs, whose §6.3.3 Distribution Point ↔ IDP correspondence lets corresponding shards accumulate reason coverage until all eight revocation reasons are covered, and delta CRLs, merged onto the complete CRL they may be combined with (§5.2.4) so a held certificate its delta releases reads good, while a delta that merges with nothing still reports what it lists and still withholds good. `ocspChecker` supplies OCSP-based revocation (RFC 6960: CertID binding, responder authorization, signature, currency) over the same pluggable hook. `build(leaf, opts)` is the discovering complement (RFC 4158): from a leaf, an untrusted pool of candidate CA certificates, and a trust store, it finds the ordered leaf-to-anchor path `validate` accepts, using name chaining plus the RFC 4158 §3.5 sort hints (an AKI/SKI match, an anchor-adjacent issuer, CA plus keyCertSign, validity at the check time — ordering hints, never filters), a depth-first search with backtracking so the first accepted path wins, and a bounded search (chain-length cap, candidate-expansion cap, identity-tuple visited set) so a cross-certificate cycle or Bridge-CA fan-out terminates deterministically. Every accept flows through `validate`, and its verdict is cross-checked against `openssl verify`. Opt-in AIA `caIssuers` fetching (`opts.fetchAia: true`) discovers a missing intermediate from a certificate's Authority Information Access URL (§4.2.2.1) over `pki.transport`, triggered only on a pool miss and bounded against SSRF and amplification: HTTPS only, a total fetch budget that caps fetching silently rather than throwing, a per-cert URL cap, a build-wide URL dedupe, a response-size and certificate-count cap, no redirect following, and every fault a silent skip. The TLS trust (`opts.tls`) stays distinct from the PKI `trustAnchors`, and every fetched certificate remains untrusted pool material that still flows through `validate` (never a trust anchor). It is off by default, so the default build is byte-identical offline. An `opts.direction` of `"reverse"` searches from a trust anchor toward the leaf (RFC 4158 §3.1), narrower when the anchor set is small and the leaf's issuer options fan out, and `"auto"` picks the direction by first-hop fan-out; reverse building reuses the same pool, visited set, caps, and `validate` gate, so the direction changes only search order, and the anchor is excluded from the returned path. Reverse building is pool-only and does not combine with `fetchAia`. When `opts.userInitialPolicySet` names acceptable certificate-policy OIDs and more than one path validates, build returns the accepted path whose user-constrained policy set best satisfies that set (RFC 4158 §4) rather than the first accepted path, the ranking bounded by the same candidate cap and a malformed set refused with `path/bad-input`; an `anyPolicy` entry is unconstrained and returns the first accepted path. In a mesh of cross-certified domains, where many candidates chain by name to the same place, a candidate is ranked by how many leading relative distinguished names it shares with the name the search is heading for (§3.5.16 and the §3.5.19 reverse method), so a certificate in the target's own domain is tried before one from a cross-certified domain, and forward building sorts a candidate under every candidate that can complete the path when its path length constraint cannot cover the certificates already below it (§3.5.7), an ordering that outranks the other hints rather than competing with them. No candidate is removed and an unbounded search still reaches every path the pool holds; a bounded one spends `maxCandidatesConsidered` on whichever branches the order steers it to. Pure and re-entrant — `validate`, `build`, `crlChecker`, `ocspChecker` |
|
|
@@ -235,7 +235,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
|
|
|
235
235
|
| `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` |
|
|
236
236
|
| `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` |
|
|
237
237
|
| `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` |
|
|
238
|
-
| `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`, `krr` (key recovery, §5.3.7), `ccr` (cross-certification, §5.3.11: a `CertReqMessages` at the normative floor, where the requesting CA keeps its private key so a private-key-transport encryptedKey proof-of-possession is refused, and the optional App. D.6 single-request cardinality is not enforced), `p10cr`, `certConf`, `pollReq`, `genm`, `rr`, responder-side `ip`, `cp`, `kup`, `ccp`, `rp`, `genp`, `error`, `pollRep`, `krp`, `pkiconf`, and the registration-authority `nested` wrapper of complete PKIMessages (RFC 9810 §5.1.3.5). 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. A `p10cr` request's PKCS#10 proof-of-possession is verified before the message is protected, so one whose self-signature does not verify under its subject public key is refused rather than sent. `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 same session also drives the other two RFC 9483 operations under that shell: `revoke(request)` sends an `rr` naming a certificate as `{ certificate }` or `{ certDetails }` with an optional CRLReason `reason`, and returns `revoked` / `rejected` / `poll-timeout`; `info(request)` sends a `genm` for one of the four support messages — `{ caCerts }`, `{ rootCaCert }`, `{ certReqTemplate }`, `{ crlUpdate }` — and returns `answered` with the decoded `value` and a `present` flag, since an absent response value is how each says nothing is available. A session revokes its own certificate: the signature over the request is the proof of authorization (§4.2), so the named certificate must be `opts.cert` and a PBMAC1 session is refused. 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` |
|
|
238
|
+
| `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`, `krr` (key recovery, §5.3.7), `ccr` (cross-certification, §5.3.11: a `CertReqMessages` at the normative floor, where the requesting CA keeps its private key so a private-key-transport encryptedKey proof-of-possession is refused, and the optional App. D.6 single-request cardinality is not enforced), `p10cr`, `certConf`, `pollReq`, `genm`, `rr`, responder-side `ip`, `cp`, `kup`, `ccp`, `rp`, `genp`, `error`, `pollRep`, `krp`, `pkiconf`, and the registration-authority `nested` wrapper of complete PKIMessages (RFC 9810 §5.1.3.5). 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. A `p10cr` request's PKCS#10 proof-of-possession is verified before the message is protected, so one whose self-signature does not verify under its subject public key is refused rather than sent. `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 }`. A certification authority can take longer to answer than a process is held open, so a `poll-timeout` carries a `resumeToken` and `resumePoll(token)` continues the same transaction in a later process: the token is plain JSON naming the transaction, the nonce the next request echoes, the polled request and the arm its grant arrives on, and the key the grant must certify. It carries no secret and grants nothing, since the protection material and the endpoint come from the session built to resume with, and the resumed poll verifies, nonce-binds, and key-binds every response. Its fields are what the resumed exchange is held to, so store it where the enrollment's own state is stored: someone who can rewrite it can widen what the resumed session accepts, as far as that session's trust anchors and the authority's protection allow and no further. The same session also drives the other two RFC 9483 operations under that shell: `revoke(request)` sends an `rr` naming a certificate as `{ certificate }` or `{ certDetails }` with an optional CRLReason `reason`, and returns `revoked` / `rejected` / `poll-timeout`; `info(request)` sends a `genm` for one of the four support messages — `{ caCerts }`, `{ rootCaCert }`, `{ certReqTemplate }`, `{ crlUpdate }` — and returns `answered` with the decoded `value` and a `present` flag, since an absent response value is how each says nothing is available. A session revokes its own certificate: the signature over the request is the proof of authorization (§4.2), so the named certificate must be `opts.cert` and a PBMAC1 session is refused. 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` |
|
|
239
239
|
| `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` |
|
|
240
240
|
| `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` |
|
|
241
241
|
| `pki.pkcs12` | PKCS#12 (.p12/.pfx) issuance and reading (RFC 7292 / RFC 9579). `build(spec, opts)` assembles a store from the OpenSSL-style `{ key, cert, ca?, friendlyName?, localKeyId? }` or the full `{ safeContents: [...] }`, where each element is a plaintext or PBES2-encrypted `SafeContents` of key, shroudedKey, cert, crl, secret, or nested `safeContents` bags. Keys and certs are validated before wrapping, and `friendlyName` (BMPString) and `localKeyId` are single-value. Integrity is a classic Appendix B HMAC (the default, for maximum interoperability) or an RFC 9579 PBMAC1 (`opts.mac.algorithm`) over SHA-256/384/512, with shrouded keys and cert safes encrypted under RFC 8018 PBES2 (AES-128/192/256-CBC). Every password is encoded the PKCS#12 way — BMPString+NULL for the classic MAC, UTF-8 for the PBES2 bags and PBMAC1 — which is what OpenSSL and NSS consume, so a file it emits opens in both, cross-checked bidirectionally. The MAC covers the exact AuthenticatedSafe byte range, a DEFAULT-1 `MacData.iterations` is rejected up front, and the store is re-parsed before return. `verifyMac(pfx, password, opts)` recomputes a classic or PBMAC1 MAC over `macedBytes` and constant-time-compares it, throwing on a MAC-less or public-key-integrity store. Public-key integrity (`opts.integrity.mode: "public-key"`) wraps the AuthenticatedSafe in a CMS SignedData instead of a MAC, signed by any `pki.cms.sign` signer and carrying no MacData (§4); privacy stays independent, so `password` still PBES2-encrypts the bags. Public-key privacy wraps a SafeContents as a CMS EnvelopedData (AES-CBC, `id-envelopedData`, never GCM) encrypted to recipient public keys through the `pki.cms.encrypt` recipient model, via per-safe `recipients` or the `opts.recipientCerts` convenience, restricted to certificate recipients (RSA-OAEP, ECDH, X25519, X448, ML-KEM) since a password or KEK recipient could not be reopened by `open`. All four integrity-by-privacy combinations are permitted (§3.1). `open(pfx, password, opts)` reads a store back: it verifies the MAC first, so a wrong password is the MAC verdict rather than a decrypt error, then PBES2-decrypts every privacy safe and shrouded key bag and returns `{ integrityMode, macVerified, signers, keys, certs, crls, secrets }` — keys as re-validated PKCS#8 DER, certs, CRLs and secrets as raw DER, all with `friendlyName` and `localKeyId`, nested safes recursively. A MAC-less store is refused unless `opts.allowUnauthenticated`. A public-key-integrity store is verified through its CMS SignedData signature first (`pkcs12/signature-invalid` on failure), with the signer surfaced in `signers` but never trust-chained, which remains the caller's `pki.path.validate` step. A legacy-PBE store's Appendix C 3DES and RC2 bags are decrypted, RC2 through an in-tree RFC 2268 cipher, so an `openssl pkcs12 -legacy` or NSS store opens; the legacy RC4 schemes are refused. An `id-envelopedData` safe is decrypted with `opts.recipientKey` after the integrity gate (`pkcs12/no-recipient-key` when absent), every recipient-side fault and every post-integrity decrypt failure collapsing to the uniform `pkcs12/decrypt-failed`, and `opts.keys: 'crypto'` imports each key to a `CryptoKey`. It reads what OpenSSL and NSS produce. Returns DER or a PEM `PKCS12`, with a typed `Pkcs12Error` on failure. Parsing stays at `pki.schema.pkcs12.parse` — `build`, `verifyMac`, `open` |
|
package/lib/cmc-build.js
CHANGED
|
@@ -15,9 +15,14 @@ var crmf = require("./schema-crmf");
|
|
|
15
15
|
var cmcFmt = require("./schema-cmc");
|
|
16
16
|
var oid = require("./oid");
|
|
17
17
|
var cmsSign = require("./cms-sign");
|
|
18
|
+
var cmsEncrypt = require("./cms-encrypt");
|
|
18
19
|
var guard = require("./guard-all");
|
|
19
20
|
var intrinsic = require("./guard-intrinsic");
|
|
20
21
|
var _hasOwn = intrinsic.hasOwn;
|
|
22
|
+
var _isArray = intrinsic.isArray;
|
|
23
|
+
var _isBuffer = intrinsic.isBuffer;
|
|
24
|
+
var _bufferFrom = intrinsic.bufferFrom;
|
|
25
|
+
var _bufferConcat = intrinsic.bufferConcat;
|
|
21
26
|
var frameworkError = require("./framework-error");
|
|
22
27
|
|
|
23
28
|
var CmcError = frameworkError.CmcError;
|
|
@@ -100,6 +105,61 @@ var KNOWN_REQUEST_KEYS = intrinsic.assign(intrinsic.create(null), { tcr: 1, crm:
|
|
|
100
105
|
var KNOWN_CONTROL_KEYS = intrinsic.assign(intrinsic.create(null), { type: 1, value: 1 });
|
|
101
106
|
var KNOWN_IDENTITY_PROOF_KEYS = intrinsic.assign(intrinsic.create(null), { identity: 1, secret: 1 });
|
|
102
107
|
var KNOWN_POP_LINK_KEYS = intrinsic.assign(intrinsic.create(null), { secret: 1 });
|
|
108
|
+
var KNOWN_MAC_KEYS = intrinsic.assign(intrinsic.create(null), { identifier: 1, secret: 1 });
|
|
109
|
+
var KNOWN_MAC_CARRIER_KEYS = intrinsic.assign(intrinsic.create(null), { mac: 1 });
|
|
110
|
+
var UTF8_STRING_TAG = 12;
|
|
111
|
+
|
|
112
|
+
/** @internal Whether two caller-supplied secrets are the same secret, comparing the bytes each spells
|
|
113
|
+
* out so a string and the same bytes are not read as two different credentials. Compared in constant
|
|
114
|
+
* time: the two values come from one caller here, but the primitive is the one this toolkit compares
|
|
115
|
+
* secret-derived bytes with everywhere. */
|
|
116
|
+
function _sameSecret(a, byIdentity) {
|
|
117
|
+
var ab = null, bb = null;
|
|
118
|
+
try {
|
|
119
|
+
ab = _secretCopy(a, "the shared secret");
|
|
120
|
+
bb = _secretCopy(byIdentity, "the identityProof secret");
|
|
121
|
+
return ab !== null && bb !== null && ab.length === bb.length && guard.crypto.constantTimeEqual(ab, bb);
|
|
122
|
+
} finally {
|
|
123
|
+
/** @internal Both copies, on every exit: one input being unusable is the path that leaves the other
|
|
124
|
+
* one allocated, and a comparison that refuses is still a comparison that copied. */
|
|
125
|
+
var made = [];
|
|
126
|
+
if (ab) guard.list.append(made, ab);
|
|
127
|
+
if (bb) guard.list.append(made, bb);
|
|
128
|
+
if (made.length) guard.secret.zeroizeAll(made, CmcError, "cmc/bad-input", "the compared shared-secret copies");
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
function _secretCopy(v, what) {
|
|
132
|
+
if (typeof v === "string") return _bufferFrom(v, "utf8");
|
|
133
|
+
if (guard.bytes.isByteSource(v)) return guard.bytes.snapshotSource(v, CmcError, "cmc/bad-input", what);
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** @internal The key a shared-secret carrier derives its MAC key from: the identifier encoded as UTF-8
|
|
138
|
+
* followed by the shared secret (RFC 5272 sec. 3.2(c)). Both halves of the toolkit read this one
|
|
139
|
+
* function, so a request it builds and a message it authenticates derive the same bytes. The caller
|
|
140
|
+
* owns the returned buffer and wipes it. */
|
|
141
|
+
function macPassword(mac) {
|
|
142
|
+
if (!mac || typeof mac !== "object" || _isArray(mac) || _isBuffer(mac)) {
|
|
143
|
+
throw E("cmc/bad-input", "a shared-secret carrier is { identifier, secret } (RFC 5272 sec. 3.2)");
|
|
144
|
+
}
|
|
145
|
+
guard.identifier.assertKnownKeys(mac, KNOWN_MAC_KEYS, E, "cmc/bad-input", "unknown shared-secret field ");
|
|
146
|
+
if (typeof mac.identifier !== "string" || mac.identifier.length === 0) {
|
|
147
|
+
throw E("cmc/bad-input", "a shared-secret carrier needs the identifier the authority knows the client by, as a non-empty string (RFC 5272 sec. 3.2)");
|
|
148
|
+
}
|
|
149
|
+
if (typeof mac.secret !== "string" && !guard.bytes.isByteSource(mac.secret)) {
|
|
150
|
+
throw E("cmc/bad-input", "a shared-secret carrier needs the secret as a string or bytes (RFC 5272 sec. 3.2)");
|
|
151
|
+
}
|
|
152
|
+
var secretBytes = typeof mac.secret === "string" ? _bufferFrom(mac.secret, "utf8")
|
|
153
|
+
: guard.bytes.snapshotSource(mac.secret, CmcError, "cmc/bad-input", "the shared secret");
|
|
154
|
+
if (secretBytes.length === 0) {
|
|
155
|
+
guard.secret.zeroize(secretBytes, CmcError, "cmc/bad-input", "the shared secret");
|
|
156
|
+
throw E("cmc/bad-input", "a shared-secret carrier needs a non-empty secret (RFC 5272 sec. 3.2)");
|
|
157
|
+
}
|
|
158
|
+
var idBytes = _bufferFrom(mac.identifier, "utf8");
|
|
159
|
+
var joined = _bufferConcat([idBytes, secretBytes]);
|
|
160
|
+
guard.secret.zeroizeAll([idBytes, secretBytes], CmcError, "cmc/bad-input", "the shared-secret encoding");
|
|
161
|
+
return joined;
|
|
162
|
+
}
|
|
103
163
|
|
|
104
164
|
function fixedRequestId(req, index) {
|
|
105
165
|
if (!req || typeof req !== "object") throw E("cmc/bad-input", "each request must be an object");
|
|
@@ -373,7 +433,17 @@ async function _build(spec, signer, opts) {
|
|
|
373
433
|
"a renewal request carries no " + forbidden + " control (RFC 5272 sec. 3.2 (a))");
|
|
374
434
|
}
|
|
375
435
|
}
|
|
376
|
-
|
|
436
|
+
/** @internal A renewal carries no Identification or Identity Proof control because, in sec. 3.2(a)'s
|
|
437
|
+
* words, "the same information is provided by the use of an existing certificate from a CA when
|
|
438
|
+
* signing the PKI Request". A shared secret authenticates the message without naming any
|
|
439
|
+
* certificate, so a renewal carried that way would assert an identity by nothing at all. */
|
|
440
|
+
if (signer && typeof signer === "object" && !_isArray(signer) && signer.mac != null) {
|
|
441
|
+
throw E("cmc/bad-signer",
|
|
442
|
+
"a renewal request is signed with the certificate being renewed, which is what carries the " +
|
|
443
|
+
"original identity in place of the Identification and Identity Proof controls (RFC 5272 sec. 3.2 (a)); " +
|
|
444
|
+
"a shared secret names no certificate, so it cannot renew");
|
|
445
|
+
}
|
|
446
|
+
var renewalSigners = _isArray(signer) ? signer : [signer];
|
|
377
447
|
for (var si = 0; si < renewalSigners.length; si++) {
|
|
378
448
|
var rs = renewalSigners[si];
|
|
379
449
|
if (rs && rs.cert == null && rs.spki != null) {
|
|
@@ -385,6 +455,9 @@ async function _build(spec, signer, opts) {
|
|
|
385
455
|
}
|
|
386
456
|
|
|
387
457
|
var controls = [];
|
|
458
|
+
/** @internal The names a caller-written Identification control gives this client, collected as those
|
|
459
|
+
* controls are encoded so the name checked is the name carried (RFC 5272 sec. 6.2.3). */
|
|
460
|
+
var controlIdentifiers = [], controlIdentificationCount = 0, controlIdentifierUnreadable = false;
|
|
388
461
|
callerControls.forEach(function (c) {
|
|
389
462
|
if (!c || typeof c !== "object" || c.type == null || c.value == null) {
|
|
390
463
|
throw E("cmc/bad-input", "each control is { type, value }");
|
|
@@ -393,7 +466,26 @@ async function _build(spec, signer, opts) {
|
|
|
393
466
|
return "unknown field " + JSON.stringify(k) + " on a control -- a control is { type, value }, " +
|
|
394
467
|
"and its bodyPartID is allocated by the builder";
|
|
395
468
|
});
|
|
396
|
-
|
|
469
|
+
/** @internal Taken once. A control is a caller object, so reading `type` or `value` a second time
|
|
470
|
+
* can answer differently than it did here, and what this request is checked against has to be what
|
|
471
|
+
* it carries. The Identification name below is read off THESE bytes for the same reason. */
|
|
472
|
+
var controlType = _oidOf(c.type);
|
|
473
|
+
var controlValue = _der(c.value, "a control value");
|
|
474
|
+
if (controlType === OID_IDENTIFICATION) {
|
|
475
|
+
controlIdentificationCount += 1;
|
|
476
|
+
var idNode;
|
|
477
|
+
try { idNode = asn1.decode(controlValue); }
|
|
478
|
+
catch (_e) { controlIdentifierUnreadable = true; }
|
|
479
|
+
/** @internal The control is a UTF8String (RFC 5272 sec. 6.2.3). Another string type carrying the
|
|
480
|
+
* same characters is a different value on the wire, so it cannot stand in for the control this
|
|
481
|
+
* request needs while a strict authority refuses the message. */
|
|
482
|
+
if (idNode && idNode.tagClass === "universal" && idNode.tagNumber === UTF8_STRING_TAG) {
|
|
483
|
+
guard.list.append(controlIdentifiers, asn1.read.string(idNode));
|
|
484
|
+
} else {
|
|
485
|
+
controlIdentifierUnreadable = true;
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
controls.push(encodeControl(controlType, [controlValue], ids));
|
|
397
489
|
});
|
|
398
490
|
|
|
399
491
|
_assertNoDuplicateBinding(callerControls, spec);
|
|
@@ -410,6 +502,22 @@ async function _build(spec, signer, opts) {
|
|
|
410
502
|
[b.octetString(_der(spec.dataReturn, "spec.dataReturn"))], ids));
|
|
411
503
|
}
|
|
412
504
|
|
|
505
|
+
/** @internal The name the request gives the authority for this client, from whichever of the two
|
|
506
|
+
* places names it. Read before either control is emitted, so the pair can be compared. */
|
|
507
|
+
var macIdentifier = signer && typeof signer === "object" && !_isArray(signer) && signer.mac != null &&
|
|
508
|
+
typeof signer.mac === "object" && typeof signer.mac.identifier === "string" ? signer.mac.identifier : null;
|
|
509
|
+
var identityIdentifier = spec.identityProof && typeof spec.identityProof.identity === "string"
|
|
510
|
+
? spec.identityProof.identity : null;
|
|
511
|
+
|
|
512
|
+
/** @internal Settled BEFORE the Identity Proof witness is computed, because the presence of an
|
|
513
|
+
* Identification control changes how that witness is derived: with one, the hash is over the secret
|
|
514
|
+
* and the identity together rather than the secret alone (RFC 5272 sec. 6.2.3). A name reaching the
|
|
515
|
+
* request from anywhere therefore has to be known here, or the witness is derived one way and the
|
|
516
|
+
* request carries the control that demands the other. */
|
|
517
|
+
var carriedIdentity = identityIdentifier;
|
|
518
|
+
if (carriedIdentity == null && controlIdentifiers.length > 0) carriedIdentity = controlIdentifiers[0];
|
|
519
|
+
if (carriedIdentity == null) carriedIdentity = macIdentifier;
|
|
520
|
+
|
|
413
521
|
if (spec.identityProof) {
|
|
414
522
|
guard.identifier.assertKnownKeys(spec.identityProof, KNOWN_IDENTITY_PROOF_KEYS, E, "cmc/bad-input",
|
|
415
523
|
function (k) { return "unknown field " + JSON.stringify(k) + " on identityProof -- it is { secret, identity? }"; });
|
|
@@ -419,7 +527,49 @@ async function _build(spec, signer, opts) {
|
|
|
419
527
|
}
|
|
420
528
|
if (identity != null) controls.push(encodeControl(OID_IDENTIFICATION, [b.utf8(identity)], ids));
|
|
421
529
|
controls.push(encodeControl(OID_IDENTITY_PROOF_V2,
|
|
422
|
-
[identityProofV2(spec.identityProof.secret, reqSequenceBytes,
|
|
530
|
+
[identityProofV2(spec.identityProof.secret, reqSequenceBytes, carriedIdentity)], ids));
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
/** @internal A PasswordRecipientInfo names no recipient, so an authority holding secrets for many
|
|
534
|
+
* clients has nothing in the carrier to select one by. The Identification control is what carries
|
|
535
|
+
* that name: it "assists the server in locating the shared-secret" (RFC 5272 sec. 6.2.3), so a
|
|
536
|
+
* request authenticated by a secret says whose secret it is. Two names for one client is refused
|
|
537
|
+
* rather than picked between. */
|
|
538
|
+
if (macIdentifier != null) {
|
|
539
|
+
var named = [];
|
|
540
|
+
for (var nc = 0; nc < controlIdentifiers.length; nc++) guard.list.append(named, controlIdentifiers[nc]);
|
|
541
|
+
if (identityIdentifier != null) guard.list.append(named, identityIdentifier);
|
|
542
|
+
for (var ni = 0; ni < named.length; ni++) {
|
|
543
|
+
if (named[ni] !== macIdentifier) {
|
|
544
|
+
throw E("cmc/bad-input",
|
|
545
|
+
"the shared-secret identifier and the Identification the request already carries name the same " +
|
|
546
|
+
"client to the authority, so a request cannot carry two different ones (RFC 5272 sec. 6.2.3)");
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
if (controlIdentifierUnreadable) {
|
|
550
|
+
throw E("cmc/bad-input",
|
|
551
|
+
"the Identification control this request carries does not read as the UTF8String the client is " +
|
|
552
|
+
"named by, so it cannot be confirmed to name the client whose secret authenticates the request (RFC 5272 sec. 6.2.3)");
|
|
553
|
+
}
|
|
554
|
+
/** @internal One client, one shared secret. The carrier's MAC and an Identity Proof witness are both
|
|
555
|
+
* keyed from "the shared-secret" (RFC 5272 sec. 3.2 and 6.2.1), so two different ones would leave an
|
|
556
|
+
* authority able to check one and not the other, and unable to tell which credential is the client's. */
|
|
557
|
+
if (spec.identityProof && !_sameSecret(signer.mac.secret, spec.identityProof.secret)) {
|
|
558
|
+
throw E("cmc/bad-input",
|
|
559
|
+
"the shared secret that authenticates this request and the one its Identity Proof is computed " +
|
|
560
|
+
"from are the same secret, so a request cannot carry two different ones (RFC 5272 sec. 3.2 / 6.2.1)");
|
|
561
|
+
}
|
|
562
|
+
/** @internal One request names one client once. Two controls saying the same thing still leave an
|
|
563
|
+
* authority choosing between them, so the request carries exactly one however it was assembled. */
|
|
564
|
+
var alreadyNamed = controlIdentificationCount + (identityIdentifier == null ? 0 : 1);
|
|
565
|
+
if (alreadyNamed > 1) {
|
|
566
|
+
throw E("cmc/bad-input",
|
|
567
|
+
"a request names its client once, and this one carries " + alreadyNamed + " Identification controls " +
|
|
568
|
+
"(RFC 5272 sec. 6.2.3)");
|
|
569
|
+
}
|
|
570
|
+
if (alreadyNamed === 0) {
|
|
571
|
+
guard.list.append(controls, encodeControl(OID_IDENTIFICATION, [b.utf8(macIdentifier)], ids));
|
|
572
|
+
}
|
|
423
573
|
}
|
|
424
574
|
|
|
425
575
|
if (spec.popLink) {
|
|
@@ -450,6 +600,27 @@ async function _build(spec, signer, opts) {
|
|
|
450
600
|
(e && e.message ? e.message : "malformed"), e);
|
|
451
601
|
}
|
|
452
602
|
|
|
603
|
+
/** @internal RFC 5272 sec. 3.2 gives a Full PKI Request two carriers, and a request uses one: a
|
|
604
|
+
* SignedData signed by a key, or an AuthenticatedData whose MAC a shared secret keys. A client
|
|
605
|
+
* enrolling under a secret has no key to sign with, so naming both is a contradiction rather than a
|
|
606
|
+
* preference. */
|
|
607
|
+
if (signer && typeof signer === "object" && !_isArray(signer) && signer.mac != null) {
|
|
608
|
+
if (signer.key != null || signer.cert != null || signer.spki != null || signer.keyIdentifier != null) {
|
|
609
|
+
throw E("cmc/bad-input", "a request is carried by a signature or by a shared secret, not both (RFC 5272 sec. 3.2)");
|
|
610
|
+
}
|
|
611
|
+
guard.identifier.assertKnownKeys(signer, KNOWN_MAC_CARRIER_KEYS, E, "cmc/bad-input", "unknown shared-secret carrier field ");
|
|
612
|
+
var macBytes = macPassword(signer.mac);
|
|
613
|
+
try {
|
|
614
|
+
await _assertTcrPops(requests);
|
|
615
|
+
/** @internal The Password Recipient Info option, which sec. 3.2(a) requires, is what the CMS
|
|
616
|
+
* producer selects for a password recipient, and it generates the MAC key sec. 3.2(b) calls for. */
|
|
617
|
+
return await cmsEncrypt.authenticate(pkiData, [{ password: macBytes }],
|
|
618
|
+
{ contentType: "id-cct-PKIData", pem: opts.pem });
|
|
619
|
+
} finally {
|
|
620
|
+
guard.secret.zeroize(macBytes, CmcError, "cmc/bad-input", "the derived shared-secret key");
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
|
|
453
624
|
_assertKeyOnlySigner(signer, requests);
|
|
454
625
|
|
|
455
626
|
var ownedKeyBytes = [];
|
|
@@ -582,4 +753,4 @@ function _csrKeyIdentity(csrDer) {
|
|
|
582
753
|
return { ski: found, spki: (spki && spki.bytes) || null };
|
|
583
754
|
}
|
|
584
755
|
|
|
585
|
-
module.exports = { build: build };
|
|
756
|
+
module.exports = { build: build, macPassword: macPassword };
|
package/lib/cmc-verify.js
CHANGED
|
@@ -261,7 +261,9 @@ function _governingStatus(statuses, outcome) {
|
|
|
261
261
|
* - `dataReturn` (Buffer) -- the Data Return payload the request sent, echoed verbatim.
|
|
262
262
|
* - `certs` (Buffer[]) -- extra certificates for signer lookup, for a message that does not carry
|
|
263
263
|
* its own signer; the certificates the message carries are searched either way.
|
|
264
|
-
* - `recipient` (object) --
|
|
264
|
+
* - `recipient` (object) -- `{ identifier, secret }` for a response MACed under the shared secret
|
|
265
|
+
* the client enrolled with, which derives the key the way RFC 5272 sec. 3.2(c) states, or key
|
|
266
|
+
* material for an AuthenticatedData carrier, in the shape
|
|
265
267
|
* `pki.cms.decrypt` takes. Its MAC is then checked and the verdict reports
|
|
266
268
|
* `signatureVerified: true`; the content it authenticates is bound to the content the verdict
|
|
267
269
|
* was read from, so a MAC over other bytes cannot stand in for it.
|
|
@@ -288,14 +290,29 @@ function _governingStatus(statuses, outcome) {
|
|
|
288
290
|
* v.boundToRequest; // false: nothing ties this response to a request either
|
|
289
291
|
*/
|
|
290
292
|
function verify(response, sent) {
|
|
291
|
-
var frozenResponse, frozenSent;
|
|
293
|
+
var frozenResponse, frozenSent, ownedSecret = null;
|
|
294
|
+
/** @internal The options snapshot owns a copy of a byte-valued shared secret from the moment it is
|
|
295
|
+
* taken, so it is wiped when the verification settles however it settles: a malformed response, a
|
|
296
|
+
* carrier that never needed the secret, a refusal on the way to the MAC, and a failure in the rest
|
|
297
|
+
* of this prologue all reach here. A failure DURING the snapshot is cleared by the snapshot itself,
|
|
298
|
+
* which is the only place that can still reach a half-built copy. The caller's own buffer is theirs
|
|
299
|
+
* and is never touched. */
|
|
300
|
+
function _wipeOwnedSecret() {
|
|
301
|
+
if (ownedSecret) guard.secret.zeroize(ownedSecret, CmcError, "cmc/bad-input", "the shared-secret copy");
|
|
302
|
+
ownedSecret = null;
|
|
303
|
+
}
|
|
292
304
|
try {
|
|
293
305
|
frozenSent = _snapshotSent(_assertOpts(sent));
|
|
306
|
+
ownedSecret = frozenSent.recipient && guard.bytes.isByteSource(frozenSent.recipient.secret)
|
|
307
|
+
? frozenSent.recipient.secret : null;
|
|
294
308
|
frozenResponse = _snapshotIfBytes(response);
|
|
295
309
|
} catch (e) {
|
|
310
|
+
_wipeOwnedSecret();
|
|
296
311
|
return Promise.reject(e);
|
|
297
312
|
}
|
|
298
|
-
return guard.async.deferred(function () { return _verify(frozenResponse, frozenSent); })
|
|
313
|
+
return guard.async.deferred(function () { return _verify(frozenResponse, frozenSent); })
|
|
314
|
+
.then(function (v) { _wipeOwnedSecret(); return v; },
|
|
315
|
+
function (e) { _wipeOwnedSecret(); throw e; });
|
|
299
316
|
}
|
|
300
317
|
|
|
301
318
|
function _assertOpts(sent) {
|
|
@@ -330,18 +347,30 @@ function _snapshotSent(sent) {
|
|
|
330
347
|
if (Array.isArray(out.bodyPartPaths)) {
|
|
331
348
|
out.bodyPartPaths = out.bodyPartPaths.map(function (p) { return Array.isArray(p) ? p.slice() : p; });
|
|
332
349
|
}
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
350
|
+
/** @internal Once a copy of a shared secret exists, EVERYTHING that follows is protected, to the
|
|
351
|
+
* return: the remaining copies, the last option reads, all of it. A caller field is read through
|
|
352
|
+
* whatever accessor the caller wrote, so any of these steps can throw, and the copy would then be
|
|
353
|
+
* left behind with nothing holding it. Guarding one step at a time is what let three earlier
|
|
354
|
+
* versions of this each miss the next one. */
|
|
355
|
+
var takenSecret = null;
|
|
356
|
+
try {
|
|
357
|
+
if (out.recipient && typeof out.recipient === "object") {
|
|
358
|
+
var r = intrinsic.create(null), rk;
|
|
359
|
+
for (rk in out.recipient) {
|
|
360
|
+
if (!_hasOwn(out.recipient, rk)) continue;
|
|
361
|
+
r[rk] = _copyAnyBytes(out.recipient[rk]);
|
|
362
|
+
if (rk === "secret" && guard.bytes.isByteSource(r[rk])) takenSecret = r[rk];
|
|
363
|
+
}
|
|
364
|
+
out.recipient = r;
|
|
338
365
|
}
|
|
339
|
-
out.
|
|
366
|
+
if (Array.isArray(out.certs)) out.certs = out.certs.map(_copyAnyBytes);
|
|
367
|
+
out.allowUnverified = sent.allowUnverified === true;
|
|
368
|
+
out.allowUnbound = sent.allowUnbound === true;
|
|
369
|
+
return out;
|
|
370
|
+
} catch (e) {
|
|
371
|
+
if (takenSecret) guard.secret.zeroize(takenSecret, CmcError, "cmc/bad-input", "the shared-secret copy");
|
|
372
|
+
throw e;
|
|
340
373
|
}
|
|
341
|
-
if (Array.isArray(out.certs)) out.certs = out.certs.map(_copyAnyBytes);
|
|
342
|
-
out.allowUnverified = sent.allowUnverified === true;
|
|
343
|
-
out.allowUnbound = sent.allowUnbound === true;
|
|
344
|
-
return out;
|
|
345
374
|
}
|
|
346
375
|
|
|
347
376
|
function _verify(response, sent) {
|
|
@@ -368,10 +397,28 @@ function _assertAuthentic(body, sent, responseBytes) {
|
|
|
368
397
|
"authenticating an AuthenticatedData response needs the response as DER bytes or PEM, " +
|
|
369
398
|
"because its MAC is computed over them -- pass the encoded response rather than a parsed one");
|
|
370
399
|
}
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
400
|
+
/** @internal A caller naming the shared secret it enrolled with gets the sec. 3.2(c) derivation
|
|
401
|
+
* from the same function the producer uses, rather than deriving it again by hand. Raw key
|
|
402
|
+
* material is still taken as it was, which is what an implementation that derived the key
|
|
403
|
+
* itself supplies. */
|
|
404
|
+
var recipient = sent.recipient, derivedKey = null;
|
|
405
|
+
/** @internal The concatenation this derivation owns. The secret copy it was built from belongs
|
|
406
|
+
* to the options snapshot, which `verify` wipes when the verification settles. */
|
|
407
|
+
function _wipeDerived() {
|
|
408
|
+
if (derivedKey) guard.secret.zeroize(derivedKey, CmcError, "cmc/bad-input", "the derived shared-secret key");
|
|
409
|
+
derivedKey = null;
|
|
410
|
+
}
|
|
411
|
+
if (recipient && typeof recipient === "object" && recipient.mac == null &&
|
|
412
|
+
(recipient.identifier != null || recipient.secret != null) && recipient.password == null) {
|
|
413
|
+
derivedKey = cmcBuild.macPassword(recipient);
|
|
414
|
+
recipient = { password: derivedKey };
|
|
415
|
+
}
|
|
416
|
+
return cmsDecrypt.decrypt(responseBytes, recipient).then(function (r) { _wipeDerived(); return r; },
|
|
417
|
+
function (e) {
|
|
418
|
+
_wipeDerived();
|
|
419
|
+
throw E("cmc/unverified-response",
|
|
420
|
+
"the AuthenticatedData response did not authenticate under the supplied recipient key", e);
|
|
421
|
+
}).then(function (res) {
|
|
375
422
|
if (!res || res.authenticated !== true) {
|
|
376
423
|
throw E("cmc/unverified-response", "the AuthenticatedData response did not authenticate under the supplied recipient key");
|
|
377
424
|
}
|
|
@@ -470,7 +517,20 @@ function _shape(body, sent, signatureVerified, bound) {
|
|
|
470
517
|
* requests, each naming exactly one arm: `tcr` (a PKCS#10 CSR), `crm` (a CRMF CertReqMsg, or the
|
|
471
518
|
* CertReqMessages `pki.crmf.build` returns when it carries exactly one) or `orm`
|
|
472
519
|
* (`{ type, value }`). `spec.controls` are additional controls as `{ type, value }`, and `signer`
|
|
473
|
-
* is the `{ cert, key }` that signs the enclosing CMS SignedData.
|
|
520
|
+
* is the `{ cert, key }` that signs the enclosing CMS SignedData. RFC 5272 sec. 3.2 gives a Full PKI
|
|
521
|
+
* Request a second carrier for a client that has no key to sign with: pass
|
|
522
|
+
* `{ mac: { identifier, secret } }` in place of `{ cert, key }` and the request is an
|
|
523
|
+
* AuthenticatedData whose MAC the shared secret keys, through the PasswordRecipientInfo sec. 3.2(a)
|
|
524
|
+
* requires. The key is derived from the identifier encoded as UTF-8 followed by the secret
|
|
525
|
+
* (sec. 3.2(c)), which is the derivation `pki.cmc.verify` reads a `recipient` under, so a caller names
|
|
526
|
+
* what it enrolled with at both ends rather than concatenating by hand. The request also carries the
|
|
527
|
+
* identifier in an Identification control, because a PasswordRecipientInfo names no recipient and that
|
|
528
|
+
* control is what "assists the server in locating the shared-secret" (RFC 5272 sec. 6.2.3); supplying
|
|
529
|
+
* a different name through `spec.identityProof.identity` is refused rather than chosen between. Since
|
|
530
|
+
* carrying that control also changes how an Identity Proof witness is derived (sec. 6.2.3), a request
|
|
531
|
+
* carrying both derives the witness with the name it carries, and its MAC and its Identity Proof are
|
|
532
|
+
* keyed from one secret rather than two. Naming a signature and a shared secret together is refused,
|
|
533
|
+
* since a request has one carrier. A `tcr` request is verified against
|
|
474
534
|
* its own proof-of-possession first: a PKCS#10 whose self-signature does not verify under its subject
|
|
475
535
|
* public key is refused (`cmc/bad-popo`) rather than signed into a message a CA would reject.
|
|
476
536
|
*
|
|
@@ -511,6 +571,7 @@ function _shape(body, sent, signatureVerified, bound) {
|
|
|
511
571
|
* var req = await pki.cmc.build({ requests: [{ tcr: csr }] }, { cert: cert, key: key });
|
|
512
572
|
* pki.schema.cmc.parse(req).requests[0].arm; // "tcr"
|
|
513
573
|
*/
|
|
514
|
-
var
|
|
574
|
+
var cmcBuild = require("./cmc-build");
|
|
575
|
+
var build = cmcBuild.build;
|
|
515
576
|
|
|
516
577
|
module.exports = { verify: verify, build: build };
|
package/lib/cmp-session.js
CHANGED
|
@@ -49,6 +49,12 @@ var OID_KEY_USAGE = oid.byName("keyUsage");
|
|
|
49
49
|
var HASH_OID_TO_DIGEST = Object.create(null);
|
|
50
50
|
[["sha256", "SHA-256"], ["sha384", "SHA-384"], ["sha512", "SHA-512"]].forEach(function (row) { var o = oid.byName(row[0]); if (o) HASH_OID_TO_DIGEST[o] = row[1]; });
|
|
51
51
|
var COMPOSITE_PH_HASHALG = Object.assign(Object.create(null), { "SHA-256": "sha256", "SHA-384": "sha384", "SHA-512": "sha512" });
|
|
52
|
+
var RESUMABLE_ARMS = Object.assign(Object.create(null), { ip: 1, cp: 1, kup: 1 });
|
|
53
|
+
var RESUME_TOKEN_KEYS = Object.assign(Object.create(null), {
|
|
54
|
+
transactionId: 1, recipNonce: 1, certReqId: 1, arm: 1, polls: 1, requestedSpki: 1,
|
|
55
|
+
signer: 1, signerCache: 1, chain: 1, caPubs: 1, nextPollAt: 1, implicitConfirm: 1, protection: 1,
|
|
56
|
+
});
|
|
57
|
+
var RESUMABLE_PROTECTION = Object.assign(Object.create(null), { signature: 1, mac: 1 });
|
|
52
58
|
|
|
53
59
|
var KNOWN_SESSION_OPTS = Object.assign(Object.create(null), {
|
|
54
60
|
url: 1, key: 1, cert: 1, mac: 1, trustAnchors: 1, intermediates: 1, recipient: 1, sender: 1,
|
|
@@ -98,6 +104,16 @@ Object.keys(constants.NAMES.CRL_REASON).forEach(function (v) { CRL_REASON_NAMES[
|
|
|
98
104
|
|
|
99
105
|
function _isGranted(code) { return code === 0 || code === 1; }
|
|
100
106
|
var PKI_STATUS_NAMES = Object.assign(Object.create(null), { 0: "accepted", 1: "grantedWithMods", 2: "rejection", 3: "waiting" });
|
|
107
|
+
var PKI_STATUS_WAITING = 3;
|
|
108
|
+
/** @internal The status a transaction a token can continue is in, by construction: a token exists only
|
|
109
|
+
* because a response said waiting, and a poll that times out is still waiting. A process that read no
|
|
110
|
+
* CertResponse of its own reports this, so a wait split across processes reads the same as one held in a
|
|
111
|
+
* single process. The authority's own diagnostic strings are not reproduced from stored state, since a
|
|
112
|
+
* verdict must not present text the authority did not sign in this exchange as though it had. */
|
|
113
|
+
function _waitingStatus() {
|
|
114
|
+
return { status: { code: PKI_STATUS_WAITING, name: PKI_STATUS_NAMES[PKI_STATUS_WAITING] },
|
|
115
|
+
statusString: null, failInfo: null };
|
|
116
|
+
}
|
|
101
117
|
|
|
102
118
|
function _certReqIdEq(a, b) { return a != null && b != null && BigInt(a) === BigInt(b); }
|
|
103
119
|
|
|
@@ -125,8 +141,12 @@ function _certIdentity(cert) {
|
|
|
125
141
|
|
|
126
142
|
function _spkiKeyIdentity(spkiDer) {
|
|
127
143
|
var node = asn1.decode(spkiDer);
|
|
144
|
+
_expectSeq(node, 2, 2);
|
|
128
145
|
var algId = node.children[0];
|
|
146
|
+
_expectSeq(algId, 1, 2);
|
|
129
147
|
var algOid = asn1.read.oid(algId.children[0]);
|
|
148
|
+
var key = guard.crypto.assertOctetAligned(asn1.read.bitString(node.children[1]), _err,
|
|
149
|
+
"cmp/bad-input", "a SubjectPublicKeyInfo subjectPublicKey");
|
|
130
150
|
var pn = algId.children[1];
|
|
131
151
|
var params;
|
|
132
152
|
if (algOid === OID_RSA_ENCRYPTION) {
|
|
@@ -134,10 +154,40 @@ function _spkiKeyIdentity(spkiDer) {
|
|
|
134
154
|
} else {
|
|
135
155
|
params = pn ? pn.bytes.toString("latin1") : "";
|
|
136
156
|
}
|
|
137
|
-
return algOid + "|" + params + "|" +
|
|
157
|
+
return algOid + "|" + params + "|" + key.bytes.toString("latin1");
|
|
158
|
+
}
|
|
159
|
+
/** @internal A SubjectPublicKeyInfo and the AlgorithmIdentifier inside it are SEQUENCEs of a known
|
|
160
|
+
* width. Reading a child without asking for the shape reads whatever sits in that position, which is
|
|
161
|
+
* how DER that is not a public key at all is fingerprinted as one. */
|
|
162
|
+
function _expectSeq(node, min, max) {
|
|
163
|
+
if (node.tagClass !== "universal" || node.tagNumber !== 16 || !node.children ||
|
|
164
|
+
node.children.length < min || node.children.length > max) {
|
|
165
|
+
throw _err("cmp/bad-input", "a SubjectPublicKeyInfo is a SEQUENCE of an AlgorithmIdentifier and a BIT STRING (RFC 5280 sec. 4.1.2.7)");
|
|
166
|
+
}
|
|
138
167
|
}
|
|
139
168
|
function _isDerNull(pn) { return pn.tagClass === "universal" && pn.tagNumber === 5 && pn.content.length === 0; }
|
|
140
169
|
|
|
170
|
+
var CERT_MAX_BYTES = constants.LIMITS.DER_MAX_BYTES;
|
|
171
|
+
/** @internal The spelling `String(BigInt)` produces, and only that one: an optional leading minus
|
|
172
|
+
* (0x2d), then ASCII digits (0x30 to 0x39), with a leading zero only when the value is zero itself, so
|
|
173
|
+
* `007` and `-0` are refused along with every non-digit. */
|
|
174
|
+
function _isCanonicalDecimal(s) {
|
|
175
|
+
var i = s.charCodeAt(0) === CH_MINUS ? 1 : 0;
|
|
176
|
+
if (i >= s.length) return false;
|
|
177
|
+
for (var j = i; j < s.length; j++) {
|
|
178
|
+
var c = s.charCodeAt(j);
|
|
179
|
+
if (c < CH_ZERO || c > CH_NINE) return false;
|
|
180
|
+
}
|
|
181
|
+
var leadingZero = s.charCodeAt(i) === CH_ZERO;
|
|
182
|
+
if (leadingZero && s.length - i > 1) return false;
|
|
183
|
+
return !(leadingZero && i === 1);
|
|
184
|
+
}
|
|
185
|
+
var CH_MINUS = 0x2d, CH_ZERO = 0x30, CH_NINE = 0x39;
|
|
186
|
+
/** @internal A ceiling on the decimal string, not on the identifier: converting one to a BigInt costs
|
|
187
|
+
* more than linear time, so the length is bounded before the conversion runs. It sits above the widest
|
|
188
|
+
* identifier the codec encodes (an INTEGER of the maximum width takes about 2.41 digits per byte), and
|
|
189
|
+
* the encoder itself is what the door then holds the converted value to. */
|
|
190
|
+
var CERTREQID_MAX_DIGITS = constants.LIMITS.DER_MAX_INTEGER_BYTES * 3;
|
|
141
191
|
var MAX_EXTRA_CERTS = 32, MAX_EXTRA_SCAN = 256;
|
|
142
192
|
var CAPUBS_MAX = 2 * MAX_EXTRA_CERTS;
|
|
143
193
|
var SESSION_MAX_INTERMEDIATES = constants.LIMITS.PATH_BUILD_MAX_CANDIDATES - CAPUBS_MAX - MAX_EXTRA_CERTS;
|
|
@@ -229,11 +279,42 @@ function _certConfHash(certDer) {
|
|
|
229
279
|
* confirms it (`certConf` -> `pkiConf`, unless an `implicitConfirm` was granted). A verified `rejection` /
|
|
230
280
|
* `error` or a poll-budget timeout is a terminal typed verdict the caller reads (`outcome`:
|
|
231
281
|
* `issued` / `rejected` / `poll-timeout`); a tampered / unverifiable / desynchronized response is a
|
|
232
|
-
* hard-stop `CmpError` throw.
|
|
282
|
+
* hard-stop `CmpError` throw.
|
|
283
|
+
*
|
|
284
|
+
* A certification authority can take longer to answer than a process is held open, so a `poll-timeout`
|
|
285
|
+
* carries a `resumeToken` and `session.resumePoll(token)` continues the same transaction in a later
|
|
286
|
+
* one. The token is plain JSON: the transaction identifier, the nonce the next request must echo, the
|
|
287
|
+
* polled request identifier (a decimal string, so an identifier of any width survives) and the arm its
|
|
288
|
+
* grant arrives on, whether the request that opened the transaction asked for implicit confirmation,
|
|
289
|
+
* how the transaction authenticates, the polls already spent, the key the grant must certify, the signer identity the
|
|
290
|
+
* first process authenticated and, separately, the certificate it currently verifies a response with
|
|
291
|
+
* when that response omits its extraCerts, the certificates the authority had already sent, and the
|
|
292
|
+
* instant its own `checkAfter` allows the next poll. It carries no secret, because the protection material and the
|
|
293
|
+
* endpoint come from the session built to resume with, and it grants nothing: the resumed poll verifies
|
|
294
|
+
* and nonce-binds every response, holds it to the signer identity the token names, and holds the grant to
|
|
295
|
+
* the key the token names. Those fields are what the exchange is held to, so the token is
|
|
296
|
+
* integrity-sensitive: someone who can rewrite it can widen what the resumed session accepts, as far as
|
|
297
|
+
* that session's trust anchors and the authority's protection allow and no further. Store it the way the
|
|
298
|
+
* enrollment's own state is stored, and resume it in a session configured the way the first one was: the
|
|
299
|
+
* token carries what the transaction established, and the protection material, the trust anchors, the
|
|
300
|
+
* endpoint and an `expectedSender` pin are given again, so a resumed poll accepts and refuses exactly
|
|
301
|
+
* what an uninterrupted one in the same session would. The authority's polling interval is waited out
|
|
302
|
+
* before the first resumed request, while this session's own `maxTotalWait` still bounds it: a
|
|
303
|
+
* remainder longer than the budget times out now and hands the same due time on. A further timeout
|
|
304
|
+
* hands back a token again, so a wait can span any number of processes, and each timeout reports the
|
|
305
|
+
* waiting status whether or not that process read a CertResponse of its own. The authority's own
|
|
306
|
+
* diagnostic strings are not reproduced from the token, so a verdict never presents text as the
|
|
307
|
+
* authority's that it did not send in that exchange. A token is refused before a
|
|
308
|
+
* request is sent when it is mis-shaped, when the key it names is not a `SubjectPublicKeyInfo`, when a
|
|
309
|
+
* field that names a certificate is not one, or when it carries more certificates than the list it
|
|
310
|
+
* restores is built under. The two fields that bind the transaction are required rather than
|
|
311
|
+
* optional, since a token lives in storage where it can be edited and dropping a field must not drop
|
|
312
|
+
* the check it feeds: the key the grant is held to, and, for a signature session, the identity every
|
|
313
|
+
* response is held to. A shared-secret session pins no certificate, and its secret is the binding. Exactly one protection flavor: `{ key, cert }` (signature) XOR `{ mac }`
|
|
233
314
|
* (PBMAC1). A crypto-valid response is not enough: the signer must chain to a supplied trust anchor
|
|
234
315
|
* (signature) or the shared secret must match (MAC); a valid-but-untrusted response is a hard stop, so the
|
|
235
316
|
* signature flavor REQUIRES `opts.trustAnchors` at construction. Returns a session with `enroll(request)`,
|
|
236
|
-
* `revoke(request)`, `info(request)`,
|
|
317
|
+
* `resumePoll(token)`, `revoke(request)`, `info(request)`,
|
|
237
318
|
* and read-only `transactionID` + `transcript` (each leg's request/response bytes, retained up to a
|
|
238
319
|
* transaction-wide cap; a later leg beyond the cap keeps its metadata + `byteLength` but drops the payload as
|
|
239
320
|
* `bytes: null, truncated: true`, so a padded-response flood across polls cannot exhaust memory). The granted certificate must be valid X.509, carry the key
|
|
@@ -361,11 +442,11 @@ function session(opts) {
|
|
|
361
442
|
var maxTotalWait = guard.limits.cap(opts.maxTotalWait, "opts.maxTotalWait", DEFAULT_MAX_TOTAL_WAIT, { E: _err, code: "cmp/bad-input", min: 0, max: retryAfter.MAX_RETRY_AFTER_SECONDS });
|
|
362
443
|
var sleep = opts.sleep || sleepUtil.sleep;
|
|
363
444
|
|
|
364
|
-
var transactionID = Buffer.from(webcrypto.webcrypto.getRandomValues(new Uint8Array(
|
|
445
|
+
var transactionID = Buffer.from(webcrypto.webcrypto.getRandomValues(new Uint8Array(constants.LIMITS.CMP_TRANSACTION_ID_BYTES)));
|
|
365
446
|
var lastPeerNonce = null;
|
|
366
447
|
var haveResponse = false;
|
|
367
448
|
var cachedSignerCert = null;
|
|
368
|
-
var pinnedSignerCert = null, signerPinned = false;
|
|
449
|
+
var pinnedSignerCert = null, pinnedSignerDer = null, signerPinned = false;
|
|
369
450
|
var cachedChain = [];
|
|
370
451
|
var caPubsAccum = [];
|
|
371
452
|
var caPubsSeen = Object.create(null);
|
|
@@ -377,12 +458,32 @@ function session(opts) {
|
|
|
377
458
|
var expectedInfoOp = null;
|
|
378
459
|
var crlQuery = null;
|
|
379
460
|
var requestedSpki = null;
|
|
461
|
+
/** @internal What the request asked for, not what this session was configured with. A resumed poll
|
|
462
|
+
* finishes a transaction whose confirmation was negotiated in a request an earlier process sent, so
|
|
463
|
+
* the grant is confirmed the way that request asked and not the way this session's options read. */
|
|
464
|
+
var requestedImplicitConfirm = opts.implicitConfirm === true;
|
|
380
465
|
var inFlight = false, completed = false, started = false;
|
|
381
466
|
var transcript = [];
|
|
382
467
|
var transcriptBytes = 0;
|
|
383
|
-
|
|
468
|
+
/** @internal The response size is a bound the token decode and the certificate pools are measured
|
|
469
|
+
* against, so it is checked here rather than at the first transfer: a value that is not a positive
|
|
470
|
+
* whole number of bytes is refused where it is supplied, not carried into whatever reads it first. */
|
|
471
|
+
var _perRespCap = opts.maxResponseBytes == null ? constants.LIMITS.HTTP_MAX_RESPONSE_BYTES
|
|
472
|
+
: guard.limits.cap(opts.maxResponseBytes, "opts.maxResponseBytes", constants.LIMITS.HTTP_MAX_RESPONSE_BYTES,
|
|
473
|
+
{ E: _err, code: "cmp/bad-input", min: 1, max: constants.LIMITS.HTTP_MAX_RESPONSE_BYTES });
|
|
384
474
|
var transcriptCap = _perRespCap * TRANSCRIPT_RETAIN_RESPONSES;
|
|
385
475
|
var caPubsByteBudget = _perRespCap * TRANSCRIPT_RETAIN_RESPONSES;
|
|
476
|
+
/** @internal What a restored token's certificates are held to, which is what the list it restores can
|
|
477
|
+
* hold. Every bound below is a module constant or the response size, which `guard.limits.cap` has
|
|
478
|
+
* already refused unless it is a positive whole number, so none can arrive unusable. The authority's
|
|
479
|
+
* own pool arrives in responses, so it keeps both the response size and the
|
|
480
|
+
* total the session accumulates under. The chain that validates the signer is also built from
|
|
481
|
+
* `opts.intermediates`, whose certificates never crossed the wire and are bounded only by the path
|
|
482
|
+
* length and the codec, so those two are its bounds and it carries no third one: a session holds a
|
|
483
|
+
* caller's intermediates at that same size already, and a total below the two would refuse a token
|
|
484
|
+
* the session itself issued. */
|
|
485
|
+
var CAPUBS_LIMIT = { count: CAPUBS_MAX, each: _perRespCap, total: caPubsByteBudget };
|
|
486
|
+
var CHAIN_LIMIT = { count: constants.LIMITS.PATH_MAX_CERTS, each: CERT_MAX_BYTES, total: null };
|
|
386
487
|
|
|
387
488
|
var NULL_DN = { directoryName: [] };
|
|
388
489
|
var defaultSender = NULL_DN;
|
|
@@ -443,7 +544,7 @@ function session(opts) {
|
|
|
443
544
|
|
|
444
545
|
async function _send(bodySpec, arm) {
|
|
445
546
|
var fresh = Buffer.from(webcrypto.webcrypto.getRandomValues(new Uint8Array(16)));
|
|
446
|
-
var header = Object.assign(_baseHeader(fresh), ENROLL_ARMS[arm] &&
|
|
547
|
+
var header = Object.assign(_baseHeader(fresh), ENROLL_ARMS[arm] && requestedImplicitConfirm ? { generalInfo: [{ infoType: "implicitConfirm" }] } : {});
|
|
447
548
|
var reqDer = await cmp.build({ header: header, body: bodySpec }, _buildOpts());
|
|
448
549
|
_recordTranscript({ direction: "out", arm: arm, bytes: reqDer });
|
|
449
550
|
var engaged = false;
|
|
@@ -476,7 +577,7 @@ function session(opts) {
|
|
|
476
577
|
if (_expectedSenderCert && !cmp.senderBoundToCert(verdict.header.sender, _expectedSenderCert)) {
|
|
477
578
|
throw _err("cmp/untrusted-signer", "the response signer does not match the expected CA identity (opts.expectedSender) -- refusing a response from a different trusted signer", null);
|
|
478
579
|
}
|
|
479
|
-
if (!signerPinned) { pinnedSignerCert = x509.parse(verdict.signer.cert); signerPinned = true; }
|
|
580
|
+
if (!signerPinned) { pinnedSignerCert = x509.parse(verdict.signer.cert); pinnedSignerDer = Buffer.from(verdict.signer.cert); signerPinned = true; }
|
|
480
581
|
else if (!cmp.senderBoundToCert(verdict.header.sender, pinnedSignerCert)) {
|
|
481
582
|
throw _err("cmp/untrusted-signer", "the response signer identity changed mid-transaction -- a different trusted signer, not a same-identity certificate rotation; the transaction is NOT advanced", null);
|
|
482
583
|
}
|
|
@@ -610,6 +711,60 @@ function session(opts) {
|
|
|
610
711
|
return c;
|
|
611
712
|
});
|
|
612
713
|
}
|
|
714
|
+
/** @internal What a later process needs to carry THIS transaction on: the identifier the exchange is
|
|
715
|
+
* keyed by, the nonce the next request must echo, which request is being polled and on which arm its
|
|
716
|
+
* grant will arrive, and the key the grant must certify (RFC 9810 sec. 5.1.1). Plain JSON values, since
|
|
717
|
+
* it crosses a process boundary. Everything else, the protection material and the endpoint, comes from
|
|
718
|
+
* the session the caller builds to resume with, so the token carries no secret. */
|
|
719
|
+
/** @internal The instant an outstanding checkAfter falls due, or null when the authority named none. */
|
|
720
|
+
function _pollDueAt(dueInSeconds) {
|
|
721
|
+
if (typeof dueInSeconds !== "number" || !isFinite(dueInSeconds) || dueInSeconds <= 0) return null;
|
|
722
|
+
return guard.time.instantOf(new Date()) + constants.TIME.seconds(dueInSeconds);
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
function _resumeToken(polls, nextPollAt) {
|
|
726
|
+
/** @internal Only an enrollment reaches here, and only after a response, so the nonce to echo is the
|
|
727
|
+
* one thing that could still be missing: a responder that omitted its senderNonce leaves the chain
|
|
728
|
+
* unable to continue, and a token that cannot be continued is not offered. */
|
|
729
|
+
if (!Buffer.isBuffer(lastPeerNonce) || lastPeerNonce.length === 0) return null;
|
|
730
|
+
/** @internal Two different certificates: the identity pinned on the FIRST response, which every
|
|
731
|
+
* later response is bound to, and the one currently used to verify when a response omits its
|
|
732
|
+
* extraCerts. A same-identity rotation moves the second and never the first, so collapsing them
|
|
733
|
+
* would let a restart accept an identity the uninterrupted transaction refuses. */
|
|
734
|
+
var pinDer = pinnedSignerDer;
|
|
735
|
+
return {
|
|
736
|
+
transactionId: transactionID.toString("hex"),
|
|
737
|
+
recipNonce: lastPeerNonce.toString("base64"),
|
|
738
|
+
/** @internal A request identifier is an INTEGER of any width, so it travels as a decimal string:
|
|
739
|
+
* a BigInt is not JSON, and a token that cannot be serialized is not a resumable one. */
|
|
740
|
+
certReqId: activeCertReqId.toString(),
|
|
741
|
+
arm: expectedRespArm,
|
|
742
|
+
polls: polls,
|
|
743
|
+
/** @internal Negotiated in the request this token continues, so it travels with the transaction:
|
|
744
|
+
* a later process confirms the grant the way that request asked, whatever its own options say. */
|
|
745
|
+
implicitConfirm: requestedImplicitConfirm,
|
|
746
|
+
/** @internal How the exchange authenticates. The signer identity below is only a binding under
|
|
747
|
+
* signature protection; under a shared secret the secret is the binding, so a session resuming
|
|
748
|
+
* this transaction has to authenticate it the way the transaction already does. */
|
|
749
|
+
protection: isSig ? "signature" : "mac",
|
|
750
|
+
requestedSpki: requestedSpki ? Buffer.from(requestedSpki).toString("base64") : null,
|
|
751
|
+
/** @internal The identity the first process pinned on the first response it verified. Restoring it
|
|
752
|
+
* is what keeps a restart from admitting a DIFFERENT trusted signer, which an uninterrupted
|
|
753
|
+
* transaction refuses (RFC 9483 sec. 3.1), and it carries the certificate a responder that sent
|
|
754
|
+
* its chain only once would not send again. */
|
|
755
|
+
signer: pinDer ? Buffer.from(pinDer).toString("base64") : null,
|
|
756
|
+
signerCache: cachedSignerCert != null ? Buffer.from(cachedSignerCert).toString("base64") : null,
|
|
757
|
+
chain: cachedChain.map(function (c) { return Buffer.from(c).toString("base64"); }),
|
|
758
|
+
/** @internal An authority may deliver the issued certificate's intermediate in a WAITING response
|
|
759
|
+
* and omit it from the grant, so the certificates accumulated before the timeout travel too, or
|
|
760
|
+
* the resumed grant would fail a validation the uninterrupted transaction passes. */
|
|
761
|
+
caPubs: caPubsAccum.map(function (c) { return Buffer.from(c).toString("base64"); }),
|
|
762
|
+
/** @internal The instant the authority's own checkAfter allows the next poll. Resuming earlier
|
|
763
|
+
* would poll faster than it asked to be polled. */
|
|
764
|
+
nextPollAt: nextPollAt != null ? nextPollAt : null,
|
|
765
|
+
};
|
|
766
|
+
}
|
|
767
|
+
|
|
613
768
|
function _terminal(outcome, extra) {
|
|
614
769
|
return guard.verdict.of({
|
|
615
770
|
outcome: outcome, certificate: null, chain: [], status: null, trusted: true,
|
|
@@ -618,8 +773,8 @@ function session(opts) {
|
|
|
618
773
|
}, extra);
|
|
619
774
|
}
|
|
620
775
|
|
|
621
|
-
async function _pollLoop(lastWaitingResp) {
|
|
622
|
-
var polls = 0, waited = 0, lastStatus = _statusOf(lastWaitingResp);
|
|
776
|
+
async function _pollLoop(lastWaitingResp, alreadyWaited) {
|
|
777
|
+
var polls = 0, waited = alreadyWaited || 0, lastStatus = _statusOf(lastWaitingResp);
|
|
623
778
|
for (;;) {
|
|
624
779
|
if (polls >= maxPolls || waited > maxTotalWait) return { timeout: true, polls: polls, status: lastStatus };
|
|
625
780
|
var verdict = await _send({ pollReq: [{ certReqId: activeCertReqId }] }, "pollReq");
|
|
@@ -632,8 +787,11 @@ function session(opts) {
|
|
|
632
787
|
if (!entry) return { done: { state: "unexpected", reason: "a pollRep carried no entry for certReqId " + activeCertReqId }, polls: polls, header: verdict.header };
|
|
633
788
|
var checkAfter = typeof entry.checkAfter === "number" ? entry.checkAfter : 0;
|
|
634
789
|
waited += checkAfter;
|
|
635
|
-
|
|
636
|
-
|
|
790
|
+
/** @internal The authority asked to be polled again after `checkAfter`, and the budget ran out
|
|
791
|
+
* before that wait was taken. Reporting it lets a resumed poll honor the interval rather than
|
|
792
|
+
* poll immediately in a new process. */
|
|
793
|
+
if (waited > maxTotalWait) return { timeout: true, polls: polls, status: lastStatus, dueIn: checkAfter };
|
|
794
|
+
if (polls >= maxPolls) return { timeout: true, polls: polls, status: lastStatus, dueIn: checkAfter };
|
|
637
795
|
await sleep(checkAfter * constants.TIME.seconds(1));
|
|
638
796
|
continue;
|
|
639
797
|
}
|
|
@@ -643,7 +801,7 @@ function session(opts) {
|
|
|
643
801
|
}
|
|
644
802
|
|
|
645
803
|
async function _confirm(certDer, header, info) {
|
|
646
|
-
if (
|
|
804
|
+
if (requestedImplicitConfirm && _implicitConfirmGranted(header)) return { confirmed: true, implicit: true };
|
|
647
805
|
var accept = true;
|
|
648
806
|
if (typeof opts.acceptCert === "function") accept = (await opts.acceptCert(Buffer.from(certDer), info)) === true;
|
|
649
807
|
var h = _certConfHash(certDer);
|
|
@@ -664,8 +822,13 @@ function session(opts) {
|
|
|
664
822
|
var parsed;
|
|
665
823
|
try { parsed = x509.parse(cert); }
|
|
666
824
|
catch (e) { throw _err("cmp/bad-cert-response", "the granted CertResponse's certificate is not a valid X.509 certificate", e); }
|
|
667
|
-
if (requestedSpki != null
|
|
668
|
-
|
|
825
|
+
if (requestedSpki != null) {
|
|
826
|
+
var granted, wanted;
|
|
827
|
+
try { granted = _spkiKeyIdentity(parsed.subjectPublicKeyInfo.bytes); wanted = _spkiKeyIdentity(requestedSpki); }
|
|
828
|
+
catch (e) { throw _err("cmp/bad-cert-response", "the issued certificate's public key cannot be compared with the requested key", e); }
|
|
829
|
+
if (granted !== wanted) {
|
|
830
|
+
throw _err("cmp/bad-cert-response", "the issued certificate's public key does not match the requested key -- a misrouted certificate the caller has no private key for");
|
|
831
|
+
}
|
|
669
832
|
}
|
|
670
833
|
return cert;
|
|
671
834
|
}
|
|
@@ -780,7 +943,7 @@ function session(opts) {
|
|
|
780
943
|
if (t.state === "waiting") {
|
|
781
944
|
var polled = await _pollLoop(t.resp);
|
|
782
945
|
pollCount = polled.polls;
|
|
783
|
-
if (polled.timeout) return _terminal("poll-timeout", { status: polled.status, polls: pollCount });
|
|
946
|
+
if (polled.timeout) return _terminal("poll-timeout", { status: polled.status, polls: pollCount, resumeToken: _resumeToken(pollCount, _pollDueAt(polled.dueIn)) });
|
|
784
947
|
t = polled.done;
|
|
785
948
|
grantHeader = polled.header;
|
|
786
949
|
t.polls = pollCount;
|
|
@@ -794,6 +957,248 @@ function session(opts) {
|
|
|
794
957
|
}
|
|
795
958
|
}
|
|
796
959
|
|
|
960
|
+
/** @internal The state a poll-timeout handed the caller, read back. It is the caller's own record of
|
|
961
|
+
* a transaction it started, so it says WHICH exchange to continue, never who may continue it: the
|
|
962
|
+
* protection material and the endpoint come from this session, every response is verified the way the
|
|
963
|
+
* first process verified them, and the grant is still bound to the key the token names. */
|
|
964
|
+
function _readResumeToken(token) {
|
|
965
|
+
if (token === null || typeof token !== "object" || Array.isArray(token)) {
|
|
966
|
+
throw _err("cmp/bad-input", "resumePoll expects the resumeToken a poll-timeout verdict carried");
|
|
967
|
+
}
|
|
968
|
+
guard.identifier.assertKnownKeys(token, RESUME_TOKEN_KEYS, _err, "cmp/bad-input", "the resumeToken has an unknown field ");
|
|
969
|
+
/** @internal Every field is taken once, here, and the checks below run on what was taken. A token is
|
|
970
|
+
* any object a caller hands in, so a field read a second time can answer differently than it did when
|
|
971
|
+
* it was checked, and the restored state would carry the second answer past the check. */
|
|
972
|
+
var raw = {
|
|
973
|
+
transactionId: token.transactionId, recipNonce: token.recipNonce, certReqId: token.certReqId,
|
|
974
|
+
arm: token.arm, polls: token.polls, requestedSpki: token.requestedSpki, signer: token.signer,
|
|
975
|
+
signerCache: token.signerCache, chain: token.chain, caPubs: token.caPubs,
|
|
976
|
+
nextPollAt: token.nextPollAt, implicitConfirm: token.implicitConfirm,
|
|
977
|
+
protection: token.protection,
|
|
978
|
+
};
|
|
979
|
+
var txn = _hexField(raw.transactionId, "transactionId");
|
|
980
|
+
/** @internal The width a first message opens a transaction with (RFC 9483 sec. 3.1), which is the
|
|
981
|
+
* width this session writes, so a token naming any other names a transaction it cannot have opened. */
|
|
982
|
+
if (txn.length !== constants.LIMITS.CMP_TRANSACTION_ID_BYTES) {
|
|
983
|
+
throw _err("cmp/bad-input", "the resumeToken transactionId must name the transaction to continue, as the " + constants.LIMITS.CMP_TRANSACTION_ID_BYTES + " bytes a first message opens one with (RFC 9483 sec. 3.1)");
|
|
984
|
+
}
|
|
985
|
+
var nonce = _b64Field(raw.recipNonce, "recipNonce");
|
|
986
|
+
/** @internal The same floor a received message is held to, so a nonce no response could have carried
|
|
987
|
+
* is refused here rather than echoed into a request that cannot continue the chain. */
|
|
988
|
+
if (nonce.length < constants.LIMITS.CMP_MIN_NONCE_BYTES) {
|
|
989
|
+
throw _err("cmp/bad-input", "the resumeToken recipNonce must carry the nonce the next request echoes, at least " + constants.LIMITS.CMP_MIN_NONCE_BYTES + " bytes of it (RFC 9483 sec. 3.5)");
|
|
990
|
+
}
|
|
991
|
+
/** @internal A decimal string, so an identifier of any width a request can carry survives the round
|
|
992
|
+
* trip, including the PKCS#10 sentinel (-1, which names the whole message rather than one request).
|
|
993
|
+
* The reader accepts every identifier an enrollment can put in a token: it names which response to
|
|
994
|
+
* match, and the grant is bound by the nonce, the protection, the signer and the key. */
|
|
995
|
+
var certReqId;
|
|
996
|
+
if (typeof raw.certReqId !== "string" || raw.certReqId.length === 0 || raw.certReqId.length > CERTREQID_MAX_DIGITS) {
|
|
997
|
+
throw _err("cmp/bad-input", "the resumeToken certReqId must be a decimal string identifying the polled request, of at most " + CERTREQID_MAX_DIGITS + " characters");
|
|
998
|
+
}
|
|
999
|
+
/** @internal `BigInt` also reads a hexadecimal, binary or octal literal, a leading plus and
|
|
1000
|
+
* surrounding whitespace, none of which a token carries: the identifier is written the way the
|
|
1001
|
+
* emitting session writes it, so anything else names a different request than it appears to. */
|
|
1002
|
+
if (!_isCanonicalDecimal(raw.certReqId)) {
|
|
1003
|
+
throw _err("cmp/bad-input", "the resumeToken certReqId must be written as the emitting session writes it, in decimal with no sign but a leading minus, no leading zero and no surrounding space");
|
|
1004
|
+
}
|
|
1005
|
+
try { certReqId = BigInt(raw.certReqId); }
|
|
1006
|
+
catch (_e) { throw _err("cmp/bad-input", "the resumeToken certReqId must be a decimal string identifying the polled request"); }
|
|
1007
|
+
/** @internal The identifier is encoded again on the next request, so the door asks the encoder what
|
|
1008
|
+
* it accepts rather than approximating it from a digit count: a width the encoder refuses would
|
|
1009
|
+
* otherwise pass here and fail after the restored state had already consumed the session. */
|
|
1010
|
+
try { asn1.build.integer(certReqId); }
|
|
1011
|
+
catch (e) { throw _err("cmp/bad-input", "the resumeToken certReqId is wider than a CertReqMsg request identifier can encode", e); }
|
|
1012
|
+
var arm = raw.arm;
|
|
1013
|
+
if (typeof arm !== "string" || RESUMABLE_ARMS[arm] !== 1) {
|
|
1014
|
+
throw _err("cmp/bad-input", "the resumeToken arm must be an enrollment response arm (ip, cp or kup), got " + guard.text.showValue(arm));
|
|
1015
|
+
}
|
|
1016
|
+
var polls = raw.polls;
|
|
1017
|
+
if (polls != null && (!Number.isInteger(polls) || polls < 0)) {
|
|
1018
|
+
throw _err("cmp/bad-input", "the resumeToken polls must be a non-negative integer count of the polls already spent");
|
|
1019
|
+
}
|
|
1020
|
+
/** @internal A token is state a caller stored, and storage is where it can be edited. Dropping a
|
|
1021
|
+
* field must not drop the check that field feeds, so the two that bind the transaction are required:
|
|
1022
|
+
* the key the grant is held to, and, for a signature session, the identity every response is held
|
|
1023
|
+
* to. A shared-secret session pins no certificate, and its secret is the binding instead. */
|
|
1024
|
+
if (raw.requestedSpki == null) {
|
|
1025
|
+
throw _err("cmp/bad-input", "the resumeToken requestedSpki must name the key the granted certificate certifies -- without it the grant would be bound to nothing");
|
|
1026
|
+
}
|
|
1027
|
+
var spki = _b64Field(raw.requestedSpki, "requestedSpki", CERT_MAX_BYTES);
|
|
1028
|
+
/** @internal Read at the door, not when the grant arrives: stored state that is not a public key
|
|
1029
|
+
* would otherwise advance the exchange with the authority before it was found to be unusable. */
|
|
1030
|
+
try { _spkiKeyIdentity(spki); }
|
|
1031
|
+
catch (e) { throw _err("cmp/bad-input", "the resumeToken requestedSpki is not a SubjectPublicKeyInfo", e); }
|
|
1032
|
+
var signer = null;
|
|
1033
|
+
if (raw.signer != null) signer = _certField(raw.signer, "signer", CERT_MAX_BYTES);
|
|
1034
|
+
else if (isSig) {
|
|
1035
|
+
throw _err("cmp/bad-input", "the resumeToken signer must name the identity the transaction authenticated -- without it a resumed response from a different trusted signer would be accepted (RFC 9483 sec. 3.1)");
|
|
1036
|
+
}
|
|
1037
|
+
var signerCache = null;
|
|
1038
|
+
if (raw.signerCache != null) signerCache = _certField(raw.signerCache, "signerCache", CERT_MAX_BYTES);
|
|
1039
|
+
var chain = _certListField(raw.chain, "chain", CHAIN_LIMIT);
|
|
1040
|
+
var caPubs = _certListField(raw.caPubs, "caPubs", CAPUBS_LIMIT);
|
|
1041
|
+
/** @internal How the transaction authenticates is fixed by the request that opened it, and the two
|
|
1042
|
+
* flavors bind a response differently: under signature protection the pinned signer identity is the
|
|
1043
|
+
* binding, and under a shared secret the secret is. A session that authenticates the other way would
|
|
1044
|
+
* carry the transaction on under a binding it never had, so it is refused rather than adapted to.
|
|
1045
|
+
* A token trimmed of the field is read from its own contents rather than from this session, since
|
|
1046
|
+
* taking it from the session would let either flavor answer for the other: a signature transaction
|
|
1047
|
+
* pins the signer it authenticated, and a shared-secret one has none to pin. */
|
|
1048
|
+
var protection = raw.protection == null ? (raw.signer != null ? "signature" : "mac") : raw.protection;
|
|
1049
|
+
if (typeof protection !== "string" || RESUMABLE_PROTECTION[protection] !== 1) {
|
|
1050
|
+
throw _err("cmp/bad-input", "the resumeToken protection must name how the transaction authenticates, either signature or mac, got " + guard.text.showValue(raw.protection));
|
|
1051
|
+
}
|
|
1052
|
+
if ((protection === "signature") !== isSig) {
|
|
1053
|
+
throw _err("cmp/bad-input", "the resumeToken continues a transaction protected by " + protection + ", so it cannot be resumed by a session protected by " + (isSig ? "signature" : "mac") + " (RFC 9483 sec. 3.1 binds a transaction to how its sender authenticates)");
|
|
1054
|
+
}
|
|
1055
|
+
/** @internal Read from the token, never from this session's option, since it is what the request
|
|
1056
|
+
* that opened the transaction asked for. A token that omits it resumes as though the request asked
|
|
1057
|
+
* for nothing, which sends a certConf the authority may already have made unnecessary but never
|
|
1058
|
+
* accepts an implicit confirmation the request did not solicit. */
|
|
1059
|
+
var implicitConfirm = raw.implicitConfirm == null ? false : raw.implicitConfirm;
|
|
1060
|
+
if (typeof implicitConfirm !== "boolean") {
|
|
1061
|
+
throw _err("cmp/bad-input", "the resumeToken implicitConfirm must be a boolean saying whether the request that opened this transaction asked for implicit confirmation");
|
|
1062
|
+
}
|
|
1063
|
+
/** @internal The same pairing the constructor refuses, refused again where the token can reintroduce
|
|
1064
|
+
* it: an implicitly confirmed grant has no certConf leg, so a policy that vets one would never run. */
|
|
1065
|
+
if (implicitConfirm === true && typeof opts.acceptCert === "function") {
|
|
1066
|
+
throw _err("cmp/bad-input", "the resumeToken continues a transaction that asked for implicit confirmation, which leaves no certConf leg for opts.acceptCert to reject on -- resume it with a session that vets no grant");
|
|
1067
|
+
}
|
|
1068
|
+
var nextPollAt = raw.nextPollAt;
|
|
1069
|
+
if (nextPollAt != null && (typeof nextPollAt !== "number" || !isFinite(nextPollAt) || nextPollAt < 0)) {
|
|
1070
|
+
throw _err("cmp/bad-input", "the resumeToken nextPollAt must be the instant the next poll is due, in milliseconds since the epoch");
|
|
1071
|
+
}
|
|
1072
|
+
return { transactionID: txn, recipNonce: nonce, certReqId: certReqId, arm: arm,
|
|
1073
|
+
implicitConfirm: implicitConfirm,
|
|
1074
|
+
polls: polls || 0, requestedSpki: spki, signer: signer, signerCache: signerCache,
|
|
1075
|
+
chain: chain, caPubs: caPubs,
|
|
1076
|
+
nextPollAt: nextPollAt != null ? nextPollAt : null };
|
|
1077
|
+
}
|
|
1078
|
+
|
|
1079
|
+
/** @internal The token crosses a process boundary as text, so each field is decoded through the
|
|
1080
|
+
* canonical readers, which refuse a non-alphabet character, a short group and a re-encoding that does
|
|
1081
|
+
* not reproduce the input, and cap the size before allocating. */
|
|
1082
|
+
function _hexField(v, name) {
|
|
1083
|
+
return guard.encoding.hex(v, _perRespCap, _err, "cmp/bad-input", "the resumeToken " + name);
|
|
1084
|
+
}
|
|
1085
|
+
|
|
1086
|
+
function _b64Field(v, name, cap) {
|
|
1087
|
+
return guard.encoding.base64(v, cap || _perRespCap, _err, "cmp/bad-input", "the resumeToken " + name);
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
/** @internal A certificate the token carries. Parsed at the door, not when it is first needed: stored
|
|
1091
|
+
* bytes that are not a certificate would otherwise advance the exchange with the authority, spending a
|
|
1092
|
+
* nonce the token cannot be used again after, before they were found to be unusable. The cap is the
|
|
1093
|
+
* one the bytes were admitted under. A response-borne certificate is held to the response size, while
|
|
1094
|
+
* the signer identity and the chain that validates it can be a certificate the caller supplied through
|
|
1095
|
+
* `opts.intermediates`, which never crossed the wire and is bounded by the codec instead. */
|
|
1096
|
+
function _certField(v, name, cap) {
|
|
1097
|
+
var der = _b64Field(v, name, cap);
|
|
1098
|
+
try { x509.parse(der); }
|
|
1099
|
+
catch (e) { throw _err("cmp/bad-input", "the resumeToken " + name + " is not a certificate", e); }
|
|
1100
|
+
return der;
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
/** @internal A list of certificates the token carries, held to the count and the total size the list it
|
|
1104
|
+
* restores is built under, so a token cannot hand a resumed transaction a larger pool than the
|
|
1105
|
+
* transaction itself could reach. */
|
|
1106
|
+
function _certListField(v, name, limit) {
|
|
1107
|
+
if (v == null) return [];
|
|
1108
|
+
if (!Array.isArray(v)) throw _err("cmp/bad-input", "the resumeToken " + name + " must be an array of base64 certificates");
|
|
1109
|
+
if (v.length > limit.count) throw _err("cmp/bad-input", "the resumeToken " + name + " carries more than the " + limit.count + " certificates a transaction holds");
|
|
1110
|
+
var out = [], total = 0;
|
|
1111
|
+
for (var i = 0; i < v.length; i++) {
|
|
1112
|
+
var der = _certField(v[i], name + "[" + i + "]", limit.each);
|
|
1113
|
+
total += der.length;
|
|
1114
|
+
if (limit.total !== null && total > limit.total) {
|
|
1115
|
+
throw _err("cmp/bad-input", "the resumeToken " + name + " exceeds the " + limit.total + "-byte pool a transaction holds");
|
|
1116
|
+
}
|
|
1117
|
+
out.push(der);
|
|
1118
|
+
}
|
|
1119
|
+
return out;
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
/** @internal Continue polling a transaction an earlier process started, and finish it the way that
|
|
1123
|
+
* process would have: the grant is confirmed, bound to the requested key, and returned as the same
|
|
1124
|
+
* verdict `enroll` returns. A further timeout hands back a token again, so a long wait can span any
|
|
1125
|
+
* number of processes. */
|
|
1126
|
+
async function resumePoll(token) {
|
|
1127
|
+
_assertFresh("resumed poll");
|
|
1128
|
+
var t = _readResumeToken(token);
|
|
1129
|
+
inFlight = true;
|
|
1130
|
+
try {
|
|
1131
|
+
txnKind = "enroll";
|
|
1132
|
+
/** @internal Installing the restored state consumes the session, whether or not a request follows:
|
|
1133
|
+
* this session now holds another transaction's identifier and nonce, and a later enroll on it would
|
|
1134
|
+
* open a new enrollment under them (RFC 9810 sec. 5.1.1 gives each transaction its own identifier). */
|
|
1135
|
+
started = true;
|
|
1136
|
+
transactionID = t.transactionID;
|
|
1137
|
+
lastPeerNonce = t.recipNonce;
|
|
1138
|
+
haveResponse = true;
|
|
1139
|
+
activeCertReqId = t.certReqId;
|
|
1140
|
+
expectedRespArm = t.arm;
|
|
1141
|
+
requestedSpki = t.requestedSpki;
|
|
1142
|
+
requestedImplicitConfirm = t.implicitConfirm;
|
|
1143
|
+
/** @internal Restoring the pinned identity is what makes a restart no weaker than staying in one
|
|
1144
|
+
* process: the resumed responses are held to the signer the first process authenticated, and the
|
|
1145
|
+
* certificates it had already been sent are available to verify them with. */
|
|
1146
|
+
if (t.signer != null) {
|
|
1147
|
+
try { pinnedSignerCert = x509.parse(t.signer); pinnedSignerDer = t.signer; signerPinned = true; }
|
|
1148
|
+
catch (e) { throw _err("cmp/bad-input", "the resumeToken signer is not a valid X.509 certificate", e); }
|
|
1149
|
+
}
|
|
1150
|
+
/** @internal The pin and the cache are separate state and stay separate here. The pin says which
|
|
1151
|
+
* identity every response is held to; the cache is the certificate the first process had actually
|
|
1152
|
+
* been sent to verify one with, and a token that names no cache is a transaction that had none, so
|
|
1153
|
+
* standing the pin in for it would let a resumed poll read a response, and validate a grant, that
|
|
1154
|
+
* the same exchange in one process refuses. */
|
|
1155
|
+
cachedSignerCert = t.signerCache;
|
|
1156
|
+
cachedChain = t.chain;
|
|
1157
|
+
/** @internal The certificates the earlier process was sent, restored under the same bookkeeping the
|
|
1158
|
+
* session accumulates with, so the pool stays bounded across the restart. */
|
|
1159
|
+
for (var ci = 0; ci < t.caPubs.length; ci++) {
|
|
1160
|
+
var pub = t.caPubs[ci];
|
|
1161
|
+
var pk = pub.toString("base64");
|
|
1162
|
+
if (caPubsSeen[pk]) continue;
|
|
1163
|
+
caPubsSeen[pk] = true;
|
|
1164
|
+
caPubsBytes += pub.length;
|
|
1165
|
+
guard.list.append(caPubsAccum, pub);
|
|
1166
|
+
}
|
|
1167
|
+
/** @internal Every restored certificate arrived on a waiting leg, so it is evictable the same way:
|
|
1168
|
+
* leaving the count at zero would stop the grant's own issuer displacing one when the pool is full. */
|
|
1169
|
+
caPubsWaitingCount = caPubsAccum.length;
|
|
1170
|
+
/** @internal The authority's own interval is honored, but the CALLER's wait budget still bounds
|
|
1171
|
+
* this process: a remainder longer than the budget is a timeout now, carrying the same due time on
|
|
1172
|
+
* so a later process with more room can still wait it out. */
|
|
1173
|
+
var restWaited = 0;
|
|
1174
|
+
if (t.nextPollAt != null) {
|
|
1175
|
+
var waitMs = t.nextPollAt - guard.time.instantOf(new Date());
|
|
1176
|
+
if (waitMs > 0) {
|
|
1177
|
+
var waitSeconds = Math.ceil(waitMs / constants.TIME.seconds(1));
|
|
1178
|
+
if (waitSeconds > maxTotalWait) {
|
|
1179
|
+
return _terminal("poll-timeout", { status: _waitingStatus(), polls: t.polls, resumeToken: _resumeToken(t.polls, t.nextPollAt) });
|
|
1180
|
+
}
|
|
1181
|
+
await sleep(waitMs);
|
|
1182
|
+
restWaited = waitSeconds;
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
var polled = await _pollLoop(null, restWaited);
|
|
1186
|
+
var spent = t.polls + polled.polls;
|
|
1187
|
+
if (polled.timeout) return _terminal("poll-timeout", { status: polled.status || _waitingStatus(), polls: spent, resumeToken: _resumeToken(spent, _pollDueAt(polled.dueIn)) });
|
|
1188
|
+
var done = polled.done;
|
|
1189
|
+
if (done.state === "granted") {
|
|
1190
|
+
var r = await _finish({ resp: done.resp, polls: spent, code: done.code }, polled.header);
|
|
1191
|
+
r.polls = spent;
|
|
1192
|
+
return r;
|
|
1193
|
+
}
|
|
1194
|
+
if (done.state === "rejected") return _terminal("rejected", { status: done.status || _statusOf(done.resp), polls: spent });
|
|
1195
|
+
throw _err("cmp/unexpected-arm", done.reason || "the resumed enrollment reached an unexpected state");
|
|
1196
|
+
} finally {
|
|
1197
|
+
inFlight = false;
|
|
1198
|
+
completed = started;
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
1201
|
+
|
|
797
1202
|
function _assertRevokingOwnCertificate(certTemplateDer) {
|
|
798
1203
|
var own;
|
|
799
1204
|
try {
|
|
@@ -1123,6 +1528,7 @@ function session(opts) {
|
|
|
1123
1528
|
|
|
1124
1529
|
return {
|
|
1125
1530
|
enroll: enroll,
|
|
1531
|
+
resumePoll: resumePoll,
|
|
1126
1532
|
revoke: revoke,
|
|
1127
1533
|
info: info,
|
|
1128
1534
|
get transactionID() { return Buffer.from(transactionID); },
|
package/lib/cmp-verify.js
CHANGED
|
@@ -349,7 +349,8 @@ function _headerChecks(m, opts) {
|
|
|
349
349
|
if (!guard.bytes.isByteSource(m.header.transactionID)) {
|
|
350
350
|
return { code: "cmp/bad-transaction-id", reason: "the header transactionID is absent; a received PKIMessage MUST carry one (RFC 9483 sec. 3.5)" };
|
|
351
351
|
}
|
|
352
|
-
if (!guard.bytes.isByteSource(m.header.senderNonce) ||
|
|
352
|
+
if (!guard.bytes.isByteSource(m.header.senderNonce) ||
|
|
353
|
+
guard.bytes.lengthOf(m.header.senderNonce) < constants.LIMITS.CMP_MIN_NONCE_BYTES) {
|
|
353
354
|
return { code: "cmp/bad-sender-nonce", reason: "the header senderNonce is absent or shorter than 128 bits (RFC 9483 sec. 3.5)" };
|
|
354
355
|
}
|
|
355
356
|
if (opts.transactionID != null && !_bufEq(m.header.transactionID, opts.transactionID)) {
|
package/lib/constants.js
CHANGED
|
@@ -161,6 +161,8 @@ var LIMITS = Object.assign(Object.create(null), {
|
|
|
161
161
|
SAFETYNET_JWS_MAX_BYTES: BYTES.kib(64),
|
|
162
162
|
SAFETYNET_CERT_MAX_BYTES: BYTES.kib(64),
|
|
163
163
|
ACME_TOKEN_MIN_CHARS: 22,
|
|
164
|
+
CMP_MIN_NONCE_BYTES: 16,
|
|
165
|
+
CMP_TRANSACTION_ID_BYTES: 16,
|
|
164
166
|
SCEP_TRANSACTION_ID_MAX: 255,
|
|
165
167
|
OCSP_MAX_CERTS: 32,
|
|
166
168
|
HSS_MAX_LEVELS: 8,
|
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:2d1b2e87-6386-4481-940b-f4de0f1b9227",
|
|
6
6
|
"version": 1,
|
|
7
7
|
"metadata": {
|
|
8
|
-
"timestamp": "2026-09-
|
|
8
|
+
"timestamp": "2026-09-06T18:47:52.624Z",
|
|
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.6.
|
|
22
|
+
"bom-ref": "@blamejs/pki@0.6.48",
|
|
23
23
|
"type": "application",
|
|
24
24
|
"name": "pki",
|
|
25
|
-
"version": "0.6.
|
|
25
|
+
"version": "0.6.48",
|
|
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.6.
|
|
29
|
+
"purl": "pkg:npm/%40blamejs/pki@0.6.48",
|
|
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.6.
|
|
57
|
+
"ref": "@blamejs/pki@0.6.48",
|
|
58
58
|
"dependsOn": []
|
|
59
59
|
}
|
|
60
60
|
]
|