#include "anchors.h"
#include "platform.h"
#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
// Where the system keeps its bundle, by distribution, after $SSL_CERT_FILE.
static const char *const system_bundles[] = {
"/etc/ssl/cert.pem", // macOS, Alpine, the BSDs
"/etc/ssl/certs/ca-certificates.crt", // Debian, Ubuntu, Arch
"/etc/pki/tls/certs/ca-bundle.crt", // Fedora, RHEL
"/etc/ssl/ca-bundle.pem", // openSUSE
};
constexpr size_t CANDIDATES_MAX = 1 + sizeof system_bundles / sizeof system_bundles[0];
static char pem[ANCHORS_FILE_MAX + 1];
static unsigned char der[ANCHORS_DER_MAX];
static size_t der_len;
static bool der_over;
__attribute__((format(printf, 3, 4)))
static bool fail(char *why, size_t cap, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vsnprintf(why, cap, fmt, ap);
va_end(ap);
return false;
}
static void der_append(void *ctx, const void *src, size_t len)
{
(void)ctx;
der_over = der_over || len > ANCHORS_DER_MAX - der_len;
if (der_over) return;
memcpy(der + der_len, src, len);
der_len += len;
}
static unsigned char *keep(Anchors *a, const void *src, size_t len)
{
ensure(len <= sizeof a->arena - a->used);
unsigned char *p = a->arena + a->used;
memcpy(p, src, len);
a->used += len;
return p;
}
static void dn_append(void *ctx, const void *src, size_t len)
{
(void)keep(ctx, src, len);
}
// The certificate in der, as a trust anchor. One BearSSL cannot read is
// counted and passed over: a system bundle may hold a key type it lacks.
static bool add_cert(Anchors *a, char *why, size_t cap)
{
if (der_over) {
a->skipped++;
return true;
}
if (a->n == ANCHORS_MAX) return fail(why, cap, "more than %zu certificates", ANCHORS_MAX);
size_t mark = a->used;
br_x509_decoder_context dc;
br_x509_decoder_init(&dc, dn_append, a);
br_x509_decoder_push(&dc, der, der_len);
const br_x509_pkey *pk = br_x509_decoder_get_pkey(&dc);
if (pk == nullptr) {
a->used = mark;
a->skipped++;
return true;
}
br_x509_trust_anchor *ta = &a->ta[a->n++];
ta->dn.data = a->arena + mark;
ta->dn.len = a->used - mark;
ta->flags = br_x509_decoder_isCA(&dc) ? BR_X509_TA_CA : 0;
ta->pkey.key_type = pk->key_type;
if (pk->key_type == BR_KEYTYPE_RSA) {
ta->pkey.key.rsa.n = keep(a, pk->key.rsa.n, pk->key.rsa.nlen);
ta->pkey.key.rsa.nlen = pk->key.rsa.nlen;
ta->pkey.key.rsa.e = keep(a, pk->key.rsa.e, pk->key.rsa.elen);
ta->pkey.key.rsa.elen = pk->key.rsa.elen;
} else {
ta->pkey.key.ec.curve = pk->key.ec.curve;
ta->pkey.key.ec.q = keep(a, pk->key.ec.q, pk->key.ec.qlen);
ta->pkey.key.ec.qlen = pk->key.ec.qlen;
}
return true;
}
bool anchors_parse(Anchors *a, const unsigned char *data, size_t len, char *why, size_t cap)
{
a->n = 0;
a->skipped = 0;
a->used = 0;
if (len > ANCHORS_FILE_MAX) return fail(why, cap, "it is over %zu bytes", ANCHORS_FILE_MAX);
br_pem_decoder_context pc;
br_pem_decoder_init(&pc);
bool in = false;
bool cert = false;
bool newline = true; // a last line without its newline is still read
bool ok = true;
while (ok && len > 0) {
size_t k = br_pem_decoder_push(&pc, data, len);
data += k;
len -= k;
int ev = br_pem_decoder_event(&pc);
if (ev == BR_PEM_BEGIN_OBJ) {
in = true;
der_len = 0;
der_over = false;
cert = strcmp(br_pem_decoder_name(&pc), "CERTIFICATE") == 0;
br_pem_decoder_setdest(&pc, der_append, nullptr);
} else if (ev == BR_PEM_END_OBJ) {
in = false;
ok = !cert || add_cert(a, why, cap);
} else if (ev == BR_PEM_ERROR) {
ok = fail(why, cap, "it is not PEM text");
}
if (len == 0 && newline) {
newline = false;
data = (const unsigned char *)"\n";
len = 1;
}
}
if (ok && in) ok = fail(why, cap, "its last PEM object has no END line");
if (!ok) a->n = 0;
return ok;
}
static unsigned my_uid(void)
{
#ifdef SUIT_TEST
// Tests pretend to be another user, so that a file of their own is not.
const char *forced = getenv("SUIT_UID");
if (forced != nullptr) return (unsigned)atoi(forced);
#endif
return platform_uid();
}
// Whether ST, of the file or folder WHAT names, may decide whom suit trusts:
// nobody but you or root can have written it. If not, BAD says why.
static bool trusted(const struct stat *st, const char *what, char *bad, size_t cap)
{
if (st->st_uid != my_uid() && st->st_uid != 0) {
snprintf(bad, cap, "%s belongs to another user", what);
return false;
}
if ((st->st_mode & 022) != 0) {
snprintf(bad, cap, "%s can be written by group or others", what);
return false;
}
return true;
}
// Read PATH, an absolute path, into pem, if it can be trusted (anchors.h). 0,
// an errno value (ENOENT is for the caller), or -1 with BAD saying why it is
// not trusted. A symbolic link is refused unless FOLLOW. The file is opened
// without waiting, so a FIFO is refused at once.
static int read_bundle(const char *path, bool follow, size_t *len, char *bad, size_t cap)
{
int fd = sys_open(path, O_RDONLY | O_CLOEXEC | O_NONBLOCK | (follow ? 0 : O_NOFOLLOW), 0);
if (fd < 0) return errno;
struct stat st;
char dir[1100];
snprintf(dir, sizeof dir, "%.*s", (int)(strrchr(path, '/') - path) + 1, path);
int err = sys_fstat(fd, &st) != 0 ? errno : 0;
if (err == 0 && !S_ISREG(st.st_mode)) {
snprintf(bad, cap, "it is not a regular file");
err = -1;
}
if (err == 0 && !trusted(&st, "it", bad, cap)) err = -1;
if (err == 0 && sys_stat(dir, &st) != 0) err = errno;
if (err == 0 && !trusted(&st, "its folder", bad, cap)) err = -1;
if (err != 0) {
(void)sys_close(fd);
return err;
}
*len = 0;
ssize_t n = 1;
while (*len <= ANCHORS_FILE_MAX && n > 0) {
n = sys_read(fd, pem + *len, ANCHORS_FILE_MAX + 1 - *len);
if (n < 0 && errno == EINTR) {
n = 1;
continue;
}
*len += n > 0 ? (size_t)n : 0;
}
err = n < 0 ? errno : 0;
(void)sys_close(fd);
return err;
}
bool anchors_load(Anchors *a, const char *ca_file, char *path, size_t pcap, char *why, size_t cap)
{
a->n = 0;
a->skipped = 0;
const char *list[CANDIDATES_MAX];
size_t n = 0;
if (ca_file != nullptr) {
list[n++] = ca_file;
} else {
const char *env = sys_getenv("SSL_CERT_FILE");
if (env != nullptr && env[0] != '\0') list[n++] = env;
#ifdef SUIT_TEST
// Tests name the one system bundle there is, or one that is not there.
const char *forced = getenv("SUIT_CA_BUNDLE");
if (forced != nullptr) list[n++] = forced;
for (size_t i = 0; forced == nullptr && i < sizeof system_bundles / sizeof system_bundles[0]; i++)
list[n++] = system_bundles[i];
#else
for (size_t i = 0; i < sizeof system_bundles / sizeof system_bundles[0]; i++)
list[n++] = system_bundles[i];
#endif
}
char tried[1400] = "";
size_t at = 0;
for (size_t i = 0; i < n; i++) {
size_t len = 0;
char bad[100];
const char *wrong = anchors_path_check(list[i]);
if (wrong != nullptr) return fail(why, cap, "%.300s: %s", list[i], wrong);
int err = read_bundle(list[i], ca_file == nullptr, &len, bad, sizeof bad);
if (err == ENOENT) {
int w = snprintf(tried + at, sizeof tried - at, "%s%.200s", i > 0 ? ", " : "", list[i]);
at += (size_t)w;
continue;
}
snprintf(path, pcap, "%s", list[i]);
if (err < 0) return fail(why, cap, "%.300s is not trusted: %s", list[i], bad);
if (err != 0) return fail(why, cap, "cannot read %.300s: %s", list[i], strerror(err));
char inner[200];
if (!anchors_parse(a, (const unsigned char *)pem, len, inner, sizeof inner))
return fail(why, cap, "%.300s: %s", list[i], inner);
if (a->n == 0) return fail(why, cap, "%.300s holds no certificate suit can use", list[i]);
return true;
}
snprintf(path, pcap, "%s", "");
return fail(why, cap, "no certificate file: none of %s exists%s", tried,
ca_file == nullptr ? "; set SSL_CERT_FILE to the system's bundle" : "");
}
const char *anchors_path_check(const char *path)
{
size_t n = strlen(path);
if (n == 0 || n > 1024) return "a certificate file's path is 1 to 1024 characters";
if (path[0] != '/') return "a certificate file's path is absolute";
for (size_t i = 0; i < n; i++)
if ((unsigned char)path[i] < 0x21 || (unsigned char)path[i] > 0x7e)
return "a certificate file's path has printable characters only, and no space";
return nullptr;
}