nish/crypto/pki
Whether the certificate chain a TLS server sent leads to a root the program trusts and names the host it dialled: RFC 5280 §6 path validation and RFC 6125 §6 hostname matching, at the instant the caller gives.
import {
PKI_ERR_BAD_SIGNATURE,
PKI_ERR_BUDGET,
PKI_ERR_CHAIN_TOO_LONG,
PKI_ERR_DISTRUSTED,
PKI_ERR_EXPIRED,
PKI_ERR_EXT_KEY_USAGE,
PKI_ERR_HOSTNAME,
PKI_ERR_KEY_USAGE,
PKI_ERR_MALFORMED,
PKI_ERR_NAME_CONSTRAINTS,
PKI_ERR_NOT_CA,
PKI_ERR_NOT_YET_VALID,
PKI_ERR_PATH_LENGTH,
PKI_ERR_UNKNOWN_CRITICAL,
PKI_ERR_UNSUPPORTED_ALGORITHM,
PKI_ERR_UNTRUSTED,
PKI_ERR_WEAK_KEY,
PKI_MAX_CHAIN_BYTES,
PKI_MAX_CHAIN_CERTS,
PKI_MAX_NAMES,
PKI_MAX_NAME_CHECKS,
PKI_MAX_PATH,
PKI_MAX_SIGNATURES,
PKI_MAX_SUBTREES,
PKI_MIN_RSA_BITS,
PKI_OK,
PkiResult,
PkiTrustStore,
pkiDistrustSpki,
pkiMatchHostname,
pkiReason,
pkiTrustStore,
pkiVerifyServer,
pkiVerifySignature,
} from "nish/crypto/pki";
import { pkiLoadSystemRoots } from "nish/crypto/pki-roots";
import { PKI_OK, PkiResult, PkiTrustStore, pkiReason, pkiTrustStore, pkiVerifyServer } from "nish/crypto/pki";
// chain: each certificate's DER as the server sent it, the leaf first
const check = (chain: u8[][], host: string, store: PkiTrustStore): boolean => {
const r: PkiResult = pkiVerifyServer(chain, host, toI64(Date.now()), store);
if (r.code !== PKI_OK) {
console.log(pkiReason(r.code));
return false;
}
// r.path: the leaf first, the trusted root last
return true;
};
export const main = (): i32 => {
const store: PkiTrustStore = pkiTrustStore(pkiLoadSystemRoots().roots);
const chain: u8[][] = [];
return check(chain, "example.com", store) ? 0 : 1;
};
pkiDistrustSpki
Distrusts a key in store: from now on, pkiVerifyServer refuses with PKI_ERR_DISTRUSTED a path that holds any certificate, the leaf, an intermediate or a root, whose subjectPublicKeyInfo DER hashes to spkiSha256 under SHA-256.
pkiMatchHostname
Whether leaf names hostname (RFC 6125 §6.4): an address against the subjectAltName iPAddresses, octet for octet; any other name, ASCII and compared without case after one trailing dot is stripped from each side, against the dNSNames, a wildcard only as a whole leftmost label.
pkiReason
A sentence for code, for a log or an error message.
pkiTrustStore
A store of roots, indexed by subject; a root whose DER is one already given is kept once.
pkiVerifyServer
Verifies a TLS server's chain: chain holds each certificate's DER as the server sent it, the leaf first; hostname is the name or address dialled, ASCII (an internationalised name in its A-label form); nowMs is the instant to judge validity at, milliseconds since 1970-01-01 UTC; store holds the roots trusted.
pkiVerifySignature
Whether cert's signature verifies under issuer's key: ECDSA with SHA-256 or SHA-384 under P-256 or P-384, RSA PKCS#1 v1.5 with SHA-256, SHA-384 or SHA-512 and RSASSA-PSS under a key of PKI_MIN_RSA_BITS or more whose modulus is a whole number of bytes, and Ed25519.
PkiResult
What pkiVerifyServer found.
PkiTrustStore
The roots a program trusts, indexed by their subject Name.
The network chooses every byte of chain (docs/security/crypto-pki.md,
"Threat model"), so every refusal has a reason code of its own and every
cost has a named bound: the certificates and bytes of a chain, the names
and subtrees of a certificate, the certificates of a path, the signatures
checked and the name comparisons made by one call.
The chain's first certificate is the leaf; the rest are a pool, in any order and possibly with extras, as servers send them. A path is searched for depth first from the leaf: an issuer is a root of the store, tried first, or a pool certificate, whose subject is the child's issuer Name byte for byte, and whose subjectKeyIdentifier, when both it and the child's authorityKeyIdentifier are present, is that identifier. A certificate is never twice in a path.
A path ends at a root, whose own signature is not read, but whose validity, critical extensions, basicConstraints, extKeyUsage, name constraints and key identifiers are checked as an intermediate's are, as x509-limbo's cases ask. Every check of an issuer is made as it is added, against the certificates below it, so a refusal ends that branch at once; the leaf's profile (CA/Browser Forum Baseline Requirements §7.1) is checked once a path is found.
When no path is accepted, the reason is that of the attempt that got nearest a root: one that reached a root beats any that did not, a longer one a shorter, and the first found a later one of the same length.
An extension marked against RFC 5280 §4.2 refuses the chain, but for a non-critical nameConstraints, which binds as a critical one does. Revocation (CRLs, OCSP, Certificate Transparency), certificate policies, RFC 5280 §7.1's Name folding and that nameConstraints are not checked; each is a finding of docs/security/crypto-pki.md. Nothing here is secret — certificates, names and public keys — so nothing is wiped.
Written for this module from RFC 5280 (§4.2 and §6.1), RFC 6125 (§6.4), RFC 4291 §2.2 and RFC 3986 §3.2.2 (address literals), RFC 5758, RFC 8017 and RFC 4055 (the signature algorithms), RFC 8032 (Ed25519) and the Baseline Requirements §7.1, and checked against x509-limbo (tests/link/crypto_pki_limbo).
Private helpers share the importing program's flat symbol namespace
(docs/wp26-stdlib.md §3e), which is why each one carries the module's name.
Functions
pkiDistrustSpki
Distrusts a key in store: from now on, pkiVerifyServer refuses with
PKI_ERR_DISTRUSTED a path that holds any certificate, the leaf, an
intermediate or a root, whose subjectPublicKeyInfo DER hashes to
spkiSha256 under SHA-256. A certificate's DER is X509Certificate.spki;
sha256 of nish/crypto/sha256 hashes it. The key is refused whatever
name or certificate carries it, so one entry covers a CA's cross-signs and
reissues. A store distrusts nothing until this is called.
const pkiDistrustSpki: (
store: PkiTrustStore,
spkiSha256: u8[],
) => boolean
storePkiTrustStorerequiredThe store to add the hash to.
spkiSha256u8[]requiredThe SHA-256 of the subjectPublicKeyInfo DER, 32 bytes.
returnsbooleanWhether the hash was added: false, and nothing added, unless it is 32 bytes long.
pkiMatchHostname
Whether leaf names hostname (RFC 6125 §6.4): an address against the
subjectAltName iPAddresses, octet for octet; any other name, ASCII and
compared without case after one trailing dot is stripped from each side,
against the dNSNames, a wildcard only as a whole leftmost label. The
subject's common name is never read, so a certificate without a
subjectAltName names no host. Nothing but the names is checked.
const pkiMatchHostname: (
leaf: X509Certificate,
hostname: string,
) => boolean
leafX509CertificaterequiredThe certificate the server presented as its own.
hostnamestringrequiredThe name or address dialled: a DNS name, ASCII, or an IPv4 or IPv6 address, the IPv6 one bare or in brackets.
returnsbooleantrue when one of leaf's names matches hostname.
pkiReason
A sentence for code, for a log or an error message.
const pkiReason: (code: i32) => string
codei32requiredPKI_OK or a PKI_ERR_ constant.
returnsstringWhat the code means, or "unknown reason" for any other number.
pkiTrustStore
A store of roots, indexed by subject; a root whose DER is one already
given is kept once. Nothing about a root is checked here: its validity and
extensions are checked when a path reaches it.
const pkiTrustStore: (
roots: X509Certificate[],
) => PkiTrustStore
rootsX509Certificate[]requiredThe certificates to trust, as x509ParseCertificate gave them.
returnsPkiTrustStore
A new store, whose lists hold the given certificates themselves,
not copies; roots itself is not kept.
pkiVerifyServer
Verifies a TLS server's chain: chain holds each certificate's DER as the
server sent it, the leaf first; hostname is the name or address dialled,
ASCII (an internationalised name in its A-label form); nowMs is the
instant to judge validity at, milliseconds since 1970-01-01 UTC; store
holds the roots trusted. PKI_OK with the path, or the reason it was
refused.
When several reasons apply, the first in this order is given: an empty
chain is PKI_ERR_MALFORMED; more than PKI_MAX_CHAIN_CERTS certificates
or PKI_MAX_CHAIN_BYTES bytes is PKI_ERR_CHAIN_TOO_LONG; then, certificate
by certificate in the order sent, one that does not parse is
PKI_ERR_MALFORMED and one with more than PKI_MAX_NAMES names or
PKI_MAX_SUBTREES subtrees is PKI_ERR_BUDGET; then the leaf's own checks,
in turn its validity, an unknown critical extension, being a CA, its key
usage, its extended key usage and the host name; then whether its key is
distrusted (pkiDistrustSpki); then the path search,
whose reason the module's header ranks, or PKI_ERR_BUDGET when it ran out
of signatures or name comparisons; and last, once a path is found, the
leaf's profile.
const pkiVerifyServer: (
chain: u8[][],
hostname: string,
nowMs: i64,
store: PkiTrustStore,
) => PkiResult
chainu8[][]requiredEach certificate's DER as the server sent it, the leaf first.
hostnamestringrequiredThe name or address dialled.
nowMsi64requiredThe instant to judge validity at, in milliseconds since 1970-01-01 UTC.
storePkiTrustStorerequiredThe roots trusted.
returnsPkiResult
A new result: PKI_OK with a fresh path, or a reason with an
empty one.
pkiVerifySignature
Whether cert's signature verifies under issuer's key: ECDSA with SHA-256
or SHA-384 under P-256 or P-384, RSA PKCS#1 v1.5 with SHA-256, SHA-384 or
SHA-512 and RSASSA-PSS under a key of PKI_MIN_RSA_BITS or more whose
modulus is a whole number of bytes, and Ed25519. Nothing else about either certificate is checked.
const pkiVerifySignature: (
cert: X509Certificate,
issuer: X509Certificate,
) => boolean
certX509CertificaterequiredThe certificate whose signature is checked.
issuerX509CertificaterequiredThe certificate whose subject public key is to have made it.
returnsboolean
true when the signature verifies; false for a bad signature, a
weak or unparsable key, or an algorithm not listed here.
Classes
PkiResult
What pkiVerifyServer found.
class PkiResult
| Member | |
|---|---|
new PkiResult(code: i32, path: X509Certificate[]) |
One verification's answer, as pkiVerifyServer gives it. |
code: i32 |
PKI_OK or a PKI_ERR_ constant. |
path: X509Certificate[] |
When PKI_OK, the path: the leaf first, the root last; otherwise empty. |
PkiTrustStore
The roots a program trusts, indexed by their subject Name.
class PkiTrustStore
| Member | |
|---|---|
new PkiTrustStore() |
An empty store; pkiTrustStore builds a filled one. |
roots: X509Certificate[] |
Every root, in the order given, no two with the same DER. |
Limits
1,048,576
PKI_MAX_CHAIN_BYTES: i32
The most bytes a chain's certificates may total: 1 MiB.
128
PKI_MAX_CHAIN_CERTS: i32
The most certificates a chain may hold, the leaf among them.
1,024
PKI_MAX_NAMES: i32
The most subjectAltName dNSNames and iPAddresses together a certificate may carry.
250,000
PKI_MAX_NAME_CHECKS: i32
The most name-against-subtree comparisons one call makes.
8
PKI_MAX_PATH: i32
The most certificates in a path, the leaf and the root among them.
64
PKI_MAX_SIGNATURES: i32
The most signatures one call checks.
256
PKI_MAX_SUBTREES: i32
The most permitted and excluded subtrees together a certificate may carry.
2,048
PKI_MIN_RSA_BITS: i32
The shortest RSA modulus accepted, in bits.
Constants
5
PKI_ERR_BAD_SIGNATURE: i32
A signature does not verify under its issuer's key, or the key is not one.
16
PKI_ERR_BUDGET: i32
The chain asks for more work than one call does: signatures, names or subtrees.
15
PKI_ERR_CHAIN_TOO_LONG: i32
The chain or a path is longer than its bound.
17
PKI_ERR_DISTRUSTED: i32
A certificate on the path has a key the caller distrusts: the SHA-256 of
its subjectPublicKeyInfo is one pkiDistrustSpki added to the store.
2
PKI_ERR_EXPIRED: i32
A certificate's notAfter is before the instant given.
9
PKI_ERR_EXT_KEY_USAGE: i32
An extKeyUsage lacks serverAuth, the leaf's allows any, or the root has one.
12
PKI_ERR_HOSTNAME: i32
The leaf's subjectAltName does not name the host.
8
PKI_ERR_KEY_USAGE: i32
An issuer's keyUsage lacks keyCertSign, or the leaf's lacks digitalSignature or has keyCertSign.
1
PKI_ERR_MALFORMED: i32
The chain is empty, a certificate in it is not one x509ParseCertificate
reads, or a certificate on the path breaks the profile a server's chain
keeps: a key identifier, serial number or dNSName.
11
PKI_ERR_NAME_CONSTRAINTS: i32
A name below an issuer is outside its nameConstraints, they are of a form not checked, or the leaf has some.
6
PKI_ERR_NOT_CA: i32
An issuer is not a v3 certificate with basicConstraints cA, or the leaf is a CA.
3
PKI_ERR_NOT_YET_VALID: i32
A certificate's notBefore is after the instant given.
7
PKI_ERR_PATH_LENGTH: i32
An issuer's pathLenConstraint is fewer than the intermediates below it.
10
PKI_ERR_UNKNOWN_CRITICAL: i32
A certificate carries a critical extension nish/crypto/x509 does not decode.
14
PKI_ERR_UNSUPPORTED_ALGORITHM: i32
A signature algorithm is SHA-1, unknown, or not one the issuer's key makes, or the leaf's key is of no type offered.
4
PKI_ERR_UNTRUSTED: i32
No path leads to a root of the store.
13
PKI_ERR_WEAK_KEY: i32
An RSA key is shorter than PKI_MIN_RSA_BITS, or its modulus is not a whole number of bytes.
0
PKI_OK: i32
The chain leads to a trusted root, every check passed and the leaf names the host.

