LordOS — a free, fast and secure GNU/Linux distribution based on Debian, with its own desktop environment: display server and Wayland compositor in C, a React UI engine on QuickJS, and private native apps.
C cdebiandesktop-environmentebpffirewalllandlocklinuxlinux-distributionopen-sourceprivacyquickjsraspberry-pi-5reactsecuritywaylandwayland-compositor
Package engine speaks HTTPS: lord-tls (sandboxed, the 4th OpenSSL binary) verifies the certificate and host and relays plain HTTP for the download child; https sources stay https; http→https redirects followed, never https→http; pkg_https_test 7/7 against real servers
Federico Pereira7dd27312c1f9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b907bf4..4b0e326 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,11 @@ of the matching [GitHub release](https://github.com/lordbasex/LordOS/releases),### Added+- **The Store downloads over HTTPS.** LordOS's package engine now speaks HTTPS as well as HTTP: a small+ sandboxed helper (`lord-tls`) checks the server's certificate and name and encrypts the download, so+ repositories that only accept HTTPS work, and what you install is private on the network. Every+ package is still checked against its signed index, as before; a secure download is never redirected+ to plain HTTP.- **A guide to building an appearance.** `docs/THEMES-GUIDE.md` explains, for a React developer new toLordOS, what a theme is, its parts (theme.json, tokens, the shell, window frames, menus, layers),right-to-left, light and dark, several displays and the performance rules, how to build and test one,diff --git a/assets/locales/en/errors.json b/assets/locales/en/errors.jsonindex 7cdd862..2af6e72 100644--- a/assets/locales/en/errors.json+++ b/assets/locales/en/errors.json@@ -429,12 +429,15 @@"pkg.http.connectFailed": "could not connect to {host}","pkg.http.connectionLost": "the connection was cut","pkg.http.createFailed": "could not create {path}",+ "pkg.http.downgrade": "A secure download was redirected to plain HTTP: refused","pkg.http.hostNotFound": "{host} was not found","pkg.http.httpsRedirect": "the server redirects to https, which LordOS does not use for packages","pkg.http.noResponse": "{host} did not respond",+ "pkg.http.noTls": "This LordOS can't download over HTTPS: lord-tls is missing or not root's","pkg.http.notDownloaded": "not downloaded","pkg.http.saveFailed": "could not save {path}","pkg.http.status": "the server answered {status}",+ "pkg.http.tlsFailed": "{host}'s certificate couldn't be verified (or its secure connection failed)","pkg.http.tooLarge": "the file is larger than allowed","pkg.http.writeFailed": "could not write (is the disk full?)","pkg.index.tooLarge": "the index is too large",@@ -545,8 +548,12 @@"sig.revokedVersion": "LordOS revoked this version of the app","sig.unknownFormat": "Signature in an unknown format","ssh.badConfig": "The SSH server configuration is not valid (sshd -t); nothing was changed",+ "ssh.badKey": "That isn't an SSH public key LordOS accepts (one line: type, key and an optional comment)",+ "ssh.duplicateKey": "That key is already allowed",+ "ssh.keyNotFound": "That key isn't in the list","ssh.notInstalled": "The SSH server (openssh-server) is not installed","ssh.startFailed": "The SSH server did not start (see Logs)",+ "ssh.weakRootPassword": "Root's password needs at least 8 characters, without ':' or control characters","sys.badArgument": "Invalid request (a program error)","sys.errno": "{errno}","sys.outOfMemory": "Out of memory",diff --git a/assets/locales/es/errors.json b/assets/locales/es/errors.jsonindex f15ef99..ade9b0e 100644--- a/assets/locales/es/errors.json+++ b/assets/locales/es/errors.json@@ -429,12 +429,15 @@"pkg.http.connectFailed": "no se pudo conectar con {host}","pkg.http.connectionLost": "la conexión se cortó","pkg.http.createFailed": "no se pudo crear {path}",+ "pkg.http.downgrade": "Una descarga segura fue redirigida a HTTP sin cifrar: rechazada","pkg.http.hostNotFound": "no se encontró {host}","pkg.http.httpsRedirect": "el servidor redirige a https, que LordOS no usa para paquetes","pkg.http.noResponse": "{host} no respondió",+ "pkg.http.noTls": "Este LordOS no puede descargar por HTTPS: falta lord-tls o no es de root","pkg.http.notDownloaded": "no se descargó","pkg.http.saveFailed": "no se pudo guardar {path}","pkg.http.status": "el servidor respondió {status}",+ "pkg.http.tlsFailed": "No se pudo verificar el certificado de {host} (o falló su conexión segura)","pkg.http.tooLarge": "el archivo es más grande de lo permitido","pkg.http.writeFailed": "no se pudo escribir (¿el disco está lleno?)","pkg.index.tooLarge": "el índice es demasiado grande",@@ -545,8 +548,12 @@"sig.revokedVersion": "LordOS revocó esta versión de la app","sig.unknownFormat": "Firma de un formato desconocido","ssh.badConfig": "La configuración del servidor SSH no es válida (sshd -t); no se cambió nada",+ "ssh.badKey": "Esa no es una clave pública SSH que LordOS acepte (una línea: tipo, clave y un comentario opcional)",+ "ssh.duplicateKey": "Esa clave ya está permitida",+ "ssh.keyNotFound": "Esa clave no está en la lista","ssh.notInstalled": "El servidor SSH (openssh-server) no está instalado","ssh.startFailed": "El servidor SSH no arrancó (mirá Registros)",+ "ssh.weakRootPassword": "La contraseña de root necesita al menos 8 caracteres, sin ':' ni caracteres de control","sys.badArgument": "Pedido inválido (un error del programa)","sys.errno": "{errno}","sys.outOfMemory": "Sin memoria",diff --git a/assets/locales/pt/errors.json b/assets/locales/pt/errors.jsonindex a9e80e8..20fc575 100644--- a/assets/locales/pt/errors.json+++ b/assets/locales/pt/errors.json@@ -429,12 +429,15 @@"pkg.http.connectFailed": "não foi possível conectar a {host}","pkg.http.connectionLost": "a conexão caiu","pkg.http.createFailed": "não foi possível criar {path}",+ "pkg.http.downgrade": "Um download seguro foi redirecionado para HTTP sem criptografia: recusado","pkg.http.hostNotFound": "{host} não foi encontrado","pkg.http.httpsRedirect": "o servidor redireciona para https, que o LordOS não usa para pacotes","pkg.http.noResponse": "{host} não respondeu",+ "pkg.http.noTls": "Este LordOS não consegue baixar por HTTPS: falta o lord-tls ou ele não é do root","pkg.http.notDownloaded": "não foi baixado","pkg.http.saveFailed": "não foi possível salvar {path}","pkg.http.status": "o servidor respondeu {status}",+ "pkg.http.tlsFailed": "Não foi possível verificar o certificado de {host} (ou a conexão segura falhou)","pkg.http.tooLarge": "o arquivo é maior do que o permitido","pkg.http.writeFailed": "não foi possível gravar (o disco está cheio?)","pkg.index.tooLarge": "o índice é grande demais",@@ -545,8 +548,12 @@"sig.revokedVersion": "O LordOS revogou esta versão do app","sig.unknownFormat": "Assinatura em um formato desconhecido","ssh.badConfig": "A configuração do servidor SSH não é válida (sshd -t); nada foi alterado",+ "ssh.badKey": "Essa não é uma chave pública SSH que o LordOS aceite (uma linha: tipo, chave e um comentário opcional)",+ "ssh.duplicateKey": "Essa chave já está permitida",+ "ssh.keyNotFound": "Essa chave não está na lista","ssh.notInstalled": "O servidor SSH (openssh-server) não está instalado","ssh.startFailed": "O servidor SSH não iniciou (veja Registros)",+ "ssh.weakRootPassword": "A senha do root precisa de pelo menos 8 caracteres, sem ':' nem caracteres de controle","sys.badArgument": "Pedido inválido (um erro do programa)","sys.errno": "{errno}","sys.outOfMemory": "Sem memória",diff --git a/docs/PACKAGES.md b/docs/PACKAGES.mdindex c93bbfd..7897253 100644--- a/docs/PACKAGES.md+++ b/docs/PACKAGES.md@@ -419,3 +419,21 @@ sudo build/pkg-test run pkg-install "cowsay sl"- **`control.tar.zst`** in local `.deb` files (Ubuntu); Debian's use xz.- **Incremental index diffs** (`Packages.diff`). Today the whole index is downloaded when itchanges.++## HTTPS (0.8.5)++The engine downloads `https://` sources over TLS and `http://` ones as before. The download child (nobody,+in `lordos-net-store.scope`) resolves and connects the TCP socket itself; for `https://` it starts+`lord-tls` (`server/src/tls/tlsproxy.c`, next to `lord-server`, root's) with the socket on fd 3 and a+socketpair on fd 4. lord-tls loads the system's CA bundle, takes the helpers' sandbox (no sockets, no exec,+no files), does a TLS 1.2+ handshake with SNI, checks the chain and the host name, answers `1` (or `0`,+which the engine reports as `pkg.http.tlsFailed`) and then relays plain HTTP, so the HTTP code is the+same for both schemes. Redirects may go from `http://` to `https://`, never back (`pkg.http.downgrade`).+TLS adds privacy and refuses an impostor server; what is installed is still decided by the signed+index and each file's SHA-256, exactly as over HTTP. Sources written as `https://` are no longer+rewritten to `http://`.++Tested against real servers (`server/tests/pkg_https_test.c`, run as root with network, not part of+`make test`): an HTTPS-only vendor repository, lordos.org over both schemes, an HTTP→HTTPS redirect, and+self-signed, wrong-host and expired certificates refused (7/7).+diff --git a/server/mk/tls.mk b/server/mk/tls.mknew file mode 100644index 0000000..9bb93a8--- /dev/null+++ b/server/mk/tls.mk@@ -0,0 +1,11 @@+# lord-tls (0.8.5, docs/PACKAGES.md "HTTPS"): TLS for the package engine's downloads. The download+# child (nobody) connects the socket and hands it over; lord-tls verifies the server's certificate and+# host name, applies the helpers' sandbox and relays plain HTTP. With lord-sessiond, lord-maild and+# lord-fetch, the only binaries that link OpenSSL; built when its headers are there.+TLS_SRC := src/tls/tlsproxy.c src/sec/sandbox.c src/sec/cgroup.c+ifeq ($(MAILNET),1)+all: build/lord-tls+endif+build/lord-tls: $(TLS_SRC) src/sec/sandbox.h+ @mkdir -p build+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ $(TLS_SRC) $(shell pkg-config --libs openssl) -lpthreaddiff --git a/server/src/pkg/http.c b/server/src/pkg/http.cindex 635acbc..3ff2a3f 100644--- a/server/src/pkg/http.c+++ b/server/src/pkg/http.c@@ -1,8 +1,11 @@/* http.c — HTTP/1.1 client and downloads with dropped privileges (see http.h).*- * The child (nobody) speaks HTTP: GET with Host, keep-alive, redirects (up to 5, only to- * http://), Content-Length, chunked or until the connection closes, If-Modified-Since, and- * a 30 s maximum time without data. It sends the parent messages over the pipe:+ * The child (nobody) speaks HTTP: GET with Host, keep-alive, redirects (up to 5; http:// may go to+ * https://, https:// never back to http://), Content-Length, chunked or until the connection closes,+ * If-Modified-Since, and a 30 s maximum time without data. An https:// URL (0.8.5): the child connects+ * the TCP socket itself and hands it to lord-tls (src/tls/tlsproxy.c: fixed path next to lord-server,+ * no arguments, empty environment, the helpers' sandbox), which verifies the server's certificate and+ * host name and relays plain HTTP over a socketpair; the HTTP code below is the same for both. It sends the parent messages over the pipe:* [type 1 byte][item 4][length 4][data] type H = "status date length", D = data, E = end* (E with text = error). A file: URL (a local repository) is read by the same child, as nobody. */#include "http.h"@@ -13,6 +16,7 @@#include <ctype.h>#include <errno.h>#include <fcntl.h>+#include <limits.h>#include <grp.h>#include <netdb.h>#include <poll.h>@@ -63,6 +67,8 @@ void http_format_date(int64_t t, char *out, size_t n) {typedef struct {int fd;+ int tls; /* fd is lord-tls's plaintext end (an https:// connection) */+ pid_t helper; /* lord-tls, or 0 */char host[256], port[8];char buf[16384];size_t pos, len;@@ -88,10 +94,63 @@ static void conn_close(Conn *c) {if (c->fd >= 0) close(c->fd);c->fd = -1;c->pos = c->len = 0;+ if (c->helper > 0) { kill(c->helper, SIGTERM); waitpid(c->helper, NULL, 0); }+ c->helper = 0;}-static int conn_open(Conn *c, const char *host, const char *port, char *err, size_t errlen) {- if (c->fd >= 0 && !strcmp(c->host, host) && !strcmp(c->port, port)) return 0;+/* lord-tls: next to this binary (lord-server), root's and not writable by others */+static int tls_helper_path(char *out, size_t cap) {+ char exe[PATH_MAX];+ ssize_t k = readlink("/proc/self/exe", exe, sizeof exe - 1);+ if (k <= 0) return -1;+ exe[k] = 0;+ char *slash = strrchr(exe, '/');+ if (!slash) return -1;+ *slash = 0;+ if ((size_t)snprintf(out, cap, "%s/lord-tls", exe) >= cap) return -1;+ struct stat st;+ if (stat(out, &st) || !S_ISREG(st.st_mode) || (st.st_mode & 022) || (st.st_uid != 0 && st.st_uid != getuid())) return -1;+ return 0;+}++/* Wraps the connected TCP socket `tcp` in TLS: lord-tls gets it as fd 3 and a socketpair as fd 4,+ * reads "<host>\n" and answers '1' when the certificate checks out. Returns the plaintext end, or -1. */+static int tls_start(Conn *c, int tcp, const char *host, char *err, size_t errlen) {+ char path[PATH_MAX];+ if (tls_helper_path(path, sizeof path)) { close(tcp); lerr_set(err, errlen, "pkg.http.noTls", NULL); return -1; }+ int sp[2];+ if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, sp)) { close(tcp); lerr_set(err, errlen, "pkg.http.connectFailed", "host", host, NULL); return -1; }+ pid_t pid = fork();+ if (pid < 0) { close(tcp); close(sp[0]); close(sp[1]); lerr_set(err, errlen, "pkg.http.connectFailed", "host", host, NULL); return -1; }+ if (pid == 0) {+ int a = fcntl(tcp, F_DUPFD, 10), b = fcntl(sp[1], F_DUPFD, 10);+ if (a < 0 || b < 0 || dup2(a, 3) != 3 || dup2(b, 4) != 4) _exit(127);+ syscall(SYS_close_range, 5, ~0u, 0);+ const char *const argv[] = { "lord-tls", NULL };+ char *const envp[] = { NULL };+ execve(path, (char *const *)argv, envp);+ _exit(127);+ }+ close(tcp);+ close(sp[1]);+ c->helper = pid;+ char line[300];+ int ln = snprintf(line, sizeof line, "%s\n", host);+ char ok = 0;+ struct pollfd p = { sp[0], POLLIN, 0 };+ if (write(sp[0], line, (size_t)ln) != ln || poll(&p, 1, 25000) != 1 || read(sp[0], &ok, 1) != 1 || ok != '1') {+ close(sp[0]);+ kill(pid, SIGTERM);+ waitpid(pid, NULL, 0);+ c->helper = 0;+ lerr_set(err, errlen, "pkg.http.tlsFailed", "host", host, NULL);+ return -1;+ }+ return sp[0];+}++static int conn_open(Conn *c, const char *host, const char *port, int tls, char *err, size_t errlen) {+ if (c->fd >= 0 && c->tls == tls && !strcmp(c->host, host) && !strcmp(c->port, port)) return 0;conn_close(c);struct addrinfo hints, *res = NULL;memset(&hints, 0, sizeof hints);@@ -111,6 +170,8 @@ static int conn_open(Conn *c, const char *host, const char *port, char *err, siz}freeaddrinfo(res);if (c->fd < 0) { lerr_set(err, errlen, "pkg.http.connectFailed", "host", host, NULL); return -1; }+ c->tls = tls;+ if (tls && (c->fd = tls_start(c, c->fd, host, err, errlen)) < 0) return -1;snprintf(c->host, sizeof c->host, "%s", host);snprintf(c->port, sizeof c->port, "%s", port);return 0;@@ -167,9 +228,10 @@ static int conn_line(Conn *c, char *out, size_t cap) {}}-static int parse_url(const char *url, char *host, size_t hn, char *port, size_t pn, const char **path) {- if (strncmp(url, "http://", 7)) return -1;- const char *h = url + 7, *slash = strchr(h, '/');+static int parse_url(const char *url, char *host, size_t hn, char *port, size_t pn, const char **path, int *tls) {+ *tls = !strncmp(url, "https://", 8);+ if (!*tls && strncmp(url, "http://", 7)) return -1;+ const char *h = url + (*tls ? 8 : 7), *slash = strchr(h, '/');if (!slash) slash = h + strlen(h);size_t l = (size_t)(slash - h);const char *colon = memchr(h, ':', l);@@ -184,7 +246,7 @@ static int parse_url(const char *url, char *host, size_t hn, char *port, size_tmemcpy(port, colon + 1, pl);port[pl] = 0;for (size_t i = 0; i < pl; i++) if (!isdigit((unsigned char)port[i])) return -1;- } else snprintf(port, pn, "80");+ } else snprintf(port, pn, *tls ? "443" : "80");*path = *slash ? slash : "/";return 0;}@@ -226,16 +288,18 @@ static void get_one(Conn *c, const FetchItem *it, uint32_t idx) {if (!strncmp(it->url, "file:", 5)) { get_file(c, it, idx); return; }char url[1100], err[200] = "", line[4096];snprintf(url, sizeof url, "%s", it->url);+ int was_tls = 0;for (int redirects = 0;; redirects++) {char host[256], port[8];const char *path;- if (parse_url(url, host, sizeof host, port, sizeof port, &path)) {- lerr_set(err, sizeof err, strncmp(url, "https://", 8) ? "pkg.http.badUrl" : "pkg.http.httpsRedirect", NULL);- break;- }+ int tls;+ if (parse_url(url, host, sizeof host, port, sizeof port, &path, &tls)) { lerr_set(err, sizeof err, "pkg.http.badUrl", NULL); break; }+ if (was_tls && !tls) { lerr_set(err, sizeof err, "pkg.http.downgrade", NULL); break; } /* https never back to http */+ was_tls = tls;+ const char *defport = tls ? "443" : "80";int retry = c->fd >= 0; /* a reused connection may have been closed */again:- if (conn_open(c, host, port, err, sizeof err)) break;+ if (conn_open(c, host, port, tls, err, sizeof err)) break;/* '+' as %2B, as apt does: an S3 origin (lordos.org) reads a bare '+' as a space, so* pool/rpi/k/kms++-utils/… would be a 404 */char epath[3 * sizeof url]; /* every byte of the URL could be a '+' */@@ -253,7 +317,7 @@ static void get_one(Conn *c, const FetchItem *it, uint32_t idx) {}int rl = snprintf(req, sizeof req, "GET %s HTTP/1.1\r\nHost: %s%s%s\r\nUser-Agent: LordOS-pkg/0.7\r\n""Accept-Encoding: identity\r\nConnection: keep-alive\r\n%s\r\n",- epath, host, strcmp(port, "80") ? ":" : "", strcmp(port, "80") ? port : "", ims);+ epath, host, strcmp(port, defport) ? ":" : "", strcmp(port, defport) ? port : "", ims);if (rl >= (int)sizeof req || conn_write(c, req, (size_t)rl) || conn_line(c, line, sizeof line)) {conn_close(c);if (retry) { retry = 0; goto again; }@@ -321,7 +385,7 @@ static void get_one(Conn *c, const FetchItem *it, uint32_t idx) {}if (close_after) conn_close(c);if (redirect && redirects < 5) {- if (location[0] == '/') snprintf(url, sizeof url, "http://%s%s%s%s", host, strcmp(port, "80") ? ":" : "", strcmp(port, "80") ? port : "", location);+ if (location[0] == '/') snprintf(url, sizeof url, "%s://%s%s%s%s", tls ? "https" : "http", host, strcmp(port, defport) ? ":" : "", strcmp(port, defport) ? port : "", location);else snprintf(url, sizeof url, "%s", location);continue;}@@ -393,7 +457,7 @@ int fetch_batch(FetchItem *items, int n, FetchProgress cb, void *ud) {* firewall and Monitor → Network (lordos:store); outside a LordOS session, where it is */if (getenv("LORDOS_SESSIOND")) cgroup_enter_root("lordos-net-store.scope");if (drop_to_nobody()) _exit(2);- Conn c = { .fd = -1, .out = 3 };+ Conn c = { .fd = -1, .out = 3, .tls = 0, .helper = 0 };for (int i = 0; i < n; i++) get_one(&c, &items[i], (uint32_t)i);conn_close(&c);_exit(0);diff --git a/server/src/pkg/pkg.c b/server/src/pkg/pkg.cindex 33fecee..4c4286e 100644--- a/server/src/pkg/pkg.c+++ b/server/src/pkg/pkg.c@@ -125,9 +125,8 @@ static void mirror_uri(const char *in, char *out, size_t n) {return;}if (!strncmp(in, "mirror+", 7)) in += 7;- /* no TLS of our own: https is downloaded over http (security comes from the signature, as in apt) */- if (!strncmp(in, "https://", 8)) snprintf(out, n, "http://%s", in + 8);- else if (!strncmp(in, "http://", 7)) snprintf(out, n, "%s", in);+ /* (0.8.5) https:// stays https (http.c → lord-tls); the signature is still what is trusted */+ if (!strncmp(in, "https://", 8) || !strncmp(in, "http://", 7)) snprintf(out, n, "%s", in);else if (!strncmp(in, "file:/", 6)) snprintf(out, n, "%s", in); /* a local repository (http.c) */size_t l = strlen(out);while (l && out[l - 1] == '/') out[--l] = 0;diff --git a/server/src/tls/tlsproxy.c b/server/src/tls/tlsproxy.cnew file mode 100644index 0000000..9dfccad--- /dev/null+++ b/server/src/tls/tlsproxy.c@@ -0,0 +1,155 @@+/* tlsproxy.c — lord-tls: TLS for the package engine's downloads (0.8.5; docs/PACKAGES.md, "HTTPS").+ *+ * The package engine's download child (nobody, in lordos-net-store.scope; src/pkg/http.c) connects the+ * TCP socket itself and starts this program with a fixed path, no arguments and an empty environment:+ * fd 3 the connected TCP socket to the server+ * fd 4 a socketpair to the download child: first a line "<host>\n", then plain HTTP both ways+ * lord-tls loads the system's CA bundle, applies the helpers' sandbox (no sockets, no exec, no files,+ * sandbox_apply_helper; it stays in the caller's scope), does a TLS 1.2+ handshake with SNI, checks the+ * certificate chain and the host name, answers one byte on fd 4 ('1' verified, '0' refused) and then+ * only moves bytes: plaintext from fd 4 is encrypted to fd 3, what arrives on fd 3 is decrypted to fd 4.+ * It never parses HTTP and never decides anything about packages: those are still checked by their+ * signed index (http.c and pkg.c), TLS adds privacy and refuses a server that isn't who it claims.+ * With lord-sessiond, lord-maild and lord-fetch, the only binaries that link OpenSSL. */+#include "../sec/sandbox.h"++#include <openssl/err.h>+#include <openssl/ssl.h>+#include <openssl/x509v3.h>++#include <ctype.h>+#include <errno.h>+#include <poll.h>+#include <signal.h>+#include <stdio.h>+#include <string.h>+#include <sys/prctl.h>+#include <sys/resource.h>+#include <sys/socket.h>+#include <sys/stat.h>+#include <unistd.h>++#define NET 3+#define PLAIN 4+#define HANDSHAKE_MS 20000+#define IDLE_MS 60000++static int write_all(int fd, const void *p, size_t n) {+ const char *b = p;+ while (n) {+ ssize_t w = write(fd, b, n);+ if (w < 0 && errno == EINTR) continue;+ if (w <= 0) return -1;+ b += w;+ n -= (size_t)w;+ }+ return 0;+}++/* the host line: a DNS name (letters, digits, '-', '.'), at most 253 characters */+static int read_host(char *host, size_t cap) {+ size_t n = 0;+ for (;;) {+ char ch;+ ssize_t r = read(PLAIN, &ch, 1);+ if (r < 0 && errno == EINTR) continue;+ if (r != 1) return -1;+ if (ch == '\n') break;+ if (n + 1 >= cap || !(isalnum((unsigned char)ch) || ch == '-' || ch == '.')) return -1;+ host[n++] = ch;+ }+ host[n] = 0;+ return n && host[0] != '.' && host[0] != '-' ? 0 : -1;+}++/* waits until the TLS socket can make progress for `want` (SSL_ERROR_WANT_READ/WRITE) */+static int wait_net(int want, int ms) {+ struct pollfd p = { NET, (short)(want == SSL_ERROR_WANT_WRITE ? POLLOUT : POLLIN), 0 };+ return poll(&p, 1, ms) == 1 ? 0 : -1;+}++int main(void) {+ prctl(PR_SET_DUMPABLE, 0);+ struct rlimit nocore = { 0, 0 };+ setrlimit(RLIMIT_CORE, &nocore);+ signal(SIGPIPE, SIG_IGN);+ struct stat st;+ if (fstat(NET, &st) || !S_ISSOCK(st.st_mode) || fstat(PLAIN, &st) || !S_ISSOCK(st.st_mode)) {+ fprintf(stderr, "lord-tls: started by the package engine only\n");+ return 2;+ }+ char host[254];+ if (read_host(host, sizeof host)) return 2;++ OPENSSL_init_ssl(0, NULL);+ SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());+ if (!ctx) return 3;+ SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);+ SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);+ /* the whole bundle now: inside the sandbox there are no files */+ static const char *const bundles[] = { "/etc/ssl/certs/ca-certificates.crt", "/etc/pki/tls/certs/ca-bundle.crt", NULL };+ int have_ca = 0;+ for (int i = 0; bundles[i] && !have_ca; i++) have_ca = SSL_CTX_load_verify_locations(ctx, bundles[i], NULL) == 1;+ SSL *s = SSL_new(ctx);+ if (!have_ca || !s) { write_all(PLAIN, "0", 1); return 3; }++ SandboxHelperCfg cfg = {+ .name = NULL, /* stays in the caller's scope (lordos-net-store.scope) */+ .ro_paths = NULL,+ .extra_syscalls = (int[]){ -1 },+ .allow_ioctl_classes = 0,+ .mem_max_mb = 0,+ .ro_dir_fds = NULL,+ .rw_dir_fds = NULL,+ };+ sandbox_apply_helper(&cfg);++ SSL_set_fd(s, NET);+ SSL_set_tlsext_host_name(s, host);+ SSL_set_hostflags(s, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);+ if (!SSL_set1_host(s, host)) { write_all(PLAIN, "0", 1); return 3; }+ /* the socket is non-blocking (http.c connects it that way): handshake with a deadline */+ for (;;) {+ int r = SSL_connect(s);+ if (r == 1) break;+ int e = SSL_get_error(s, r);+ if ((e != SSL_ERROR_WANT_READ && e != SSL_ERROR_WANT_WRITE) || wait_net(e, HANDSHAKE_MS)) {+ write_all(PLAIN, "0", 1);+ return 4;+ }+ }+ if (SSL_get_verify_result(s) != X509_V_OK) { write_all(PLAIN, "0", 1); return 4; }+ if (write_all(PLAIN, "1", 1)) return 5;++ /* the relay: plaintext ↔ TLS until either side closes or nothing moves for IDLE_MS */+ char buf[16384];+ for (;;) {+ if (SSL_pending(s) <= 0) {+ struct pollfd p[2] = { { NET, POLLIN, 0 }, { PLAIN, POLLIN, 0 } };+ int r = poll(p, 2, IDLE_MS);+ if (r <= 0) break;+ if (p[1].revents & (POLLIN | POLLHUP | POLLERR)) {+ ssize_t n = read(PLAIN, buf, sizeof buf);+ if (n < 0 && errno == EINTR) continue;+ if (n <= 0) break;+ for (int off = 0; off < n;) {+ int w = SSL_write(s, buf + off, (int)(n - off));+ if (w > 0) { off += w; continue; }+ int e = SSL_get_error(s, w);+ if ((e != SSL_ERROR_WANT_READ && e != SSL_ERROR_WANT_WRITE) || wait_net(e, IDLE_MS)) goto done;+ }+ }+ if (!(p[0].revents & (POLLIN | POLLHUP | POLLERR))) continue;+ }+ int n = SSL_read(s, buf, sizeof buf);+ if (n > 0) { if (write_all(PLAIN, buf, (size_t)n)) break; continue; }+ int e = SSL_get_error(s, n);+ if (e == SSL_ERROR_WANT_READ || e == SSL_ERROR_WANT_WRITE) continue;+ break; /* closed (ZERO_RETURN) or an error */+ }+done:+ SSL_shutdown(s);+ SSL_free(s);+ SSL_CTX_free(ctx);+ return 0;+}diff --git a/server/tests/pkg_https_test.c b/server/tests/pkg_https_test.cnew file mode 100644index 0000000..6259e7f--- /dev/null+++ b/server/tests/pkg_https_test.c@@ -0,0 +1,42 @@+/* pkg_https_test.c — the package engine's downloads over HTTPS (src/pkg/http.c + lord-tls), against+ * real servers: run as root on a machine with network, lord-tls next to this binary (root's).+ *+ * sudo build/pkg-https-test (not in make test: it needs the network) */+#include "../src/pkg/http.h"++#include <stdio.h>+#include <string.h>+#include <unistd.h>++static int n, bad;+#define CHECK(name, cond, it) do { n++; if (!(cond)) { bad++; printf("✗ %s (status %d, %s)\n", name, (it)->status, (it)->err); } else printf("✓ %s\n", name); } while (0)++static FetchItem one(const char *url) {+ FetchItem it;+ memset(&it, 0, sizeof it);+ snprintf(it.url, sizeof it.url, "%s", url);+ snprintf(it.dest, sizeof it.dest, "/tmp/pkg-https-test.out");+ it.max = 64u << 20;+ fetch_batch(&it, 1, NULL, NULL);+ unlink(it.dest);+ return it;+}++int main(void) {+ FetchItem a = one("https://downloads.claude.ai/claude-code/apt/stable/dists/stable/InRelease");+ CHECK("an HTTPS-only vendor repository", a.status == 200 && a.size > 100, &a);+ FetchItem b = one("https://lordos.org/apt/dists/stable/InRelease");+ CHECK("LordOS's repository over HTTPS", b.status == 200 && b.size > 100, &b);+ FetchItem c = one("http://lordos.org/apt/dists/stable/InRelease");+ CHECK("the same over plain HTTP still works", c.status == 200 && c.size == b.size, &c);+ FetchItem d = one("http://packages.microsoft.com/repos/code/dists/stable/InRelease");+ CHECK("an http:// URL redirected to https:// is followed", d.status == 200 && d.size > 100, &d);+ FetchItem e = one("https://self-signed.badssl.com/");+ CHECK("a self-signed certificate is refused", e.status != 200 && strstr(e.err, "tlsFailed"), &e);+ FetchItem f = one("https://wrong.host.badssl.com/");+ CHECK("a certificate for another host is refused", f.status != 200 && strstr(f.err, "tlsFailed"), &f);+ FetchItem g = one("https://expired.badssl.com/");+ CHECK("an expired certificate is refused", g.status != 200 && strstr(g.err, "tlsFailed"), &g);+ printf("pkg-https-test: %d/%d ok\n", n - bad, n);+ return bad ? 1 : 0;+}diff --git a/tools/iso/mkdeb.sh b/tools/iso/mkdeb.shindex 9624883..c559253 100755--- a/tools/iso/mkdeb.sh+++ b/tools/iso/mkdeb.sh@@ -91,6 +91,9 @@ strip --strip-unneeded "$L/bin/lord-server" "$L/bin/lord-sessiond" "$L/bin/lord-# lord-fetch (0.8.5): downloads the subscribed blocklists over HTTPS, sandboxed (docs/FIREWALL.md, "Blocklists")[ -x server/build/lord-fetch ] && install -m 755 server/build/lord-fetch "$L/bin/lord-fetch"[ -x "$L/bin/lord-fetch" ] && { strip --strip-unneeded "$L/bin/lord-fetch" 2>/dev/null || true; }+# lord-tls (0.8.5): HTTPS for the package engine's downloads, sandboxed (docs/PACKAGES.md, "HTTPS")+[ -x server/build/lord-tls ] && install -m 755 server/build/lord-tls "$L/bin/lord-tls"+[ -x "$L/bin/lord-tls" ] && { strip --strip-unneeded "$L/bin/lord-tls" 2>/dev/null || true; }# FIDO2 security keys reachable by the session user (lord-sessiond sessions have no logind seat)install -d "$PKG/usr/lib/udev/rules.d"install -m 644 packaging/udev/71-lordos-fido.rules "$PKG/usr/lib/udev/rules.d/71-lordos-fido.rules"