Artifact 0b8aedb0ecbdf49bd00ff652defa76455f3896a6f14f5e401c642a6fd35002ab:
- File
src/platform.c
— part of check-in
[27d847f693]
at
2026-11-18 16:19:19
on branch trunk
— suit syncs and clones over https
suit sync, suit clone and suit tend now work with https:// remotes. http:// and file:// keep libfossil's built-in channel.
libfossil is the private byot build 2f20f44ba4 in place of trunk f2983dcd78, approved while suit is being proven; only libfossil.c and libfossil.h differ from trunk's files. Its stream channel does all of the HTTP: request headers, Content-Length, chunked and close-delimited replies (the last only after a clean close), the reply-size limit and the timeout. suit supplies the transport: src/tls.c, over non-blocking TCP and BearSSL 0.6, now vendored.
- TLS 1.2 only, ECDHE key exchange, AES-GCM or ChaCha20-Poly1305. A server offering only TLS 1.3, RSA key exchange or CBC is refused. - The chain is verified against trust anchors and the host name against the certificate. Anchors come from the system's PEM bundle read at run time (SSL_CERT_FILE, then the usual macOS and Linux paths), or from a per-wardrobe CA file set with --ca, which replaces the bundle. No roots are compiled in and there is no way to trust anything. - A certificate file must be a regular file owned by the user or root, writable by no one else, in a folder that passes the same check; --ca refuses a symlink, and a FIFO is refused at once. - Redirects are refused, never followed, and the message names the new address. No proxy support. - Nothing is sent before the handshake has verified. The login goes out only as libfossil's login card. Commands that read the sync secret turn core files off first. - Every connect, read, write and name lookup waits in poll with a 30 s idle limit, and a whole command stops after 10 minutes. getaddrinfo has no deadline, so it runs in a forked child that is killed and reaped. - BearSSL makes no system call of its own: it is built without its own randomness or clock, and suit seeds it and gives it the time through its fault wrappers. - Exit 18 now means the secure connection failed (handshake, certificate, host name). 17 stays the network and 19 a refused login.
A per-wardrobe CA file is kept in cafiles in suit's home folder, one NAME PATH line each. suit-run is built without the network code and is unchanged at 35496 bytes; the speed budget passes. Release suit went from 2291288 to 2490024 bytes.
An independent security review found no critical or high issues. Its one medium finding, a CA file trusted without checking its owner, mode or type, is fixed here, as are its low ones: separate storage for each set of anchors, core files off, and the release check now covering every test-only switch.
Checked against a real server: an anonymous clone of this repository over https from its forge, 8.4 s, verified with stock fossil.
A new suite, test/https.sh, with 170 cases, runs local servers with test certificates made at test time, including servers that misbehave on purpose. It prints skip lines where openssl or nc is missing. A new fuzz target covers the bundle reader.
3788 unit checks (was 3669), 625 shell cases, 1153 store cases, 985 placement cases, 378 project cases, 236 usage cases, 288 curate cases, 376 curate-apply cases and 170 https cases, under clang, under gcc 16, with no user name set, and under a strict umask, in one run of make gate (76 minutes, on a loaded machine). 100% coverage in all 34 source files. Three store cases that expected "cannot use https yet" now expect the refusal for a missing certificate bundle. (user: dmestas, size: 18944) [annotate] [blame] [check-ins using]
#include "platform.h" #include <errno.h> #include <dirent.h> #include <fcntl.h> #include <signal.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> #include <netdb.h> #include <poll.h> #include <spawn.h> #include <sys/socket.h> #ifdef __APPLE__ #include <sys/random.h> #endif #ifdef __APPLE__ #include <mach-o/dyld.h> #endif extern char **environ; // ---- output --------------------------------------------------------------- bool sys_write_all(int fd, const char *buf, size_t len) { while (len > 0) { ssize_t n = sys_write(fd, buf, len); if (n < 0 && errno == EINTR) continue; if (n < 0) return false; buf += n; len -= (size_t)n; } return true; } void say(int fd, const char *fmt, ...) { char buf[SAY_MAX]; va_list ap; va_start(ap, fmt); int n = vsnprintf(buf, sizeof buf, fmt, ap); va_end(ap); ensure(n >= 0); size_t len = (size_t)n; if (len >= sizeof buf) { len = sizeof buf - 1; buf[len - 1] = '\n'; } (void)sys_write_all(fd, buf, len); } #ifndef SUIT_COVER void ensure_fail(const char *cond, const char *file, int line) { say(STDERR_FILENO, "suit: invariant failed: %s (%s:%d)\n", cond, file, line); abort(); } #endif void out_init(Out *o, int fd) { o->fd = fd; o->err = 0; o->failed = false; o->len = 0; } static void out_flush(Out *o) { if (o->len > 0 && !o->failed && !sys_write_all(o->fd, o->buf, o->len)) { o->failed = true; o->err = errno; } o->len = 0; } void out_str(Out *o, const char *s) { size_t n = strlen(s); while (n > 0) { size_t room = sizeof o->buf - o->len; size_t k = n < room ? n : room; memcpy(o->buf + o->len, s, k); o->len += k; s += k; n -= k; if (o->len == sizeof o->buf) out_flush(o); } } bool out_finish(Out *o) { out_flush(o); errno = o->err; return !o->failed; } #ifdef SUIT_COVER int __llvm_profile_write_file(void); #endif // ---- fault injection (test builds only) ----------------------------------- #ifdef SUIT_TEST typedef enum { F_OPEN, F_READ, F_WRITE, F_CLOSE, F_FSYNC, F_FCHMOD, F_STAT, F_FSTATAT, F_RENAME, F_MKDIR, F_UNLINK, F_GETENV, F_SPAWN, F_WAIT4, F_CLOCK, F_SELF, F_EXEC, F_LSTAT, F_READLINK, F_SYMLINK, F_RMDIR, F_LISTDIR, F_KILL, F_GETCWD, F_FSTAT, F_LSEEK, F_DUP2, F_SETENV, F_WALL, F_SOCKET, F_CONNECT, F_POLL, F_GETSOCKOPT, F_FCNTL, F_RECV, F_SEND, F_SOCKETPAIR, F_FORK, F_SIGNAL, F_GETADDRINFO, F_ENTROPY, F_SETRLIMIT, F_COUNT } Fn; static const char *const fn_names[F_COUNT] = { "open", "read", "write", "close", "fsync", "fchmod", "stat", "fstatat", "rename", "mkdir", "unlink", "getenv", "spawn", "wait4", "clock_gettime", "self_path", "exec", "lstat", "readlink", "symlink", "rmdir", "listdir", "kill", "getcwd", "fstat", "lseek", "dup2", "setenv", "wall", "socket", "connect", "poll", "getsockopt", "fcntl", "recv", "send", "socketpair", "fork", "signal", "getaddrinfo", "entropy", "setrlimit", }; typedef enum { HIT_NONE, HIT_FAIL, HIT_SHORT } Hit; typedef enum { KIND_FAIL, KIND_SHORT, KIND_DELAY, KIND_HANG } FaultKind; constexpr size_t FAULT_MAX = 4; constexpr useconds_t DELAY_US = 20000; // A hung call sleeps this long and then fails: long enough for any deadline // under test, short enough that a forgotten process goes away by itself. constexpr unsigned HANG_SEC = 600; typedef struct { Fn fn; unsigned long nth; int err; FaultKind kind; } Fault; static struct { bool parsed; size_t count; Fault faults[FAULT_MAX]; unsigned long calls[F_COUNT]; } fault; static const struct { const char *name; int value; } errno_names[] = { {"EIO", EIO}, {"ENOSPC", ENOSPC}, {"EACCES", EACCES}, {"ENOENT", ENOENT}, {"ENOTDIR", ENOTDIR}, {"EEXIST", EEXIST}, {"EINTR", EINTR}, {"EPERM", EPERM}, {"ENOMEM", ENOMEM}, {"EMFILE", EMFILE}, {"EAGAIN", EAGAIN}, {"EINPROGRESS", EINPROGRESS}, {"ECONNREFUSED", ECONNREFUSED}, }; [[noreturn]] static void fault_die(const char *why) { say(STDERR_FILENO, "suit: SUIT_FAULT: %s\n", why); exit(99); } static void fault_kind(Fault *f, const char *kind) { if (strcmp(kind, "delay") == 0) { f->kind = KIND_DELAY; return; } if (strcmp(kind, "hang") == 0) { f->kind = KIND_HANG; return; } if (strcmp(kind, "short") == 0) { if (f->fn != F_READ && f->fn != F_WRITE && f->fn != F_RECV && f->fn != F_SEND) fault_die("short applies only to read and write, and to recv and send"); f->kind = KIND_SHORT; return; } for (size_t i = 0; i < sizeof errno_names / sizeof errno_names[0]; i++) { if (strcmp(kind, errno_names[i].name) == 0) { f->err = errno_names[i].value; return; } } char *end; long v = strtol(kind, &end, 10); if (*end != '\0' || v < 1) fault_die("unknown errno"); f->err = (int)v; } // One NAME:N[:KIND] spec, SPEC being LEN bytes of the variable. static void fault_parse_one(Fault *f, const char *spec) { const char *colon = strchr(spec, ':'); if (colon == nullptr) fault_die("expected NAME:N[:ERRNO|short|delay|hang]"); size_t n = (size_t)(colon - spec); bool found = false; for (int i = 0; i < F_COUNT; i++) { if (strlen(fn_names[i]) == n && memcmp(fn_names[i], spec, n) == 0) { f->fn = (Fn)i; found = true; } } if (!found) fault_die("unknown call name"); char *end; f->nth = strtoul(colon + 1, &end, 10); if (end == colon + 1 || f->nth == 0 || (*end != '\0' && *end != ':')) fault_die("N must be a positive number"); f->err = EIO; f->kind = KIND_FAIL; if (*end == ':') fault_kind(f, end + 1); } // SPEC is NAME:N[:KIND][,NAME:N[:KIND]...]. static void fault_parse(const char *spec) { char copy[256]; if (strlen(spec) >= sizeof copy) fault_die("too long"); strcpy(copy, spec); char *save = nullptr; for (char *part = strtok_r(copy, ",", &save); part != nullptr; part = strtok_r(nullptr, ",", &save)) { if (fault.count == FAULT_MAX) fault_die("too many faults"); fault_parse_one(&fault.faults[fault.count++], part); } } void fault_reset(void) { memset(&fault, 0, sizeof fault); } // A hung call is usually ended by a kill, which writes no coverage counters: // write them first. static void hang(void) { #ifdef SUIT_COVER (void)__llvm_profile_write_file(); #endif sleep(HANG_SEC); } // Whether call number N of FN is the one a fault wants, and what it wants. static Hit inject(Fn fn, int *err) { if (!fault.parsed) { fault.parsed = true; const char *spec = getenv("SUIT_FAULT"); if (spec != nullptr) fault_parse(spec); } unsigned long call = ++fault.calls[fn]; Hit hit = HIT_NONE; for (size_t i = 0; i < fault.count; i++) { const Fault *f = &fault.faults[i]; if (f->fn != fn) continue; if (f->kind == KIND_DELAY) { if (call >= f->nth) usleep(DELAY_US); } else if (call == f->nth) { if (f->kind == KIND_HANG) hang(); *err = f->err; hit = f->kind == KIND_SHORT ? HIT_SHORT : HIT_FAIL; } } return hit; } // Fail the call, returning RET with errno set. #define FAULT(fn, ret) \ do { \ int err_; \ if (inject(fn, &err_) == HIT_FAIL) { \ errno = err_; \ return (ret); \ } \ } while (0) // Fail the call, or shrink N to between 1 and 4 bytes for a short transfer. #define FAULT_IO(fn, n) \ do { \ int err_; \ Hit hit_ = inject(fn, &err_); \ if (hit_ == HIT_FAIL) { \ errno = err_; \ return -1; \ } \ if (hit_ == HIT_SHORT) (n) = (((n) - 1) & 3) + 1; \ } while (0) #else #define FAULT(fn, ret) ((void)0) #define FAULT_IO(fn, n) ((void)0) #endif // ---- wrappers ------------------------------------------------------------- int sys_open(const char *path, int flags, mode_t mode) { FAULT(F_OPEN, -1); return open(path, flags, mode); } ssize_t sys_read(int fd, void *buf, size_t n) { ensure(n > 0); FAULT_IO(F_READ, n); return read(fd, buf, n); } ssize_t sys_write(int fd, const void *buf, size_t n) { ensure(n > 0); FAULT_IO(F_WRITE, n); return write(fd, buf, n); } int sys_close(int fd) { FAULT(F_CLOSE, -1); return close(fd); } int sys_fsync(int fd) { FAULT(F_FSYNC, -1); return fsync(fd); } int sys_fchmod(int fd, mode_t mode) { FAULT(F_FCHMOD, -1); return fchmod(fd, mode); } int sys_stat(const char *path, struct stat *st) { FAULT(F_STAT, -1); return stat(path, st); } int sys_fstatat(int dirfd, const char *name, struct stat *st) { FAULT(F_FSTATAT, -1); return fstatat(dirfd, name, st, 0); } int sys_rename(const char *from, const char *to) { FAULT(F_RENAME, -1); return rename(from, to); } int sys_mkdir(const char *path, mode_t mode) { FAULT(F_MKDIR, -1); return mkdir(path, mode); } int sys_unlink(const char *path) { FAULT(F_UNLINK, -1); return unlink(path); } int sys_lstat(const char *path, struct stat *st) { FAULT(F_LSTAT, -1); return lstat(path, st); } ssize_t sys_readlink(const char *path, char *buf, size_t cap) { FAULT(F_READLINK, -1); return readlink(path, buf, cap); } int sys_symlink(const char *target, const char *path) { FAULT(F_SYMLINK, -1); return symlink(target, path); } int sys_rmdir(const char *path) { FAULT(F_RMDIR, -1); return rmdir(path); } int sys_listdir(const char *path, int (*cb)(void *state, const char *name), void *state) { FAULT(F_LISTDIR, -1); DIR *d = opendir(path); if (d == nullptr) return -1; int rc = 0; struct dirent *de; while (rc == 0 && (de = readdir(d)) != nullptr) { bool dots = strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0; rc = dots ? 0 : cb(state, de->d_name); } closedir(d); return rc; } int sys_kill0(pid_t pid) { FAULT(F_KILL, -1); return kill(pid, 0); } char *sys_getcwd(char *buf, size_t cap) { FAULT(F_GETCWD, nullptr); return getcwd(buf, cap); } void platform_pause_ms(unsigned ms) { usleep(ms * 1000u); } // MODE is the file's whole permission set when KEEP is true, applied with fchmod so the // umask plays no part; otherwise it is only what open asks for. static bool write_temp(const char *tmp, mode_t mode, bool keep, const void *src, size_t n) { int fd = sys_open(tmp, O_WRONLY | O_CREAT | O_EXCL, mode); if (fd < 0) return false; bool written = (!keep || sys_fchmod(fd, mode) == 0) && sys_write_all(fd, src, n) && sys_fsync(fd) == 0; bool closed = sys_close(fd) == 0; return written && closed; } constexpr size_t TMP_PATH_MAX = 4096 + 64; int sys_write_atomic(const char *path, const void *src, size_t n) { return sys_write_atomic_mode(path, src, n, 0644); } static int write_atomic(const char *path, const void *src, size_t n, mode_t new_mode, bool exact) { static unsigned counter; const char *slash = strrchr(path, '/'); ensure(slash != nullptr); char tmp[TMP_PATH_MAX]; [[maybe_unused]] int len = snprintf(tmp, sizeof tmp, "%.*s/" SUIT_TMP_PREFIX "%d.%u", (int)(slash - path), path, (int)getpid(), counter++); ensure(len > 0 && (size_t)len < sizeof tmp); struct stat st; bool exists = sys_stat(path, &st) == 0; mode_t mode = exists && !exact ? (st.st_mode & 07777) : new_mode; if (!write_temp(tmp, mode, exists || exact, src, n) || sys_rename(tmp, path) != 0) { int err = errno; (void)sys_unlink(tmp); return err; } return 0; } int sys_write_atomic_mode(const char *path, const void *src, size_t n, mode_t new_mode) { return write_atomic(path, src, n, new_mode, false); } int sys_write_atomic_exact(const char *path, const void *src, size_t n, mode_t mode) { return write_atomic(path, src, n, mode, true); } int sys_fstat(int fd, struct stat *st) { FAULT(F_FSTAT, -1); return fstat(fd, st); } off_t sys_lseek(int fd, off_t off, int whence) { FAULT(F_LSEEK, -1); return lseek(fd, off, whence); } int sys_dup2(int from, int to) { FAULT(F_DUP2, -1); return dup2(from, to); } int sys_setenv(const char *name, const char *value) { FAULT(F_SETENV, -1); return setenv(name, value, 1); } const char *sys_getenv(const char *name) { FAULT(F_GETENV, nullptr); return getenv(name); } int sys_spawn(pid_t *pid, const char *path, char *const argv[]) { #ifdef SUIT_TEST int err; if (inject(F_SPAWN, &err) == HIT_FAIL) return err; #endif return posix_spawn(pid, path, nullptr, nullptr, argv, environ); } int sys_execv(const char *path, char *const argv[]) { FAULT(F_EXEC, -1); #ifdef SUIT_COVER // exec replaces the process before it can write its coverage counters. (void)__llvm_profile_write_file(); #endif return execv(path, argv); } pid_t sys_wait4(pid_t pid, int *status, struct rusage *ru) { FAULT(F_WAIT4, -1); return wait4(pid, status, 0, ru); } bool sys_now_ns(uint64_t *ns) { FAULT(F_CLOCK, false); struct timespec ts; [[maybe_unused]] int rc = clock_gettime(CLOCK_MONOTONIC, &ts); ensure(rc == 0); *ns = (uint64_t)ts.tv_sec * 1000000000u + (uint64_t)ts.tv_nsec; return true; } bool sys_wall_sec(int64_t *sec) { FAULT(F_WALL, false); #ifdef SUIT_TEST // Tests pin the date: SUIT_NOW is the seconds since 1970. const char *pinned = getenv("SUIT_NOW"); if (pinned != nullptr) { *sec = (int64_t)strtoll(pinned, nullptr, 10); return true; } #endif struct timespec ts; [[maybe_unused]] int rc = clock_gettime(CLOCK_REALTIME, &ts); ensure(rc == 0); *sec = (int64_t)ts.tv_sec; return true; } // ---- the network ---------------------------------------------------------- // suit-run, the per-minute program, is built with SUIT_NO_NET: it makes no // network call, and every libc symbol it imports costs time at each start. #ifndef SUIT_NO_NET int sys_socket(int family, int type, int protocol) { FAULT(F_SOCKET, -1); return socket(family, type, protocol); } int sys_connect(int fd, const struct sockaddr *addr, socklen_t len) { FAULT(F_CONNECT, -1); return connect(fd, addr, len); } int sys_poll(int fd, short events, int ms) { FAULT(F_POLL, -1); struct pollfd p = {.fd = fd, .events = events}; return poll(&p, 1, ms); } int sys_socket_error(int fd, int *err) { FAULT(F_GETSOCKOPT, -1); socklen_t len = sizeof *err; return getsockopt(fd, SOL_SOCKET, SO_ERROR, err, &len); } int sys_set_nonblock(int fd) { FAULT(F_FCNTL, -1); // FD is a new socket: O_NONBLOCK is the only status flag it will have. return fcntl(fd, F_SETFL, O_NONBLOCK); } ssize_t sys_recv(int fd, void *buf, size_t n) { ensure(n > 0); FAULT_IO(F_RECV, n); return recv(fd, buf, n, 0); } ssize_t sys_recv_all(int fd, void *buf, size_t n) { ensure(n > 0); FAULT_IO(F_RECV, n); return recv(fd, buf, n, MSG_WAITALL); } ssize_t sys_send(int fd, const void *buf, size_t n) { ensure(n > 0); FAULT_IO(F_SEND, n); return send(fd, buf, n, MSG_NOSIGNAL); } int sys_socketpair(int fds[2]) { FAULT(F_SOCKETPAIR, -1); return socketpair(AF_UNIX, SOCK_STREAM, 0, fds); } pid_t sys_fork(void) { FAULT(F_FORK, -1); return fork(); } int sys_signal(pid_t pid, int sig) { FAULT(F_SIGNAL, -1); return kill(pid, sig); } int sys_getaddrinfo(const char *host, const char *port, const struct addrinfo *hints, struct addrinfo **res) { FAULT(F_GETADDRINFO, EAI_FAIL); return getaddrinfo(host, port, hints, res); } int sys_entropy(void *buf, size_t n) { ensure(n <= 256); FAULT(F_ENTROPY, -1); return getentropy(buf, n); } int sys_no_core_dumps(void) { FAULT(F_SETRLIMIT, -1); struct rlimit none = {.rlim_cur = 0, .rlim_max = 0}; return setrlimit(RLIMIT_CORE, &none); } [[noreturn]] void sys_child_exit(int status) { #ifdef SUIT_COVER // _exit skips the handler that writes the coverage counters. (void)__llvm_profile_write_file(); #endif _exit(status); } #endif // ---- platform differences ------------------------------------------------- bool platform_self_path(char *buf, size_t cap) { FAULT(F_SELF, false); #ifdef __APPLE__ uint32_t size = (uint32_t)cap; return _NSGetExecutablePath(buf, &size) == 0; #else ssize_t n = readlink("/proc/self/exe", buf, cap - 1); if (n < 0) return false; buf[n] = '\0'; return (size_t)n < cap - 1; #endif } Manager platform_manager(void) { #ifdef SUIT_TEST const char *forced = sys_getenv("SUIT_PLATFORM"); if (forced != nullptr) return strcmp(forced, "linux") == 0 ? MANAGER_SYSTEMD : MANAGER_LAUNCHD; #endif #ifdef __APPLE__ return MANAGER_LAUNCHD; #else return MANAGER_SYSTEMD; #endif } const char *platform_loader(void) { #ifdef SUIT_TEST const char *forced = sys_getenv("SUIT_LOADER"); if (forced != nullptr && forced[0] != '\0') return forced; #endif return platform_manager() == MANAGER_LAUNCHD ? "/bin/launchctl" : "/usr/bin/systemctl"; } unsigned platform_uid(void) { return (unsigned)getuid(); } unsigned platform_pid(void) { return (unsigned)getpid(); } bool platform_isatty(int fd) { return isatty(fd) == 1; } int64_t platform_mtime_sec(const struct stat *st) { #ifdef __APPLE__ return st->st_mtimespec.tv_sec; #else return st->st_mtim.tv_sec; #endif } int64_t platform_mtime_nsec(const struct stat *st) { #ifdef __APPLE__ return st->st_mtimespec.tv_nsec; #else return st->st_mtim.tv_nsec; #endif } uint64_t platform_peak_resident(const struct rusage *ru) { #ifdef __APPLE__ return (uint64_t)ru->ru_maxrss; // bytes #else return (uint64_t)ru->ru_maxrss * 1024; // kibibytes #endif }