Simvik

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:

  1. not_before <= now <= not_after, or CHAIN_DATES.
  2. Find its issuer: chain[i + 1] if there is one, whose subject must equal chain[i].issuer (or CHAIN_ISSUER). For the last certificate, use the root whose subject equals its issuer (or CHAIN_UNTRUSTED if no root does).
  3. The issuer must be a CA, or CHAIN_NOT_CA.
  4. If the issuer's path_len is not -1, the number of CA certificates between the issuer and the leaf (that is, i) must not be more than it, or CHAIN_PATH_LEN.
  5. chain[i].sig_ok, or CHAIN_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 signature

A 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 root

Learn it first

More TLS for embedded systems problems