Verify a certificate chain
Walk a server's certificate chain to a trusted root, checking names, CA flags, path length, dates and signatures. A hard embedded C problem (TLS for embedded…
hard · TLS for embedded systems · tls · certificates · security · x509
A TLS server sends its certificate chain[0] (the leaf), then the intermediate CAs that issued it, chain[1] up to chain[n-1]. The device keeps a few trusted root certificates, roots[0..nroots). The server does not send the root.
Write verify_chain(chain, n, roots, nroots, now, at). Check each certificate chain[i], for i from 0 to n - 1, in this order:
not_before <= now <= not_after, orCHAIN_DATES.- Find its issuer:
chain[i + 1]if there is one, whosesubjectmust equalchain[i].issuer(orCHAIN_ISSUER). For the last certificate, use the root whose subject equals its issuer (orCHAIN_UNTRUSTEDif no root does). - The issuer must be a CA, or
CHAIN_NOT_CA. - If the issuer's
path_lenis not -1, the number of CA certificates between the issuer and the leaf (that is,i) must not be more than it, orCHAIN_PATH_LEN. chain[i].sig_ok, orCHAIN_SIGNATURE.
Then check the root's dates (or return CHAIN_DATES with *at = n). Set *at to the index of the certificate that failed (n for the root), and return CHAIN_OK if everything passes.
Starter code
int verify_chain(const cert_t *chain, int n, const cert_t *roots, int nroots, const char *now, int *at) {
(void)roots; (void)nroots; (void)now;
for (int i = 0; i < n; i++) {
if (!chain[i].sig_ok) { *at = i; return CHAIN_SIGNATURE; }
}
return CHAIN_OK;
}Example tests
A good chain, and one with a broken signature
cert_t chain[2] = {
{ "broker.example.com", "Example Issuing CA", false, -1, NB, NA, true },
{ "Example Issuing CA", "Example Root", true, 0, NB, NA, true },
};
verify("good", chain, 2, &root_ca, 1);
chain[1].sig_ok = false;
verify("tampered intermediate", chain, 2, &root_ca, 1);Expected output:
good: ok
tampered intermediate: cert 1 bad signatureA leaf used as a CA, and an unknown root
cert_t chain[2] = {
{ "evil.example.com", "broker.example.com", false, -1, NB, NA, true },
{ "broker.example.com", "Example Root", false, -1, NB, NA, true },
};
verify("leaf as CA", chain, 2, &root_ca, 1);
verify("wrong trust store", chain + 1, 1, &other_ca, 1);Expected output:
leaf as CA: cert 0 issuer is not a CA
wrong trust store: cert 0 no trusted rootLearn it first
- TLS for embedded systems · Handshakes, certificates, PSK, DTLS and fitting TLS in RAM.
More TLS for embedded systems problems
- Is the certificate valid? · Check a server certificate's validity period and hostname, including wildcards.
- Read TLS records from a byte stream · Validate a TLS record header as soon as it arrives, and tell the caller whether to wait for more bytes.