Artifact a35e19d530460e65f60c3c8036526d2cad05a2cfd33da7151724a002d447af66:
- File
test/badsrv.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: 11412) [annotate] [blame] [check-ins using]
// badsrv PORT MODE CHAIN.pem KEY.pem BACKEND_PORT SECONDS // // A TLS server for test/https.sh, made with BearSSL, that misbehaves on // purpose. It listens on 127.0.0.1:PORT and serves one connection at a time: // it reads the request whole, then, by MODE: // ok relays it to http://127.0.0.1:BACKEND_PORT and the reply back // nothing sends nothing and holds the connection for up to 60 seconds // midclose relays the first 60 bytes of the reply, then drops TCP // truncated relays the headers and half the body, then closes cleanly // noclen relays the reply without its Content-Length, then closes cleanly // noclen-unclean the same, then drops TCP with no close_notify // chunked relays the reply's body in chunks // redirect answers 302 to https://localhost:BACKEND_PORT/ // error500 answers HTTP 500 // garbage sends bytes that are not a TLS record // rsakex offers only TLS_RSA_WITH_AES_128_GCM_SHA256 (KEY must be RSA) // cbc offers only TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 // tls13 answers the ClientHello with a protocol_version alert, as a // server that speaks only TLS 1.3 does // It exits by itself after SECONDS (1 to 900). A test helper, not part of suit. #define _GNU_SOURCE #include <bearssl.h> #include <errno.h> #include <netinet/in.h> #include <poll.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <sys/socket.h> #include <sys/time.h> #include <time.h> #include <unistd.h> static unsigned char req[1 << 22]; static unsigned char rep[1 << 24]; static unsigned char out[(1 << 24) + (1 << 16)]; static unsigned char file[1 << 20]; static unsigned char der[8][16384]; static size_t der_len[8]; static br_x509_certificate chain[8]; static size_t nchain; static unsigned char keyder[16384]; static size_t keyder_len; static br_skey_decoder_context skey; static int sock_rd(void *ctx, unsigned char *b, size_t n) { ssize_t r = read(*(int *)ctx, b, n); return r > 0 ? (int)r : -1; } static int sock_wr(void *ctx, const unsigned char *b, size_t n) { ssize_t r = write(*(int *)ctx, b, n); return r > 0 ? (int)r : -1; } static void limits(int fd, int secs) { struct timeval tv = {.tv_sec = secs}; setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv); setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof tv); } static unsigned char *sink; static size_t *sink_len; static void append(void *ctx, const void *src, size_t len) { (void)ctx; if (*sink_len + len <= 16384) memcpy(sink + *sink_len, src, len); *sink_len += len; } // The certificates of PATH into chain, its private key into skey. static int read_pem(const char *path, bool key) { FILE *f = fopen(path, "rb"); if (f == NULL) return -1; size_t len = fread(file, 1, sizeof file - 1, f); fclose(f); file[len++] = '\n'; br_pem_decoder_context pc; br_pem_decoder_init(&pc); const unsigned char *p = file; bool is_cert = false; while (len > 0) { size_t k = br_pem_decoder_push(&pc, p, len); p += k; len -= k; switch (br_pem_decoder_event(&pc)) { case BR_PEM_BEGIN_OBJ: is_cert = strcmp(br_pem_decoder_name(&pc), "CERTIFICATE") == 0; if (is_cert && nchain == 8) return -1; sink = is_cert ? der[nchain] : keyder; sink_len = is_cert ? &der_len[nchain] : &keyder_len; *sink_len = 0; br_pem_decoder_setdest(&pc, append, NULL); break; case BR_PEM_END_OBJ: if (is_cert && !key) { chain[nchain].data = der[nchain]; chain[nchain].data_len = der_len[nchain]; nchain++; } break; case BR_PEM_ERROR: return -1; default: break; } } if (!key) return nchain > 0 ? 0 : -1; br_skey_decoder_init(&skey); br_skey_decoder_push(&skey, keyder, keyder_len); return br_skey_decoder_last_error(&skey) == 0 ? 0 : -1; } // Sends any pending close_notify, a bounded number of records. static void tls_close(br_ssl_server_context *sc, int fd) { br_ssl_engine_close(&sc->eng); for (int i = 0; i < 8 && (br_ssl_engine_current_state(&sc->eng) & BR_SSL_SENDREC); i++) { size_t len; unsigned char *buf = br_ssl_engine_sendrec_buf(&sc->eng, &len); ssize_t w = write(fd, buf, len); if (w <= 0) break; br_ssl_engine_sendrec_ack(&sc->eng, (size_t)w); } } // Plain HTTP round trip to the backend. static size_t backend(int port, const unsigned char *q, size_t n) { int fd = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in a = {.sin_family = AF_INET, .sin_port = htons((unsigned short)port)}; a.sin_addr.s_addr = htonl(INADDR_LOOPBACK); size_t got = 0; limits(fd, 20); if (connect(fd, (struct sockaddr *)&a, sizeof a) == 0 && write(fd, q, n) == (ssize_t)n) { ssize_t r; while (got < sizeof rep && (r = read(fd, rep + got, sizeof rep - got)) > 0) got += (size_t)r; } close(fd); return got; } static size_t header_end(const unsigned char *m, size_t n) { const unsigned char *e = memmem(m, n, "\r\n\r\n", 4); return e != NULL ? (size_t)(e - m) + 4 : n; } // The reply of M (N bytes) with its Content-Length line taken out and, when // CHUNKED, its body sent in chunks of 1000 bytes. The length of out. static size_t rewrite(const unsigned char *m, size_t n, bool chunked) { size_t h = header_end(m, n), o = 0; for (size_t i = 0; i < h;) { const unsigned char *nl = memchr(m + i, '\n', h - i); size_t end = nl != NULL ? (size_t)(nl - m) + 1 : h; bool clen = end - i > 15 && strncasecmp((const char *)m + i, "content-length:", 15) == 0; bool last = end == h; if (last && chunked) o += (size_t)sprintf((char *)out + o, "Transfer-Encoding: chunked\r\n"); if (!clen) { memcpy(out + o, m + i, end - i); o += end - i; } i = end; } if (chunked && memcmp(out, "HTTP/1.0", 8) == 0) out[7] = '1'; for (size_t i = h; i < n;) { size_t k = n - i < 1000 ? n - i : 1000; if (chunked) o += (size_t)sprintf((char *)out + o, "%zx\r\n", k); memcpy(out + o, m + i, k); o += k; i += k; if (chunked) o += (size_t)sprintf((char *)out + o, "\r\n"); } if (chunked) o += (size_t)sprintf((char *)out + o, "0\r\n\r\n"); return o; } static void serve(int fd, const char *mode, br_ssl_server_context *sc, int bport) { limits(fd, 10); if (strcmp(mode, "tls13") == 0) { static const unsigned char alert[] = {0x15, 0x03, 0x03, 0x00, 0x02, 0x02, 0x46}; unsigned char hello[4096]; if (read(fd, hello, sizeof hello) > 0) (void)!write(fd, alert, sizeof alert); return; } br_sslio_context io; br_ssl_server_reset(sc); br_sslio_init(&io, &sc->eng, sock_rd, &fd, sock_wr, &fd); size_t n = 0, hdr = 0, need = 0; while (n < sizeof req) { int r = br_sslio_read(&io, req + n, sizeof req - n); if (r <= 0) return; n += (size_t)r; if (hdr == 0) { unsigned char *e = memmem(req, n, "\r\n\r\n", 4); if (e == NULL) continue; hdr = (size_t)(e - req) + 4; req[n < sizeof req ? n : n - 1] = 0; char *cl = strcasestr((char *)req, "content-length:"); need = hdr + (cl != NULL && (unsigned char *)cl < e ? strtoul(cl + 15, NULL, 10) : 0); } if (n >= need) break; } if (strcmp(mode, "nothing") == 0) { struct pollfd p = {.fd = fd, .events = POLLIN}; (void)poll(&p, 1, 60000); return; } if (strcmp(mode, "garbage") == 0) { (void)!write(fd, "HTTP/1.0 200 OK\r\n\r\nnot a TLS record at all, 64 bytes or so....\n", 64); return; } char canned[256] = ""; if (strcmp(mode, "redirect") == 0) snprintf(canned, sizeof canned, "HTTP/1.0 302 Found\r\nLocation: https://localhost:%d/\r\n" "Content-Length: 0\r\n\r\n", bport); if (strcmp(mode, "error500") == 0) snprintf(canned, sizeof canned, "HTTP/1.0 500 Internal Server Error\r\nContent-Type: text/plain\r\n" "Content-Length: 6\r\n\r\noops\r\n"); if (canned[0] != '\0') { br_sslio_write_all(&io, canned, strlen(canned)); br_sslio_flush(&io); tls_close(sc, fd); return; } size_t m = backend(bport, req, n); const unsigned char *send = rep; if (strcmp(mode, "midclose") == 0) m = m < 60 ? m : 60; if (strcmp(mode, "truncated") == 0) m = header_end(rep, m) + (m - header_end(rep, m)) / 2; if (strncmp(mode, "noclen", 6) == 0 || strcmp(mode, "chunked") == 0) { m = rewrite(rep, m, strcmp(mode, "chunked") == 0); send = out; } br_sslio_write_all(&io, send, m); br_sslio_flush(&io); if (strcmp(mode, "midclose") != 0 && strcmp(mode, "noclen-unclean") != 0) tls_close(sc, fd); } int main(int argc, char **argv) { if (argc != 7) { fprintf(stderr, "usage: badsrv PORT MODE CHAIN KEY BACKEND_PORT SECONDS\n"); return 2; } signal(SIGPIPE, SIG_IGN); int port = atoi(argv[1]), bport = atoi(argv[5]), secs = atoi(argv[6]); const char *mode = argv[2]; if (secs < 1 || secs > 900) return 2; time_t end = time(NULL) + secs; if (read_pem(argv[3], false) != 0 || read_pem(argv[4], true) != 0) { fprintf(stderr, "badsrv: cannot read %s or %s\n", argv[3], argv[4]); return 1; } static br_ssl_server_context sc; static unsigned char iobuf[BR_SSL_BUFSIZE_BIDI]; if (br_skey_decoder_key_type(&skey) == BR_KEYTYPE_RSA) { br_ssl_server_init_full_rsa(&sc, chain, nchain, br_skey_decoder_get_rsa(&skey)); } else { br_ssl_server_init_full_ec(&sc, chain, nchain, BR_KEYTYPE_EC, br_skey_decoder_get_ec(&skey)); } static const uint16_t rsakex[] = {BR_TLS_RSA_WITH_AES_128_GCM_SHA256}; static const uint16_t cbc[] = {BR_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256}; if (strcmp(mode, "rsakex") == 0) br_ssl_engine_set_suites(&sc.eng, rsakex, 1); if (strcmp(mode, "cbc") == 0) br_ssl_engine_set_suites(&sc.eng, cbc, 1); br_ssl_engine_set_buffer(&sc.eng, iobuf, sizeof iobuf, 1); // The server's own random seed: this helper is not part of suit. unsigned char seed[32]; FILE *u = fopen("/dev/urandom", "rb"); if (u == NULL || fread(seed, 1, sizeof seed, u) != sizeof seed) return 1; fclose(u); br_ssl_engine_inject_entropy(&sc.eng, seed, sizeof seed); int ls = socket(AF_INET, SOCK_STREAM, 0), one = 1; setsockopt(ls, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one); struct sockaddr_in a = {.sin_family = AF_INET, .sin_port = htons((unsigned short)port)}; a.sin_addr.s_addr = htonl(INADDR_LOOPBACK); if (bind(ls, (struct sockaddr *)&a, sizeof a) != 0 || listen(ls, 8) != 0) { perror("badsrv: bind"); return 1; } fprintf(stderr, "badsrv %s on %d\n", mode, port); while (time(NULL) < end) { struct pollfd p = {.fd = ls, .events = POLLIN}; if (poll(&p, 1, 1000) <= 0) continue; int fd = accept(ls, NULL, NULL); if (fd < 0) continue; serve(fd, mode, &sc, bport); close(fd); } return 0; }