Simvik

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 strings YYYYMMDDhhmmss (which compare correctly as strings),
  • names the host: the certificate name equals the hostname (ignoring case), or is a wildcard *.example.com that matches exactly one extra label (api.example.com matches, example.com and a.b.example.com do 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: valid

Dates

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 valid

Learn it first

More TLS for embedded systems problems