Artifact 34711dda3f40401162295843bc1f73dad49ff3eccc3f0451848f260d0289e151:
- File
src/net.c
— part of check-in
[9542357f2e]
at
2026-11-19 18:07:00
on branch seams
— Platform and executor seams (ticket d131051152)
pic's OS dependencies now sit behind two interfaces, with the host as the only implementation and no change in behaviour. pic_platform (src/platform.h) holds the wall and monotonic clocks, entropy, the journal lock, input reading and the SQLite VFS name, which the journal and pic.sqlite now open with. pic_executor (src/pic.h) holds the file operations the tools use (stat, read, write, remove, mkdir, list) and running a command; it mirrors libfossil's checkout filesystem so a database-backed workspace can drop in later. test_files covers the host file operations. (user: dmestas, size: 20441) [annotate] [blame] [check-ins using] [more...]
/* Outgoing connections over TCP and BearSSL, adapted from suit's tls.c and * anchors.c. TLS 1.2 only, ECDHE key exchange, AEAD ciphers only. BearSSL is * built to make no system call: this file gives it entropy and the date. */ #include <errno.h> #include <fcntl.h> #include <netdb.h> #include <poll.h> #include <signal.h> #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> #include "bearssl.h" #include "net.h" #include "input.h" #include "platform.h" #include "ca_bundle.inc" #define ANCHORS_FILE_MAX (1u << 20) /* bytes of PEM */ #define ANCHORS_MAX 512 /* certificates kept */ #define ANCHORS_DER_MAX 16384 /* bytes of one certificate */ #define ADDRS_MAX 16 #ifdef MSG_NOSIGNAL #define SEND_FLAGS MSG_NOSIGNAL #else #define SEND_FLAGS 0 #endif /* One address from the name lookup, as the lookup's child sends it. The first * record's err is getaddrinfo's result. */ typedef struct { int32_t err, family, socktype, protocol; uint32_t len; struct sockaddr_storage addr; } addr_rec; struct pic_net { br_ssl_client_context cc; br_x509_minimal_context xc; br_sslio_context io; unsigned char iobuf[BR_SSL_BUFSIZE_BIDI]; size_t anchors_n; br_x509_trust_anchor ta[ANCHORS_MAX]; size_t arena_used; unsigned char *arena; /* anchors' names and keys; fits in the PEM's size */ int fd, tls, eof, failed_tls, idle_ms; uint64_t deadline; /* CLOCK_MONOTONIC ns */ char err[300]; }; static int why(pic_net *n, const char *fmt, ...) { va_list ap; va_start(ap, fmt); (void)vsnprintf(n->err, sizeof n->err, fmt, ap); va_end(ap); return -1; } static uint64_t now_ns(void) { return pic_platform_get()->mono_ns(); } volatile sig_atomic_t pic_interrupted; /* Waits until fd is ready for ev, within the idle limit and the deadline. */ static int wait_fd(pic_net *n, int fd, short ev, const char *what) { for (;;) { uint64_t now = now_ns(), left; int ms, r; struct pollfd p; if (pic_interrupted) { return why(n, "%s: interrupted", what); } if (now >= n->deadline) { return why(n, "%s: the request ran past its deadline", what); } left = (n->deadline - now) / 1000000u + 1; ms = left < (uint64_t)n->idle_ms ? (int)left : n->idle_ms; p.fd = fd; p.events = ev; p.revents = 0; r = poll(&p, 1, ms); if (r > 0) { return 0; } if (r == 0 && ms == n->idle_ms) { return why(n, "%s sent nothing for %d seconds", what, n->idle_ms / 1000); } if (r < 0 && errno != EINTR) { return why(n, "poll: %s", strerror(errno)); } } } /* ---- trust anchors ---------------------------------------------------------- */ 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 */ }; typedef struct { unsigned char der[ANCHORS_DER_MAX]; size_t len; int over; } der_buf; static void der_append(void *ctx, const void *src, size_t len) { der_buf *d = ctx; d->over = d->over || len > ANCHORS_DER_MAX - d->len; if (!d->over) { memcpy(d->der + d->len, src, len); d->len += len; } } static unsigned char *keep(pic_net *n, const void *src, size_t len) { unsigned char *p = n->arena + n->arena_used; /* fits: see struct pic_net */ memcpy(p, src, len); n->arena_used += len; return p; } static void dn_append(void *ctx, const void *src, size_t len) { (void)keep(ctx, src, len); } /* Adds the certificate in d as a trust anchor; one BearSSL cannot use (an * unsupported key type) is passed over. */ static void add_cert(pic_net *n, const der_buf *d) { br_x509_decoder_context dc; const br_x509_pkey *pk; br_x509_trust_anchor *ta; size_t mark = n->arena_used; if (d->over || n->anchors_n == ANCHORS_MAX) { return; } br_x509_decoder_init(&dc, dn_append, n); br_x509_decoder_push(&dc, d->der, d->len); pk = br_x509_decoder_get_pkey(&dc); if (!pk) { n->arena_used = mark; return; } ta = &n->ta[n->anchors_n++]; ta->dn.data = n->arena + mark; ta->dn.len = n->arena_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(n, pk->key.rsa.n, pk->key.rsa.nlen); ta->pkey.key.rsa.nlen = pk->key.rsa.nlen; ta->pkey.key.rsa.e = keep(n, 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(n, pk->key.ec.q, pk->key.ec.qlen); ta->pkey.key.ec.qlen = pk->key.ec.qlen; } } static int parse_pem(pic_net *n, const unsigned char *data, size_t len, const char *path) { br_pem_decoder_context pc; der_buf *d = calloc(1, sizeof *d); int in = 0, cert = 0, newline = 1, ok = 1; if (!d) { return why(n, "out of memory"); } br_pem_decoder_init(&pc); while (ok && len > 0) { size_t k = br_pem_decoder_push(&pc, data, len); int ev; data += k; len -= k; ev = br_pem_decoder_event(&pc); if (ev == BR_PEM_BEGIN_OBJ) { in = 1; d->len = 0; d->over = 0; cert = strcmp(br_pem_decoder_name(&pc), "CERTIFICATE") == 0; br_pem_decoder_setdest(&pc, der_append, d); } else if (ev == BR_PEM_END_OBJ) { in = 0; if (cert) { add_cert(n, d); } } else if (ev == BR_PEM_ERROR) { ok = 0; } if (len == 0 && newline) { /* a last line without its newline */ newline = 0; data = (const unsigned char *)"\n"; len = 1; } } free(d); if (!ok || in) { return why(n, "%s is not PEM text", path); } return n->anchors_n > 0 ? 0 : why(n, "%s holds no certificate pic can use", path); } /* Only you or root may have written the file or its folder. */ static int load_anchors(pic_net *n) { const char *list[1 + sizeof system_bundles / sizeof system_bundles[0]]; const char *env = getenv("SSL_CERT_FILE"); size_t count = 0; const char *ca = getenv("PIC_CA"); /* "builtin": skip the system bundles */ if (env && env[0] == '/') { list[count++] = env; } for (size_t i = 0; !(ca && strcmp(ca, "builtin") == 0) && i < sizeof system_bundles / sizeof system_bundles[0]; i++) { list[count++] = system_bundles[i]; } for (size_t i = 0; i < count; i++) { size_t len = 0; int rc; char *pem = pic_input_read(list[i], ANCHORS_FILE_MAX, PIC_INPUT_TRUSTED, &len, NULL); if (!pem) { if (errno == ENOENT) { continue; } return errno == EPERM ? why(n, "%s is not trusted: not a regular file owned by you or root and writable only by its owner", list[i]) : errno == EFBIG ? why(n, "%s is over %u bytes", list[i], ANCHORS_FILE_MAX) : why(n, "cannot read %s: %s", list[i], strerror(errno)); } if (!(n->arena = malloc(ANCHORS_FILE_MAX + 1))) { free(pem); return why(n, "out of memory"); } rc = parse_pem(n, (unsigned char *)pem, len, list[i]); free(pem); return rc; } /* No system bundle (a minimal host, or a VM with no userland): Mozilla's * roots as compiled in (tools/ca-bundle.sh). */ { size_t total = 0, at = 0; unsigned char *pem; int rc; for (size_t i = 0; i < sizeof builtin_anchors / sizeof builtin_anchors[0]; i++) { total += strlen(builtin_anchors[i]); } if (total > ANCHORS_FILE_MAX || !(pem = malloc(total + 1)) || !(n->arena = malloc(ANCHORS_FILE_MAX + 1))) { return why(n, "no certificate file found and the built-in bundle does not fit"); } for (size_t i = 0; i < sizeof builtin_anchors / sizeof builtin_anchors[0]; i++) { size_t l = strlen(builtin_anchors[i]); memcpy(pem + at, builtin_anchors[i], l); at += l; } rc = parse_pem(n, pem, total, "the built-in bundle"); free(pem); return rc; } } /* ---- setup ------------------------------------------------------------------ */ pic_net *pic_net_new(char *err, size_t cap) { 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}, }; unsigned char seed[32]; int64_t wall = pic_platform_get()->wall_ns(); time_t now = wall < 0 ? (time_t)-1 : (time_t)(wall / 1000000000); br_ssl_engine_context *eng; pic_net *n = calloc(1, sizeof *n); if (!n) { (void)snprintf(err, cap, "out of memory"); return NULL; } n->fd = -1; if (load_anchors(n) != 0) { (void)snprintf(err, cap, "%s", n->err); pic_net_free(n); return NULL; } if (pic_platform_get()->entropy(seed, sizeof seed) != 0 || now == (time_t)-1) { (void)snprintf(err, cap, "cannot get random bytes or the date for TLS: %s", strerror(errno)); pic_net_free(n); return NULL; } eng = &n->cc.eng; br_ssl_client_zero(&n->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(&n->xc, &br_sha256_vtable, n->ta, n->anchors_n); br_ssl_engine_set_default_rsavrfy(eng); br_ssl_engine_set_default_ecdsa(eng); br_x509_minimal_set_rsa(&n->xc, br_ssl_engine_get_rsavrfy(eng)); br_x509_minimal_set_ecdsa(&n->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(&n->xc, hashes[i].id, hashes[i].impl); } br_ssl_engine_set_x509(eng, &n->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, n->iobuf, sizeof n->iobuf, 1); br_ssl_engine_inject_entropy(eng, seed, sizeof seed); memset(seed, 0, sizeof seed); /* BearSSL counts days from year 0; 719528 of them end in 1970. */ br_x509_minimal_set_time(&n->xc, (uint32_t)(now / 86400 + 719528), (uint32_t)(now % 86400)); return n; } void pic_net_free(pic_net *n) { if (n) { pic_net_close(n); free(n->arena); free(n); } } /* ---- name lookup and TCP ---------------------------------------------------- */ /* getaddrinfo has no time limit, so it runs in a child that sends what it * found and exits. A fork without exec: pic runs no threads. */ static void resolve_child(int fd, const char *host, const char *port) { struct addrinfo hints, *res = NULL; addr_rec a; memset(&hints, 0, sizeof hints); memset(&a, 0, sizeof a); hints.ai_socktype = SOCK_STREAM; a.err = getaddrinfo(host, port, &hints, &res); if (a.err != 0) { (void)!write(fd, &a, sizeof a); } for (const struct addrinfo *r = res; r; r = r->ai_next) { if (r->ai_addrlen > sizeof a.addr) { continue; } 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)!write(fd, &a, sizeof a); } _exit(0); } static int lookup(pic_net *n, const char *host, int port, addr_rec *addrs) { char p[8]; int sv[2], count = -1; pid_t pid; (void)snprintf(p, sizeof p, "%d", port); if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != 0) { return why(n, "cannot look up %s: %s", host, strerror(errno)); } pid = fork(); if (pid < 0) { int e = errno; close(sv[0]); close(sv[1]); return why(n, "cannot look up %s: fork: %s", host, strerror(e)); } if (pid == 0) { close(sv[0]); resolve_child(sv[1], host, p); } close(sv[1]); { size_t got = 0; ssize_t r = 1; while (got < ADDRS_MAX * sizeof *addrs && r > 0) { if (wait_fd(n, sv[0], POLLIN, "the name lookup") != 0) { got = 0; r = -2; break; } r = read(sv[0], (char *)addrs + got, ADDRS_MAX * sizeof *addrs - got); if (r < 0 && errno == EINTR) { r = 1; continue; } got += r > 0 ? (size_t)r : 0; } if (r != -2) { count = got < sizeof *addrs ? why(n, "the name lookup of %s gave no answer", host) : addrs[0].err != 0 ? why(n, "cannot find %s: %s", host, gai_strerror(addrs[0].err)) : (int)(got / sizeof *addrs); } } (void)kill(pid, SIGKILL); /* one still busy is stopped; one that ended is reaped */ (void)waitpid(pid, NULL, 0); close(sv[0]); return count; } static int try_addr(pic_net *n, const addr_rec *a, const char *host, int port) { int r, e = 0; socklen_t elen = sizeof e; n->fd = socket(a->family, a->socktype, a->protocol); if (n->fd < 0) { return why(n, "cannot connect to %s:%d: %s", host, port, strerror(errno)); } #ifdef SO_NOSIGPIPE { int one = 1; (void)setsockopt(n->fd, SOL_SOCKET, SO_NOSIGPIPE, &one, sizeof one); } #endif if (fcntl(n->fd, F_SETFD, FD_CLOEXEC) != 0 || fcntl(n->fd, F_SETFL, fcntl(n->fd, F_GETFL) | O_NONBLOCK) != 0) { e = errno; } else { r = connect(n->fd, (const struct sockaddr *)&a->addr, (socklen_t)a->len); if (r != 0 && errno != EINPROGRESS) { e = errno; } else if (wait_fd(n, n->fd, POLLOUT, "the server") != 0) { pic_net_close(n); return -1; } else if (getsockopt(n->fd, SOL_SOCKET, SO_ERROR, &e, &elen) != 0) { e = errno; } } if (e != 0) { pic_net_close(n); return why(n, "cannot connect to %s:%d: %s", host, port, strerror(e)); } return 0; } static int is_loopback(const char *host) { return strcmp(host, "127.0.0.1") == 0 || strcmp(host, "localhost") == 0 || strcmp(host, "::1") == 0; } /* ---- BearSSL's transport ---------------------------------------------------- */ static int ll_read(void *ctx, unsigned char *buf, size_t len) { pic_net *n = ctx; for (;;) { ssize_t r; if (wait_fd(n, n->fd, POLLIN, "the server") != 0) { return -1; } r = recv(n->fd, buf, len, 0); if (r > 0) { return (int)r; } if (r == 0) { n->eof = 1; return why(n, "the server closed the connection"); } if (errno != EINTR && errno != EAGAIN) { return why(n, "recv: %s", strerror(errno)); } } } static int ll_write(void *ctx, const unsigned char *buf, size_t len) { pic_net *n = ctx; for (;;) { ssize_t r; if (wait_fd(n, n->fd, POLLOUT, "the server") != 0) { return -1; } r = send(n->fd, buf, len, SEND_FLAGS); if (r >= 0) { return (int)r; } if (errno != EINTR && errno != EAGAIN) { return why(n, "send: %s", strerror(errno)); } } } static int tls_failure(pic_net *n, const char *step) { int e = br_ssl_engine_last_error(&n->cc.eng); if (e == BR_ERR_OK || e == BR_ERR_IO) { return why(n, "%s: %.200s", step, n->err); } n->failed_tls = 1; if (e == BR_ERR_X509_EXPIRED) { return why(n, "%s: the server's certificate has expired or is not valid yet", step); } if (e == BR_ERR_X509_BAD_SERVER_NAME) { return why(n, "%s: the server's certificate is for another host name", step); } if (e == BR_ERR_X509_NOT_TRUSTED) { return why(n, "%s: the server's certificate is not signed by a trusted CA", step); } if (e >= BR_ERR_SEND_FATAL_ALERT) { return why(n, "%s: pic ended the handshake with TLS alert %d", step, e - BR_ERR_SEND_FATAL_ALERT); } if (e >= BR_ERR_RECV_FATAL_ALERT) { int alert = e - BR_ERR_RECV_FATAL_ALERT; return why(n, "%s: the server ended the handshake with TLS alert %d%s", step, alert, alert == 70 ? " (protocol version): it may now require TLS 1.3, which BearSSL lacks" : ": pic offers only TLS 1.2 with ECDHE and AES-GCM or ChaCha20-Poly1305"); } return why(n, "%s: TLS error %d (BearSSL's code)", step, e); } /* ---- the connection ---------------------------------------------------------- */ int pic_net_connect(pic_net *n, const char *host, int port, int tls, int idle_seconds, int deadline_seconds) { addr_rec *addrs; int count; pic_net_close(n); n->eof = n->failed_tls = 0; n->err[0] = '\0'; n->idle_ms = idle_seconds * 1000; n->deadline = now_ns() + (uint64_t)deadline_seconds * 1000000000u; if (!tls && !is_loopback(host)) { return why(n, "refusing plain HTTP to %s: only loopback may skip TLS", host); } addrs = calloc(ADDRS_MAX, sizeof *addrs); if (!addrs) { return why(n, "out of memory"); } count = lookup(n, host, port, addrs); for (int i = 0; i < count && n->fd < 0; i++) { (void)try_addr(n, &addrs[i], host, port); } free(addrs); if (n->fd < 0) { return -1; } n->tls = tls; if (tls) { /* A failed reset leaves the engine closed with its error, which the * handshake reports. */ (void)br_ssl_client_reset(&n->cc, host, 0); br_sslio_init(&n->io, &n->cc.eng, ll_read, n, ll_write, n); if (br_sslio_flush(&n->io) != 0) { tls_failure(n, "the TLS handshake"); pic_net_close(n); return -1; } } return 0; } int pic_net_write(pic_net *n, const void *bytes, size_t len) { if (n->tls) { if (br_sslio_write_all(&n->io, bytes, len) != 0 || br_sslio_flush(&n->io) != 0) { return tls_failure(n, "send the request"); } return 0; } for (size_t off = 0; off < len;) { int r = ll_write(n, (const unsigned char *)bytes + off, len - off); if (r < 0) { return -1; } off += (size_t)r; } return 0; } long pic_net_read(pic_net *n, void *bytes, size_t cap) { int got; if (!n->tls) { got = ll_read(n, bytes, cap); return got > 0 ? got : n->eof ? 0 : -1; } got = br_sslio_read(&n->io, bytes, cap); if (got > 0) { return got; } if (br_ssl_engine_last_error(&n->cc.eng) == BR_ERR_OK) { return 0; /* the server closed TLS cleanly */ } if (n->eof) { return why(n, "the server closed the connection without ending TLS"); } return tls_failure(n, "read the reply"); } void pic_net_close(pic_net *n) { if (n->fd >= 0) { close(n->fd); n->fd = -1; } } const char *pic_net_error(const pic_net *n) { return n->err; } int pic_net_tls_failed(const pic_net *n) { return n->failed_tls; }