@blamejs/pki 0.7.32 → 0.7.34
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 +22 -0
- package/README.md +2 -2
- package/lib/attrcert-sign.js +1 -1
- package/lib/crl-sign.js +6 -3
- package/lib/lint.js +5 -5
- package/lib/ocsp.js +76 -8
- package/lib/pki-build.js +15 -4
- package/lib/schema-crl.js +32 -0
- package/lib/schema-ocsp.js +15 -0
- package/lib/x509-sign.js +162 -2
- package/package.json +1 -1
- package/sbom.cdx.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,28 @@ 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.7.34 — 2026-09-12
|
|
8
|
+
|
|
9
|
+
The OCSP signer refuses what its own lint grades an error.
|
|
10
|
+
|
|
11
|
+
### Changed
|
|
12
|
+
|
|
13
|
+
- A revoked response for a non-issued certificate (revocationReason certificateHold at 1970-01-01T00:00:00Z, RFC 6960 sec. 2.2, judged on the time as it is encoded, so any instant inside that first second counts) carries the extended revoked definition in responseExtensions whether or not opts.extendedRevoke names it, since sec. 4.4.8 requires it there; extendedRevoke: false on such a response is refused, and CRL references or any CRL entry extension on that SingleResponse, in the object form or pre-encoded, are refused as sec. 2.2 forbids them.
|
|
14
|
+
- A pre-encoded singleExtension is held to where RFC 6960 places it after its value is read: the request-only extensions (acceptable responses sec. 4.4.3, service locator sec. 4.4.6, preferred signature algorithms sec. 4.4.7) and the two a response carries in responseExtensions alone (the extended revoked definition sec. 4.4.8, the RFC 9654 nonce) are refused in singleExtensions, and a CRL entry extension carried there (sec. 4.4.5) must have the criticality RFC 5280 sec. 5.3 fixes for it (reasonCode and invalidityDate non-critical, certificateIssuer critical), must read with the CRL parser's own reader, and may not carry reasonCode removeFromCRL(8), which RFC 5280 sec. 5.3.1 keeps to a delta CRL. A private critical singleExtension is still signed; RFC 6960 places the rejection of an unrecognized critical extension on the relying party, and pki.lint.ocsp grades it.
|
|
15
|
+
- The CRL entry-extension criticality table and the OCSP extension-placement table now live in the CRL and OCSP schema modules, and the CRL signer, the OCSP signer and the linter read them from there.
|
|
16
|
+
|
|
17
|
+
## v0.7.33 — 2026-09-12
|
|
18
|
+
|
|
19
|
+
pki.x509.extension encodes one certificate extension from its plain value form.
|
|
20
|
+
|
|
21
|
+
### Added
|
|
22
|
+
|
|
23
|
+
- pki.x509.extension(name, value, opts) returns one Extension as DER. name is any extension name spec.extensions takes, or a dotted OID; value is the plain form spec.extensions takes for that name (the key-usage and purpose lists, the basicConstraints object, GeneralName lists, the policy, constraint, access and distribution-point objects, the qualified-certificate statements, the Active Directory enrollment values, true for the NULL-valued markers, and the explicit forms of the two key identifiers). For an unregistered dotted OID, value is the already-encoded extnValue as bytes and opts.critical is taken as stated. The criticality of a registered extension follows what pki.x509.sign emits for the object form: where RFC 5280 fixes it or the toolkit issues one form only, opts.critical may only restate that value and is otherwise refused with x509/bad-input; keyUsage, extendedKeyUsage, certificatePolicies, policyMappings, qcStatements and subjectAltName take opts.critical, and basicConstraints carries critical inside its value. subjectKeyIdentifier: true and authorityKeyIdentifier: true, which derive a value from the subject key or the issuer, are refused here and the message names spec.extensions; the authorityKeyIdentifier object form requires the key id bytes. Every registered extension encodes byte-identically through this verb and through spec.extensions. An unregistered OID's extnValue must hold exactly one DER-encoded value (RFC 5280 sec. 4.1), and a dotted string that is not a canonical OID (a first arc above 2, a second arc above 39 under arcs 0 and 1, a leading-zero arc) is refused as x509/bad-input rather than surfacing the OID codec's own error.
|
|
24
|
+
|
|
25
|
+
### Changed
|
|
26
|
+
|
|
27
|
+
- The pre-encoded array form of extensions on the certificate, CSR, CRL, attribute-certificate and timestamp signers holds an extension no decoder answers for to the same rule: its extnValue must be exactly one DER-encoded value, or the signer refuses it with its own bad-input code. An extension the signer decodes keeps the decoder's typed refusal.
|
|
28
|
+
|
|
7
29
|
## v0.7.32 — 2026-09-12
|
|
8
30
|
|
|
9
31
|
The certificate and CRL signers issue the RFC 5280 key identifiers without being asked.
|
package/README.md
CHANGED
|
@@ -231,7 +231,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
|
|
|
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` |
|
|
234
|
-
| `pki.x509` | Certificate issuance (RFC 5280 §4). `sign(spec, issuer, opts)` builds and signs a certificate from a `spec` of subject (a common-name string, an array of RDNs, or raw Name DER), the public key being certified, the validity window, an optional serial, and an optional `extensions` object. `randomSerial()` draws the same 20-octet CSPRNG serial the signer uses when the spec names none, so a serial can be reserved or logged before the certificate is issued. The `issuer` is a key alone (self-signed: issuer equals subject, signed with that key), a name plus public key plus key, or an issuing certificate plus key. The signature algorithm is resolved from the signing key through the shared registry, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA P-256/384/521, Ed25519, Ed448, ML-DSA-44/65/87, the twelve SLH-DSA sets, and the composite arms all issue without a per-algorithm branch. It encodes basic constraints, key usage, extended key usage, subject and authority key identifiers (the SKI derived by SHA-1 of the subject key; the AKI optionally naming the issuing certificate by name and serial; both emitted without being named, the SKI on every certificate and the AKI on every certificate that is not self-signed, which is what RFC 5280 §4.2.1.1 and §4.2.1.2 place on the issuing CA, and `false` declines each only where the RFC allows the omission), subject alternative names, certificate policies with their RFC 5280 section 4.2.1.4 qualifiers (a CPS pointer and a user notice), name constraints, authority information access, CRL distribution points, the freshest CRL, issuer alternative names, the policy machinery path validation acts on (policy constraints, inhibit anyPolicy, policy mappings), the RFC 3739 qualified-certificate statements including the ETSI EN 319 412-5 set, the RFC 6962 certificate-transparency pair (the precertificate poison and the embedded SCT list), the Active Directory Certificate Services enrollment extensions (certificate template, legacy template name, CA version, previous-CA-certificate hash, application policies), subject information access, subject directory attributes, and the RFC 6960 OCSP no-check responder marker, from the spec. That is every extension the shared certificate-extension decoders read, so any certificate `pki.lint.certificate` and `pki.inspect` can read in full the toolkit can also issue; any other extension is taken as pre-encoded DER. `extensions.nameConstraints` takes `{ permitted, excluded }` lists of GeneralName-form objects, restricting what the CA being issued may itself issue; each base is held to the rule for a constraint base, and the extension is emitted critical as §4.2.1.10 requires. It derives the version from the field set and enforces the serial bounds, the UTCTime/GeneralizedTime cutover, the DER default omissions, and the CA cross-field rules; a violation throws a typed `CertificateError`. Returns DER, or a PEM `CERTIFICATE` with `opts.pem`. Every arm is independently verified by OpenSSL. Parsing stays at `pki.schema.x509.parse` — `sign` |
|
|
234
|
+
| `pki.x509` | Certificate issuance (RFC 5280 §4). `sign(spec, issuer, opts)` builds and signs a certificate from a `spec` of subject (a common-name string, an array of RDNs, or raw Name DER), the public key being certified, the validity window, an optional serial, and an optional `extensions` object. `randomSerial()` draws the same 20-octet CSPRNG serial the signer uses when the spec names none, so a serial can be reserved or logged before the certificate is issued. The `issuer` is a key alone (self-signed: issuer equals subject, signed with that key), a name plus public key plus key, or an issuing certificate plus key. The signature algorithm is resolved from the signing key through the shared registry, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA P-256/384/521, Ed25519, Ed448, ML-DSA-44/65/87, the twelve SLH-DSA sets, and the composite arms all issue without a per-algorithm branch. It encodes basic constraints, key usage, extended key usage, subject and authority key identifiers (the SKI derived by SHA-1 of the subject key; the AKI optionally naming the issuing certificate by name and serial; both emitted without being named, the SKI on every certificate and the AKI on every certificate that is not self-signed, which is what RFC 5280 §4.2.1.1 and §4.2.1.2 place on the issuing CA, and `false` declines each only where the RFC allows the omission), subject alternative names, certificate policies with their RFC 5280 section 4.2.1.4 qualifiers (a CPS pointer and a user notice), name constraints, authority information access, CRL distribution points, the freshest CRL, issuer alternative names, the policy machinery path validation acts on (policy constraints, inhibit anyPolicy, policy mappings), the RFC 3739 qualified-certificate statements including the ETSI EN 319 412-5 set, the RFC 6962 certificate-transparency pair (the precertificate poison and the embedded SCT list), the Active Directory Certificate Services enrollment extensions (certificate template, legacy template name, CA version, previous-CA-certificate hash, application policies), subject information access, subject directory attributes, and the RFC 6960 OCSP no-check responder marker, from the spec. That is every extension the shared certificate-extension decoders read, so any certificate `pki.lint.certificate` and `pki.inspect` can read in full the toolkit can also issue; any other extension is taken as pre-encoded DER. `extensions.nameConstraints` takes `{ permitted, excluded }` lists of GeneralName-form objects, restricting what the CA being issued may itself issue; each base is held to the rule for a constraint base, and the extension is emitted critical as §4.2.1.10 requires. It derives the version from the field set and enforces the serial bounds, the UTCTime/GeneralizedTime cutover, the DER default omissions, and the CA cross-field rules; a violation throws a typed `CertificateError`. Returns DER, or a PEM `CERTIFICATE` with `opts.pem`. Every arm is independently verified by OpenSSL. `extension(name, value, opts)` encodes one Extension DER from the same plain value form, for the pre-encoded array form on the certificate, CSR, and CRL signers: the criticality follows what the signer emits, `opts.critical` reaches only the extensions whose criticality is the issuer's choice, and an unregistered dotted OID takes its extnValue as bytes. Parsing stays at `pki.schema.x509.parse` — `sign`, `randomSerial`, `extension` |
|
|
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, the RFC 3739 qualified-certificate statements, the Microsoft certificate template and application policies, subject information access, subject directory attributes, or an array of pre-encoded Extension DER; an extension the issuing CA assigns, such as the authority key identifier or the OCSP no-check marker, is refused by name rather than requested), 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. `pop.method: 'agreeMAC'` completes the four: `pop.key` is the requester's finite-field Diffie-Hellman private key, as a PKCS#8 DER, a PEM `PRIVATE KEY` block or a `KeyObject`, and `pop.caCert` the authority's certificate it already holds; the two agree a static secret (RFC 2875 sec. 3), and the key derived from it MACs the DER `certReq` under `id-dhPop-static-HMAC-SHA1`. Either key may name its group in the PKCS#3 or the X9.42 encoding. `pop.key` must be the private half of `certTemplate.publicKey`, and the template must name both a subject and a public key. 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` |
|
|
@@ -242,7 +242,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
|
|
|
242
242
|
| `pki.cms` | CMS signing, verification, encryption, and compression (RFC 5652). `sign(content, signers, opts)` produces a SignedData (§5), attached or detached, with one or many signers over RSA, RSASSA-PSS, ECDSA, EdDSA, the post-quantum ML-DSA-44/65/87 (RFC 9882) and SLH-DSA (all twelve FIPS 205 sets, RFC 9814), and composite ML-DSA pairing ML-DSA with a traditional RSA, ECDSA, or EdDSA key (accepted only when both components verify, draft-ietf-lamps-cms-composite-sigs). It builds the signed attributes (content-type, message-digest, signing-time) as canonical DER, signs the exact §5.4 preimage, and emits a DER `Buffer` or PEM. The content may also be an async iterable of byte chunks, which signs a large detached payload without holding it in memory: the payload is hashed incrementally under every signer's digest algorithm in one pass, and `verify` accepts the same streamed form as its `content` option. A signer may also be key-only — `{ key, spki, keyIdentifier }` with no certificate — which RFC 5272 §3.2 requires when a Full PKI Request's signer is the key of a certification request that request carries: the signer identifier takes the subjectKeyIdentifier form carrying the identifier the request declares, the signature scheme resolves from the request's own public key, and no certificate is embedded. `verify(input, opts)` parses a SignedData over the strict `pki.schema.cms` codec, locates each SignerInfo's signer certificate by its issuerAndSerialNumber or subjectKeyIdentifier, and checks the signature over the exact §5.4 preimage: with signed attributes present it confirms the message-digest attribute equals the content digest and verifies over the DER re-encoding of the SignedAttributes (the on-wire `[0]` tag replaced by a universal SET OF), and otherwise directly over the content. It returns a per-signer verdict with the matched signer certificate. `valid` and `trusted` are separate claims and neither implies the other: a SignedData carries its own certificates, so `valid` says the signature is sound under one of them and nothing about who signed, while `trusted` says every signer chained to a root named in `opts.trustAnchors`, validated through the same RFC 5280 path engine `pki.path.validate` uses. Without anchors there is nothing to chain to and `trusted` is `false`; anchors that cannot be read throw, rather than reading as untrusted. An unrecognized option is refused rather than ignored. `countersign(cms, signers, opts)` adds a countersignature (§11.4) — a `SignerInfo` over the countersigned SignerInfo's signature value, any signer algorithm, nestable, with the primary bytes preserved so it still verifies — attached as the id-countersignature unsigned attribute; `verify` returns each countersignature's verdict under `signers[i].countersignatures` and every unsigned attribute — including an RFC 3161 timestamp token, attachable via `sign`'s `unsignedAttributes` — under `signers[i].unsignedAttrs`, surfaced unauthenticated. `encrypt(content, recipients, opts)` produces an EnvelopedData, AuthEnvelopedData (AES-GCM, the authenticated default), or EncryptedData, with recipients auto-dispatched off the certificate key to key transport (RSAES-OAEP; v1.5 is never emitted), key agreement (ephemeral-static ECDH over P-256/384/521 with the X9.63 KDF, and X25519/X448 with HKDF), symmetric key wrap, password (PBKDF2 with RFC 3211 PWRI-KEK), or the post-quantum ML-KEM (and composite ML-KEM, draft-lamps-pq-composite-kem) KEMRecipientInfo (RFC 9629/9936), wrapping one fresh content key for every recipient. The content may also be an async iterable of byte chunks, streamed through the AES-GCM or AES-CBC content cipher so a large plaintext is encrypted without being buffered whole; the ciphertext is assembled before the definite-length encryptedContent is emitted, byte-for-byte the buffered form. `decrypt(input, keyMaterial, opts)` recovers the content through the matching arm and returns it with an `authenticated` flag; every secret-dependent failure collapses to one uniform `cms/decrypt-failed` verdict (Bleichenbacher, EFAIL, and password-oracle freedom), and PKCS#1 v1.5 is decrypt-only under the RFC 3218 implicit-rejection countermeasure. With `opts.stream: true` the recovered `content` is an async iterable of plaintext chunks instead of a single Buffer, for a payload too large to hold whole; the authenticated modes (AuthEnvelopedData, AuthenticatedData, AES-GCM) verify integrity before the iterable yields, so a forged message throws before any plaintext is exposed, while a CBC EnvelopedData or EncryptedData yields the plaintext as the cipher produces it. Every key-establishment secret the toolkit allocates is wiped once used, on the failing path as well as the succeeding one: the KEM shared secret and its derived key-encryption key, the raw ECDH / X25519 / X448 agreement secret, a password-derived key-encryption key, and the content-encryption key itself, cleared once the message is complete since all recipients share it. Caller-supplied key material is never written to (best-effort; NIST SP 800-227 §4.2, RFC 9629 §7). `authenticate(content, recipients, opts)` produces an `id-ct-authData` (§9): cleartext content plus an HMAC-SHA-256/384/512 MAC, authenticated but not encrypted, with the fresh MAC key wrapped for every recipient through the same RecipientInfo model. The MAC covers the authenticated attributes (content-type and message-digest) re-tagged to the EXPLICIT SET OF (§9.2), or the content octets directly; `decrypt` recovers the MAC key, recomputes the MAC and independently the message-digest (§9.3), and releases the content only after both pass, with every secret-dependent failure collapsing to the uniform `cms/decrypt-failed`. `compress(content, opts)` and `decompress(input, opts)` produce and consume a CompressedData (RFC 3274; ZLIB, version 0, id-alg-zlibCompress); decompress bounds the uncompressed output at 16 MiB and stops before it is materialized, so a decompression bomb fails closed as `cms/decompress-too-large`. Compression is a size transform with no integrity or confidentiality (RFC 8551 §2.4.5). `certsOnly(certs, opts?)` builds a certs-only certificate-management message (RFC 8551 §3.8): a degenerate SignedData with an empty signerInfos and no eContent that conveys certificates and CRLs without signing anything, `parseCertsOnly(input, opts?)` reads one back to its raw certificate and CRL DER (a CRL-only message is valid here, unlike the cert-required RFC 5272 form that `pki.est.parseCertsOnly` reads), and `isCertsOnly(input)` recognizes one structurally. Fail-closed with typed `cms/*` errors — `sign`, `verify`, `countersign`, `encrypt`, `authenticate`, `decrypt`, `compress`, `decompress`, `certsOnly`, `parseCertsOnly`, `isCertsOnly` |
|
|
243
243
|
| `pki.smime` | S/MIME message assembly, verification, encryption, and compression over the CMS layer (RFC 8551). `sign(content, signers, opts)` wraps a MIME entity in either form: `multipart/signed`, where the content stays readable in any MUA and a detached CMS SignedData rides alongside as `application/pkcs7-signature` with a matching `micalg`, or `application/pkcs7-mime; smime-type=signed-data`, where the whole entity is a base64 CMS SignedData. The signed bytes are the entity's §3.1.1 canonical form with CRLF line endings, and `verify(message, opts)` unwraps both forms and recomputes over the same canonicalizer, so a transport that re-wraps line endings still verifies while a tampered part fails. `encrypt(content, recipients, opts)` envelopes a MIME entity as an opaque `application/pkcs7-mime` message and `decrypt(message, keyMaterial, opts)` opens one, as `smime-type=authEnveloped-data` (AES-GCM, confidentiality and integrity, the default) or `smime-type=enveloped-data` (AES-CBC, confidentiality only, so `decrypt` reports `authenticated: false`, the §3.3 no-integrity caveat). The `smime-type` is derived from the CMS body rather than the header, and decryption is fail-closed and oracle-free. The crypto is entirely `pki.cms.sign` / `verify` / `encrypt` / `decrypt`, so it is algorithm-agnostic: any RSA / RSASSA-PSS / ECDSA / EdDSA / ML-DSA / SLH-DSA signer and any RSA-OAEP / ECDH / X25519 / X448 / AES-KW / PBKDF2 / ML-KEM recipient carries through. As with `cms.verify`, `verify` returns the per-signer verdict plus the recovered content, and `valid` and `trusted` are separate claims: `valid` says the signature is sound under a certificate the message carried, `trusted` says every signer chained to a root named in `opts.trustAnchors`. Anchoring here is validated for email at both ends of the chain — the signer certificate must carry `emailProtection` (RFC 8551 §4.4.4) and the anchor's own trust metadata must permit that purpose, since a root can be distrusted for email while remaining a good TLS root. Override either with `requiredEku` / `checkPurpose`. `compress(content, opts)` and `decompress(message, opts)` add the opaque `application/pkcs7-mime; smime-type=compressed-data; name=smime.p7z` frame (§3.6, RFC 3274), a size transform with no integrity or confidentiality (§2.4.5), bounded against a bomb; the recovered content, which may itself be signed or enveloped, is returned for the caller to re-verify. Header protection (RFC 9788): `sign` and `encrypt` take `opts.protectHeaders`, which inlines the caller's `opts.headers` on the Cryptographic Payload root (its Content-Type gaining `hp="clear"` when signed or `hp="cipher"` when encrypted) so the CMS signature or encryption covers them, defeating a transport that rewrites or reads Subject, From, and the rest. `verify` and `decrypt` surface the authenticated inner set as `protectedHeaders` plus `headerProtection { present, mode, fromMismatch, confidential, legacy }`, so a tampered outer header cannot alter it and `fromMismatch` flags an outer From that disagrees. Encryption applies a Header Confidentiality Policy: the default `hcp_baseline` obscures the outer Subject to `[...]` and removes Comments and Keywords, so the real values live only in the ciphertext, and `decrypt` recovers them. Every emitted header routes through a fail-closed injection guard that rejects a CR, LF, or NUL value and a non-ftext name, and a malformed or contradictory `hp` wrap fails closed as `smime/bad-header-protection` rather than silently downgrading. The CMS crypto is unchanged. Inbound legacy RFC 8551 header protection is recognized opt-in: `verify` and `decrypt` with `opts.legacyHeaderProtection` detect a legacy `message/rfc822`-wrapped payload by the RFC 9788 §4.10.1 four-condition identification and surface the inner headers under `headerProtection.legacy = { headers, mode, fromMismatch, confidential }`, where `headers` is an ordered `[{ name, value }]` array retaining legally repeated fields such as `Received`. Those never appear in `protectedHeaders` and never set `present: true`. Because a legacy message is structurally indistinguishable from an ordinary forwarded `message/rfc822`, this is an explicit heuristic (§4.10.2, "no strong end-to-end guarantees"): a caller keying trust off `present` or `protectedHeaders` is never misled, and only one that explicitly reads `headerProtection.legacy.headers` and cross-checks `legacy.fromMismatch` consumes it. It is off by default, and a nested crypto layer, an inner `hp=`, a non-`message/rfc822` payload, or a duplicate Content-Type reports `legacy: null`. Bidirectionally interoperable with `openssl smime` and `openssl cms`. `buildCertsOnly(certs, opts?)` wraps a `pki.cms.certsOnly` certificate-management message in one `application/pkcs7-mime; smime-type=certs-only; name=smime.p7c` entity, read back by OpenSSL's `pkcs7 -print_certs`. Fail-closed with typed `smime/*` errors — `sign`, `verify`, `encrypt`, `decrypt`, `compress`, `decompress`, `buildCertsOnly` |
|
|
244
244
|
| `pki.tsp` | Time-Stamp Protocol (RFC 3161). `sign(messageImprint, tsa, opts)` produces a TimeStampToken: a CMS SignedData over `pki.cms.sign` whose content is a `TSTInfo` carrying the timestamped message imprint, the TSA policy, a serial number, and `genTime` with optional accuracy, nonce, and ordering, plus the §2.4.2 signing-certificate attribute binding the token to the TSA certificate (SHA-2 imprints, any `pki.cms.sign` TSA key). `request` and `parseRequest` build and parse the TimeStampReq a client sends (imprint, requested policy, nonce, certReq); `response` and `parseResponse` handle the TimeStampResp a TSA returns, either a granted status wrapping a token or a rejection with PKIStatus and failure info, with the §2.4.2 status-to-token coupling enforced in both directions. `verify(token, data, opts)` verifies a token fail-closed: the CMS signature over the exact signed bytes, the message imprint recomputed from the data, the TSTInfo content type, the ESSCertID(V2) binding to the TSA certificate, the §2.3 critical timeStamping-only extendedKeyUsage, the request nonce when used, and, with a trust anchor supplied, full certification-path validation of the TSA certificate at the token's `genTime` — judged under the `timeStamping` purpose, so an anchor's own per-purpose trust metadata reaches the decision rather than sitting inert. It returns `{ valid, trusted, genTime, serialNumber, tstInfo, ... }`, where `trusted` is the separate claim that the authority chained to an anchor you named: without one there is nothing to chain to and it is `false`, which is the distinction a timestamp re-read years later turns on — `sign`, `request`, `parseRequest`, `response`, `parseResponse`, `verify` |
|
|
245
|
-
| `pki.ocsp` | Online Certificate Status Protocol (RFC 6960), both the responder and relying-party surface. `buildRequest(query, opts)` builds an OCSPRequest for one or more `{ cert, issuer }` pairs, with the CertID hashed under SHA-1 by default per the RFC 5019 lightweight profile or under SHA-2, plus an optional RFC 9654 nonce and an optional requestor signature. `sign(responseData, responder, opts)` produces a signed BasicOCSPResponse over the exact `ResponseData` DER, from the issuing CA directly or a delegated responder, under any `pki.cms.sign` key including the post-quantum ML-DSA and SLH-DSA sets, with `good`, `revoked` (reason and time), or `unknown` per-certificate status, and per-response `singleExtensions` naming the §4.4.4 archive cutoff and the §4.4.2 CRL reference as fields, each read back by name by the parser. `buildErrorResponse(status)` produces the unsigned §2.3 error (`tryLater`, `unauthorized`, and the rest). `verify(response, opts)` verifies a response fail-closed against the same hardened gates `pki.path.ocspChecker` runs: the CertID binding, responder authorization (the issuing CA, or a CA-issued delegate bearing id-kp-OCSPSigning and id-pkix-ocsp-nocheck and passing the full out-of-path certificate gates), the signature over `tbsResponseDataBytes`, currency against `thisUpdate` and `nextUpdate`, and the request-nonce echo. It returns `{ status: "good" / "revoked" / "unknown", ... }` and never silently accepts. `verifyRequest(request, opts)` is the responder-side inverse of `buildRequest`: it verifies a client's signed request (RFC 6960 §4.1.1) under the requestor certificate the request carries, trying each embedded certificate since the field is unordered, and reports `signed`, `signatureValid`, every certificate whose key verified (`signerCerts`, so a key carried under an expired certificate beside its renewal is not hidden behind ordering) with the first one's decoded subject, the full embedded certificate bag (`certs`, including intermediates for path building), and the request's CertIDs; an unsigned request is reported with `signed: false` rather than refused. Transport-free — `buildRequest`, `sign`, `buildErrorResponse`, `verify`, `verifyRequest` |
|
|
245
|
+
| `pki.ocsp` | Online Certificate Status Protocol (RFC 6960), both the responder and relying-party surface. `buildRequest(query, opts)` builds an OCSPRequest for one or more `{ cert, issuer }` pairs, with the CertID hashed under SHA-1 by default per the RFC 5019 lightweight profile or under SHA-2, plus an optional RFC 9654 nonce and an optional requestor signature. `sign(responseData, responder, opts)` produces a signed BasicOCSPResponse over the exact `ResponseData` DER, from the issuing CA directly or a delegated responder, under any `pki.cms.sign` key including the post-quantum ML-DSA and SLH-DSA sets, with `good`, `revoked` (reason and time), or `unknown` per-certificate status, and per-response `singleExtensions` naming the §4.4.4 archive cutoff and the §4.4.2 CRL reference as fields, each read back by name by the parser. The signer refuses what its own lint would grade an error: a pre-encoded singleExtension that RFC 6960 places in requests or in responseExtensions, a CRL entry extension carried at the wrong criticality, and CRL references or entry extensions on a non-issued response, which itself places the §4.4.8 extended revoked definition in responseExtensions without being asked. `buildErrorResponse(status)` produces the unsigned §2.3 error (`tryLater`, `unauthorized`, and the rest). `verify(response, opts)` verifies a response fail-closed against the same hardened gates `pki.path.ocspChecker` runs: the CertID binding, responder authorization (the issuing CA, or a CA-issued delegate bearing id-kp-OCSPSigning and id-pkix-ocsp-nocheck and passing the full out-of-path certificate gates), the signature over `tbsResponseDataBytes`, currency against `thisUpdate` and `nextUpdate`, and the request-nonce echo. It returns `{ status: "good" / "revoked" / "unknown", ... }` and never silently accepts. `verifyRequest(request, opts)` is the responder-side inverse of `buildRequest`: it verifies a client's signed request (RFC 6960 §4.1.1) under the requestor certificate the request carries, trying each embedded certificate since the field is unordered, and reports `signed`, `signatureValid`, every certificate whose key verified (`signerCerts`, so a key carried under an expired certificate beside its renewal is not hidden behind ordering) with the first one's decoded subject, the full embedded certificate bag (`certs`, including intermediates for path building), and the request's CertIDs; an unsigned request is reported with `signed: false` rather than refused. Transport-free — `buildRequest`, `sign`, `buildErrorResponse`, `verify`, `verifyRequest` |
|
|
246
246
|
| `pki.ct` | Certificate Transparency (RFC 6962). `parseSctList` decodes the `SignedCertificateTimestampList` a certificate or OCSP response carries, a TLS-presentation-language payload inside the §3.3 double DER wrap, into per-SCT log id, exact `timestamp` (BigInt), named signature algorithm, and raw signature. `reconstructSignedData` rebuilds the exact `digitally-signed` preimage, and `verifySct` verifies an SCT signature against a log's public key, routing an ECDSA signature through the strict DER-conformance gate and verifying through the crypto engine, resolving true or false and throwing a typed error on a structural fault. On the producing side, `encodeSctList` builds the extension value byte for byte as the exact inverse of `parseSctList`, and `signSct` performs a log's signing step. For trust, `parseLogList` ingests the CT log-list JSON into constraint-carrying trusted logs, recomputing each log's id as SHA-256 of its key and refusing a disagreeing id (a swapped key, §3.2) and decoding the state and temporal-interval constraints; `verifySctWithLogList` resolves the log key from an SCT's log id, enforces the state (usable, qualified, and readonly trusted; retired only before retirement; pending and rejected refused) and the temporal-interval window, then delegates the signature check to `verifySct`. `verifyLogListSignature(json, signature, publicKey)` verifies the detached `log_list.sig` over the raw log-list bytes against a caller-pinned signer key (RSASSA-PKCS1-v1.5/SHA-256 and an EC P-256 arm, with forgeable-key defenses failing closed), cross-checked against `openssl dgst`. `fetchLogList(opts)` turns that chain into a live client: it GETs the `log_list.json` and its detached `log_list.sig` over `pki.transport`, verifies the detached signature over the raw fetched bytes against a caller-pinned distributor key before parsing, so an unverified document is never parsed, read, cached, or surfaced, then ingests the same bytes through `parseLogList` and returns the trusted-log set plus the surfaced `version` and `timestamp`. Above the per-SCT layer, `verifySctList` renders a certificate-level verdict over every SCT a certificate carries (§3.3), reporting how many distinct trusted logs verified an SCT (so a duplicated SCT cannot inflate the count) and from how many distinct trusted operators against a caller's CT policy (`minScts` and `minOperators`, both defaulting to the RFC floor of one), where a policy shortfall is a verdict and a per-SCT failure is a recorded row rather than a thrown call; `x509CertEntry` reconstructs the precertificate log entry from a final certificate by removing the SCT-list extension from its TBSCertificate as byte surgery, so its embedded SCTs verify end to end (§3.2). The toolkit bakes in no vendor URL or key, TLS trust is explicit with `rejectUnauthorized` always on, each response is size-capped before the trust chain, and the transport is injectable so the whole path is testable offline — `parseSctList`, `reconstructSignedData`, `verifySct`, `encodeSctList`, `signSct`, `parseLogList`, `verifySctWithLogList`, `verifySctList`, `x509CertEntry`, `verifyLogListSignature`, `fetchLogList` |
|
|
247
247
|
| `pki.merkle` | Merkle-tree proof verification (RFC 6962 / RFC 9162). `leafHash`, `nodeHash`, and `emptyRootHash` build the domain-separated (0x00 leaf, 0x01 node) SHA-256 tree hashes. `verifyInclusion` folds an audit proof back to a root, and `verifyConsistency` reconstructs both the old and new root, which is the append-only guarantee; each is constant-time-compared to a trusted checkpoint root. Fail-closed on bad geometry, sync hashing, transport-free — `leafHash`, `nodeHash`, `emptyRootHash`, `verifyInclusion`, `verifyConsistency` |
|
|
248
248
|
| `pki.trust` | Mozilla and CCADB trust-store ingestion. `parseCertdata` reads the NSS `certdata.txt` object stream and `parseCcadbCsv` the CCADB CSV export, both into one constraint-carrying anchor shape: the per-purpose trust bits, where only `CKT_NSS_TRUSTED_DELEGATOR` grants, and the per-purpose distrust-after dates the bare root list omits. Certificate and trust objects pair by byte-exact issuer and serial rather than adjacency and are cross-checked against the parsed DER, so metadata cannot attach to the wrong root. `anchor()` hands an entry to `pki.path.validate({ trustAnchors, checkPurpose })`, and `anchor(entry, { nameConstraints })` attaches the namespace a root program trusts a root for when that is narrower than the root certificate states, a `{ permitted, excluded }` pair of `{ tag, base }` subtrees that `validate` seeds as the RFC 5280 §6.1.1(h)(i) initial value, intersecting with each certificate's own constraints. Offline, fail-closed, bounded — `parseCertdata`, `parseCcadbCsv`, `anchor` |
|
package/lib/attrcert-sign.js
CHANGED
|
@@ -307,7 +307,7 @@ function _buildExtensions(extSpec, aaSpki) {
|
|
|
307
307
|
var seenA = intrinsic.create(null);
|
|
308
308
|
var exts = extSpec.map(function (e, i) {
|
|
309
309
|
var der = _b.reqDer(e, "extension");
|
|
310
|
-
_b.assertValidExtension(der, i);
|
|
310
|
+
_b.assertValidExtension(der, i, EXT_DECODERS);
|
|
311
311
|
var n = asn1.decode(der);
|
|
312
312
|
var extnId = asn1.read.oid(n.children[0]);
|
|
313
313
|
if (seenA[extnId]) throw _err("attrcert/bad-input", "duplicate extension " + extnId + " (RFC 5755 sec. 4.2.9)");
|
package/lib/crl-sign.js
CHANGED
|
@@ -100,7 +100,10 @@ var REQUIRED_CRITICALITY = intrinsic.create(null);
|
|
|
100
100
|
["issuingDistributionPoint", true], ["deltaCRLIndicator", true]].forEach(function (r) { REQUIRED_CRITICALITY[O(r[0])] = r[1]; });
|
|
101
101
|
|
|
102
102
|
var REQUIRED_ENTRY_CRITICALITY = intrinsic.create(null);
|
|
103
|
-
|
|
103
|
+
(function () {
|
|
104
|
+
var shared = crlSchema.entryExtensionCriticality(oid);
|
|
105
|
+
intrinsic.forEach(intrinsic.keys(shared), function (k) { REQUIRED_ENTRY_CRITICALITY[k] = shared[k].critical; });
|
|
106
|
+
})();
|
|
104
107
|
|
|
105
108
|
var _CERT_ISSUER_DEFERRED = "certificateIssuer (indirect CRLs) is not yet supported -- pki.path.crlChecker skips a CRL carrying any critical entry extension other than reasonCode, so an indirect CRL would never be authoritative for revocation. Re-enabled once the checker processes certificateIssuer / indirect CRLs.";
|
|
106
109
|
var _INDIRECT_IDP_DEFERRED = "issuingDistributionPoint indirectCRL (indirect CRLs) is not yet supported -- pki.path.crlChecker skips a CRL whose IDP marks it indirect, so it would never be authoritative for revocation. Re-enabled once the checker processes indirect CRLs.";
|
|
@@ -233,7 +236,7 @@ function _buildCrlExtensions(spec, ctx) {
|
|
|
233
236
|
var arrBase = null, arrCrlNum = null;
|
|
234
237
|
ext.forEach(function (e, i) {
|
|
235
238
|
var der = _reqDer(e, "extension");
|
|
236
|
-
_assertValidExtension(der, i);
|
|
239
|
+
_assertValidExtension(der, i, EXT_DECODERS);
|
|
237
240
|
var node = asn1.decode(der);
|
|
238
241
|
var extnId = asn1.read.oid(node.children[0]);
|
|
239
242
|
if (seen[extnId]) throw _err("crl/bad-input", "duplicate extension " + extnId + " (RFC 5280 sec. 5.2)");
|
|
@@ -326,7 +329,7 @@ function _buildRevoked(entryList, isDelta) {
|
|
|
326
329
|
if (!Array.isArray(e.extensions)) throw _err("crl/bad-input", "revoked entry [" + idx + "] extensions must be an array of pre-encoded Extension DER");
|
|
327
330
|
e.extensions.forEach(function (x, j) {
|
|
328
331
|
var der = _reqDer(x, "entry extension");
|
|
329
|
-
_assertValidExtension(der, j);
|
|
332
|
+
_assertValidExtension(der, j, EXT_DECODERS);
|
|
330
333
|
var xnode = asn1.decode(der);
|
|
331
334
|
var extnId = asn1.read.oid(xnode.children[0]);
|
|
332
335
|
if (seen[extnId]) throw _err("crl/bad-input", "duplicate entry extension " + extnId + " in revoked entry [" + idx + "]");
|
package/lib/lint.js
CHANGED
|
@@ -632,8 +632,10 @@ var CRL_CRITICALITY = Object.create(null);
|
|
|
632
632
|
["issuingDistributionPoint", true], ["deltaCRLIndicator", true]]
|
|
633
633
|
.forEach(function (r) { CRL_CRITICALITY[oid.byName(r[0])] = r[1]; });
|
|
634
634
|
var CRL_ENTRY_CRITICALITY = Object.create(null);
|
|
635
|
-
|
|
636
|
-
|
|
635
|
+
(function () {
|
|
636
|
+
var shared = crlSchema.entryExtensionCriticality(oid);
|
|
637
|
+
Object.keys(shared).forEach(function (k) { CRL_ENTRY_CRITICALITY[k] = shared[k].critical; });
|
|
638
|
+
})();
|
|
637
639
|
|
|
638
640
|
function _crlExtList(crl) { return crl.crlExtensions || []; }
|
|
639
641
|
function _crlExtByName(crl, name) {
|
|
@@ -1330,9 +1332,7 @@ var OCSP_RESPONSE_KNOWN = Object.create(null);
|
|
|
1330
1332
|
var OCSP_SINGLE_KNOWN = Object.create(null);
|
|
1331
1333
|
["ocspArchiveCutoff", "ocspCrl", "reasonCode", "invalidityDate", "certificateIssuer"]
|
|
1332
1334
|
.forEach(function (n) { OCSP_SINGLE_KNOWN[oid.byName(n)] = true; });
|
|
1333
|
-
var OCSP_REQUEST_ONLY =
|
|
1334
|
-
[["ocspResponse", "RFC 6960 4.4.3"], ["ocspServiceLocator", "RFC 6960 4.4.6"], ["ocspPrefSigAlgs", "RFC 6960 4.4.7"]]
|
|
1335
|
-
.forEach(function (r) { OCSP_REQUEST_ONLY[oid.byName(r[0])] = r[1]; });
|
|
1335
|
+
var OCSP_REQUEST_ONLY = ocspSchema.extensionPlacement(oid).requestOnly;
|
|
1336
1336
|
/** @internal Only the criticality a clause states. Sec. 4.4.8 forbids a critical extended revoked
|
|
1337
1337
|
* definition; sec. 4.4.5 carries the RFC 5280 sec. 5.3 rules for the three entry extensions. RFC
|
|
1338
1338
|
* 6960 states nothing about the criticality of the nonce, the archive cutoff or the CRL references,
|
package/lib/ocsp.js
CHANGED
|
@@ -29,6 +29,7 @@ var pkiBuild = require("./pki-build");
|
|
|
29
29
|
var oid = require("./oid");
|
|
30
30
|
var x509 = require("./schema-x509");
|
|
31
31
|
var ocspSchema = require("./schema-ocsp");
|
|
32
|
+
var crlSchema = require("./schema-crl");
|
|
32
33
|
var pathValidate = require("./path-validate");
|
|
33
34
|
var signScheme = require("./sign-scheme");
|
|
34
35
|
var ocspVerify = require("./ocsp-verify");
|
|
@@ -51,6 +52,11 @@ Object.keys(constants.NAMES.CRL_REASON).forEach(function (k) { REASON_CODE[const
|
|
|
51
52
|
var OID_OCSP_NONCE = O("ocspNonce");
|
|
52
53
|
var OID_OCSP_BASIC = O("ocspBasic");
|
|
53
54
|
var OID_EXTENDED_REVOKE = O("ocspExtendedRevoke");
|
|
55
|
+
var OID_OCSP_CRL = O("ocspCrl");
|
|
56
|
+
var EXTENSION_PLACEMENT = ocspSchema.extensionPlacement(oid);
|
|
57
|
+
var ENTRY_EXTENSION_CRITICALITY = crlSchema.entryExtensionCriticality(oid);
|
|
58
|
+
var CERTIFICATE_HOLD = REASON_CODE.certificateHold, REMOVE_FROM_CRL = REASON_CODE.removeFromCRL;
|
|
59
|
+
var OID_REASON_CODE = O("reasonCode");
|
|
54
60
|
|
|
55
61
|
function _digest(wcHash, buf) { return subtle.digest(wcHash, buf).then(function (h) { return Buffer.from(h); }); }
|
|
56
62
|
function _certOf(arg, what) {
|
|
@@ -228,11 +234,21 @@ function _normCertDer(cert, what) {
|
|
|
228
234
|
* the status was drawn from (sec. 4.4.2), any subset of the three. A pre-encoded entry is read with
|
|
229
235
|
* the parser's own singleExtensions reader before it is emitted, so a response this verb signs is
|
|
230
236
|
* one `pki.schema.ocsp.parseResponse` reads back, and a malformed archiveCutoff or CrlID is refused
|
|
231
|
-
* here with the code the parser would have raised.
|
|
237
|
+
* here with the code the parser would have raised. A pre-encoded entry is also held to where RFC
|
|
238
|
+
* 6960 places it: the request-only extensions (sec. 4.4.3, 4.4.6, 4.4.7) and the two a response
|
|
239
|
+
* carries in responseExtensions alone (the extended revoked definition, sec. 4.4.8, and the RFC 9654
|
|
240
|
+
* nonce) are refused in singleExtensions, and a CRL entry extension carried here (sec. 4.4.5) keeps
|
|
241
|
+
* the criticality RFC 5280 sec. 5.3 fixes for it.
|
|
242
|
+
*
|
|
243
|
+
* A "revoked" status for a non-issued certificate (revocationReason certificateHold at
|
|
244
|
+
* 1970-01-01T00:00:00Z, sec. 2.2) places the extended revoked definition in responseExtensions
|
|
245
|
+
* whether or not `opts.extendedRevoke` names it, refuses `extendedRevoke: false`, and refuses CRL
|
|
246
|
+
* references or any CRL entry extension on that SingleResponse.
|
|
232
247
|
*
|
|
233
248
|
* @opts
|
|
234
249
|
* nonce a request nonce Buffer to echo back in responseExtensions (RFC 9654).
|
|
235
|
-
* extendedRevoke emit the id-pkix-ocsp-extended-revoke extension (RFC 6960 sec. 4.4.8)
|
|
250
|
+
* extendedRevoke emit the id-pkix-ocsp-extended-revoke extension (RFC 6960 sec. 4.4.8); implied
|
|
251
|
+
* by a non-issued response, where `false` is refused.
|
|
236
252
|
* embedCert `false` to omit certs [0] (a direct-CA response the client already trusts).
|
|
237
253
|
* pem emit a PEM `OCSP RESPONSE` string instead of DER.
|
|
238
254
|
* @example
|
|
@@ -287,11 +303,19 @@ function _signResponse(responseData, responder, respCert, respCertDer, responder
|
|
|
287
303
|
if (!responses.length) throw _err("ocsp/bad-input", "a response MUST include at least one SingleResponse (RFC 6960 sec. 4.2.1)");
|
|
288
304
|
|
|
289
305
|
return _responderID(responseData.responderID, respCert).then(function (ridNode) {
|
|
290
|
-
return Promise.all(responses.map(function (r) { return _buildSingleResponse(r, opts); })).then(function (
|
|
306
|
+
return Promise.all(responses.map(function (r) { return _buildSingleResponse(r, opts); })).then(function (built) {
|
|
307
|
+
var srNodes = built.map(function (x) { return x.node; });
|
|
308
|
+
var anyNonIssued = built.some(function (x) { return x.nonIssued; });
|
|
309
|
+
/** @internal Sec. 2.2 and 4.4.8: a "revoked" answer for a non-issued certificate MUST carry the
|
|
310
|
+
* extended revoked definition in responseExtensions, so the shape itself places it there,
|
|
311
|
+
* and a caller declining it is refused rather than left with a response the section forbids. */
|
|
312
|
+
if (anyNonIssued && opts.extendedRevoke === false) {
|
|
313
|
+
throw _err("ocsp/bad-input", "a revoked response for a non-issued certificate MUST carry the extended-revoke response extension, so extendedRevoke: false is refused here (RFC 6960 sec. 2.2 / 4.4.8)");
|
|
314
|
+
}
|
|
291
315
|
var rdChildren = [ridNode, b.generalizedTime(_asEncodableDate(responseData.producedAt, "producedAt") || new Date()), b.sequence(srNodes)];
|
|
292
316
|
var respExts = [];
|
|
293
317
|
if (opts.nonce != null) { _assertNonce(opts.nonce); respExts.push(_nonceExt(opts.nonce)); }
|
|
294
|
-
if (opts.extendedRevoke) respExts.push(b.sequence([b.oid(OID_EXTENDED_REVOKE), b.octetString(b.nullValue())]));
|
|
318
|
+
if (opts.extendedRevoke || anyNonIssued) respExts.push(b.sequence([b.oid(OID_EXTENDED_REVOKE), b.octetString(b.nullValue())]));
|
|
295
319
|
if (respExts.length) rdChildren.push(b.explicit(1, b.sequence(respExts)));
|
|
296
320
|
var responseDataDer = b.sequence(rdChildren);
|
|
297
321
|
var scheme = signScheme.resolveSignScheme(respCert, { combinedRsaSig: true }, true, _signE);
|
|
@@ -366,15 +390,55 @@ function _buildSingleResponse(r, opts) {
|
|
|
366
390
|
throw _err("ocsp/bad-input", "thisUpdate must not be after nextUpdate (RFC 6960 sec. 4.2.2.1)");
|
|
367
391
|
}
|
|
368
392
|
var statusNode = _certStatusNode(r.status, opts);
|
|
393
|
+
var nonIssued = _isNonIssuedStatus(r.status);
|
|
369
394
|
var srChildren = [certID, statusNode, b.generalizedTime(thisUpdate)];
|
|
370
395
|
if (nextUpdate !== null) srChildren.push(b.explicit(0, b.generalizedTime(nextUpdate)));
|
|
371
396
|
if (r.singleExtensions != null) {
|
|
372
|
-
var singleDer = _singleExtensionsDer(r.singleExtensions);
|
|
397
|
+
var singleDer = _singleExtensionsDer(r.singleExtensions, nonIssued);
|
|
373
398
|
if (singleDer.length) srChildren.push(b.explicit(1, b.sequence(singleDer)));
|
|
374
399
|
}
|
|
375
|
-
return b.sequence(srChildren);
|
|
400
|
+
return { node: b.sequence(srChildren), nonIssued: nonIssued };
|
|
376
401
|
});
|
|
377
402
|
}
|
|
403
|
+
/** @internal Sec. 2.2 defines the non-issued shape by its two fields: revocationReason
|
|
404
|
+
* certificateHold and revocationTime 1970-01-01T00:00:00Z. The time is judged as it is ENCODED: a
|
|
405
|
+
* GeneralizedTime carries whole seconds, so any instant inside the first second of 1970 reaches
|
|
406
|
+
* the relying party as that value. */
|
|
407
|
+
function _isNonIssuedStatus(status) {
|
|
408
|
+
if (!status || typeof status !== "object" || status.revoked == null || status.revocationReason == null) return false;
|
|
409
|
+
var code = typeof status.revocationReason === "number" ? status.revocationReason : REASON_CODE[guard.text.keyOf(status.revocationReason)];
|
|
410
|
+
if (code !== CERTIFICATE_HOLD) return false;
|
|
411
|
+
var instant = guard.time.instantOf(_asEncodableDate(status.revoked, "the revocation time"));
|
|
412
|
+
return instant >= 0 && instant < constants.TIME.seconds(1);
|
|
413
|
+
}
|
|
414
|
+
var NON_ISSUED_FORBIDDEN = "a revoked response for a non-issued certificate MUST NOT carry CRL references or any CRL entry extension (RFC 6960 sec. 2.2)";
|
|
415
|
+
/** @internal What a pre-encoded singleExtension may be, beyond decoding: not one of the extensions
|
|
416
|
+
* RFC 6960 defines for requests alone, not one a response carries in responseExtensions alone, with
|
|
417
|
+
* the criticality RFC 5280 sec. 5.3 fixes for a CRL entry extension carried here (sec. 4.4.5), and
|
|
418
|
+
* not a CRL reference or entry extension on the non-issued shape (sec. 2.2). */
|
|
419
|
+
function _assertSingleExtensionPlacement(e, nonIssued) {
|
|
420
|
+
var label = "pre-encoded singleExtension " + (e.name || e.oid);
|
|
421
|
+
/** @internal The three tables have a null prototype, so an absent OID reads as undefined. */
|
|
422
|
+
var requestClause = EXTENSION_PLACEMENT.requestOnly[e.oid], responseClause = EXTENSION_PLACEMENT.responseOnly[e.oid];
|
|
423
|
+
if (requestClause !== undefined) throw _err("ocsp/bad-input", label + " is a request extension and does not belong in a response (" + requestClause + ")");
|
|
424
|
+
if (responseClause !== undefined) throw _err("ocsp/bad-input", label + " belongs in responseExtensions, not in singleExtensions (" + responseClause + ")");
|
|
425
|
+
var entry = ENTRY_EXTENSION_CRITICALITY[e.oid];
|
|
426
|
+
if (entry !== undefined && (e.critical === true) !== entry.critical) {
|
|
427
|
+
throw _err("ocsp/bad-input", label + " must be marked " + (entry.critical ? "critical" : "non-critical") + " (" + entry.citation + ", carried by RFC 6960 sec. 4.4.5)");
|
|
428
|
+
}
|
|
429
|
+
if (nonIssued && (entry !== undefined || e.oid === OID_OCSP_CRL)) throw _err("ocsp/bad-input", NON_ISSUED_FORBIDDEN);
|
|
430
|
+
if (entry !== undefined) {
|
|
431
|
+
/** @internal Sec. 4.4.5 carries the CRL entry extensions as they are, so the CRL parser's own
|
|
432
|
+
* reader decides whether the value reads, and RFC 5280 sec. 5.3.1 keeps removeFromCRL(8) to a
|
|
433
|
+
* delta CRL, which a SingleResponse is not. */
|
|
434
|
+
var read;
|
|
435
|
+
try { read = crlSchema.readEntryExtension(e); }
|
|
436
|
+
catch (err) { throw _err("ocsp/bad-input", label + " value is malformed (" + entry.citation + ")", err); }
|
|
437
|
+
if (e.oid === OID_REASON_CODE && read.value === REMOVE_FROM_CRL) {
|
|
438
|
+
throw _err("ocsp/bad-input", label + " removeFromCRL(8) appears only in a delta CRL (RFC 5280 sec. 5.3.1), never in an OCSP response");
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
}
|
|
378
442
|
function _defaultNextUpdate() { return new Date(Date.now() + constants.TIME.days(7)); }
|
|
379
443
|
var _SINGLE_EXT_KEYS = Object.assign(Object.create(null), { archiveCutoff: 1, crlReferences: 1 });
|
|
380
444
|
var _CRL_ID_KEYS = Object.assign(Object.create(null), { crlUrl: 1, crlNum: 1, crlTime: 1 });
|
|
@@ -383,13 +447,16 @@ var _CRL_ID_KEYS = Object.assign(Object.create(null), { crlUrl: 1, crlNum: 1, cr
|
|
|
383
447
|
* SingleResponse's singleExtensions. The object form names them as fields; the array form carries
|
|
384
448
|
* pre-encoded Extension DER, and each entry is run through the parser's own singleExtensions reader
|
|
385
449
|
* first, so this verb never emits an entry pki.schema.ocsp.parseResponse would refuse. */
|
|
386
|
-
function _singleExtensionsDer(spec) {
|
|
450
|
+
function _singleExtensionsDer(spec, nonIssued) {
|
|
387
451
|
if (Array.isArray(spec)) {
|
|
388
452
|
var dense = pkiBuild.reqDenseArray(spec, "singleExtensions", _err, "ocsp/bad-input");
|
|
389
453
|
var ders = dense.map(function (d, i) {
|
|
390
454
|
return guard.bytes.snapshotSource(d, OcspError, "ocsp/bad-input", "singleExtensions[" + i + "]");
|
|
391
455
|
});
|
|
392
|
-
if (ders.length)
|
|
456
|
+
if (ders.length) {
|
|
457
|
+
var parsed = ocspSchema.readSingleExtensionsDer(ders);
|
|
458
|
+
parsed.forEach(function (e) { _assertSingleExtensionPlacement(e, nonIssued); });
|
|
459
|
+
}
|
|
393
460
|
return ders;
|
|
394
461
|
}
|
|
395
462
|
if (!spec || typeof spec !== "object" || Buffer.isBuffer(spec)) {
|
|
@@ -404,6 +471,7 @@ function _singleExtensionsDer(spec) {
|
|
|
404
471
|
out.push(b.sequence([b.oid(oid.byName("ocspArchiveCutoff")), b.octetString(b.generalizedTime(spec.archiveCutoff))]));
|
|
405
472
|
}
|
|
406
473
|
if (spec.crlReferences != null) {
|
|
474
|
+
if (nonIssued) throw _err("ocsp/bad-input", NON_ISSUED_FORBIDDEN);
|
|
407
475
|
var c = spec.crlReferences;
|
|
408
476
|
if (!c || typeof c !== "object" || Array.isArray(c) || Buffer.isBuffer(c)) {
|
|
409
477
|
throw _err("ocsp/bad-input", "singleExtensions crlReferences must be an object { crlUrl?, crlNum?, crlTime? }");
|
package/lib/pki-build.js
CHANGED
|
@@ -1088,12 +1088,15 @@ function makeBuilder(ctx) {
|
|
|
1088
1088
|
throw E("bad-input", what + " is not a well-formed SubjectPublicKeyInfo", e);
|
|
1089
1089
|
}
|
|
1090
1090
|
}
|
|
1091
|
-
|
|
1092
|
-
|
|
1091
|
+
/** @internal `decoders`, when given, names the extensions the caller decodes itself after this
|
|
1092
|
+
* check, so a malformed value there keeps the decoder's own code; every other extnValue is held
|
|
1093
|
+
* here to being one DER value. */
|
|
1094
|
+
function assertValidExtension(der, idx, decoders) {
|
|
1095
|
+
var n, extnId;
|
|
1093
1096
|
try { n = asn1.decode(der); }
|
|
1094
1097
|
catch (e) { throw E("bad-input", "pre-encoded extension [" + idx + "] is not valid DER", e); }
|
|
1095
1098
|
if (n.tagNumber !== asn1.TAGS.SEQUENCE || n.tagClass !== "universal" || !n.children || n.children.length < 2 || n.children.length > 3) throw E("bad-input", "pre-encoded extension [" + idx + "] must be an Extension SEQUENCE { extnID, critical?, extnValue }");
|
|
1096
|
-
try { asn1.read.oid(n.children[0]); }
|
|
1099
|
+
try { extnId = asn1.read.oid(n.children[0]); }
|
|
1097
1100
|
catch (e) { throw E("bad-input", "pre-encoded extension [" + idx + "] extnID is not an OBJECT IDENTIFIER", e); }
|
|
1098
1101
|
if (n.children.length === 3) {
|
|
1099
1102
|
var crit;
|
|
@@ -1103,6 +1106,13 @@ function makeBuilder(ctx) {
|
|
|
1103
1106
|
}
|
|
1104
1107
|
var last = n.children[n.children.length - 1];
|
|
1105
1108
|
if (last.tagNumber !== asn1.TAGS.OCTET_STRING || last.tagClass !== "universal") throw E("bad-input", "pre-encoded extension [" + idx + "] extnValue must be an OCTET STRING");
|
|
1109
|
+
if (!(decoders && intrinsic.hasOwn(decoders, extnId))) assertExtnValueIsDer(last.content, "pre-encoded extension [" + idx + "]");
|
|
1110
|
+
}
|
|
1111
|
+
/** @internal RFC 5280 sec. 4.1: extnValue holds the DER encoding of one ASN.1 value, so the octets
|
|
1112
|
+
* must decode as exactly one TLV, which the strict codec's trailing-byte refusal also enforces. */
|
|
1113
|
+
function assertExtnValueIsDer(content, label) {
|
|
1114
|
+
try { asn1.decode(content); }
|
|
1115
|
+
catch (e) { throw E("bad-input", label + " extnValue must hold exactly one DER-encoded value (RFC 5280 sec. 4.1)", e); }
|
|
1106
1116
|
}
|
|
1107
1117
|
/** @internal Applies the certificate profile's fixed-criticality table. The CRL, CRL-entry and
|
|
1108
1118
|
* attribute-certificate profiles set their own criticality in their own signers. */
|
|
@@ -1136,7 +1146,7 @@ function makeBuilder(ctx) {
|
|
|
1136
1146
|
var seen = intrinsic.create(null);
|
|
1137
1147
|
return b.sequence(extSpec.map(function (e, i) {
|
|
1138
1148
|
var der = reqDer(e, "extension");
|
|
1139
|
-
assertValidExtension(der, i);
|
|
1149
|
+
assertValidExtension(der, i, EXT_DECODERS);
|
|
1140
1150
|
var n = asn1.decode(der);
|
|
1141
1151
|
var extnId = asn1.read.oid(n.children[0]);
|
|
1142
1152
|
if (seen[extnId]) throw E("bad-input", "duplicate requested extension " + extnId + " (RFC 5280 sec. 4.2)");
|
|
@@ -1260,6 +1270,7 @@ function makeBuilder(ctx) {
|
|
|
1260
1270
|
extMsPreviousCertHash: extMsPreviousCertHash, extMsEnrollCertType: extMsEnrollCertType,
|
|
1261
1271
|
spkiKeyId: spkiKeyId, skiKeyId: skiKeyId,
|
|
1262
1272
|
reqDer: reqDer, reqDenseArray: reqDenseArray, reqDerSequence: reqDerSequence, assertValidSpki: assertValidSpki, assertValidExtension: assertValidExtension,
|
|
1273
|
+
assertExtnValueIsDer: assertExtnValueIsDer,
|
|
1263
1274
|
assertCertCriticality: assertCertCriticality,
|
|
1264
1275
|
certLikeFromSpki: certLikeFromSpki, assertSignatureVerifies: assertSignatureVerifies,
|
|
1265
1276
|
samePublicKey: samePublicKey,
|
package/lib/schema-crl.js
CHANGED
|
@@ -234,6 +234,36 @@ function matches(root) {
|
|
|
234
234
|
return schema.isUniversalOneOf(pos, [TAGS.UTC_TIME, TAGS.GENERALIZED_TIME]);
|
|
235
235
|
}
|
|
236
236
|
|
|
237
|
+
/** @internal The criticality RFC 5280 sec. 5.3 fixes for each CRL entry extension, keyed by dotted
|
|
238
|
+
* OID through the registry the caller passes: the CRL signer, the OCSP signer (sec. 4.4.5 carries
|
|
239
|
+
* the same extensions into a SingleResponse) and the linter all read this one table. */
|
|
240
|
+
var ENTRY_EXTENSION_CRITICALITY_ROWS = [
|
|
241
|
+
["reasonCode", false, "RFC 5280 sec. 5.3.1"], ["invalidityDate", false, "RFC 5280 sec. 5.3.2"],
|
|
242
|
+
["certificateIssuer", true, "RFC 5280 sec. 5.3.3"],
|
|
243
|
+
];
|
|
244
|
+
function entryExtensionCriticality(oidRegistry) {
|
|
245
|
+
var table = intrinsic.create(null);
|
|
246
|
+
intrinsic.forEach(ENTRY_EXTENSION_CRITICALITY_ROWS, function (r) {
|
|
247
|
+
table[oidRegistry.byName(r[0])] = { critical: r[1], citation: r[2] };
|
|
248
|
+
});
|
|
249
|
+
return table;
|
|
250
|
+
}
|
|
251
|
+
/** @internal Reads a CRL entry extension's value the way this parser reads it, for a consumer that
|
|
252
|
+
* meets one outside a CRL (an OCSP SingleResponse, RFC 6960 sec. 4.4.5): reasonCode and
|
|
253
|
+
* invalidityDate through `decodeExt`, certificateIssuer as the GeneralNames the CRL profile leaves
|
|
254
|
+
* raw. Returns the record with its decoded `value`; throws `crl/bad-extension-value`. */
|
|
255
|
+
var OID_CERTIFICATE_ISSUER = oid.byName("certificateIssuer");
|
|
256
|
+
var CERTIFICATE_ISSUER_NAMES = pkix.generalNames(NS, { code: "crl/bad-extension-value" });
|
|
257
|
+
function readEntryExtension(ext) {
|
|
258
|
+
if (ext.oid !== OID_CERTIFICATE_ISSUER) return decodeExt(ext);
|
|
259
|
+
var names;
|
|
260
|
+
try { names = schema.walk(CERTIFICATE_ISSUER_NAMES, asn1.decode(ext.value), NS).result; }
|
|
261
|
+
catch (e) {
|
|
262
|
+
throw NS.E("crl/bad-extension-value", "malformed certificateIssuer extension value: " + ((e && e.message) || intrinsic.String(e)), e);
|
|
263
|
+
}
|
|
264
|
+
return { oid: ext.oid, name: ext.name, critical: ext.critical, value: names };
|
|
265
|
+
}
|
|
266
|
+
|
|
237
267
|
module.exports = {
|
|
238
268
|
parse: parse,
|
|
239
269
|
pemDecode: pemDecode,
|
|
@@ -244,4 +274,6 @@ module.exports = {
|
|
|
244
274
|
* entry extension into an OCSP SingleResponse, and the linter reads it with this rather than a
|
|
245
275
|
* second one. Not on the curated `pki.schema.crl` surface. */
|
|
246
276
|
decodeExtension: decodeExt,
|
|
277
|
+
entryExtensionCriticality: entryExtensionCriticality,
|
|
278
|
+
readEntryExtension: readEntryExtension,
|
|
247
279
|
};
|
package/lib/schema-ocsp.js
CHANGED
|
@@ -574,4 +574,19 @@ module.exports = {
|
|
|
574
574
|
catch (e) { throw NS.E("ocsp/bad-single-response", "a pre-encoded singleExtension is not DER", e); }
|
|
575
575
|
return _validateOcspExtensions(schema.walk(EXTENSIONS, node, NS).result);
|
|
576
576
|
},
|
|
577
|
+
extensionPlacement: extensionPlacement,
|
|
577
578
|
};
|
|
579
|
+
|
|
580
|
+
/** @internal Where each OCSP extension belongs, keyed by dotted OID through the registry the caller
|
|
581
|
+
* passes, with the clause that places it: the three request-only extensions (RFC 6960 sec. 4.4.3,
|
|
582
|
+
* 4.4.6, 4.4.7) and the two that a response carries in responseExtensions alone (the extended
|
|
583
|
+
* revoked definition, sec. 4.4.8, and the nonce, RFC 9654 sec. 2.1). The signer refuses one in
|
|
584
|
+
* singleExtensions and the linter grades it there from this one table. */
|
|
585
|
+
var REQUEST_ONLY_EXTENSION_ROWS = [["ocspResponse", "RFC 6960 4.4.3"], ["ocspServiceLocator", "RFC 6960 4.4.6"], ["ocspPrefSigAlgs", "RFC 6960 4.4.7"]];
|
|
586
|
+
var RESPONSE_ONLY_EXTENSION_ROWS = [["ocspExtendedRevoke", "RFC 6960 4.4.8"], ["ocspNonce", "RFC 9654 2.1"]];
|
|
587
|
+
function extensionPlacement(oidRegistry) {
|
|
588
|
+
var out = { requestOnly: intrinsic.create(null), responseOnly: intrinsic.create(null) };
|
|
589
|
+
intrinsic.forEach(REQUEST_ONLY_EXTENSION_ROWS, function (r) { out.requestOnly[oidRegistry.byName(r[0])] = r[1]; });
|
|
590
|
+
intrinsic.forEach(RESPONSE_ONLY_EXTENSION_ROWS, function (r) { out.responseOnly[oidRegistry.byName(r[0])] = r[1]; });
|
|
591
|
+
return out;
|
|
592
|
+
}
|
package/lib/x509-sign.js
CHANGED
|
@@ -140,7 +140,7 @@ function _buildExtensions(extSpec, ctx) {
|
|
|
140
140
|
var oidBc = O("basicConstraints"), oidKu = O("keyUsage"), oidNc = O("nameConstraints");
|
|
141
141
|
var arr = extSpec.map(function (e, i) {
|
|
142
142
|
var der = _reqDer(e, "extension");
|
|
143
|
-
_assertValidExtension(der, i);
|
|
143
|
+
_assertValidExtension(der, i, EXT_DECODERS);
|
|
144
144
|
var n = asn1.decode(der);
|
|
145
145
|
var extnId = asn1.read.oid(n.children[0]);
|
|
146
146
|
if (seenExt[extnId]) throw _err("x509/bad-input", "duplicate extension " + extnId + " in the extensions array (RFC 5280 sec. 4.2 -- at most one instance of an extension)");
|
|
@@ -622,4 +622,164 @@ function _sign(spec, issuer, opts) {
|
|
|
622
622
|
*/
|
|
623
623
|
function randomSerial() { return pkiBuild.randomSerial(); }
|
|
624
624
|
|
|
625
|
-
|
|
625
|
+
/** @internal One row per extension the object form of `spec.extensions` encodes, for the standalone
|
|
626
|
+
* encoder: the registry OID name, the value encoder, and how the criticality is decided. `fixed`
|
|
627
|
+
* is the value the RFC or the toolkit's posture emits, refused if a knob disagrees; `knob` marks
|
|
628
|
+
* the extensions whose criticality is the issuer's choice (or, for subjectAltName, follows a
|
|
629
|
+
* subject this encoder does not hold); `flag` marks a NULL-valued marker given as `true`. The two
|
|
630
|
+
* key identifiers take only their explicit forms here: deriving one needs the subject key or the
|
|
631
|
+
* issuer, which live in the assembled spec. */
|
|
632
|
+
function _flagValue(name, v) {
|
|
633
|
+
if (v !== true) throw _err("x509/bad-input", name + " is a flag, so it is true or omitted");
|
|
634
|
+
return asn1.build.nullValue();
|
|
635
|
+
}
|
|
636
|
+
function _standaloneSki(v) {
|
|
637
|
+
if (v === true) throw _err("x509/bad-input", "subjectKeyIdentifier: true derives the key id from the subject key, which this encoder does not hold; pass the key id bytes, or name it in spec.extensions");
|
|
638
|
+
return _extSki(_skiKeyId(v, null));
|
|
639
|
+
}
|
|
640
|
+
function _standaloneAki(v) {
|
|
641
|
+
if (v === true) throw _err("x509/bad-input", "authorityKeyIdentifier: true derives the key id from the issuer, which this encoder does not hold; pass { keyIdentifier } bytes, or name it in spec.extensions");
|
|
642
|
+
if (guard.bytes.isByteSource(v)) return _extAki(_akiKeyId(v, {}), null, null);
|
|
643
|
+
if (typeof v !== "object" || _isArray(v) || v === null) throw _err("x509/bad-input", "authorityKeyIdentifier must be a Buffer key id or an object { keyIdentifier, authorityCertIssuer, authorityCertSerialNumber }");
|
|
644
|
+
if (!guard.bytes.isByteSource(v.keyIdentifier)) {
|
|
645
|
+
throw _err("x509/bad-input", "authorityKeyIdentifier keyIdentifier must be the key id bytes here (RFC 5280 sec. 4.2.1.1 requires the field, and deriving it needs the issuer); name it in spec.extensions to derive it");
|
|
646
|
+
}
|
|
647
|
+
var f = _akiFields(v, { selfSigned: false });
|
|
648
|
+
return _extAki(f[0], f[1], f[2]);
|
|
649
|
+
}
|
|
650
|
+
var EXTENSION_ROWS = [
|
|
651
|
+
["subjectKeyIdentifier", "subjectKeyIdentifier", { fixed: false, cite: "RFC 5280 sec. 4.2.1.2" }, _standaloneSki],
|
|
652
|
+
["authorityKeyIdentifier", "authorityKeyIdentifier", { fixed: false, cite: "RFC 5280 sec. 4.2.1.1" }, _standaloneAki],
|
|
653
|
+
["keyUsage", "keyUsage", { knob: true, dflt: true }, function (v) { return _extKeyUsage(v); }],
|
|
654
|
+
["extendedKeyUsage", "extKeyUsage", { knob: true, dflt: false }, function (v) { return _extExtKeyUsage(v); }],
|
|
655
|
+
["basicConstraints", "basicConstraints", { inValue: true }, function (v) {
|
|
656
|
+
_validateBcSpec(v);
|
|
657
|
+
if (v.cA === true && v.critical === false) throw _err("x509/bad-input", "a CA certificate's basicConstraints MUST be critical (RFC 5280 sec. 4.2.1.9)");
|
|
658
|
+
if (v.pathLen != null && v.cA !== true) throw _err("x509/bad-input", "basicConstraints pathLenConstraint requires cA=TRUE (RFC 5280 sec. 4.2.1.9)");
|
|
659
|
+
return _extBasicConstraints(v);
|
|
660
|
+
}],
|
|
661
|
+
["subjectAltName", "subjectAltName", { knob: true, dflt: false }, function (v) { return _extSan(v); }],
|
|
662
|
+
["issuerAltName", "issuerAltName", { fixed: false, cite: "RFC 5280 sec. 4.2.1.7" }, function (v) { return _encodeGeneralNames(_reqDenseArray(v, "issuerAltName")); }],
|
|
663
|
+
["certificatePolicies", "certificatePolicies", { knob: true, dflt: false }, function (v) { return _extCertPolicies(v); }],
|
|
664
|
+
["nameConstraints", "nameConstraints", { fixed: true, cite: "RFC 5280 sec. 4.2.1.10" }, function (v) { return _extNameConstraints(v); }],
|
|
665
|
+
["policyConstraints", "policyConstraints", { fixed: true, cite: "RFC 5280 sec. 4.2.1.11" }, function (v) { return _extPolicyConstraints(v); }],
|
|
666
|
+
["inhibitAnyPolicy", "inhibitAnyPolicy", { fixed: true, cite: "RFC 5280 sec. 4.2.1.14" }, function (v) { return _extInhibitAnyPolicy(v); }],
|
|
667
|
+
["policyMappings", "policyMappings", { knob: true, dflt: false }, function (v) { return _extPolicyMappings(v); }],
|
|
668
|
+
["authorityInfoAccess", "authorityInfoAccess", { fixed: false, cite: "RFC 5280 sec. 4.2.2.1" }, function (v) { return _extAia(v); }],
|
|
669
|
+
["subjectInfoAccess", "subjectInfoAccess", { fixed: false, cite: "RFC 5280 sec. 4.2.2.2" }, function (v) { return _b.extSubjectInfoAccess(v); }],
|
|
670
|
+
["cRLDistributionPoints", "cRLDistributionPoints", { fixed: false, cite: "RFC 5280 sec. 4.2.1.13" }, function (v) { return _extCrlDp(v, "cRLDistributionPoints"); }],
|
|
671
|
+
["freshestCRL", "freshestCRL", { fixed: false, cite: "RFC 5280 sec. 4.2.1.15" }, function (v) { return _extCrlDp(v, "freshestCRL"); }],
|
|
672
|
+
["qcStatements", "qcStatements", { knob: true, dflt: false }, function (v) { return _extQcStatements(v); }],
|
|
673
|
+
["subjectDirectoryAttributes", "subjectDirectoryAttributes", { fixed: false, cite: "RFC 5280 sec. 4.2.1.8" }, function (v) { return _b.extSubjectDirectoryAttributes(v); }],
|
|
674
|
+
["msCertificateTemplate", "msCertificateTemplate", { fixed: false, cite: "the toolkit issues the form its readers accept" }, function (v) { return _b.extMsCertificateTemplate(v); }],
|
|
675
|
+
["msEnrollCertType", "msEnrollCertType", { fixed: false, cite: "the toolkit issues the form its readers accept" }, function (v) { return _b.extMsEnrollCertType(v); }],
|
|
676
|
+
["msCaVersion", "msCaVersion", { fixed: false, cite: "the toolkit issues the form its readers accept" }, function (v) { return _b.extMsCaVersion(v); }],
|
|
677
|
+
["msPreviousCertHash", "msPreviousCertHash", { fixed: false, cite: "the toolkit issues the form its readers accept" }, function (v) { return _b.extMsPreviousCertHash(v); }],
|
|
678
|
+
["msApplicationPolicies", "msApplicationPolicies", { fixed: false, cite: "the toolkit issues the form its readers accept" }, function (v) { return _extCertPolicies(v); }],
|
|
679
|
+
["ocspNoCheck", "ocspNoCheck", { fixed: false, cite: "RFC 6960 sec. 4.2.2.2.1" }, function (v) { return _flagValue("ocspNoCheck", v); }],
|
|
680
|
+
["precertificatePoison", "precertificatePoison", { fixed: true, cite: "RFC 6962 sec. 3.1" }, function (v) { return _flagValue("precertificatePoison", v); }],
|
|
681
|
+
["signedCertificateTimestampList", "signedCertificateTimestampList", { fixed: false, cite: "RFC 6962 sec. 3.3" }, function (v) { return _encodeSctList(v); }],
|
|
682
|
+
];
|
|
683
|
+
var EXTENSION_BY_NAME = intrinsic.create(null), EXTENSION_BY_OID = intrinsic.create(null);
|
|
684
|
+
intrinsic.forEach(EXTENSION_ROWS, function (r) {
|
|
685
|
+
var row = { name: r[0], oid: O(r[1]), rule: r[2], encode: r[3] };
|
|
686
|
+
EXTENSION_BY_NAME[r[0]] = row;
|
|
687
|
+
EXTENSION_BY_OID[row.oid] = row;
|
|
688
|
+
});
|
|
689
|
+
var KNOWN_EXTENSION_OPTS = intrinsic.assign(intrinsic.create(null), { critical: 1 });
|
|
690
|
+
|
|
691
|
+
function _extensionRow(name) {
|
|
692
|
+
if (typeof name !== "string") throw _err("x509/bad-input", "the extension name must be a registered extension name or a dotted OID string, got " + guard.text.showValue(name));
|
|
693
|
+
if (intrinsic.hasOwn(EXTENSION_BY_NAME, name)) return EXTENSION_BY_NAME[name];
|
|
694
|
+
if (oid.isDottedDecimal(name)) return intrinsic.hasOwn(EXTENSION_BY_OID, name) ? EXTENSION_BY_OID[name] : null;
|
|
695
|
+
throw _err("x509/bad-input", "unknown extension " + guard.text.showValue(name) + "; the names spec.extensions takes are accepted, and any other extension is named by its dotted OID with its extnValue pre-encoded");
|
|
696
|
+
}
|
|
697
|
+
function _extensionCritical(row, opts) {
|
|
698
|
+
var rule = row.rule, stated = opts.critical;
|
|
699
|
+
if (rule.inValue) {
|
|
700
|
+
if (stated !== undefined) throw _err("x509/bad-input", row.name + " carries its criticality in the value ({ cA, pathLen, critical }), so opts.critical does not apply");
|
|
701
|
+
return null;
|
|
702
|
+
}
|
|
703
|
+
if (rule.knob) return stated === undefined ? rule.dflt : stated;
|
|
704
|
+
if (stated !== undefined && stated !== rule.fixed) {
|
|
705
|
+
throw _err("x509/bad-input", row.name + " is emitted " + (rule.fixed ? "critical" : "non-critical") + " (" + rule.cite + "), so opts.critical cannot say otherwise");
|
|
706
|
+
}
|
|
707
|
+
return rule.fixed;
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
/**
|
|
711
|
+
* @primitive pki.x509.extension
|
|
712
|
+
* @signature pki.x509.extension(name, value, opts?) -> Buffer
|
|
713
|
+
* @since 0.7.33
|
|
714
|
+
* @status stable
|
|
715
|
+
* @spec RFC 5280 sec. 4.2
|
|
716
|
+
* @related pki.x509.sign, pki.csr.sign, pki.crl.sign
|
|
717
|
+
*
|
|
718
|
+
* Encode one X.509 `Extension` as DER, ready for the pre-encoded array form of `extensions` on
|
|
719
|
+
* `pki.x509.sign`, `pki.csr.sign`, or `pki.crl.sign`. `name` is one of the extension names
|
|
720
|
+
* `spec.extensions` takes, or a dotted OID string. For a name (or the dotted OID of one), `value`
|
|
721
|
+
* is the same plain form `spec.extensions` takes for it: the key-usage and purpose name lists, the
|
|
722
|
+
* `{ cA, pathLen, critical }` object, the GeneralName lists, the policy, constraint, access, and
|
|
723
|
+
* distribution-point objects, the statement and template objects, `true` for the NULL-valued
|
|
724
|
+
* markers, and for the two key identifiers their explicit forms (the key id bytes for
|
|
725
|
+
* `subjectKeyIdentifier`; bytes or `{ keyIdentifier, authorityCertIssuer, authorityCertSerialNumber }`
|
|
726
|
+
* with the key id present for `authorityKeyIdentifier`). The forms that derive a value from the
|
|
727
|
+
* subject key or the issuer (`true`) are refused here, since only the assembled spec holds those.
|
|
728
|
+
* For any other dotted OID, `value` is a `BufferSource` holding the already-encoded `extnValue`.
|
|
729
|
+
*
|
|
730
|
+
* The criticality follows what the signer emits for the object form. Where RFC 5280 fixes it
|
|
731
|
+
* (the key identifiers, the constraint and policy-constraint extensions, the access and
|
|
732
|
+
* distribution extensions), or the toolkit issues one form only, `opts.critical` may only restate
|
|
733
|
+
* that value. `keyUsage` (default critical), `extendedKeyUsage`, `certificatePolicies`,
|
|
734
|
+
* `policyMappings`, `qcStatements` (default non-critical), and `subjectAltName` (critical exactly
|
|
735
|
+
* when the subject is empty, which the caller knows) take `opts.critical`; `basicConstraints`
|
|
736
|
+
* carries `critical` inside its value. An unregistered OID takes `opts.critical` as stated.
|
|
737
|
+
*
|
|
738
|
+
* @opts
|
|
739
|
+
* - `critical` (boolean) -- the criticality, where the extension admits a choice.
|
|
740
|
+
*
|
|
741
|
+
* @example
|
|
742
|
+
* var ku = pki.x509.extension("keyUsage", ["digitalSignature"]);
|
|
743
|
+
* var san = pki.x509.extension("subjectAltName", ["leaf.example"]);
|
|
744
|
+
* var custom = pki.x509.extension("1.3.6.1.4.1.99999.7", pki.asn1.build.utf8("v1"), { critical: false });
|
|
745
|
+
* var pair = await pki.key.generate("Ed25519");
|
|
746
|
+
* var der = await pki.x509.sign(
|
|
747
|
+
* { subject: "leaf.example", subjectPublicKey: await pki.key.export(pair.publicKey),
|
|
748
|
+
* notBefore: new Date("2026-01-01T00:00:00Z"), notAfter: new Date("2027-01-01T00:00:00Z"),
|
|
749
|
+
* extensions: [ku, san, custom] },
|
|
750
|
+
* { key: pair.privateKey });
|
|
751
|
+
* pki.schema.x509.parse(der).extensions.length; // 3
|
|
752
|
+
*/
|
|
753
|
+
function extension(name, value, opts) {
|
|
754
|
+
var fixed = guard.bytes.fixArguments(CertificateError, "x509/bad-input", [
|
|
755
|
+
[value, "the extension value"], [opts, "pki.x509.extension options"],
|
|
756
|
+
]);
|
|
757
|
+
try { return _extension(name, fixed.values[0], fixed.values[1]); }
|
|
758
|
+
finally { fixed.release(); }
|
|
759
|
+
}
|
|
760
|
+
function _extension(name, value, opts) {
|
|
761
|
+
opts = guard.identifier.optionsObject(opts, _err, "x509/bad-input", "pki.x509.extension options");
|
|
762
|
+
guard.identifier.assertKnownKeys(opts, KNOWN_EXTENSION_OPTS, _err, "x509/bad-input", "pki.x509.extension has an unknown option ");
|
|
763
|
+
if (opts.critical !== undefined && typeof opts.critical !== "boolean") throw _err("x509/bad-input", "opts.critical must be a boolean");
|
|
764
|
+
if (value === undefined || value === null) throw _err("x509/bad-input", "the extension value is required");
|
|
765
|
+
var row = _extensionRow(name);
|
|
766
|
+
if (row === null) {
|
|
767
|
+
if (!guard.bytes.isByteSource(value)) throw _err("x509/bad-input", "an extension named by a dotted OID takes its extnValue as pre-encoded bytes");
|
|
768
|
+
var raw = guard.bytes.snapshotSource(value, CertificateError, "x509/bad-input", "the pre-encoded extnValue");
|
|
769
|
+
_b.assertExtnValueIsDer(raw, "the " + name + " extension");
|
|
770
|
+
try { return _ext(name, opts.critical === true, raw); }
|
|
771
|
+
catch (e) {
|
|
772
|
+
if (e instanceof CertificateError) throw e;
|
|
773
|
+
throw _err("x509/bad-input", "the extension name " + guard.text.showValue(name) + " is not a valid OBJECT IDENTIFIER", e);
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
if (guard.bytes.isByteSource(value) && !(row.name === "subjectKeyIdentifier" || row.name === "authorityKeyIdentifier" || row.name === "msPreviousCertHash")) {
|
|
777
|
+
throw _err("x509/bad-input", row.name + " takes the plain form spec.extensions takes, not pre-encoded bytes; name the extension by a dotted OID that is not registered to pass raw bytes");
|
|
778
|
+
}
|
|
779
|
+
var critical = _extensionCritical(row, opts);
|
|
780
|
+
var valueDer = row.encode(value);
|
|
781
|
+
if (critical === null) critical = value.critical !== false;
|
|
782
|
+
return _ext(row.oid, critical, valueDer);
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
module.exports = { sign: sign, randomSerial: randomSerial, extension: extension };
|
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:0278421d-1579-47eb-90cb-53f880acc978",
|
|
6
6
|
"version": 1,
|
|
7
7
|
"metadata": {
|
|
8
|
-
"timestamp": "2026-09-
|
|
8
|
+
"timestamp": "2026-09-12T09:51:26.213Z",
|
|
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.7.
|
|
22
|
+
"bom-ref": "@blamejs/pki@0.7.34",
|
|
23
23
|
"type": "application",
|
|
24
24
|
"name": "pki",
|
|
25
|
-
"version": "0.7.
|
|
25
|
+
"version": "0.7.34",
|
|
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.7.
|
|
29
|
+
"purl": "pkg:npm/%40blamejs/pki@0.7.34",
|
|
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.7.
|
|
57
|
+
"ref": "@blamejs/pki@0.7.34",
|
|
58
58
|
"dependsOn": []
|
|
59
59
|
}
|
|
60
60
|
]
|