#include "tls.h"
#include "anchors.h"
#include "platform.h"
#include "remote.h"
#include <errno.h>
#include <netdb.h>
#include <poll.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// One address from the name lookup, as the lookup's child process sends it.
// The first record's err is getaddrinfo's result.
typedef struct {
int32_t err;
int32_t family;
int32_t socktype;
int32_t protocol;
uint32_t len;
struct sockaddr_storage addr;
} Addr;
constexpr size_t ADDRS_MAX = 16;
typedef struct {
Anchors anchors;
br_ssl_client_context cc;
br_x509_minimal_context xc;
br_sslio_context io;
unsigned char iobuf[BR_SSL_BUFSIZE_BIDI];
fsl_xfer *xf;
int fd;
uint64_t deadline; // CLOCK_MONOTONIC ns; 0 until the first connection
bool eof; // the server closed TCP
bool stalled; // nothing moved for the idle limit
bool unflushed; // write() put bytes in the engine that are not sent yet
bool failed_tls;
char why[300]; // what failed in the transport, for the message
} Tls;
static Tls tls;
static Addr addrs[ADDRS_MAX];
static fsl_sc channel;
__attribute__((format(printf, 2, 3)))
static int why(Tls *t, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vsnprintf(t->why, sizeof t->why, fmt, ap);
va_end(ap);
return -1;
}
int tls_idle_seconds(void)
{
#ifdef SUIT_TEST
const char *forced = getenv("SUIT_NET_TIMEOUT");
if (forced != nullptr) return atoi(forced);
#endif
return TLS_IDLE_SECONDS;
}
static uint64_t deadline_ns(void)
{
#ifdef SUIT_TEST
const char *forced = getenv("SUIT_NET_DEADLINE");
if (forced != nullptr) return (uint64_t)atoi(forced) * 1000000000u;
#endif
return (uint64_t)TLS_DEADLINE_SECONDS * 1000000000u;
}
// Wait until FD is ready for EV, within the idle limit and the deadline.
// WHAT names the other end for the message.
static int wait_fd(Tls *t, int fd, short ev, const char *what)
{
int idle = fsl_xfer_socket_timeout(t->xf);
for (;;) {
uint64_t now;
if (!sys_now_ns(&now)) return why(t, "cannot read the clock: %s", strerror(errno));
if (t->deadline == 0) t->deadline = now + deadline_ns();
if (now >= t->deadline)
return why(t, "the transfer took longer than %d seconds", (int)(deadline_ns() / 1000000000u));
uint64_t left = (t->deadline - now) / 1000000u + 1;
int ms = left < (uint64_t)idle * 1000u ? (int)left : idle * 1000;
int r = sys_poll(fd, ev, ms);
if (r > 0) return 0;
if (r == 0 && ms == idle * 1000) {
t->stalled = true;
return why(t, "%s sent nothing for %d seconds", what, idle);
}
if (r < 0 && errno != EINTR) return why(t, "poll: %s", strerror(errno));
}
}
// ---- the name lookup --------------------------------------------------------
// getaddrinfo has no time limit, so it runs in a child process that sends
// what it found down FD and ends.
[[noreturn]] static void resolve_child(int fd, const char *host, const char *port)
{
struct addrinfo hints;
memset(&hints, 0, sizeof hints);
hints.ai_socktype = SOCK_STREAM;
struct addrinfo *res = nullptr;
Addr a;
memset(&a, 0, sizeof a);
a.err = sys_getaddrinfo(host, port, &hints, &res);
if (a.err != 0) (void)sys_send(fd, &a, sizeof a);
for (const struct addrinfo *r = res; r != nullptr; r = r->ai_next) {
ensure(r->ai_addrlen <= sizeof a.addr);
a.family = r->ai_family;
a.socktype = r->ai_socktype;
a.protocol = r->ai_protocol;
a.len = (uint32_t)r->ai_addrlen;
memcpy(&a.addr, r->ai_addr, r->ai_addrlen);
(void)sys_send(fd, &a, sizeof a);
}
sys_child_exit(0);
}
// The addresses of HOST, in addrs: how many, or -1.
static int lookup(Tls *t, const char *host, int port)
{
char p[8];
snprintf(p, sizeof p, "%d", port);
int sv[2];
if (sys_socketpair(sv) != 0) return why(t, "cannot look up %s: socketpair: %s", host, strerror(errno));
// A fork without exec: safe because suit is single-threaded.
pid_t pid = sys_fork();
if (pid < 0) {
int err = errno;
(void)sys_close(sv[0]);
(void)sys_close(sv[1]);
return why(t, "cannot look up %s: fork: %s", host, strerror(err));
}
if (pid == 0) {
(void)sys_close(sv[0]);
resolve_child(sv[1], host, p);
}
(void)sys_close(sv[1]);
int n = -1;
if (wait_fd(t, sv[0], POLLIN, "the name lookup") == 0) {
// The child sends everything and ends, so this stops at its end.
ssize_t got = sys_recv_all(sv[0], addrs, sizeof addrs);
n = got < (ssize_t)sizeof addrs[0] ? why(t, "the name lookup of %s gave no answer", host)
: addrs[0].err != 0 ? why(t, "cannot find %s: %s", host, gai_strerror(addrs[0].err))
: (int)((size_t)got / sizeof addrs[0]);
}
// A child still busy with the lookup is stopped; one that ended is reaped.
if (sys_signal(pid, SIGKILL) == 0) (void)sys_wait4(pid, nullptr, nullptr);
(void)sys_close(sv[0]);
return n;
}
// ---- TCP ---------------------------------------------------------------------
static void drop(Tls *t)
{
(void)sys_close(t->fd);
t->fd = -1;
}
static int try_addr(Tls *t, const Addr *a, const char *host, int port)
{
t->fd = sys_socket(a->family, a->socktype, a->protocol);
if (t->fd < 0) return why(t, "cannot connect to %s:%d: socket: %s", host, port, strerror(errno));
if (sys_set_nonblock(t->fd) != 0) {
why(t, "cannot connect to %s:%d: fcntl: %s", host, port, strerror(errno));
drop(t);
return -1;
}
int r = sys_connect(t->fd, (const struct sockaddr *)&a->addr, (socklen_t)a->len);
// Both sides are evaluated: errno matters only when connect failed.
int err = ((r != 0) & (errno != EINPROGRESS)) ? errno : 0;
if (err == 0 && wait_fd(t, t->fd, POLLOUT, "the server") != 0) {
drop(t);
return -1;
}
if (err == 0 && sys_socket_error(t->fd, &err) != 0) err = errno;
if (err != 0) {
why(t, "cannot connect to %s:%d: %s", host, port, strerror(err));
drop(t);
return -1;
}
return 0;
}
static int tcp_open(Tls *t, const char *host, int port)
{
int n = lookup(t, host, port);
for (int i = 0; i < n; i++)
if (try_addr(t, &addrs[i], host, port) == 0) return 0;
return -1;
}
// ---- BearSSL's transport -----------------------------------------------------
static int ll_read(void *ctx, unsigned char *buf, size_t len)
{
Tls *t = ctx;
for (;;) {
if (wait_fd(t, t->fd, POLLIN, "the server") != 0) return -1;
ssize_t n = sys_recv(t->fd, buf, len);
if (n > 0) return (int)n;
if (n == 0) {
t->eof = true;
return why(t, "the server closed the connection");
}
if (errno != EINTR && errno != EAGAIN) return why(t, "recv: %s", strerror(errno));
}
}
static int ll_write(void *ctx, const unsigned char *buf, size_t len)
{
Tls *t = ctx;
for (;;) {
if (wait_fd(t, t->fd, POLLOUT, "the server") != 0) return -1;
ssize_t n = sys_send(t->fd, buf, len);
if (n >= 0) return (int)n;
if (errno != EINTR && errno != EAGAIN) return why(t, "send: %s", strerror(errno));
}
}
// ---- the stream channel's callbacks -----------------------------------------
static const struct {
int err;
const char *text;
} tls_texts[] = {
{BR_ERR_X509_EXPIRED, "the server's certificate has expired or is not valid yet"},
{BR_ERR_X509_BAD_SERVER_NAME, "the server's certificate is for another host name"},
{BR_ERR_X509_NOT_TRUSTED, "the server's certificate is not signed by a CA suit trusts"},
};
void tls_error_text(int e, char *out, size_t cap)
{
for (size_t i = 0; i < sizeof tls_texts / sizeof tls_texts[0]; i++) {
if (tls_texts[i].err == e) {
snprintf(out, cap, "%s", tls_texts[i].text);
return;
}
}
if (e >= BR_ERR_SEND_FATAL_ALERT) {
snprintf(out, cap, "suit ended the handshake with TLS alert %d", e - BR_ERR_SEND_FATAL_ALERT);
return;
}
if (e >= BR_ERR_RECV_FATAL_ALERT) {
int alert = e - BR_ERR_RECV_FATAL_ALERT;
snprintf(out, cap, "the server ended the handshake with TLS alert %d%s", alert,
alert == 70 ? " (protocol version): it may offer only TLS 1.3, and suit speaks TLS 1.2"
: ": suit offers only TLS 1.2 with ECDHE and AES-GCM or ChaCha20-Poly1305");
return;
}
snprintf(out, cap, "TLS error %d (BearSSL's code)", e);
}
// Report the failure of STEP, as TLS's or the transport's. Returns -1.
static int failed(Tls *t, const char *step)
{
int e = br_ssl_engine_last_error(&t->cc.eng);
t->failed_tls = (e != BR_ERR_OK) & (e != BR_ERR_IO);
char text[200];
tls_error_text(e, text, sizeof text);
(void)fsl_xfer_errorf(t->xf, FSL_RC_IO, "%s: %s", step, t->failed_tls ? text : t->why);
return -1;
}
static int ch_connect(void *state, fsl_url const *url, fsl_xfer *xf)
{
Tls *t = state;
t->xf = xf;
t->eof = false;
t->stalled = false;
t->unflushed = false;
t->failed_tls = false;
snprintf(t->why, sizeof t->why, "the connection ended");
int port = url->port > 0 ? url->port : 443;
if (tcp_open(t, url->host, port) != 0) return fsl_xfer_errorf(xf, FSL_RC_IO, "%s", t->why);
// A failed reset leaves the engine closed with its error, which the
// handshake reports.
(void)br_ssl_client_reset(&t->cc, url->host, 1);
br_sslio_init(&t->io, &t->cc.eng, ll_read, t, ll_write, t);
if (br_sslio_flush(&t->io) == 0) return 0;
int rc = failed(t, "the TLS handshake");
drop(t);
return rc;
}
static fsl_int_t ch_read(void *state, void *dest, fsl_size_t n, fsl_xfer *xf)
{
Tls *t = state;
t->xf = xf;
if (t->unflushed) {
t->unflushed = false;
if (br_sslio_flush(&t->io) != 0) return failed(t, "send the request");
}
int got = br_sslio_read(&t->io, dest, (size_t)n);
if (got > 0) return got;
int e = br_ssl_engine_last_error(&t->cc.eng);
if (e == BR_ERR_OK) return 0;
if (t->eof) return FSL_SC_STREAM_UNCLEAN;
if (t->stalled) return FSL_SC_STREAM_TIMEOUT;
return failed(t, "read the reply");
}
static fsl_int_t ch_write(void *state, void const *src, fsl_size_t n, fsl_xfer *xf)
{
Tls *t = state;
t->xf = xf;
int got = br_sslio_write(&t->io, src, (size_t)n);
if (got < 0) return failed(t, "send the request");
t->unflushed = true;
return got;
}
// BearSSL answers the server's close_notify while it reads, so by now the
// engine is closed or failed and there is nothing left to send.
static void ch_close(void *state)
{
drop(state);
}
static const fsl_sc_stream_ops ops = {ch_connect, ch_read, ch_write, ch_close, &tls};
// ---- setting up --------------------------------------------------------------
static void configure(Tls *t, const unsigned char *seed, size_t seed_len, int64_t now)
{
// TLS 1.2 only, ECDHE key exchange only, AEAD ciphers only.
static const uint16_t suites[] = {
BR_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
BR_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
BR_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
BR_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
BR_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
BR_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
};
static const struct {
int id;
const br_hash_class *impl;
} hashes[] = {
{br_sha224_ID, &br_sha224_vtable},
{br_sha256_ID, &br_sha256_vtable},
{br_sha384_ID, &br_sha384_vtable},
{br_sha512_ID, &br_sha512_vtable},
};
br_ssl_engine_context *eng = &t->cc.eng;
br_ssl_client_zero(&t->cc);
br_ssl_engine_set_versions(eng, BR_TLS12, BR_TLS12);
br_ssl_engine_set_suites(eng, suites, sizeof suites / sizeof suites[0]);
br_x509_minimal_init(&t->xc, &br_sha256_vtable, t->anchors.ta, t->anchors.n);
br_ssl_engine_set_default_rsavrfy(eng);
br_ssl_engine_set_default_ecdsa(eng);
br_x509_minimal_set_rsa(&t->xc, br_ssl_engine_get_rsavrfy(eng));
br_x509_minimal_set_ecdsa(&t->xc, br_ssl_engine_get_ec(eng), br_ssl_engine_get_ecdsa(eng));
for (size_t i = 0; i < sizeof hashes / sizeof hashes[0]; i++) {
br_ssl_engine_set_hash(eng, hashes[i].id, hashes[i].impl);
br_x509_minimal_set_hash(&t->xc, hashes[i].id, hashes[i].impl);
}
br_ssl_engine_set_x509(eng, &t->xc.vtable);
br_ssl_engine_set_prf_sha256(eng, &br_tls12_sha256_prf);
br_ssl_engine_set_prf_sha384(eng, &br_tls12_sha384_prf);
br_ssl_engine_set_default_aes_gcm(eng);
br_ssl_engine_set_default_chapol(eng);
br_ssl_engine_set_buffer(eng, t->iobuf, sizeof t->iobuf, 1);
br_ssl_engine_inject_entropy(eng, seed, seed_len);
// BearSSL counts days from year 0; 719528 of them end in 1970.
br_x509_minimal_set_time(&t->xc, (uint32_t)(now / 86400 + 719528), (uint32_t)(now % 86400));
}
bool tls_begin(const char *ca_file, char *msg, size_t cap)
{
Tls *t = &tls;
t->deadline = 0;
t->failed_tls = false;
t->fd = -1;
char path[1100];
if (!anchors_load(&t->anchors, ca_file, path, sizeof path, msg, cap)) return false;
unsigned char seed[32];
if (sys_entropy(seed, sizeof seed) != 0) {
snprintf(msg, cap, "cannot get random bytes for TLS: %s", strerror(errno));
return false;
}
int64_t now;
if (!sys_wall_sec(&now)) {
snprintf(msg, cap, "cannot read the date to check certificates: %s", strerror(errno));
secret_wipe(seed, sizeof seed);
return false;
}
configure(t, seed, sizeof seed, now);
secret_wipe(seed, sizeof seed);
[[maybe_unused]] int rc = fsl_sc_stream_init(&channel, &ops);
ensure(rc == 0);
channel.name = "https";
return true;
}
fsl_sc *tls_channel(void)
{
return &channel;
}
bool tls_failed(void)
{
return tls.failed_tls;
}