Is the certificate valid?
Check a server certificate's validity period and hostname, including wildcards. A medium embedded C problem (TLS for embedded systems), run and graded in the…
medium · TLS for embedded systems · tls · certificates · strings
Before trusting a server, a TLS client checks (besides the signature chain) that the certificate:
- is currently valid:
not_before <= now <= not_after, with times as 14-character stringsYYYYMMDDhhmmss(which compare correctly as strings), - names the host: the certificate name equals the hostname (ignoring case), or is a wildcard
*.example.comthat matches exactly one extra label (api.example.commatches,example.comanda.b.example.comdo not).
Write name_matches(cert_name, host) and cert_ok(not_before, not_after, now, cert_name, host), returning 0 if valid, 1 if not yet valid, 2 if expired, 3 if the name does not match (checking the dates first).
Starter code
bool name_matches(const char *cert_name, const char *host) {
return strcmp(cert_name, host) == 0;
}
int cert_ok(const char *not_before, const char *not_after, const char *now, const char *cert_name, const char *host) {
if (strcmp(now, not_after) > 0) return 2;
(void)not_before;
return name_matches(cert_name, host) ? 0 : 3;
}Example tests
An exact name
show("20260101000000", "20270101000000", "20261012120000", "broker.example.com", "broker.example.com");
show("20260101000000", "20270101000000", "20261012120000", "broker.example.com", "Broker.Example.COM");Expected output:
broker.example.com for broker.example.com: valid
broker.example.com for Broker.Example.COM: validDates
show("20260101000000", "20260601000000", "20261012120000", "a.io", "a.io");
show("20261101000000", "20271101000000", "20261012120000", "a.io", "a.io");Expected output:
a.io for a.io: expired
a.io for a.io: not yet validLearn it first
- TLS for embedded systems · Handshakes, certificates, PSK, DTLS and fitting TLS in RAM.
More TLS for embedded systems problems
- 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.
- Verify a certificate chain · Walk a server's certificate chain to a trusted root, checking names, CA flags, path length, dates and signatures.