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
Imager: verified image writer, downloads and the first-run file applier
Federico Pereira51d7b070cea8
diff --git a/server/Makefile b/server/Makefileindex 482414d..9e4511e 100644--- a/server/Makefile+++ b/server/Makefile@@ -101,6 +101,31 @@ build/obj/backup/%.o: CPPFLAGS += -isystem ../third_party/monocypherDISK_SRC := src/disk/disk.c src/disk/smart.c src/disk/smartctl.c src/disk/disk_admin.c src/disk/smartctl_admin.c src/ui/js_disk.cSRC += $(DISK_SRC)HDR += $(wildcard src/disk/*.h)+# LordOS Imager (docs/IMAGER.md): the imager-* actions (verified image → removable disk, downloads+# as the user) and lordos-firstrun, the Raspberry Pi first-run file applier (src/firstrun)+IMAGER_SRC := src/imager/imgverify.c src/imager/imager_admin.c+SRC += $(IMAGER_SRC)+HDR += $(wildcard src/imager/*.h)+FIRSTRUN_SRC := src/firstrun/firstrun.c src/firstrun/firstrun_apply.c src/users/homedirs.c+ALL += build/lordos-firstrun+build/lordos-firstrun: $(FIRSTRUN_SRC) src/firstrun/firstrun.h src/users/homedirs.h+ @mkdir -p build+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ $(FIRSTRUN_SRC)+test: build/firstrun-test build/firstrun-fuzz build/imager-test+build/firstrun-test: tests/firstrun_test.c src/firstrun/firstrun.c src/firstrun/firstrun.h+ @mkdir -p build+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/firstrun_test.c src/firstrun/firstrun.c+ ./$@ || { rm -f $@; exit 1; }+build/firstrun-fuzz: tests/firstrun_test.c src/firstrun/firstrun.c src/firstrun/firstrun.h+ @mkdir -p build+ $(CC) $(CPPFLAGS) -O1 -g $(WARN) -std=c11 -fsanitize=address,undefined -fno-sanitize-recover=all -fno-omit-frame-pointer \+ -o $@ tests/firstrun_test.c src/firstrun/firstrun.c+ ./$@ 300000 || { rm -f $@; exit 1; }+build/imager-test: tests/imager_test.c src/imager/imgverify.c src/imager/imgverify.h src/pkg/crypto.c+ @mkdir -p build+ $(CC) $(CPPFLAGS) -O1 -g $(WARN) -std=c11 -fsanitize=address,undefined -fno-sanitize-recover=all -fno-omit-frame-pointer \+ -o $@ tests/imager_test.c src/imager/imgverify.c src/pkg/crypto.c+ ./$@ || { rm -f $@; exit 1; }OBJ := $(SRC:src/%.c=build/obj/%.o)HDR += $(wildcard src/tp/*.h)@@ -569,9 +594,11 @@ build/disktemp-test: tests/disktemp_test.c src/monitor/disktemp.c src/monitor/di$(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -D_GNU_SOURCE -o $@ tests/disktemp_test.c src/monitor/disktemp.c./$@ || { rm -f $@; exit 1; }# manual test of the disk-* actions (root and real devices; not part of `test`)-build/disk-cli: tests/disk_cli.c src/disk/disk.c src/disk/smart.c src/disk/smartctl.c src/disk/disk_admin.c src/disk/smartctl_admin.c src/pkg/crypto.c src/disk/disk.h+DISKCLI_SRC := tests/disk_cli.c src/disk/disk.c src/disk/smart.c src/disk/smartctl.c src/disk/disk_admin.c src/disk/smartctl_admin.c src/pkg/crypto.c \+ src/imager/imgverify.c src/imager/imager_admin.c tests/imager_key.c+build/disk-cli: $(DISKCLI_SRC) src/disk/disk.h src/imager/imager_admin.h@mkdir -p build- $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/disk_cli.c src/disk/disk.c src/disk/smart.c src/disk/smartctl.c src/disk/disk_admin.c src/disk/smartctl_admin.c src/pkg/crypto.c+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ $(DISKCLI_SRC)# user folders (src/users/homedirs.c): languages, user-dirs.dirs, no overwriting, no symlinkstest: build/homedirs-testbuild/homedirs-test: tests/homedirs_test.c src/users/homedirs.c src/users/homedirs.hdiff --git a/server/src/admin.c b/server/src/admin.cindex 2363f26..6d964d0 100644--- a/server/src/admin.c+++ b/server/src/admin.c@@ -35,6 +35,7 @@#include "remote/ssh_admin.h"#include "users/users_admin.h"#include "disk/disk.h"+#include "imager/imager_admin.h"#include "logs/logs_admin.h"#include "hw/hw_admin.h"#include "monitor/proc_admin.h"@@ -394,6 +395,7 @@ static const struct { const char *name; ActionFn fn; int flags; } actions[] = {SSH_ADMIN_ACTIONSUSERS_ADMIN_ACTIONSDISK_ADMIN_ACTIONS+ IMAGER_ADMIN_ACTIONSLOGS_ADMIN_ACTIONSHW_ADMIN_ACTIONSPROC_ADMIN_ACTIONSdiff --git a/server/src/disk/disk.c b/server/src/disk/disk.cindex 47faa58..538f565 100644--- a/server/src/disk/disk.c+++ b/server/src/disk/disk.c@@ -538,3 +538,19 @@ int disk_watch_dispatch(void) {if (h != last_mounts) { last_mounts = h; changed = 1; }return changed;}++/* The disk's identity as lord.disks.list() shows it (the LordOS Imager re-checks it right before+ * writing, so a stick swapped under the same name is refused): the model (sysfs or udev; a loop+ * device's backing file) and the short serial (udev, may be empty). */+int disk_identity(const char *name, char *model, size_t mn, char *serial, size_t sn) {+ if (!disk_valid_name(name) || !mn || !sn) return -1;+ model[0] = serial[0] = 0;+ if (sysfs(name, "device/model", model, mn)) disk_udev_prop(name, "ID_MODEL", model, mn);+ if (!strncmp(name, "loop", 4)) {+ char p[PATH_MAX];+ snprintf(p, sizeof p, "/sys/block/%s/loop/backing_file", name);+ read_small(p, model, mn);+ }+ disk_udev_prop(name, "ID_SERIAL_SHORT", serial, sn);+ return 0;+}diff --git a/server/src/disk/disk.h b/server/src/disk/disk.hindex d7c8290..ddd07e3 100644--- a/server/src/disk/disk.h+++ b/server/src/disk/disk.h@@ -11,6 +11,7 @@#include <stddef.h>#include <stdint.h>#include <sys/types.h>+#include <sys/stat.h>#include "../admin.h"@@ -30,6 +31,8 @@ int disk_udev_prop(const char *name, const char *key, char *out, size_t n);void disk_fs_label(const char *name, char *out, size_t n);/* Size in bytes (/sys/class/block/<n>/size × 512). */uint64_t disk_size(const char *name);+/* Model and short serial, exactly as disk_list_json() reports them (the imager's identity check). */+int disk_identity(const char *name, char *model, size_t mn, char *serial, size_t sn);/* Mount points of the device (separated by \n) from mountinfo; returns how many. */int disk_mounts(const char *name, char *out, size_t n);@@ -102,6 +105,30 @@ void smart_act_health(const AdminReq *r, const char *arg, size_t len);void smart_act_test(const AdminReq *r, const char *arg, size_t len);void smart_act_abort(const AdminReq *r, const char *arg, size_t len);+/* ---- for the LordOS Imager's actions (imager/imager_admin.c), the same checks as disk-* ---- */+typedef struct {+ char name[32], disk[32], dev[48];+ int part, removable;+ uint64_t size;+ unsigned major, minor;+} DiskTarget;+/* A whole disk that is not the system disk (after admin_err on failure: -1). */+int disk_admin_whole(const AdminReq *r, const char *name, DiskTarget *t);+/* Unmounts its partitions under /media or /run/media; refuses anything mounted elsewhere. */+int disk_admin_unmount(const DiskTarget *t);+/* O_RDWR | O_EXCL | extra, with admin_err on failure. */+int disk_admin_open_excl(const DiskTarget *t, int extra);+/* The user's image file: regular, from their home or their mounts, opened as them. */+int disk_admin_open_user_file(const AdminReq *r, const char *path, struct stat *st);+int disk_admin_wipe_ends(int fd, uint64_t size);+/* Cancellable job (disk-cancel), low priority; disk_admin_cancelled() after SIGTERM. */+void disk_admin_job_begin(const AdminReq *r, const char *disk);+void disk_admin_job_end(const char *disk);+int disk_admin_cancelled(void);+void disk_admin_reread(const char *disk); /* uevent "change" and udevadm settle */+/* The disk holding the file st describes is this one (an image can't be read from the disk being written). */+int disk_admin_file_on(const struct stat *st, const char *disk);+void disk_act_smart(const AdminReq *r, const char *arg, size_t len);void disk_act_mount(const AdminReq *r, const char *arg, size_t len);void disk_act_unmount(const AdminReq *r, const char *arg, size_t len);diff --git a/server/src/disk/disk_admin.c b/server/src/disk/disk_admin.cindex 28b2a8e..4aec42c 100644--- a/server/src/disk/disk_admin.c+++ b/server/src/disk/disk_admin.c@@ -780,3 +780,49 @@ void disk_act_eject(const AdminReq *r, const char *arg, size_t len) {}admin_ok("disk.ejected", NULL);}++/* ---- for the LordOS Imager (imager/imager_admin.c) ---- */++int disk_admin_whole(const AdminReq *r, const char *name, DiskTarget *o) {+ Target t;+ if (target(r, name, 1, 0, &t)) return -1;+ memset(o, 0, sizeof *o);+ snprintf(o->name, sizeof o->name, "%s", t.name);+ snprintf(o->disk, sizeof o->disk, "%s", t.disk);+ snprintf(o->dev, sizeof o->dev, "%s", t.dev);+ o->part = t.part;+ o->removable = t.removable;+ o->size = t.size;+ struct stat st;+ if (lstat(t.dev, &st) || !S_ISBLK(st.st_mode)) { admin_err("disk.notBlock", "name", t.dev, NULL); return -1; }+ o->major = major(st.st_rdev);+ o->minor = minor(st.st_rdev);+ return 0;+}++static void to_target(const DiskTarget *d, Target *t) {+ memset(t, 0, sizeof *t);+ snprintf(t->name, sizeof t->name, "%s", d->name);+ snprintf(t->disk, sizeof t->disk, "%s", d->disk);+ snprintf(t->dev, sizeof t->dev, "%s", d->dev);+ t->part = d->part;+ t->removable = d->removable;+ t->size = d->size;+}++int disk_admin_unmount(const DiskTarget *d) { Target t; to_target(d, &t); return unmount_disk(&t); }+int disk_admin_open_excl(const DiskTarget *d, int extra) { Target t; to_target(d, &t); return open_excl(&t, extra); }+int disk_admin_open_user_file(const AdminReq *r, const char *path, struct stat *st) { return open_image(r, path, st); }+int disk_admin_wipe_ends(int fd, uint64_t size) { return wipe_ends(fd, size); }+void disk_admin_job_begin(const AdminReq *r, const char *disk) { job_begin(r, disk); }+void disk_admin_job_end(const char *disk) { job_end(disk); }+int disk_admin_cancelled(void) { return cancelled != 0; }+void disk_admin_reread(const char *disk) { uevent_change(disk); settle(); }++int disk_admin_file_on(const struct stat *st, const char *disk) {+ char dn[32] = "", base[32] = "", p[64], real[PATH_MAX];+ snprintf(p, sizeof p, "/sys/dev/block/%u:%u", major(st->st_dev), minor(st->st_dev));+ if (realpath(p, real) && strrchr(real, '/')) snprintf(dn, sizeof dn, "%s", strrchr(real, '/') + 1);+ if (dn[0] && !disk_parent(dn, base, sizeof base)) snprintf(base, sizeof base, "%s", dn);+ return base[0] && !strcmp(base, disk);+}diff --git a/server/src/firstrun/firstrun.c b/server/src/firstrun/firstrun.cnew file mode 100644index 0000000..e7bbf91--- /dev/null+++ b/server/src/firstrun/firstrun.c@@ -0,0 +1,516 @@+/* firstrun.c — strict parser of lordos-firstrun.txt (see firstrun.h and docs/IMAGER.md).+ *+ * Pure: no I/O, no locale, no allocation except the SSH key lines. Every byte is accounted for:+ * the file is UTF-8 text with LF or CRLF line ends, at most FR_MAX_FILE bytes, no NUL. A line is+ * empty, a comment ("#…") or "key=value" with a key from the table below, exactly once (ssh_key+ * may repeat). The first non-comment line must be "version=1". */+#include "firstrun.h"++#include <stdio.h>+#include <stdlib.h>+#include <string.h>++static int is_lower(char c) { return c >= 'a' && c <= 'z'; }+static int is_digit(char c) { return c >= '0' && c <= '9'; }+static int is_alnum_l(char c) { return is_lower(c) || is_digit(c); }++int fr_valid_hostname(const char *s) {+ size_t n = strlen(s);+ if (n < 1 || n > 63) return 0;+ if (!is_alnum_l(s[0]) || !is_alnum_l(s[n - 1])) return 0;+ for (size_t i = 0; i < n; i++) if (!is_alnum_l(s[i]) && s[i] != '-') return 0;+ /* all digits looks like a number (RFC 1123 allows it, but resolvers and people get confused) */+ size_t d = 0;+ for (size_t i = 0; i < n; i++) d += is_digit(s[i]);+ if (d == n) return 0;+ if (!strcmp(s, "localhost")) return 0;+ return 1;+}++static const char *const RESERVED[] = {+ "root", "daemon", "bin", "sys", "sync", "games", "man", "lp", "mail", "news", "uucp", "proxy",+ "www-data", "backup", "list", "irc", "nobody", "lordos", "lordos-greeter", "messagebus",+ "polkitd", "sshd", "pipewire", "sudo", "admin", "wheel", "users", "staff", "adm", "disk",+ "audio", "video", "input", "render", "plugdev", "netdev", "bluetooth", "avahi", "_apt",+ "lordos-remote", "operator", "shadow", "utmp", "tty", "kmem", "dialout", "cdrom",+};++int fr_valid_user(const char *s) {+ size_t n = strlen(s);+ if (n < 1 || n > 32) return 0;+ if (!is_lower(s[0]) && s[0] != '_') return 0;+ for (size_t i = 1; i < n; i++) if (!is_alnum_l(s[i]) && s[i] != '_' && s[i] != '-') return 0;+ if (!strncmp(s, "systemd-", 8)) return 0;+ for (size_t i = 0; i < sizeof RESERVED / sizeof *RESERVED; i++) if (!strcmp(s, RESERVED[i])) return 0;+ return 1;+}++static int is_b64crypt(char c) { return is_alnum_l(c) || (c >= 'A' && c <= 'Z') || c == '.' || c == '/'; }++/* $6$[rounds=N$]<salt 1..16>$<86 chars> or $y$<params>$<salt>$<43 chars> */+int fr_valid_hash(const char *s) {+ size_t n = strlen(s);+ if (n > 250) return 0;+ if (!strncmp(s, "$6$", 3)) {+ const char *p = s + 3;+ if (!strncmp(p, "rounds=", 7)) {+ p += 7;+ unsigned long r = 0;+ int nd = 0;+ while (is_digit(*p) && nd < 10) { r = r * 10 + (unsigned long)(*p - '0'); p++; nd++; }+ if (!nd || *p != '$' || r < 1000 || r > 999999999UL) return 0;+ p++;+ }+ size_t sl = 0;+ while (p[sl] && p[sl] != '$') { if (!is_b64crypt(p[sl])) return 0; sl++; }+ if (sl < 1 || sl > 16 || p[sl] != '$') return 0;+ p += sl + 1;+ if (strlen(p) != 86) return 0;+ for (; *p; p++) if (!is_b64crypt(*p)) return 0;+ return 1;+ }+ if (!strncmp(s, "$y$", 3)) {+ const char *p = s + 3;+ int parts = 0;+ size_t len[3] = { 0, 0, 0 };+ for (; *p; p++) {+ if (*p == '$') { if (++parts > 2) return 0; continue; }+ if (!is_b64crypt(*p)) return 0;+ len[parts]++;+ }+ return parts == 2 && len[0] >= 1 && len[0] <= 32 && len[1] >= 1 && len[1] <= 86 && len[2] == 43;+ }+ return 0;+}++int fr_valid_timezone(const char *s) {+ size_t n = strlen(s);+ if (n < 3 || n > 63) return 0;+ if (s[0] == '/' || s[n - 1] == '/') return 0;+ if (strstr(s, "..") || strstr(s, "//")) return 0;+ if (!((s[0] >= 'A' && s[0] <= 'Z'))) return 0; /* Area names start with a capital (and UTC) */+ for (size_t i = 0; i < n; i++) {+ char c = s[i];+ if (!(is_alnum_l(c) || (c >= 'A' && c <= 'Z') || c == '_' || c == '-' || c == '+' || c == '/')) return 0;+ }+ if (!strncmp(s, "posix/", 6) || !strncmp(s, "right/", 6)) return 0;+ return 1;+}++/* Valid UTF-8 (shortest form, no surrogates, <= U+10FFFF); returns 0 on a bad sequence. */+static int utf8_ok(const unsigned char *p, size_t n, int allow_ctl) {+ for (size_t i = 0; i < n;) {+ unsigned c = p[i];+ if (c < 0x80) {+ if (!allow_ctl && (c < 0x20 || c == 0x7f)) return 0;+ if (!c) return 0;+ i++;+ continue;+ }+ size_t len;+ unsigned cp;+ if ((c & 0xe0) == 0xc0) { len = 2; cp = c & 0x1f; }+ else if ((c & 0xf0) == 0xe0) { len = 3; cp = c & 0x0f; }+ else if ((c & 0xf8) == 0xf0) { len = 4; cp = c & 0x07; }+ else return 0;+ if (i + len > n) return 0;+ for (size_t k = 1; k < len; k++) {+ if ((p[i + k] & 0xc0) != 0x80) return 0;+ cp = cp << 6 | (p[i + k] & 0x3f);+ }+ if ((len == 2 && cp < 0x80) || (len == 3 && cp < 0x800) || (len == 4 && cp < 0x10000)) return 0;+ if (cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff)) return 0;+ if (cp >= 0x80 && cp < 0xa0) return 0; /* C1 controls */+ if (cp == 0x2028 || cp == 0x2029 || (cp >= 0x202a && cp <= 0x202e) || (cp >= 0x2066 && cp <= 0x2069)) return 0; /* line separators, bidi overrides */+ i += len;+ }+ return 1;+}++int fr_valid_fullname(const char *s) {+ size_t n = strlen(s);+ if (n < 1 || n > 128) return 0;+ if (strpbrk(s, ":,=\\")) return 0; /* passwd GECOS separators; no escapes */+ if (s[0] == ' ' || s[n - 1] == ' ' || s[0] == '-') return 0;+ return utf8_ok((const unsigned char *)s, n, 0);+}++int fr_valid_wallpaper(const char *s) {+ size_t n = strlen(s);+ if (n < 1 || n > 48) return 0;+ if (!is_alnum_l(s[0]) || !is_alnum_l(s[n - 1])) return 0;+ for (size_t i = 0; i < n; i++) if (!is_alnum_l(s[i]) && s[i] != '-') return 0;+ return 1;+}++static const char *const ACCENTS[] = { "azul", "violeta", "rosa", "naranja", "verde", "grafito", "rojo", "amarillo", "turquesa", "celeste" };++int fr_valid_accent(const char *s) {+ for (size_t i = 0; i < sizeof ACCENTS / sizeof *ACCENTS; i++) if (!strcmp(s, ACCENTS[i])) return 1;+ return 0;+}++/* ---- SSH public keys ---- */++static int b64val(unsigned char c) {+ if (c >= 'A' && c <= 'Z') return c - 'A';+ if (c >= 'a' && c <= 'z') return c - 'a' + 26;+ if (c >= '0' && c <= '9') return c - '0' + 52;+ if (c == '+') return 62;+ if (c == '/') return 63;+ return -1;+}++/* Strict base64 (padding required, no whitespace); returns the decoded length or -1. */+static long b64_decode(const char *s, size_t n, unsigned char *out, size_t cap) {+ if (n == 0 || n % 4) return -1;+ size_t o = 0;+ for (size_t i = 0; i < n; i += 4) {+ int v[4], pad = 0;+ for (int k = 0; k < 4; k++) {+ unsigned char c = (unsigned char)s[i + k];+ if (c == '=') {+ if (i + 4 != n || k < 2) return -1;+ v[k] = 0;+ pad++;+ } else {+ if (pad) return -1;+ v[k] = b64val(c);+ if (v[k] < 0) return -1;+ }+ }+ unsigned trip = (unsigned)v[0] << 18 | (unsigned)v[1] << 12 | (unsigned)v[2] << 6 | (unsigned)v[3];+ unsigned char b[3] = { (unsigned char)(trip >> 16), (unsigned char)(trip >> 8), (unsigned char)trip };+ for (int k = 0; k < 3 - pad; k++) {+ if (o >= cap) return -1;+ out[o++] = b[k];+ }+ }+ return (long)o;+}++static const char *const KEY_TYPES[] = {+ "ssh-ed25519", "[email protected]", "ecdsa-sha2-nistp256", "ecdsa-sha2-nistp384",+ "ecdsa-sha2-nistp521", "[email protected]", "ssh-rsa",+};++int fr_valid_ssh_key(const char *s) {+ size_t n = strlen(s);+ if (n < 20 || n >= FR_KEY_MAX) return 0;+ const char *sp = strchr(s, ' ');+ if (!sp) return 0;+ size_t tl = (size_t)(sp - s);+ int known = -1;+ for (size_t i = 0; i < sizeof KEY_TYPES / sizeof *KEY_TYPES; i++)+ if (strlen(KEY_TYPES[i]) == tl && !memcmp(s, KEY_TYPES[i], tl)) known = (int)i;+ if (known < 0) return 0;+ const char *b = sp + 1;+ const char *e = strchr(b, ' ');+ size_t bl = e ? (size_t)(e - b) : strlen(b);+ static unsigned char blob[FR_KEY_MAX];+ long dl = b64_decode(b, bl, blob, sizeof blob);+ if (dl < 4 + (long)tl) return 0;+ /* the blob starts with the same type as a length-prefixed string */+ unsigned long sl = (unsigned long)blob[0] << 24 | (unsigned long)blob[1] << 16 | (unsigned long)blob[2] << 8 | blob[3];+ if (sl != tl || memcmp(blob + 4, s, tl)) return 0;+ if (known == 0 && dl != 4 + 11 + 4 + 32) return 0; /* ssh-ed25519: exactly one 32-byte key */+ if (known == 6 && dl < 260) return 0; /* ssh-rsa: at least 2048 bits */+ if (e) {+ const char *c = e + 1;+ size_t cl = strlen(c);+ if (cl > 256 || !utf8_ok((const unsigned char *)c, cl, 0)) return 0;+ }+ return 1;+}++int fr_unhex(const char *hex, unsigned char *out, size_t cap) {+ size_t n = strlen(hex);+ if (n % 2 || n / 2 > cap) return -1;+ for (size_t i = 0; i < n; i += 2) {+ int v = 0;+ for (int k = 0; k < 2; k++) {+ char c = hex[i + (size_t)k];+ int d = is_digit(c) ? c - '0' : (c >= 'a' && c <= 'f') ? c - 'a' + 10 : -1;+ if (d < 0) return -1;+ v = v * 16 + d;+ }+ out[i / 2] = (unsigned char)v;+ }+ return (int)(n / 2);+}++/* ---- the parser ---- */++enum {+ K_VERSION, K_HOSTNAME, K_LANG, K_TIMEZONE, K_KEYBOARD, K_VARIANT, K_WIFI_COUNTRY, K_USER, K_FULLNAME,+ K_HASH, K_AUTOLOGIN, K_SSID, K_PSK, K_HIDDEN, K_SSH, K_SSH_KEY, K_REMOTE, K_BLUETOOTH, K_THEME, K_MODE,+ K_ACCENT, K_WALLPAPER, K_COOLER, K_PERF, K_OVERCLOCK, K_UPDATES, K_COUNT+};+static const char *const KEYS[K_COUNT] = {+ "version", "hostname", "lang", "timezone", "keyboard", "keyboard_variant", "wifi_country", "user", "fullname",+ "password_hash", "autologin", "wifi_ssid_hex", "wifi_psk", "wifi_hidden", "ssh", "ssh_key", "remote_desktop",+ "bluetooth", "theme", "mode", "accent", "wallpaper", "cooler", "performance", "overclock", "auto_updates",+};++static int set_err(char *err, size_t errn, int line, const char *what) {+ if (err && errn) snprintf(err, errn, "line %d: %s", line, what);+ return -1;+}++static int bool01(const char *v, int *out) {+ if (!strcmp(v, "1")) { *out = 1; return 0; }+ if (!strcmp(v, "0")) { *out = 0; return 0; }+ return -1;+}++static int copy_to(char *dst, size_t cap, const char *v) {+ size_t n = strlen(v);+ if (n >= cap) return -1;+ memcpy(dst, v, n + 1);+ return 0;+}++static int pick(const char *v, const char *const *names, int n) {+ for (int i = 0; i < n; i++) if (!strcmp(v, names[i])) return i;+ return -1;+}++static int value(FirstRun *fr, int k, const char *v, char *why, size_t whyn) {+#define BAD(msg) do { snprintf(why, whyn, "%s: %s", KEYS[k], msg); return -1; } while (0)+ switch (k) {+ case K_VERSION:+ if (strcmp(v, "1")) BAD("only version 1 is understood");+ fr->version = 1;+ return 0;+ case K_HOSTNAME:+ if (!fr_valid_hostname(v) || copy_to(fr->hostname, sizeof fr->hostname, v)) BAD("not a host name (a-z, 0-9 and -, up to 63)");+ fr->has_hostname = 1;+ return 0;+ case K_LANG: {+ static const char *const L[] = { "en", "es", "pt" };+ if (pick(v, L, 3) < 0) BAD("not a LordOS language");+ copy_to(fr->lang, sizeof fr->lang, v);+ fr->has_lang = 1;+ return 0;+ }+ case K_TIMEZONE:+ if (!fr_valid_timezone(v) || copy_to(fr->timezone, sizeof fr->timezone, v)) BAD("not a time zone name");+ fr->has_timezone = 1;+ return 0;+ case K_KEYBOARD: {+ size_t n = strlen(v);+ if (n < 2 || n > 10) BAD("not a keyboard layout");+ for (size_t i = 0; i < n; i++) if (!is_lower(v[i])) BAD("not a keyboard layout");+ copy_to(fr->keyboard, sizeof fr->keyboard, v);+ fr->has_keyboard = 1;+ return 0;+ }+ case K_VARIANT: {+ size_t n = strlen(v);+ if (n > 32) BAD("too long");+ for (size_t i = 0; i < n; i++) if (!is_alnum_l(v[i]) && !(v[i] >= 'A' && v[i] <= 'Z') && v[i] != '_' && v[i] != '-') BAD("not a keyboard variant");+ copy_to(fr->variant, sizeof fr->variant, v);+ fr->has_variant = 1;+ return 0;+ }+ case K_WIFI_COUNTRY:+ if (strlen(v) != 2 || v[0] < 'A' || v[0] > 'Z' || v[1] < 'A' || v[1] > 'Z') BAD("two capital letters");+ copy_to(fr->wifi_country, sizeof fr->wifi_country, v);+ fr->has_wifi_country = 1;+ return 0;+ case K_USER:+ if (!fr_valid_user(v) || copy_to(fr->user, sizeof fr->user, v)) BAD("not a valid user name, or a reserved one");+ fr->has_user = 1;+ return 0;+ case K_FULLNAME:+ if (!fr_valid_fullname(v) || copy_to(fr->fullname, sizeof fr->fullname, v)) BAD("not a valid name");+ fr->has_fullname = 1;+ return 0;+ case K_HASH:+ if (!fr_valid_hash(v) || copy_to(fr->hash, sizeof fr->hash, v)) BAD("not a SHA-512 crypt or yescrypt hash");+ fr->has_hash = 1;+ return 0;+ case K_AUTOLOGIN:+ if (bool01(v, &fr->autologin)) BAD("0 or 1");+ fr->has_autologin = 1;+ return 0;+ case K_SSID: {+ if (!*v) BAD("empty");+ int n = fr_unhex(v, fr->ssid, sizeof fr->ssid);+ if (n < 1) BAD("1 to 32 bytes in lower-case hex");+ fr->ssid_len = (size_t)n;+ for (int i = 0; i < n; i++) if (!fr->ssid[i]) BAD("contains a NUL byte");+ fr->has_wifi = 1;+ return 0;+ }+ case K_PSK: {+ unsigned char tmp[32];+ if (strlen(v) != 64 || fr_unhex(v, tmp, sizeof tmp) != 32) BAD("64 lower-case hex digits (the derived key, never the password)");+ memset(tmp, 0, sizeof tmp);+ copy_to(fr->psk, sizeof fr->psk, v);+ fr->has_psk = 1;+ return 0;+ }+ case K_HIDDEN:+ if (bool01(v, &fr->hidden)) BAD("0 or 1");+ fr->has_hidden = 1;+ return 0;+ case K_SSH: {+ static const char *const S[] = { "off", "password", "keys" };+ int i = pick(v, S, 3);+ if (i < 0) BAD("off, password or keys");+ fr->ssh = i;+ fr->has_ssh = 1;+ return 0;+ }+ case K_SSH_KEY:+ if (fr->nkeys >= FR_MAX_KEYS) BAD("too many keys (16 at most)");+ if (!fr_valid_ssh_key(v)) BAD("not an OpenSSH public key of an accepted type");+ if (!(fr->keys[fr->nkeys] = strdup(v))) BAD("out of memory");+ fr->nkeys++;+ return 0;+ case K_REMOTE:+ if (bool01(v, &fr->remote)) BAD("0 or 1");+ fr->has_remote = 1;+ return 0;+ case K_BLUETOOTH:+ if (bool01(v, &fr->bluetooth)) BAD("0 or 1");+ fr->has_bluetooth = 1;+ return 0;+ case K_THEME: {+ static const char *const T[] = { "default", "classic" };+ if (pick(v, T, 2) < 0) BAD("default or classic");+ copy_to(fr->theme, sizeof fr->theme, v);+ fr->has_theme = 1;+ return 0;+ }+ case K_MODE: {+ static const char *const M[] = { "light", "dark" };+ if (pick(v, M, 2) < 0) BAD("light or dark");+ copy_to(fr->mode, sizeof fr->mode, v);+ fr->has_mode = 1;+ return 0;+ }+ case K_ACCENT:+ if (!fr_valid_accent(v)) BAD("not a LordOS accent");+ copy_to(fr->accent, sizeof fr->accent, v);+ fr->has_accent = 1;+ return 0;+ case K_WALLPAPER:+ if (!fr_valid_wallpaper(v)) BAD("not a wallpaper id");+ copy_to(fr->wallpaper, sizeof fr->wallpaper, v);+ fr->has_wallpaper = 1;+ return 0;+ case K_COOLER: {+ static const char *const C[] = { "case-fan", "active-cooler", "passive", "none" };+ int i = pick(v, C, 4);+ if (i < 0) BAD("case-fan, active-cooler, passive or none");+ fr->cooler = FR_COOL_CASE_FAN + i;+ fr->has_cooler = 1;+ return 0;+ }+ case K_PERF: {+ static const char *const P[] = { "balanced", "performance", "quiet", "conservative" };+ int i = pick(v, P, 4);+ if (i < 0) BAD("balanced, performance, quiet or conservative");+ fr->perf = FR_PERF_BALANCED + i;+ fr->has_perf = 1;+ return 0;+ }+ case K_OVERCLOCK:+ if (bool01(v, &fr->overclock)) BAD("0 or 1");+ fr->has_overclock = 1;+ return 0;+ case K_UPDATES:+ if (bool01(v, &fr->updates)) BAD("0 or 1");+ fr->has_updates = 1;+ return 0;+ }+ snprintf(why, whyn, "unknown key");+ return -1;+#undef BAD+}++/* Rules between keys, once everything is read. */+static int cross_check(const FirstRun *fr, char *why, size_t whyn) {+#define BAD(msg) do { snprintf(why, whyn, "%s", msg); return -1; } while (0)+ int user_keys = fr->has_fullname || fr->has_hash || fr->has_autologin;+ if (user_keys && !fr->has_user) BAD("fullname, password_hash or autologin without user");+ if (fr->has_user && !fr->has_hash) BAD("user without password_hash");+ if (fr->has_variant && !fr->has_keyboard) BAD("keyboard_variant without keyboard");+ if ((fr->has_psk || fr->has_hidden) && !fr->has_wifi) BAD("wifi_psk or wifi_hidden without wifi_ssid_hex");+ if (fr->has_ssh && fr->ssh == FR_SSH_KEYS && fr->nkeys == 0) BAD("ssh=keys without any ssh_key");+ if (fr->nkeys && !(fr->has_ssh && fr->ssh != FR_SSH_OFF)) BAD("ssh_key with ssh off");+ if (fr->nkeys && !fr->has_user) BAD("ssh_key without user");+ if (fr->has_ssh && fr->ssh != FR_SSH_OFF && !fr->has_user) BAD("ssh on without a user (root never logs in)");+ if (fr->has_remote && fr->remote && !fr->has_user) BAD("remote_desktop=1 without a user");+ if (fr->has_overclock && fr->overclock && !(fr->has_cooler && (fr->cooler == FR_COOL_CASE_FAN || fr->cooler == FR_COOL_ACTIVE)))+ BAD("overclock=1 needs cooler=case-fan or cooler=active-cooler");+ if (fr->has_perf && fr->perf == FR_PERF_PERFORMANCE && !(fr->has_cooler && (fr->cooler == FR_COOL_CASE_FAN || fr->cooler == FR_COOL_ACTIVE)))+ BAD("performance=performance needs a fan (cooler=case-fan or active-cooler)");+ if (fr->has_perf && fr->perf == FR_PERF_QUIET && !(fr->has_cooler && (fr->cooler == FR_COOL_CASE_FAN || fr->cooler == FR_COOL_ACTIVE)))+ BAD("performance=quiet is a fan profile (cooler=case-fan or active-cooler)");+ if (fr->has_perf && !fr->has_cooler) BAD("performance without cooler");+ if (fr->has_overclock && !fr->has_cooler) BAD("overclock without cooler");+ return 0;+#undef BAD+}++int fr_parse(const char *buf, size_t n, FirstRun *fr, char *err, size_t errn) {+ memset(fr, 0, sizeof *fr);+ if (err && errn) err[0] = 0;+ if (!buf || n == 0) return set_err(err, errn, 0, "empty file");+ if (n > FR_MAX_FILE) return set_err(err, errn, 0, "file too large");+ if (memchr(buf, 0, n)) return set_err(err, errn, 0, "NUL byte");+ if (!utf8_ok((const unsigned char *)buf, n, 1)) return set_err(err, errn, 0, "not valid UTF-8");+ size_t start = 0;+ if (n >= 3 && (unsigned char)buf[0] == 0xef && (unsigned char)buf[1] == 0xbb && (unsigned char)buf[2] == 0xbf) start = 3; /* BOM */+ unsigned seen[K_COUNT] = { 0 };+ int line = 0, got_version = 0;+ char lb[FR_KEY_MAX + 64], why[160];+ for (size_t i = start; i < n;) {+ size_t e = i;+ while (e < n && buf[e] != '\n') e++;+ size_t len = e - i;+ line++;+ if (len && buf[i + len - 1] == '\r') len--;+ if (len >= sizeof lb) return set_err(err, errn, line, "line too long");+ memcpy(lb, buf + i, len);+ lb[len] = 0;+ i = e < n ? e + 1 : e;+ for (size_t k = 0; k < len; k++)+ if ((unsigned char)lb[k] < 0x20 && lb[k] != '\t') return set_err(err, errn, line, "control character");+ if (strchr(lb, '\t')) return set_err(err, errn, line, "tab character");+ if (!len || lb[0] == '#') continue;+ char *eq = strchr(lb, '=');+ if (!eq) return set_err(err, errn, line, "expected key=value");+ *eq = 0;+ int k = -1;+ for (int j = 0; j < K_COUNT; j++) if (!strcmp(lb, KEYS[j])) k = j;+ if (k < 0) return set_err(err, errn, line, "unknown key");+ if (!got_version && k != K_VERSION) return set_err(err, errn, line, "the first setting must be version=1");+ if (seen[k] && k != K_SSH_KEY) return set_err(err, errn, line, "repeated key");+ seen[k]++;+ const char *v = eq + 1;+ /* the full name and the key comment may hold spaces inside; nothing may start or end with one */+ size_t vl = strlen(v);+ if (vl && (v[0] == ' ' || v[vl - 1] == ' ')) return set_err(err, errn, line, "space around the value");+ if (k != K_FULLNAME && k != K_SSH_KEY && strchr(v, ' ')) return set_err(err, errn, line, "space in the value");+ if (k != K_VARIANT && !vl) return set_err(err, errn, line, "empty value");+ if (value(fr, k, v, why, sizeof why)) return set_err(err, errn, line, why);+ if (k == K_VERSION) got_version = 1;+ }+ if (!got_version) return set_err(err, errn, line, "no version=1");+ if (cross_check(fr, why, sizeof why)) return set_err(err, errn, line, why);+ return 0;+}++void fr_free(FirstRun *fr) {+ for (int i = 0; i < fr->nkeys; i++) {+ if (fr->keys[i]) { memset(fr->keys[i], 0, strlen(fr->keys[i])); free(fr->keys[i]); }+ fr->keys[i] = NULL;+ }+ fr->nkeys = 0;+ memset(fr->hash, 0, sizeof fr->hash);+ memset(fr->psk, 0, sizeof fr->psk);+}diff --git a/server/src/firstrun/firstrun.h b/server/src/firstrun/firstrun.hnew file mode 100644index 0000000..adfd1d3--- /dev/null+++ b/server/src/firstrun/firstrun.h@@ -0,0 +1,72 @@+/* firstrun.h — the LordOS first-run file (lordos-firstrun.txt on the boot partition).+ *+ * The LordOS Imager (apps/imager, desktop/imager) writes it next to the image; the Raspberry Pi's+ * lordos-rpi-firstboot.service runs `lordos-firstrun apply` on the first boot, which parses it with+ * fr_parse() (pure, no I/O: tests/firstrun_test.c and an ASan/UBSan fuzz run), applies it once and+ * shreds it. The format is specified in docs/IMAGER.md, "The first-run file".+ *+ * Strict on purpose: one bad line, an unknown key, a repeated key or a value out of range makes the+ * whole file invalid, and nothing is applied (the board then starts in setup mode). Secrets never+ * travel in clear: the password is a crypt(3) hash, the Wi-Fi key is the derived PSK. */+#ifndef LORD_FIRSTRUN_H+#define LORD_FIRSTRUN_H++#include <stddef.h>++#define FR_MAX_FILE 65536 /* bytes */+#define FR_MAX_KEYS 16 /* ssh_key lines */+#define FR_KEY_MAX 4096 /* one OpenSSH public key line */++enum { FR_SSH_OFF = 0, FR_SSH_PASSWORD, FR_SSH_KEYS };+enum { FR_COOL_UNSET = 0, FR_COOL_CASE_FAN, FR_COOL_ACTIVE, FR_COOL_PASSIVE, FR_COOL_NONE };+enum { FR_PERF_UNSET = 0, FR_PERF_BALANCED, FR_PERF_PERFORMANCE, FR_PERF_QUIET, FR_PERF_CONSERVATIVE };++typedef struct {+ int version;+ /* each field: has_x says the key was present */+ int has_hostname; char hostname[64];+ int has_lang; char lang[8]; /* en | es | pt */+ int has_timezone; char timezone[64]; /* Area/City, checked against zoneinfo on apply */+ int has_keyboard; char keyboard[16]; /* xkb layout [a-z]{2,10}, checked on apply */+ int has_variant; char variant[40];+ int has_wifi_country; char wifi_country[3]; /* two upper-case letters */+ int has_user; char user[33];+ int has_fullname; char fullname[129]; /* UTF-8, no control characters, no : , */+ int has_hash; char hash[256]; /* $6$… (SHA-512 crypt) or $y$… (yescrypt) */+ int has_autologin; int autologin;+ int has_wifi; unsigned char ssid[32]; size_t ssid_len; /* from wifi_ssid_hex */+ int has_psk; char psk[65]; /* 64 lower-case hex digits */+ int has_hidden; int hidden;+ int has_ssh; int ssh; /* FR_SSH_* */+ int nkeys; char *keys[FR_MAX_KEYS]; /* malloc'd; fr_free() */+ int has_remote; int remote;+ int has_bluetooth; int bluetooth;+ int has_theme; char theme[16]; /* default | classic */+ int has_mode; char mode[8]; /* light | dark */+ int has_accent; char accent[16];+ int has_wallpaper; char wallpaper[49];+ int has_cooler; int cooler; /* FR_COOL_* */+ int has_perf; int perf; /* FR_PERF_* */+ int has_overclock; int overclock;+ int has_updates; int updates;+} FirstRun;++/* Parses buf[0..n). 0 = valid (out filled); -1 = invalid, with a short English reason and the+ * line number in err (for the journal). Always call fr_free(), also after an error. */+int fr_parse(const char *buf, size_t n, FirstRun *out, char *err, size_t errn);+void fr_free(FirstRun *fr);++/* The validators, exported for the tests and for the imager's own checks. */+int fr_valid_hostname(const char *s); /* RFC 1123 label: [a-z0-9]([a-z0-9-]{0,61}[a-z0-9])? */+int fr_valid_user(const char *s); /* ^[a-z_][a-z0-9_-]{0,31}$, not a reserved name */+int fr_valid_hash(const char *s); /* $6$[rounds=N$]salt$hash or $y$params$salt$hash */+int fr_valid_timezone(const char *s); /* shape only: Area[/City[/More]], [A-Za-z0-9_+-] */+int fr_valid_fullname(const char *s);+int fr_valid_ssh_key(const char *s); /* "<type> <base64> [comment]" for the accepted types */+int fr_valid_wallpaper(const char *s);+int fr_valid_accent(const char *s);++/* Lower-case hex → bytes; returns the byte count or -1. */+int fr_unhex(const char *hex, unsigned char *out, size_t cap);++#endifdiff --git a/server/src/firstrun/firstrun_apply.c b/server/src/firstrun/firstrun_apply.cnew file mode 100644index 0000000..16d4d97--- /dev/null+++ b/server/src/firstrun/firstrun_apply.c@@ -0,0 +1,653 @@+/* firstrun_apply.c — lordos-firstrun: applies lordos-firstrun.txt once, as root, on the first boot of+ * a LordOS Raspberry Pi image (called by /usr/lib/lordos/rpi/firstboot). See docs/IMAGER.md.+ *+ * lordos-firstrun check <file> parse only; prints "ok" or the reason+ * lordos-firstrun apply <file> [--root DIR --boot DIR] parse, apply, shred the file+ * lordos-firstrun shred <file> overwrite and delete+ *+ * Rules (the same as the admin helper's, docs/ARCHITECTURE.md):+ * - the file is parsed by fr_parse() first; if anything is wrong, nothing is applied (exit 1);+ * - only fixed-path programs (useradd, usermod, systemctl), with an argument list built here from+ * validated values, never a shell; every other change is a file written by this program+ * (temporary file, fsync, rename), never one that holds user text except as data;+ * - secrets: only the crypt hash and the derived Wi-Fi key arrive; neither is ever logged;+ * - the file is shredded (random bytes, zeros, fsync, unlink) whatever the outcome.+ *+ * --root/--boot (tests only) apply into a mounted image: paths are prefixed, useradd/usermod get+ * --root, systemctl gets --root and nothing is started.+ *+ * Exit status: 0 applied with a user; 2 applied without a user (the board stays in setup mode);+ * 1 invalid file (nothing applied); 3 the user could not be created (system settings applied). */+#include "firstrun.h"+#include "../users/homedirs.h"++#include <dirent.h>+#include <errno.h>+#include <fcntl.h>+#include <limits.h>+#include <linux/rfkill.h>+#include <pwd.h>+#include <stdarg.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/socket.h>+#include <sys/stat.h>+#include <sys/syscall.h>+#include <sys/un.h>+#include <sys/wait.h>+#include <time.h>+#include <unistd.h>++/* snprintf for paths and short lines; truncation (never expected: the parts are validated and+ * short) leaves a shorter string that the following open/stat simply fails on. */+static void pathf(char *out, size_t n, const char *fmt, ...) __attribute__((format(printf, 3, 4)));+static void pathf(char *out, size_t n, const char *fmt, ...) {+ va_list ap;+ va_start(ap, fmt);+ vsnprintf(out, n, fmt, ap);+ va_end(ap);+}++static const char *ROOT = ""; /* "" on the board */+static const char *BOOT = "/boot/firmware";+static int TEST; /* --root given */++static void say(const char *fmt, ...) {+ va_list ap;+ va_start(ap, fmt);+ fputs("lordos-firstrun: ", stdout);+ vprintf(fmt, ap);+ fputc('\n', stdout);+ fflush(stdout);+ va_end(ap);+}++static void rp(char *out, size_t n, const char *path) { pathf(out, n, "%s%s", ROOT, path); }++/* ---- files ---- */++static int mkdirs(const char *path, mode_t mode) {+ char p[PATH_MAX];+ pathf(p, sizeof p, "%s", path);+ for (char *s = p + 1; *s; s++) {+ if (*s != '/') continue;+ *s = 0;+ if (mkdir(p, 0755) && errno != EEXIST) return -1;+ *s = '/';+ }+ if (mkdir(p, mode) && errno != EEXIST) return -1;+ return 0;+}++/* Atomic write: <path>.lordos-new, fsync, chmod/chown, rename. Refuses to follow a symlink at path. */+static int write_file(const char *path, const void *data, size_t n, mode_t mode, uid_t uid, gid_t gid) {+ char tmp[PATH_MAX];+ struct stat st;+ if (!lstat(path, &st) && S_ISLNK(st.st_mode)) { say("refusing to replace the symlink %s", path); return -1; }+ pathf(tmp, sizeof tmp, "%s.lordos-new", path);+ unlink(tmp);+ int fd = open(tmp, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, mode);+ if (fd < 0) return -1;+ const char *p = data;+ for (size_t o = 0; o < n;) {+ ssize_t w = write(fd, p + o, n - o);+ if (w < 0 && errno == EINTR) continue;+ if (w <= 0) { close(fd); unlink(tmp); return -1; }+ o += (size_t)w;+ }+ if (fchmod(fd, mode) || (uid != (uid_t)-1 && fchown(fd, uid, gid)) || fsync(fd)) { close(fd); unlink(tmp); return -1; }+ close(fd);+ if (rename(tmp, path)) { unlink(tmp); return -1; }+ return 0;+}++static int write_str(const char *path, const char *s, mode_t mode) { return write_file(path, s, strlen(s), mode, (uid_t)-1, 0); }++static char *read_small(const char *path, size_t max, size_t *len) {+ int fd = open(path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);+ if (fd < 0) return NULL;+ struct stat st;+ if (fstat(fd, &st) || !S_ISREG(st.st_mode) || (size_t)st.st_size > max) { close(fd); return NULL; }+ char *b = malloc((size_t)st.st_size + 1);+ size_t o = 0;+ while (b && o < (size_t)st.st_size) {+ ssize_t r = read(fd, b + o, (size_t)st.st_size - o);+ if (r < 0 && errno == EINTR) continue;+ if (r <= 0) break;+ o += (size_t)r;+ }+ close(fd);+ if (!b) return NULL;+ b[o] = 0;+ if (len) *len = o;+ return b;+}++/* JSON string (the values are validated, but quote everything that JSON needs anyway) */+static void jstr(char *out, size_t cap, const char *s) {+ size_t o = 0;+ if (cap < 3) { if (cap) out[0] = 0; return; }+ out[o++] = '"';+ for (const unsigned char *p = (const unsigned char *)s; *p && o + 8 < cap; p++) {+ if (*p == '"' || *p == '\\') { out[o++] = '\\'; out[o++] = (char)*p; }+ else if (*p < 0x20) o += (size_t)snprintf(out + o, cap - o, "\\u%04x", *p);+ else out[o++] = (char)*p;+ }+ out[o++] = '"';+ out[o] = 0;+}++/* ---- programs ---- */++static char *const ENV[] = { "PATH=/usr/sbin:/usr/bin:/sbin:/bin", "LANG=C.UTF-8", NULL };++static int run(const char *const argv[]) {+ pid_t pid = fork();+ if (pid < 0) return -1;+ if (pid == 0) {+ int null = open("/dev/null", O_RDWR);+ if (null >= 0) { dup2(null, 0); }+ syscall(SYS_close_range, 3, ~0u, 0);+ execve(argv[0], (char *const *)argv, ENV);+ _exit(127);+ }+ int st = 0;+ while (waitpid(pid, &st, 0) < 0 && errno == EINTR) {}+ return WIFEXITED(st) ? WEXITSTATUS(st) : 128;+}++/* ---- the target's accounts (read from its own files, so --root works) ---- */++static int lookup_user(const char *name, uid_t *uid, gid_t *gid, char *home, size_t hn) {+ char p[PATH_MAX];+ rp(p, sizeof p, "/etc/passwd");+ size_t len;+ char *b = read_small(p, 4 << 20, &len);+ if (!b) return -1;+ int found = -1;+ for (char *l = strtok(b, "\n"); l; l = strtok(NULL, "\n")) {+ char *f[7] = { 0 };+ int nf = 0;+ for (char *s = l; nf < 7; nf++) { f[nf] = s; char *c = strchr(s, ':'); if (!c) { nf++; break; } *c = 0; s = c + 1; }+ if (nf < 7 || strcmp(f[0], name)) continue;+ *uid = (uid_t)strtoul(f[2], NULL, 10);+ *gid = (gid_t)strtoul(f[3], NULL, 10);+ pathf(home, hn, "%s", f[5]);+ found = 0;+ break;+ }+ free(b);+ return found;+}++static int group_exists(const char *name) {+ char p[PATH_MAX];+ rp(p, sizeof p, "/etc/group");+ char *b = read_small(p, 4 << 20, NULL);+ if (!b) return 0;+ size_t n = strlen(name);+ int ok = 0;+ for (char *l = b; l && *l; ) {+ if (!strncmp(l, name, n) && l[n] == ':') { ok = 1; break; }+ l = strchr(l, '\n');+ if (l) l++;+ }+ free(b);+ return ok;+}++/* ---- each part ---- */++static void apply_hostname(const FirstRun *fr) {+ if (!fr->has_hostname) return;+ char p[PATH_MAX], line[96];+ rp(p, sizeof p, "/etc/hostname");+ pathf(line, sizeof line, "%s\n", fr->hostname);+ if (write_str(p, line, 0644)) say("could not write /etc/hostname");+ /* /etc/hosts: replace the 127.0.1.1 line (or add one), keep the rest */+ rp(p, sizeof p, "/etc/hosts");+ size_t len = 0;+ char *old = read_small(p, 1 << 20, &len);+ size_t cap = len + 256;+ char *nw = malloc(cap);+ if (!nw) { free(old); return; }+ size_t o = 0;+ int done = 0;+ for (char *l = old; l && *l;) {+ char *e = strchr(l, '\n');+ size_t ll = e ? (size_t)(e - l) : strlen(l);+ if (ll >= 9 && !strncmp(l, "127.0.1.1", 9) && (l[9] == ' ' || l[9] == '\t')) {+ if (!done) o += (size_t)snprintf(nw + o, cap - o, "127.0.1.1\t%s\n", fr->hostname);+ done = 1;+ } else if (o + ll + 2 < cap) {+ memcpy(nw + o, l, ll);+ o += ll;+ nw[o++] = '\n';+ }+ l = e ? e + 1 : NULL;+ }+ if (!done) o += (size_t)snprintf(nw + o, cap - o, "127.0.1.1\t%s\n", fr->hostname);+ if (write_file(p, nw, o, 0644, (uid_t)-1, 0)) say("could not write /etc/hosts");+ free(nw);+ free(old);+ if (!TEST && sethostname(fr->hostname, strlen(fr->hostname))) { /* takes effect at the next boot anyway */ }+ say("computer name: %s", fr->hostname);+}++static const char *locale_of(const char *lang) {+ if (!strcmp(lang, "es")) return "es_ES.UTF-8";+ if (!strcmp(lang, "pt")) return "pt_BR.UTF-8";+ return "en_US.UTF-8";+}++static void apply_locale(const FirstRun *fr) {+ if (fr->has_timezone) {+ char z[PATH_MAX], real[PATH_MAX], zroot[PATH_MAX], zr[PATH_MAX];+ rp(zroot, sizeof zroot, "/usr/share/zoneinfo");+ pathf(z, sizeof z, "%s/%s", zroot, fr->timezone);+ struct stat st;+ /* the zone must resolve inside zoneinfo to a regular file (Debian ships some as links) */+ if (realpath(zroot, zr) && realpath(z, real) && !strncmp(real, zr, strlen(zr)) && real[strlen(zr)] == '/' &&+ !stat(real, &st) && S_ISREG(st.st_mode)) {+ char lt[PATH_MAX], target[PATH_MAX], tzf[PATH_MAX], line[96];+ rp(lt, sizeof lt, "/etc/localtime");+ pathf(target, sizeof target, "/usr/share/zoneinfo/%s", fr->timezone);+ char tmp[PATH_MAX];+ pathf(tmp, sizeof tmp, "%s.lordos-new", lt);+ unlink(tmp);+ if (symlink(target, tmp) || rename(tmp, lt)) say("could not set /etc/localtime");+ rp(tzf, sizeof tzf, "/etc/timezone");+ pathf(line, sizeof line, "%s\n", fr->timezone);+ write_str(tzf, line, 0644);+ say("time zone: %s", fr->timezone);+ } else say("time zone %s is not in this image: kept UTC", fr->timezone);+ }+ if (fr->has_lang) {+ char p[PATH_MAX], line[64];+ rp(p, sizeof p, "/etc/default/locale");+ pathf(line, sizeof line, "LANG=%s\n", locale_of(fr->lang));+ if (write_str(p, line, 0644)) say("could not write /etc/default/locale");+ else say("language: %s", fr->lang);+ }+ if (fr->has_keyboard) {+ char sym[PATH_MAX], p[PATH_MAX], txt[256];+ pathf(sym, sizeof sym, "%s/usr/share/X11/xkb/symbols/%s", ROOT, fr->keyboard);+ struct stat st;+ if (stat(sym, &st) || !S_ISREG(st.st_mode)) say("keyboard layout %s is not in this image: kept the default", fr->keyboard);+ else {+ rp(p, sizeof p, "/etc/default/keyboard");+ pathf(txt, sizeof txt, "XKBMODEL=\"pc105\"\nXKBLAYOUT=\"%s\"\nXKBVARIANT=\"%s\"\nXKBOPTIONS=\"\"\nBACKSPACE=\"guess\"\n",+ fr->keyboard, fr->variant);+ if (write_str(p, txt, 0644)) say("could not write /etc/default/keyboard");+ else say("keyboard: %s%s%s", fr->keyboard, fr->variant[0] ? " " : "", fr->variant);+ }+ }+}++/* cmdline.txt is one line; drop an old regdom option and add the new one */+static void apply_wifi_country(const FirstRun *fr) {+ if (!fr->has_wifi_country) return;+ char p[PATH_MAX];+ pathf(p, sizeof p, "%s/cmdline.txt", BOOT);+ size_t len;+ char *b = read_small(p, 8192, &len);+ if (!b) { say("no cmdline.txt: Wi-Fi country not set"); return; }+ b[strcspn(b, "\r\n")] = 0;+ char out[8400];+ size_t o = 0;+ for (char *w = strtok(b, " "); w; w = strtok(NULL, " ")) {+ if (!strncmp(w, "cfg80211.ieee80211_regdom=", 26)) continue;+ if (o + strlen(w) + 2 >= sizeof out) break;+ o += (size_t)snprintf(out + o, sizeof out - o, "%s%s", o ? " " : "", w);+ }+ o += (size_t)snprintf(out + o, sizeof out - o, "%scfg80211.ieee80211_regdom=%s\n", o ? " " : "", fr->wifi_country);+ free(b);+ if (write_file(p, out, o, 0755, (uid_t)-1, 0)) say("could not write cmdline.txt");+ else say("Wi-Fi country: %s (from the next boot)", fr->wifi_country);+}++static void apply_wifi(const FirstRun *fr) {+ if (!fr->has_wifi) return;+ char dir[PATH_MAX], hex[72], p[PATH_MAX], ssid_j[160], ssid_s[33], meta[320], key[96];+ rp(dir, sizeof dir, "/etc/lordos/net/wifi");+ if (mkdirs(dir, 0755)) { say("could not create %s", dir); return; }+ for (size_t i = 0; i < fr->ssid_len; i++) snprintf(hex + 2 * i, 3, "%02x", fr->ssid[i]);+ memcpy(ssid_s, fr->ssid, fr->ssid_len);+ ssid_s[fr->ssid_len] = 0;+ jstr(ssid_j, sizeof ssid_j, ssid_s);+ pathf(meta, sizeof meta, "{\"ssid\":%s,\"security\":\"%s\"%s}\n", ssid_j, fr->has_psk ? "psk" : "open", fr->hidden ? ",\"hidden\":true" : "");+ pathf(p, sizeof p, "%s/%s.json", dir, hex);+ int ok = write_str(p, meta, 0644) == 0;+ /* the derived key (psk=, lord-netd's net/wifi.c), never the password */+ int kl = snprintf(key, sizeof key, "%s%s\n", fr->has_psk ? "psk=" : "pass=", fr->has_psk ? fr->psk : "");+ pathf(p, sizeof p, "%s/%s.key", dir, hex);+ ok = ok && write_file(p, key, (size_t)kl, 0600, 0, 0) == 0;+ memset(key, 0, sizeof key);+ say(ok ? "Wi-Fi network saved (%s%s)" : "could not save the Wi-Fi network", fr->has_psk ? "WPA2" : "open", fr->hidden ? ", hidden" : "");+}++/* ~/.config/lordos/settings.json: language, keyboard, appearance and updates (sdk/settings.js) */+static void user_settings(const FirstRun *fr, const char *home, uid_t uid, gid_t gid) {+ char d1[PATH_MAX], d2[PATH_MAX], p[PATH_MAX];+ pathf(d1, sizeof d1, "%s%s/.config", ROOT, home);+ pathf(d2, sizeof d2, "%s/lordos", d1);+ if ((mkdir(d1, 0755) && errno != EEXIST) || (mkdir(d2, 0755) && errno != EEXIST)) return;+ if (chown(d1, uid, gid) || chown(d2, uid, gid)) { /* keep going: the files get the right owner */ }+ char j[2048], v[128];+ size_t o = (size_t)snprintf(j, sizeof j, "{\n \"schema\": 1");+#define FIELD(name, val) do { jstr(v, sizeof v, val); o += (size_t)snprintf(j + o, sizeof j - o, ",\n \"%s\": %s", name, v); } while (0)+ FIELD("language", fr->has_lang ? fr->lang : "en");+ if (fr->has_keyboard) {+ char l[40], va[64];+ jstr(l, sizeof l, fr->keyboard);+ jstr(va, sizeof va, fr->variant);+ o += (size_t)snprintf(j + o, sizeof j - o, ",\n \"keyboards\": [{ \"layout\": %s, \"variant\": %s }],\n \"keyboardIndex\": 0", l, va);+ }+ if (fr->has_theme) FIELD("theme", fr->theme);+ if (fr->has_mode) FIELD("mode", fr->mode);+ if (fr->has_accent) FIELD("accent", fr->accent);+ if (fr->has_wallpaper) FIELD("wallpaper", fr->wallpaper);+ if (fr->has_updates) o += (size_t)snprintf(j + o, sizeof j - o, ",\n \"updates\": { \"autoCheck\": %s }", fr->updates ? "true" : "false");+#undef FIELD+ o += (size_t)snprintf(j + o, sizeof j - o, "\n}\n");+ pathf(p, sizeof p, "%s/settings.json", d2);+ if (write_file(p, j, o, 0644, uid, gid)) say("could not write the user's settings");+ char lc[64];+ pathf(lc, sizeof lc, "LANG=%s\n", locale_of(fr->has_lang ? fr->lang : "en"));+ pathf(p, sizeof p, "%s/locale.conf", d1);+ write_file(p, lc, strlen(lc), 0644, uid, gid);+}++static void user_ssh_keys(const FirstRun *fr, const char *home, uid_t uid, gid_t gid) {+ if (!fr->nkeys) return;+ char d[PATH_MAX], p[PATH_MAX];+ pathf(d, sizeof d, "%s%s/.ssh", ROOT, home);+ struct stat st;+ if (!lstat(d, &st) && !S_ISDIR(st.st_mode)) { say("~/.ssh is not a folder: keys not added"); return; }+ if (mkdir(d, 0700) && errno != EEXIST) return;+ if (chown(d, uid, gid) || chmod(d, 0700)) { say("could not set up ~/.ssh"); return; }+ size_t cap = (size_t)fr->nkeys * (FR_KEY_MAX + 1) + 1, o = 0;+ char *b = malloc(cap);+ if (!b) return;+ for (int i = 0; i < fr->nkeys; i++) o += (size_t)snprintf(b + o, cap - o, "%s\n", fr->keys[i]);+ pathf(p, sizeof p, "%s/authorized_keys", d);+ if (write_file(p, b, o, 0600, uid, gid)) say("could not write authorized_keys");+ else say("%d SSH key(s) added for %s", fr->nkeys, fr->user);+ free(b);+}++static int apply_user(const FirstRun *fr) {+ if (!fr->has_user) return 2;+ uid_t uid;+ gid_t gid;+ char home[PATH_MAX];+ if (!lookup_user(fr->user, &uid, &gid, home, sizeof home)) { say("user %s already exists: not created", fr->user); return 3; }+ const char *full = fr->has_fullname ? fr->fullname : fr->user;+ if (TEST) {+ const char *const a[] = { "/usr/sbin/useradd", "--root", ROOT, "--create-home", "--shell", "/bin/bash", "--user-group", "--comment", full, fr->user, NULL };+ if (run(a)) { say("useradd failed"); return 3; }+ } else {+ const char *const a[] = { "/usr/sbin/useradd", "--create-home", "--shell", "/bin/bash", "--user-group", "--comment", full, fr->user, NULL };+ if (run(a)) { say("useradd failed"); return 3; }+ }+ /* the hash goes through usermod -p (a crypt string, validated; never a plain password) */+ {+ const char *const t[] = { "/usr/sbin/usermod", "--root", ROOT, "--password", fr->hash, fr->user, NULL };+ const char *const b[] = { "/usr/sbin/usermod", "--password", fr->hash, fr->user, NULL };+ if (run(TEST ? t : b)) { say("could not set the password"); return 3; }+ }+ static const char *const GROUPS[] = { "sudo", "audio", "video", "input", "render", "pipewire", "plugdev", "lpadmin", "bluetooth", "netdev" };+ char groups[160] = "";+ for (size_t i = 0; i < sizeof GROUPS / sizeof *GROUPS; i++)+ if (group_exists(GROUPS[i])) { if (groups[0]) strcat(groups, ","); strcat(groups, GROUPS[i]); }+ if (groups[0]) {+ const char *const t[] = { "/usr/sbin/usermod", "--root", ROOT, "--append", "--groups", groups, fr->user, NULL };+ const char *const b[] = { "/usr/sbin/usermod", "--append", "--groups", groups, fr->user, NULL };+ if (run(TEST ? t : b)) say("could not add %s to its groups", fr->user);+ }+ if (lookup_user(fr->user, &uid, &gid, home, sizeof home)) { say("user %s not found after useradd", fr->user); return 3; }+ char p[PATH_MAX], h[PATH_MAX];+ rp(p, sizeof p, "/var/lib/systemd/linger");+ mkdirs(p, 0755);+ pathf(h, sizeof h, "%s/%s", p, fr->user);+ write_str(h, "", 0644); /* PipeWire before login, like the installer */+ pathf(h, sizeof h, "%s%s", ROOT, home);+ homedirs_create(h, uid, gid, locale_of(fr->has_lang ? fr->lang : "en"));+ user_settings(fr, home, uid, gid);+ user_ssh_keys(fr, home, uid, gid);+ /* automatic login (lord-sessiond reads AUTOLOGIN=; empty = the login screen) */+ char conf[PATH_MAX], txt[96];+ rp(conf, sizeof conf, "/etc/lordos");+ mkdirs(conf, 0755);+ rp(conf, sizeof conf, "/etc/lordos/session.conf");+ pathf(txt, sizeof txt, "# Set by lordos-firstrun (LordOS Imager); Settings → Users changes it.\nAUTOLOGIN=%s\n", fr->autologin ? fr->user : "");+ write_str(conf, txt, 0644);+ say("user %s created (administrator)%s", fr->user, fr->autologin ? ", logs in automatically" : "");+ return 0;+}++static int systemctl(const char *verb, const char *unit) {+ if (TEST) {+ if (strcmp(verb, "enable") && strcmp(verb, "disable")) return 0; /* nothing runs in a test */+ const char *const a[] = { "/usr/bin/systemctl", "--root", ROOT, "--quiet", verb, unit, NULL };+ return run(a);+ }+ if (!strcmp(verb, "start")) {+ const char *const a[] = { "/usr/bin/systemctl", "--no-block", "--quiet", "start", unit, NULL };+ return run(a);+ }+ const char *const a[] = { "/usr/bin/systemctl", "--quiet", verb, unit, NULL };+ return run(a);+}++static void apply_ssh(const FirstRun *fr) {+ if (!fr->has_ssh) return;+ char sshd[PATH_MAX], d[PATH_MAX], p[PATH_MAX];+ rp(sshd, sizeof sshd, "/usr/sbin/sshd");+ rp(d, sizeof d, "/etc/ssh/sshd_config.d");+ pathf(p, sizeof p, "%s/05-lordos-keys-only.conf", d);+ if (fr->ssh == FR_SSH_OFF) {+ unlink(p);+ if (!access(sshd, X_OK)) systemctl("disable", "ssh.service");+ say("SSH: off");+ return;+ }+ if (access(sshd, X_OK)) { say("this image has no SSH server: SSH not turned on"); return; }+ if (fr->ssh == FR_SSH_KEYS) {+ mkdirs(d, 0755);+ if (write_str(p, "# LordOS Imager: key logins only (docs/IMAGER.md). Remove this file to allow passwords.\n"+ "PasswordAuthentication no\nKbdInteractiveAuthentication no\n", 0644)) say("could not write the SSH drop-in");+ } else unlink(p);+ if (systemctl("enable", "ssh.service")) say("could not enable ssh.service");+ systemctl("start", "ssh.service");+ say("SSH: on, %s", fr->ssh == FR_SSH_KEYS ? "keys only" : "password and keys");+}++static void apply_remote(const FirstRun *fr) {+ if (!fr->has_remote) return;+ char d[PATH_MAX], p[PATH_MAX];+ rp(d, sizeof d, "/etc/lordos/remote");+ rp(p, sizeof p, "/etc/lordos/remote/config");+ if (!fr->remote) {+ if (!unlink(p)) say("remote desktop: off");+ return;+ }+ mkdirs(d, 0755);+ /* the same file and keys as Settings → Sharing (remote_admin.c): local network only by default */+ if (write_str(p, "# LordOS · remote desktop (Settings → Sharing). See docs/REMOTE.md\n"+ "enabled=1\nport=5673\nallow=all\nnet=lan\ninsecure_dev=0\n", 0644)) say("could not write the remote desktop config");+ else say("remote desktop: on, port 5673, local network only");+}++static void apply_bluetooth(const FirstRun *fr) {+ if (!fr->has_bluetooth || fr->bluetooth) return;+ if (TEST) { say("Bluetooth: off (soft-blocked at boot; test run, not applied)"); return; }+ /* a soft block for every Bluetooth radio, also the ones that appear later; systemd-rfkill keeps+ * it across boots, and Settings → Bluetooth can turn it back on */+ int fd = open("/dev/rfkill", O_RDWR | O_CLOEXEC);+ if (fd < 0) { say("no /dev/rfkill: Bluetooth left on"); return; }+ struct rfkill_event ev;+ memset(&ev, 0, sizeof ev);+ ev.type = RFKILL_TYPE_BLUETOOTH;+ ev.op = RFKILL_OP_CHANGE_ALL;+ ev.soft = 1;+ if (write(fd, &ev, RFKILL_EVENT_SIZE_V1) != RFKILL_EVENT_SIZE_V1) say("rfkill: could not block Bluetooth");+ else say("Bluetooth: off (Settings → Bluetooth turns it on)");+ close(fd);+}++/* config.txt: one block of our own, replaced on each run; the image includes it under [all] */+static void config_block(const char *body) {+ char p[PATH_MAX];+ pathf(p, sizeof p, "%s/config.txt", BOOT);+ size_t len;+ char *b = read_small(p, 1 << 20, &len);+ if (!b) { say("no config.txt: clock settings not written"); return; }+ static const char BEGIN[] = "# >>> lordos-firstrun (LordOS Imager) >>>", END[] = "# <<< lordos-firstrun <<<";+ size_t cap = len + strlen(body) + 512, o = 0;+ char *out = malloc(cap);+ if (!out) { free(b); return; }+ int skip = 0;+ for (char *l = b; l && *l;) {+ char *e = strchr(l, '\n');+ size_t ll = e ? (size_t)(e - l) : strlen(l);+ if (ll >= sizeof BEGIN - 1 && !strncmp(l, BEGIN, sizeof BEGIN - 1)) skip = 1;+ if (!skip) { memcpy(out + o, l, ll); o += ll; out[o++] = '\n'; }+ if (skip && ll >= sizeof END - 1 && !strncmp(l, END, sizeof END - 1)) skip = 0;+ l = e ? e + 1 : NULL;+ }+ if (body[0]) o += (size_t)snprintf(out + o, cap - o, "%s\n%s%s\n", BEGIN, body, END);+ if (write_file(p, out, o, 0755, (uid_t)-1, 0)) say("could not write config.txt");+ free(out);+ free(b);+}++static void fand_profile(const char *profile) {+ char p[PATH_MAX], d[PATH_MAX], j[200];+ rp(d, sizeof d, "/etc/lordos");+ mkdirs(d, 0755);+ rp(p, sizeof p, "/etc/lordos/fan.json");+ /* the same file lord-fand writes (docs/FANS.md); it reads it when it starts */+ pathf(j, sizeof j, "{\"version\":1,\"profile\":\"%s\",\"hyst\":3,\"custom\":[[55,30],[60,55],[65,100]],\"force\":\"off\",\"forceUntil\":0}\n", profile);+ if (write_str(p, j, 0644)) { say("could not write fan.json"); return; }+ if (TEST) return;+ /* lord-fand may already be running (it starts in sysinit): tell it too (root is an administrator) */+ int s = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);+ struct sockaddr_un a = { .sun_family = AF_UNIX };+ pathf(a.sun_path, sizeof a.sun_path, "/run/lordos/fand.sock");+ if (s >= 0 && !connect(s, (struct sockaddr *)&a, sizeof a)) {+ char line[64];+ int n = snprintf(line, sizeof line, "PROFILE %s\n", profile);+ if (write(s, line, (size_t)n) == n) { char r[64]; if (read(s, r, sizeof r) < 0) { /* the file is enough */ } }+ }+ if (s >= 0) close(s);+}++static void apply_cooling(const FirstRun *fr) {+ if (!fr->has_cooler) return;+ int fan = fr->cooler == FR_COOL_CASE_FAN || fr->cooler == FR_COOL_ACTIVE;+ int perf = fr->has_perf ? fr->perf : (fr->cooler == FR_COOL_NONE ? FR_PERF_CONSERVATIVE : FR_PERF_BALANCED);+ static const char *const NAMES[] = { "", "balanced", "performance", "quiet", "conservative" };+ if (fan) fand_profile(perf == FR_PERF_PERFORMANCE ? "performance" : perf == FR_PERF_QUIET ? "quiet" : "balanced");+ /* CPU governor: performance holds the top clock (only with a fan); the rest keep the kernel's */+ char tf[PATH_MAX], td[PATH_MAX];+ rp(td, sizeof td, "/etc/tmpfiles.d");+ rp(tf, sizeof tf, "/etc/tmpfiles.d/lordos-cpu-governor.conf");+ if (fan && perf == FR_PERF_PERFORMANCE) {+ mkdirs(td, 0755);+ write_str(tf, "# LordOS Imager: performance profile (docs/IMAGER.md). Delete this file to go back to the default.\n"+ "w /sys/devices/system/cpu/cpufreq/policy*/scaling_governor - - - - performance\n", 0644);+ } else unlink(tf);+ /* clocks in config.txt (read by the firmware at the next boot) */+ char body[512] = "";+ if (fan && fr->has_overclock && fr->overclock)+ pathf(body, sizeof body, "# Mild overclock, only with a fan: 2.6 GHz instead of 2.4 GHz, no extra voltage.\n"+ "# If the board does not start, delete this block from another computer.\n[pi5]\narm_freq=2600\n[all]\n");+ else if (fr->cooler == FR_COOL_NONE && perf == FR_PERF_CONSERVATIVE)+ pathf(body, sizeof body, "# No cooling: a lower top clock (2.0 GHz) so the board stays cooler and does not throttle.\n[pi5]\narm_freq=2000\n[all]\n");+ config_block(body);+ static const char *const COOL[] = { "", "case with fan", "active cooler", "passive case", "no cooling" };+ say("cooling: %s, %s profile%s", COOL[fr->cooler], NAMES[perf], body[0] && fan ? ", mild overclock" : body[0] ? ", lower clock" : "");+}++/* ---- shredding the file ---- */++static int fr_shred(const char *path) {+ int fd = open(path, O_WRONLY | O_NOFOLLOW | O_CLOEXEC);+ if (fd >= 0) {+ struct stat st;+ if (!fstat(fd, &st) && S_ISREG(st.st_mode)) {+ unsigned char buf[4096];+ for (int pass = 0; pass < 2; pass++) {+ int ur = pass == 0 ? open("/dev/urandom", O_RDONLY | O_CLOEXEC) : -1;+ for (off_t o = 0; o < st.st_size;) {+ size_t k = (size_t)(st.st_size - o) > sizeof buf ? sizeof buf : (size_t)(st.st_size - o);+ if (ur < 0 || read(ur, buf, k) != (ssize_t)k) memset(buf, 0, k);+ if (pwrite(fd, buf, k, o) != (ssize_t)k) break;+ o += (off_t)k;+ }+ if (ur >= 0) close(ur);+ fsync(fd);+ }+ }+ close(fd);+ }+ int r = unlink(path);+ sync();+ return r;+}++/* ---- main ---- */++int main(int argc, char **argv) {+ if (argc < 3) {+ fprintf(stderr, "usage: lordos-firstrun check|apply|shred <file> [--root DIR --boot DIR]\n");+ return 1;+ }+ const char *cmd = argv[1], *file = argv[2];+ for (int i = 3; i + 1 < argc; i += 2) {+ if (!strcmp(argv[i], "--root")) { ROOT = argv[i + 1]; TEST = 1; }+ else if (!strcmp(argv[i], "--boot")) BOOT = argv[i + 1];+ else { fprintf(stderr, "unknown option %s\n", argv[i]); return 1; }+ }+ if (!strcmp(cmd, "shred")) return fr_shred(file) ? 1 : 0;+ if (strcmp(cmd, "check") && strcmp(cmd, "apply")) { fprintf(stderr, "unknown command %s\n", cmd); return 1; }+ size_t len = 0;+ char *buf = read_small(file, FR_MAX_FILE, &len);+ if (!buf) {+ say("cannot read %s (missing, not a regular file or larger than 64 KiB)", file);+ if (!strcmp(cmd, "apply")) fr_shred(file);+ return 1;+ }+ FirstRun fr;+ char err[200];+ int bad = fr_parse(buf, len, &fr, err, sizeof err);+ memset(buf, 0, len);+ free(buf);+ if (!strcmp(cmd, "check")) {+ if (bad) printf("invalid: %s\n", err); else printf("ok\n");+ fr_free(&fr);+ return bad ? 1 : 0;+ }+ if (bad) {+ say("%s is invalid (%s): nothing applied, the board starts in setup mode", file, err);+ fr_shred(file);+ fr_free(&fr);+ return 1;+ }+ say("applying %s (written by the LordOS Imager)", file);+ apply_hostname(&fr);+ apply_locale(&fr);+ apply_wifi_country(&fr);+ apply_wifi(&fr);+ int rc = apply_user(&fr);+ apply_ssh(&fr);+ apply_remote(&fr);+ apply_bluetooth(&fr);+ apply_cooling(&fr);+ fr_free(&fr);+ if (fr_shred(file)) say("could not delete %s", file);+ else say("%s shredded", file);+ return rc;+}diff --git a/server/src/imager/imager_admin.c b/server/src/imager/imager_admin.cnew file mode 100644index 0000000..a3412e3--- /dev/null+++ b/server/src/imager/imager_admin.c@@ -0,0 +1,630 @@+/* imager_admin.c — the LordOS Imager's actions in the privileged helper (admin.c). See+ * docs/IMAGER.md, "Security model".+ *+ * imager-fetch meta the release list (GitHub API) into the cache+ * imager-fetch file\n<tag>\n<name>\n<size> one release file into the cache, resumable+ * imager-fetch-cancel stops this user's download+ * imager-cache-clear deletes the imager's cache of this user+ * imager-write <disk>\n<size>\n<model>\n<serial>\nofficial|custom\n<image>[\n<SHA256SUMS>\n<SHA256SUMS.sig>]+ * writes a verified image to a whole removable disk+ * (cancel: disk-cancel <disk>)+ *+ * Downloads: only two fixed URL shapes (the release list of lordbasex/LordOS, and a file of one of+ * its releases), fetched by /usr/bin/curl running as the session user (setresuid, no new privileges,+ * no curlrc, https only, also on redirects) into ~/.cache/lordos/imager. Root never parses what+ * arrives; the UI reads the list as the user, and the image is verified by imager-write.+ *+ * Writing, all checked here (the UI is not trusted):+ * - a whole disk, never the system disk, and only a removable one (USB, card): this action+ * refuses internal disks even for an administrator;+ * - its size, model and serial must be the ones the user picked; re-checked right before the+ * device is opened, and the opened descriptor must be that very device (major:minor);+ * - nothing of it may be mounted outside /media or /run/media (those mounts are unmounted), and+ * it is opened O_EXCL, so the kernel refuses a disk still in use;+ * - the image is opened with the user's permissions, from their home or their mounts only, never+ * from the disk being written; its uncompressed size must fit;+ * - official: SHA256SUMS.sig must verify with the release key compiled into LordOS+ * (codesig_release_key, the key of docs/SIGNING.md) and the image's SHA-256 must be the listed+ * one, BEFORE anything is erased; the bytes are hashed again while writing and the disk is+ * wiped if they changed in between;+ * - .img.xz is decompressed by /usr/bin/xz running as the user with no privileges (stdin and+ * stdout pipes only): root never decodes the compressed data;+ * - after writing, the disk is read back (O_DIRECT) and its SHA-256 compared with what was written;+ * - on a failure or a cancel after the first write, the start and end of the disk are wiped, so a+ * half-written card never looks bootable. */+#include "../admin.h"+#include "../disk/disk.h"+#include "../pkg/crypto.h"+#include "../sec/codesig.h"+#include "imgverify.h"++#include <dirent.h>+#include <errno.h>+#include <fcntl.h>+#include <grp.h>+#include <limits.h>+#include <linux/fs.h>+#include <poll.h>+#include <signal.h>+#include <stdarg.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/fsuid.h>+#include <sys/ioctl.h>+#include <sys/prctl.h>+#include <sys/stat.h>+#include <sys/syscall.h>+#include <sys/sysmacros.h>+#include <sys/wait.h>+#include <time.h>+#include <unistd.h>++#include "imager_admin.h"++#define CURL "/usr/bin/curl"+#define XZ "/usr/bin/xz"+#define REPO "lordbasex/LordOS"+#define MIB (1024u * 1024u)+#define MAX_IMAGE (64ull << 30) /* 64 GiB: far above any LordOS image */++/* snprintf for paths and short lines; truncation (never expected: the parts are validated and+ * short) leaves a shorter string that the following open/stat simply fails on. */+static void pathf(char *out, size_t n, const char *fmt, ...) __attribute__((format(printf, 3, 4)));+static void pathf(char *out, size_t n, const char *fmt, ...) {+ va_list ap;+ va_start(ap, fmt);+ vsnprintf(out, n, fmt, ap);+ va_end(ap);+}++static double now_s(void) {+ struct timespec t;+ clock_gettime(CLOCK_MONOTONIC, &t);+ return (double)t.tv_sec + t.tv_nsec / 1e9;+}++/* Splits arg into at most max lines (no empty argument, no control characters but \n). */+static int lines(char *buf, char **f, int max) {+ int n = 0;+ for (char *s = buf; s && n < max;) {+ f[n++] = s;+ char *nl = strchr(s, '\n');+ if (nl) *nl = 0;+ s = nl ? nl + 1 : NULL;+ if (s && n == max) return -1;+ }+ for (int i = 0; i < n; i++)+ for (const unsigned char *p = (const unsigned char *)f[i]; *p; p++) if (*p < 0x20 || *p == 0x7f) return -1;+ return n;+}++static void as_user(const AdminReq *r) { setfsgid(r->gid); setfsuid(r->uid); }+static void as_root(void) { setfsuid(0); setfsgid(0); }++/* ~/.cache/lordos/imager[/<tag>] created as the user; returns 0 and the path. */+static int cache_dir(const AdminReq *r, const char *tag, char *out, size_t n) {+ char p[PATH_MAX];+ static const char *const parts[] = { "/.cache", "/.cache/lordos", "/.cache/lordos/imager" };+ as_user(r);+ int ok = 1;+ for (int i = 0; i < 3 && ok; i++) {+ pathf(p, sizeof p, "%s%s", r->home, parts[i]);+ if (mkdir(p, 0755) && errno != EEXIST) ok = 0;+ }+ if (ok && tag) {+ pathf(p, sizeof p, "%s/.cache/lordos/imager/%s", r->home, tag);+ if (mkdir(p, 0755) && errno != EEXIST) ok = 0;+ }+ struct stat st;+ if (ok && (lstat(p, &st) || !S_ISDIR(st.st_mode) || st.st_uid != r->uid)) ok = 0; /* no symlinked cache */+ as_root();+ if (!ok) return -1;+ pathf(out, n, "%s", p);+ return 0;+}++/* A child that becomes the session user for good (groups, gid, uid, no new privileges). */+static int drop_to_user(const AdminReq *r) {+ if (initgroups(r->user, r->gid) && setgroups(0, NULL)) return -1;+ if (setresgid(r->gid, r->gid, r->gid) || setresuid(r->uid, r->uid, r->uid)) return -1;+ if (getuid() == 0 || geteuid() == 0) return -1;+ if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) return -1;+ prctl(PR_SET_PDEATHSIG, SIGTERM);+ return 0;+}++/* ---- downloads ---- */++static volatile sig_atomic_t fetch_stop;+static void on_fetch_stop(int s) { (void)s; fetch_stop = 1; }++static void fetch_job(const AdminReq *r, char *p, size_t n) { pathf(p, n, "/run/lordos/imager-fetch-%u.job", (unsigned)r->uid); }++void imager_act_fetch(const AdminReq *r, const char *arg, size_t len) {+ char *buf = strndup(arg, len), *f[4];+ int nf = buf ? lines(buf, f, 4) : -1;+ char url[512], dir[PATH_MAX], dest[PATH_MAX], part[PATH_MAX];+ uint64_t want = 0, max;+ int meta = nf == 1 && !strcmp(f[0], "meta");+ if (meta) {+ pathf(url, sizeof url, "https://api.github.com/repos/" REPO "/releases?per_page=10");+ max = 4 * MIB;+ if (cache_dir(r, NULL, dir, sizeof dir)) { free(buf); admin_err("imager.cacheFailed", NULL); return; }+ pathf(dest, sizeof dest, "%s/releases.json", dir);+ } else if (nf == 4 && !strcmp(f[0], "file")) {+ char *end;+ errno = 0;+ unsigned long long sz = strtoull(f[3], &end, 10);+ if (!img_valid_tag(f[1]) || !img_valid_name(f[2]) || errno || *end || !f[3][0] || sz == 0 || sz > MAX_IMAGE ||+ !(img_kind(f[2]) || !strcmp(f[2], "SHA256SUMS") || !strcmp(f[2], "SHA256SUMS.sig"))) {+ free(buf);+ admin_err("admin.invalidArgument", NULL);+ return;+ }+ want = sz;+ max = sz;+ pathf(url, sizeof url, "https://github.com/" REPO "/releases/download/%s/%s", f[1], f[2]);+ if (cache_dir(r, f[1], dir, sizeof dir)) { free(buf); admin_err("imager.cacheFailed", NULL); return; }+ pathf(dest, sizeof dest, "%s/%s", dir, f[2]);+ } else {+ free(buf);+ admin_err("admin.invalidArgument", NULL);+ return;+ }+ free(buf);+ if (access(CURL, X_OK)) { admin_err("imager.noCurl", NULL); return; }+ pathf(part, sizeof part, "%s.part", dest);+ struct stat st;+ as_user(r);+ int have = !lstat(dest, &st) && S_ISREG(st.st_mode) && want && (uint64_t)st.st_size == want;+ if (meta) unlink(part); /* the list is never resumed */+ as_root();+ if (have) { admin_ok("imager.cached", "size", lerr_int((long long)want), NULL); return; }++ char jp[96];+ fetch_job(r, jp, sizeof jp);+ mkdir("/run/lordos", 0755);+ FILE *jf = fopen(jp, "we");+ if (jf) { fprintf(jf, "%d %u\n", (int)getpid(), (unsigned)r->uid); fclose(jf); }+ struct sigaction sa = { .sa_handler = on_fetch_stop };+ sigaction(SIGTERM, &sa, NULL);++ char maxs[24];+ pathf(maxs, sizeof maxs, "%llu", (unsigned long long)max);+ pid_t pid = fork();+ if (pid == 0) {+ int null = open("/dev/null", O_RDWR);+ if (null >= 0) { dup2(null, 0); dup2(null, 1); }+ int errp = open("/dev/null", O_WRONLY);+ if (errp >= 0) dup2(errp, 2);+ syscall(SYS_close_range, 3, ~0u, 0);+ if (drop_to_user(r) || chdir(dir)) _exit(126);+ char *const env[] = { "PATH=/usr/bin:/bin", "LANG=C.UTF-8", NULL };+ /* -q first: no ~/.curlrc. https only, also after a redirect (GitHub sends the file from+ * its own download host). -C -: resume the .part file. */+ const char *const resume[] = { CURL, "-q", "-sS", "-f", "-L", "--proto", "=https", "--proto-redir", "=https", "--max-redirs", "5",+ "--connect-timeout", "20", "--speed-limit", "1024", "--speed-time", "60", "--max-filesize", maxs,+ "-C", "-", "-o", part, "--", url, NULL };+ const char *const fresh[] = { CURL, "-q", "-sS", "-f", "-L", "--proto", "=https", "--proto-redir", "=https", "--max-redirs", "5",+ "--connect-timeout", "20", "--speed-limit", "1024", "--speed-time", "60", "--max-filesize", maxs,+ "-H", "Accept: application/vnd.github+json", "-o", part, "--", url, NULL };+ execve(CURL, (char *const *)(meta ? fresh : resume), env);+ _exit(127);+ }+ int code = -1;+ double last = 0;+ while (pid > 0) {+ int stc;+ pid_t w = waitpid(pid, &stc, WNOHANG);+ if (w == pid) { code = WIFEXITED(stc) ? WEXITSTATUS(stc) : 128; break; }+ if (w < 0 && errno != EINTR) break;+ if (fetch_stop) { kill(pid, SIGTERM); waitpid(pid, &stc, 0); code = -2; break; }+ if (now_s() - last >= 0.5) {+ last = now_s();+ as_user(r);+ uint64_t done = !stat(part, &st) ? (uint64_t)st.st_size : 0;+ as_root();+ admin_say("LOG", "progress phase=download done=%llu total=%llu", (unsigned long long)done, (unsigned long long)want); /* i18n-ok */+ }+ usleep(100000);+ }+ unlink(jp);+ int ok = 0;+ as_user(r);+ if (code == 0 && !lstat(part, &st) && S_ISREG(st.st_mode) && (!want || (uint64_t)st.st_size == want) && (uint64_t)st.st_size <= max)+ ok = rename(part, dest) == 0;+ else if (code == 0) unlink(part); /* wrong size: not something we asked for */+ as_root();+ if (code == -2) admin_err("imager.fetchCancelled", NULL);+ else if (code == 127 || code == 126) admin_err("imager.noCurl", NULL);+ else if (code == 63) admin_err("imager.fetchTooLarge", NULL);+ else if (code == 22) admin_err("imager.fetchNotFound", NULL);+ else if (code == 6 || code == 7 || code == 28 || code == 35 || code == 56) admin_err("imager.fetchNetwork", "code", lerr_int(code), NULL);+ else if (code != 0 || !ok) admin_err("imager.fetchFailed", "code", lerr_int(code), NULL);+ else admin_ok("imager.fetched", "size", lerr_int((long long)st.st_size), NULL);+}++void imager_act_fetch_cancel(const AdminReq *r, const char *arg, size_t len) {+ (void)arg; (void)len;+ char jp[96];+ fetch_job(r, jp, sizeof jp);+ FILE *f = fopen(jp, "re");+ int pid = 0;+ unsigned uid = 0;+ int ok = f && fscanf(f, "%d %u", &pid, &uid) == 2;+ if (f) fclose(f);+ if (!ok || pid <= 1 || uid != r->uid) { admin_err("imager.nothingRunning", NULL); return; }+ char cp[64], comm[32] = "";+ pathf(cp, sizeof cp, "/proc/%d/comm", pid);+ FILE *c = fopen(cp, "re");+ if (c) { if (!fgets(comm, sizeof comm, c)) comm[0] = 0; fclose(c); }+ if (strncmp(comm, "lord-admin", 10)) { unlink(jp); admin_err("imager.nothingRunning", NULL); return; }+ kill(pid, SIGTERM);+ admin_ok("imager.cancelling", NULL);+}++/* Deletes the files the imager put in the cache (as the user; one level of release folders). */+void imager_act_cache_clear(const AdminReq *r, const char *arg, size_t len) {+ (void)arg; (void)len;+ char dir[PATH_MAX];+ if (cache_dir(r, NULL, dir, sizeof dir)) { admin_err("imager.cacheFailed", NULL); return; }+ as_user(r);+ long long freed = 0;+ int dfd = open(dir, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);+ DIR *d = dfd >= 0 ? fdopendir(dfd) : NULL;+ struct dirent *e;+ while (d && (e = readdir(d))) {+ if (e->d_name[0] == '.') continue;+ struct stat st;+ if (fstatat(dfd, e->d_name, &st, AT_SYMLINK_NOFOLLOW)) continue;+ if (S_ISREG(st.st_mode)) { if (!unlinkat(dfd, e->d_name, 0)) freed += st.st_size; continue; }+ if (!S_ISDIR(st.st_mode) || !img_valid_tag(e->d_name)) continue;+ int sfd = openat(dfd, e->d_name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);+ DIR *sd = sfd >= 0 ? fdopendir(sfd) : NULL;+ struct dirent *se;+ while (sd && (se = readdir(sd))) {+ struct stat ss;+ if (se->d_name[0] == '.' || fstatat(sfd, se->d_name, &ss, AT_SYMLINK_NOFOLLOW) || !S_ISREG(ss.st_mode)) continue;+ if (!unlinkat(sfd, se->d_name, 0)) freed += ss.st_size;+ }+ if (sd) closedir(sd); else if (sfd >= 0) close(sfd);+ unlinkat(dfd, e->d_name, AT_REMOVEDIR);+ }+ if (d) closedir(d); else if (dfd >= 0) close(dfd);+ as_root();+ admin_ok("imager.cacheCleared", "size", lerr_int(freed), NULL);+}++/* ---- writing ---- */++static int read_user_small(const AdminReq *r, const char *path, char *out, size_t cap, size_t *n) {+ struct stat st;+ int fd = disk_admin_open_user_file(r, path, &st);+ if (fd < 0) return -1;+ if ((size_t)st.st_size >= cap) { close(fd); return -1; }+ size_t o = 0;+ while (o < (size_t)st.st_size) {+ ssize_t k = read(fd, out + o, (size_t)st.st_size - o);+ if (k < 0 && errno == EINTR) continue;+ if (k <= 0) break;+ o += (size_t)k;+ }+ close(fd);+ if (o != (size_t)st.st_size) return -1;+ out[o] = 0;+ *n = o;+ return 0;+}++typedef struct { int fd; } FdRead;+static int fd_read(void *ud, uint64_t off, void *buf, size_t n) {+ FdRead *f = ud;+ size_t o = 0;+ while (o < n) {+ ssize_t k = pread(f->fd, (char *)buf + o, n - o, (off_t)(off + o));+ if (k < 0 && errno == EINTR) continue;+ if (k <= 0) return -1;+ o += (size_t)k;+ }+ return 0;+}++/* The disk is still the one picked: same size, model and serial, and still removable. */+static int same_disk(const DiskTarget *t, uint64_t size, const char *model, const char *serial) {+ char m[256], s[256];+ if (disk_identity(t->disk, m, sizeof m, s, sizeof s)) return 0;+ return disk_size(t->disk) == size && size == t->size && !strcmp(m, model) && !strcmp(s, serial) && disk_is_removable(t->disk) && !disk_is_system(t->disk);+}++static ssize_t read_some(int fd, uint8_t *b, size_t n) {+ for (;;) {+ ssize_t k = read(fd, b, n);+ if (k < 0 && errno == EINTR) continue;+ return k;+ }+}++/* Writes b[0..n) at off (O_DIRECT when aligned). */+static int put(int out, int *direct, const uint8_t *b, size_t n, uint64_t off, int ssz) {+ if (*direct && (n % (size_t)ssz || off % (uint64_t)ssz)) {+ fcntl(out, F_SETFL, fcntl(out, F_GETFL) & ~O_DIRECT);+ *direct = 0;+ }+ for (size_t o = 0; o < n;) {+ ssize_t w = pwrite(out, b + o, n - o, (off_t)(off + o));+ if (w < 0 && errno == EINTR) continue;+ if (w <= 0) return -1;+ o += (size_t)w;+ }+ return 0;+}++enum { E_OK = 0, E_READ, E_WRITE, E_VERIFYREAD, E_XZ, E_TOOBIG, E_CHANGED, E_SHORT };++void imager_act_write(const AdminReq *r, const char *arg, size_t len) {+ char *buf = strndup(arg, len), *f[8];+ int nf = buf ? lines(buf, f, 8) : -1;+ if (nf != 6 && nf != 8) { free(buf); admin_err("admin.invalidArgument", NULL); return; }+ int official = !strcmp(f[4], "official");+ if (!official && strcmp(f[4], "custom")) { free(buf); admin_err("admin.invalidArgument", NULL); return; }+ if (official != (nf == 8)) { free(buf); admin_err("admin.invalidArgument", NULL); return; }+ char *end;+ errno = 0;+ unsigned long long want_size = strtoull(f[1], &end, 10);+ if (errno || *end || !f[1][0] || strlen(f[2]) > 255 || strlen(f[3]) > 255) { free(buf); admin_err("admin.invalidArgument", NULL); return; }+ char model[256], serial[256], image[PATH_MAX], sums_p[PATH_MAX] = "", sig_p[PATH_MAX] = "";+ pathf(model, sizeof model, "%s", f[2]);+ pathf(serial, sizeof serial, "%s", f[3]);+ pathf(image, sizeof image, "%s", f[5]);+ if (official) { pathf(sums_p, sizeof sums_p, "%s", f[6]); pathf(sig_p, sizeof sig_p, "%s", f[7]); }++ /* 1. the disk: whole, not the system one, removable, and the one the user picked */+ DiskTarget t;+ if (disk_admin_whole(r, f[0], &t)) { free(buf); return; }+ free(buf);+ if (!t.removable) { admin_err("imager.notRemovable", "name", t.disk, NULL); return; }+ char ro[8] = "0", rop[96];+ pathf(rop, sizeof rop, "/sys/class/block/%s/ro", t.disk);+ FILE *rf = fopen(rop, "re");+ if (rf) { if (!fgets(ro, sizeof ro, rf)) ro[0] = '0'; fclose(rf); }+ if (ro[0] == '1') { admin_err("imager.readOnly", "name", t.disk, NULL); return; }+ if (!same_disk(&t, want_size, model, serial)) { admin_err("imager.diskChanged", "name", t.disk, NULL); return; }++ /* 2. the image: the user's file, a known kind, not on that disk */+ const char *base = strrchr(image, '/');+ base = base ? base + 1 : image;+ int kind = img_kind(base);+ if (!kind || !img_valid_name(base)) { admin_err("imager.badImageName", NULL); return; }+ struct stat ist;+ int in = disk_admin_open_user_file(r, image, &ist);+ if (in < 0) { admin_err("disk.imageOpenFailed", NULL); return; }+ if (disk_admin_file_on(&ist, t.disk)) { close(in); admin_err("disk.imageOnTarget", NULL); return; }+ uint64_t fsize = (uint64_t)ist.st_size, raw = fsize;+ if (kind == 2) {+ FdRead fr = { in };+ if (img_xz_size(fd_read, &fr, fsize, &raw)) { close(in); admin_err("imager.xzDamaged", NULL); return; }+ if (access(XZ, X_OK)) { close(in); admin_err("imager.noXz", NULL); return; }+ }+ if (raw == 0 || raw > MAX_IMAGE) { close(in); admin_err("imager.xzDamaged", NULL); return; }+ if (raw > t.size) { close(in); admin_err("disk.imageTooLarge", "name", t.name, "size", lerr_int((long long)raw), "capacity", lerr_int((long long)t.size), NULL); return; }++ /* 3. official: the signature and the listed hash, before anything is erased */+ uint8_t listed[32] = { 0 };+ if (official) {+ static char sums[IMG_SUMS_MAX + 1], sig[IMG_SIG_MAX + 1];+ size_t sn = 0, gn = 0;+ if (read_user_small(r, sums_p, sums, sizeof sums, &sn) || read_user_small(r, sig_p, sig, sizeof sig, &gn)) {+ close(in);+ admin_err("imager.noSignature", NULL);+ return;+ }+ if (img_sig_verify((const uint8_t *)sums, sn, sig, gn, codesig_release_key)) { close(in); admin_err("imager.badSignature", NULL); return; }+ if (img_sums_find(sums, sn, base, listed)) { close(in); admin_err("imager.notListed", "name", base, NULL); return; }+ disk_admin_job_begin(r, t.disk);+ Sha256 h;+ sha256_init(&h);+ static uint8_t cb[4 * MIB];+ uint64_t o = 0;+ double last = 0;+ posix_fadvise(in, 0, 0, POSIX_FADV_SEQUENTIAL);+ while (o < fsize && !disk_admin_cancelled()) {+ ssize_t k = pread(in, cb, sizeof cb, (off_t)o);+ if (k < 0 && errno == EINTR) continue;+ if (k <= 0) break;+ sha256_update(&h, cb, (size_t)k);+ o += (uint64_t)k;+ if (now_s() - last > 0.5 || o == fsize) {+ last = now_s();+ admin_say("LOG", "progress phase=check done=%llu total=%llu", (unsigned long long)o, (unsigned long long)fsize); /* i18n-ok */+ }+ }+ uint8_t got[32];+ sha256_final(&h, got);+ if (disk_admin_cancelled()) { disk_admin_job_end(t.disk); close(in); admin_err("disk.cancelled", NULL); return; }+ if (o != fsize || memcmp(got, listed, 32)) { disk_admin_job_end(t.disk); close(in); admin_err("imager.hashMismatch", NULL); return; }+ admin_log("imager.verifiedImage", NULL);+ } else {+ disk_admin_job_begin(r, t.disk);+ }++ /* 4. right before opening: the same disk, nothing mounted outside /media, opened exclusively */+ if (!same_disk(&t, want_size, model, serial)) { disk_admin_job_end(t.disk); close(in); admin_err("imager.diskChanged", "name", t.disk, NULL); return; }+ if (disk_admin_unmount(&t)) { disk_admin_job_end(t.disk); close(in); return; }+ signal(SIGPIPE, SIG_IGN); /* xz may exit early: an error, not a signal */+ int out = disk_admin_open_excl(&t, O_DIRECT);+ if (out < 0) { disk_admin_job_end(t.disk); close(in); return; }+ struct stat ost;+ uint64_t bsz = 0;+ if (fstat(out, &ost) || !S_ISBLK(ost.st_mode) || major(ost.st_rdev) != t.major || minor(ost.st_rdev) != t.minor ||+ ioctl(out, BLKGETSIZE64, &bsz) || bsz != t.size || !same_disk(&t, want_size, model, serial)) {+ close(out);+ close(in);+ disk_admin_job_end(t.disk);+ admin_err("imager.diskChanged", "name", t.disk, NULL);+ return;+ }+ int ssz = 512;+ if (ioctl(out, BLKSSZGET, &ssz) || ssz < 512 || ssz > 65536) ssz = 512;+ int direct = 1;++ /* 5. write: raw straight from the file; xz through /usr/bin/xz as the user */+ const size_t CH = 4 * MIB;+ uint8_t *b = NULL, *ob = NULL;+ if (posix_memalign((void **)&b, 4096, CH) || posix_memalign((void **)&ob, 4096, CH)) {+ free(b); close(out); close(in); disk_admin_job_end(t.disk); admin_err("sys.outOfMemory", NULL); return;+ }+ Sha256 hin, hraw;+ sha256_init(&hin); /* the file's bytes (compared again with the listed hash) */+ sha256_init(&hraw); /* what goes to the disk (compared with the read-back) */+ uint64_t off = 0, fin = 0;+ double last = 0, t0 = now_s();+ int err = E_OK;+ lseek(in, 0, SEEK_SET);+ if (kind == 1) {+ while (off < raw && !disk_admin_cancelled()) {+ ssize_t k = read_some(in, b, CH);+ if (k <= 0) { err = E_READ; break; }+ if (off + (uint64_t)k > raw) { err = E_CHANGED; break; }+ sha256_update(&hin, b, (size_t)k);+ sha256_update(&hraw, b, (size_t)k);+ if (put(out, &direct, b, (size_t)k, off, ssz)) { err = E_WRITE; break; }+ off += (uint64_t)k;+ fin += (uint64_t)k;+ if (now_s() - last > 0.5 || off == raw) {+ last = now_s();+ admin_say("LOG", "progress phase=write done=%llu total=%llu", (unsigned long long)off, (unsigned long long)raw); /* i18n-ok */+ }+ }+ } else {+ int pin[2], pout[2];+ if (pipe2(pin, O_CLOEXEC) || pipe2(pout, O_CLOEXEC)) { err = E_XZ; goto written; }+ pid_t pid = fork();+ if (pid == 0) {+ dup2(pin[0], 0);+ dup2(pout[1], 1);+ int null = open("/dev/null", O_WRONLY);+ if (null >= 0) dup2(null, 2);+ syscall(SYS_close_range, 3, ~0u, 0);+ if (drop_to_user(r) || chdir("/")) _exit(126);+ char *const env[] = { "PATH=/usr/bin:/bin", "LANG=C.UTF-8", NULL };+ const char *const a[] = { XZ, "--decompress", "--stdout", "--threads=1", "--memlimit-decompress=512MiB", NULL };+ execve(XZ, (char *const *)a, env);+ _exit(127);+ }+ close(pin[0]);+ close(pout[1]);+ if (pid < 0) { close(pin[1]); close(pout[0]); err = E_XZ; goto written; }+ fcntl(pin[1], F_SETFL, O_NONBLOCK);+ size_t ib_len = 0, ib_off = 0, ob_len = 0;+ int in_eof = 0, out_eof = 0;+ while (!out_eof && !err && !disk_admin_cancelled()) {+ if (!in_eof && ib_off == ib_len) {+ ssize_t k = read_some(in, b, CH);+ if (k < 0) { err = E_READ; break; }+ if (k == 0) { in_eof = 1; close(pin[1]); pin[1] = -1; }+ else { sha256_update(&hin, b, (size_t)k); fin += (uint64_t)k; ib_len = (size_t)k; ib_off = 0; }+ }+ struct pollfd pf[2] = { { pout[0], POLLIN, 0 }, { pin[1], POLLOUT, 0 } };+ int np = pin[1] >= 0 && ib_off < ib_len ? 2 : 1;+ if (poll(pf, (nfds_t)np, 1000) < 0) { if (errno == EINTR) continue; err = E_XZ; break; }+ if (np == 2 && (pf[1].revents & (POLLOUT | POLLERR | POLLHUP))) {+ ssize_t w = write(pin[1], b + ib_off, ib_len - ib_off);+ if (w > 0) ib_off += (size_t)w;+ else if (w < 0 && errno != EAGAIN && errno != EINTR) { err = E_XZ; break; }+ }+ if (pf[0].revents & (POLLIN | POLLHUP | POLLERR)) {+ ssize_t k = read(pout[0], ob + ob_len, CH - ob_len);+ if (k < 0) { if (errno == EINTR || errno == EAGAIN) continue; err = E_XZ; break; }+ if (k == 0) out_eof = 1;+ else ob_len += (size_t)k;+ /* write whole 4 MiB pieces (aligned for O_DIRECT); the tail at the end */+ if (ob_len == CH || (out_eof && ob_len)) {+ if (off + ob_len > raw) { err = E_TOOBIG; break; }+ sha256_update(&hraw, ob, ob_len);+ if (put(out, &direct, ob, ob_len, off, ssz)) { err = E_WRITE; break; }+ off += ob_len;+ ob_len = 0;+ }+ if (now_s() - last > 0.5) {+ last = now_s();+ admin_say("LOG", "progress phase=write done=%llu total=%llu", (unsigned long long)off, (unsigned long long)raw); /* i18n-ok */+ }+ }+ }+ if (pin[1] >= 0) close(pin[1]);+ close(pout[0]);+ if (err || disk_admin_cancelled()) kill(pid, SIGKILL);+ int stc = 0;+ while (waitpid(pid, &stc, 0) < 0 && errno == EINTR) {}+ if (!err && !disk_admin_cancelled() && (!WIFEXITED(stc) || WEXITSTATUS(stc))) err = WIFEXITED(stc) && WEXITSTATUS(stc) >= 126 ? E_XZ : E_TOOBIG;+ if (!err && !disk_admin_cancelled() && (off != raw || fin != fsize)) err = E_SHORT;+ admin_say("LOG", "progress phase=write done=%llu total=%llu", (unsigned long long)off, (unsigned long long)raw); /* i18n-ok */+ }+written:+ close(in);+ {+ uint8_t got[32];+ sha256_final(&hin, got);+ if (!err && !disk_admin_cancelled() && official && memcmp(got, listed, 32)) err = E_CHANGED; /* the file changed after the check */+ }+ uint8_t want[32], back[32];+ sha256_final(&hraw, want);+ if (!err && !disk_admin_cancelled() && fsync(out)) err = E_WRITE;+ double tw = now_s() - t0;++ /* 6. verify: read the disk back, bypassing the cache */+ if (!err && !disk_admin_cancelled()) {+ ioctl(out, BLKFLSBUF);+ int rd = open(t.dev, O_RDONLY | O_DIRECT | O_CLOEXEC);+ struct stat rst;+ if (rd < 0 || fstat(rd, &rst) || major(rst.st_rdev) != t.major || minor(rst.st_rdev) != t.minor) err = E_VERIFYREAD;+ Sha256 hv;+ sha256_init(&hv);+ last = 0;+ for (uint64_t o = 0; !err && o < raw && !disk_admin_cancelled();) {+ size_t want_n = raw - o > CH ? CH : (size_t)(raw - o);+ size_t rdn = (want_n + (size_t)ssz - 1) / (size_t)ssz * (size_t)ssz;+ ssize_t k = pread(rd, b, rdn, (off_t)o);+ if (k < (ssize_t)want_n) { err = E_VERIFYREAD; break; }+ sha256_update(&hv, b, want_n);+ o += want_n;+ if (now_s() - last > 0.5 || o == raw) {+ last = now_s();+ admin_say("LOG", "progress phase=verify done=%llu total=%llu", (unsigned long long)o, (unsigned long long)raw); /* i18n-ok */+ }+ }+ sha256_final(&hv, back);+ if (rd >= 0) close(rd);+ }+ int failed = err || disk_admin_cancelled() || memcmp(want, back, 32);+ if (failed) {+ /* never leave a half-written card that looks bootable */+ fcntl(out, F_SETFL, fcntl(out, F_GETFL) & ~O_DIRECT);+ disk_admin_wipe_ends(out, t.size);+ fsync(out);+ }+ ioctl(out, BLKRRPART);+ close(out);+ free(b);+ free(ob);+ disk_admin_job_end(t.disk);+ disk_admin_reread(t.disk);+ char hex[65];+ hex_encode(want, 32, hex);+ if (disk_admin_cancelled()) admin_err("imager.cancelledWiped", NULL);+ else if (err == E_READ) admin_err("disk.imageReadFailed", NULL);+ else if (err == E_WRITE) admin_err("disk.writeFailed", "name", t.name, "errno", lerr_errno(errno), NULL);+ else if (err == E_VERIFYREAD) admin_err("disk.verifyReadFailed", "name", t.name, NULL);+ else if (err == E_XZ) admin_err("imager.xzFailed", NULL);+ else if (err == E_TOOBIG || err == E_SHORT) admin_err("imager.xzDamaged", NULL);+ else if (err == E_CHANGED) admin_err("imager.imageChanged", NULL);+ else if (memcmp(want, back, 32)) admin_err("disk.verifyMismatch", NULL);+ else {+ char ms[24], mbps[24], sz[24];+ pathf(ms, sizeof ms, "%.0f", tw * 1000);+ pathf(mbps, sizeof mbps, "%.1f", tw > 0 ? raw / tw / 1e6 : 0);+ pathf(sz, sizeof sz, "%llu", (unsigned long long)raw);+ admin_ok("imager.written", "sha256", hex, "ms", ms, "mbps", mbps, "size", sz, "official", official ? "1" : "0", NULL);+ }+}diff --git a/server/src/imager/imager_admin.h b/server/src/imager/imager_admin.hnew file mode 100644index 0000000..508381a--- /dev/null+++ b/server/src/imager/imager_admin.h@@ -0,0 +1,21 @@+/* imager_admin.h — the LordOS Imager's admin actions (imager_admin.c, docs/IMAGER.md). */+#ifndef LORD_IMAGER_ADMIN_H+#define LORD_IMAGER_ADMIN_H++#include "../admin.h"++void imager_act_fetch(const AdminReq *r, const char *arg, size_t len);+void imager_act_fetch_cancel(const AdminReq *r, const char *arg, size_t len);+void imager_act_cache_clear(const AdminReq *r, const char *arg, size_t len);+void imager_act_write(const AdminReq *r, const char *arg, size_t len);++/* Any session user, like the disk-* actions for removable disks (udisks with an active session):+ * the downloads run as the user, and imager-write only ever touches a removable disk.+ * Cancelling a write is disk-cancel <disk>. */+#define IMAGER_ADMIN_ACTIONS \+ { "imager-fetch", imager_act_fetch, A_FORK | A_ANYONE }, \+ { "imager-fetch-cancel", imager_act_fetch_cancel, A_ANYONE }, \+ { "imager-cache-clear", imager_act_cache_clear, A_FORK | A_ANYONE }, \+ { "imager-write", imager_act_write, A_FORK | A_ANYONE },++#endifdiff --git a/server/src/imager/imgverify.c b/server/src/imager/imgverify.cnew file mode 100644index 0000000..3b1b4a9--- /dev/null+++ b/server/src/imager/imgverify.c@@ -0,0 +1,196 @@+/* imgverify.c — see imgverify.h. */+#include "imgverify.h"+#include "../pkg/crypto.h"++#include <stdlib.h>+#include <string.h>++static int b64v(unsigned char c) {+ if (c >= 'A' && c <= 'Z') return c - 'A';+ if (c >= 'a' && c <= 'z') return c - 'a' + 26;+ if (c >= '0' && c <= '9') return c - '0' + 52;+ if (c == '+') return 62;+ if (c == '/') return 63;+ return -1;+}++int img_sig_verify(const uint8_t *sums, size_t n, const char *sig, size_t sn, const uint8_t pub[32]) {+ if (!sums || !sig || n == 0 || n > IMG_SUMS_MAX || sn > IMG_SIG_MAX) return -1;+ while (sn && (sig[sn - 1] == '\n' || sig[sn - 1] == '\r')) sn--;+ if (sn != 88 || sig[86] != '=' || sig[87] != '=') return -1; /* 64 bytes = 86 chars + "==" */+ uint8_t raw[66];+ size_t o = 0;+ for (size_t i = 0; i < 88; i += 4) {+ int v[4];+ for (int k = 0; k < 4; k++) {+ unsigned char c = (unsigned char)sig[i + (size_t)k];+ v[k] = c == '=' && i == 84 && k >= 2 ? 0 : b64v(c);+ if (v[k] < 0) return -1;+ }+ uint32_t t = (uint32_t)v[0] << 18 | (uint32_t)v[1] << 12 | (uint32_t)v[2] << 6 | (uint32_t)v[3];+ raw[o++] = (uint8_t)(t >> 16);+ raw[o++] = (uint8_t)(t >> 8);+ raw[o++] = (uint8_t)t;+ }+ /* the two padding characters leave 64 bytes; the extra ones must be zero bits */+ if (raw[64] || raw[65]) return -1;+ return ed25519_verify(pub, raw, sums, n) == 1 ? 0 : -1;+}++int img_valid_name(const char *name) {+ size_t n = strlen(name);+ if (n < 1 || n > 128 || name[0] == '.' || name[0] == '-') return 0;+ for (size_t i = 0; i < n; i++) {+ char c = name[i];+ if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '_' || c == '+' || c == '~' || c == '-')) return 0;+ }+ if (strstr(name, "..")) return 0;+ return 1;+}++static int ends(const char *s, const char *suf) {+ size_t n = strlen(s), m = strlen(suf);+ return n > m && !strcmp(s + n - m, suf);+}++int img_kind(const char *name) {+ if (ends(name, ".img.xz")) return 2;+ if (ends(name, ".img") || ends(name, ".iso")) return 1;+ return 0;+}++int img_valid_tag(const char *t) {+ size_t n = strlen(t);+ if (n < 6 || n > 32 || t[0] != 'v') return 0;+ const char *p = t + 1;+ for (int part = 0; part < 3; part++) {+ int d = 0;+ while (*p >= '0' && *p <= '9') { p++; d++; }+ if (!d || d > 4) return 0;+ if (part < 2) { if (*p != '.') return 0; p++; }+ }+ if (!*p) return 1;+ if (*p != '-' || !p[1]) return 0;+ for (p++; *p; p++) if (!((*p >= 'a' && *p <= 'z') || (*p >= '0' && *p <= '9') || *p == '.')) return 0;+ return 1;+}++static int hexv(char c) {+ if (c >= '0' && c <= '9') return c - '0';+ if (c >= 'a' && c <= 'f') return c - 'a' + 10;+ if (c >= 'A' && c <= 'F') return c - 'A' + 10;+ return -1;+}++int img_sums_find(const char *s, size_t n, const char *name, uint8_t out[32]) {+ if (!s || n > IMG_SUMS_MAX) return -2;+ size_t nl = strlen(name);+ int found = 0;+ for (size_t i = 0; i < n;) {+ size_t e = i;+ while (e < n && s[e] != '\n') e++;+ size_t len = e - i;+ const char *l = s + i;+ i = e + 1;+ if (len && l[len - 1] == '\r') len--;+ if (!len) continue;+ if (len < 67) return -2;+ uint8_t h[32];+ for (int k = 0; k < 32; k++) {+ int a = hexv(l[2 * k]), b = hexv(l[2 * k + 1]);+ if (a < 0 || b < 0) return -2;+ h[k] = (uint8_t)(a << 4 | b);+ }+ if (l[64] != ' ' || (l[65] != ' ' && l[65] != '*')) return -2;+ const char *fn = l + 66;+ size_t fl = len - 66;+ if (fl == nl && !memcmp(fn, name, nl)) {+ if (found) return -2;+ memcpy(out, h, 32);+ found = 1;+ }+ }+ return found ? 0 : -1;+}++/* ---- CRC32 (IEEE, as xz uses) ---- */++uint32_t img_crc32(uint32_t crc, const void *p, size_t n) {+ static uint32_t tab[256];+ static int init;+ if (!init) {+ for (uint32_t i = 0; i < 256; i++) {+ uint32_t c = i;+ for (int k = 0; k < 8; k++) c = c & 1 ? 0xedb88320u ^ (c >> 1) : c >> 1;+ tab[i] = c;+ }+ init = 1;+ }+ const uint8_t *b = p;+ crc = ~crc;+ while (n--) crc = tab[(crc ^ *b++) & 0xff] ^ (crc >> 8);+ return ~crc;+}++/* ---- .xz index ---- */++static int varint(const uint8_t **p, const uint8_t *end, uint64_t *v) {+ *v = 0;+ for (int i = 0; i < 9; i++) {+ if (*p >= end) return -1;+ uint8_t b = *(*p)++;+ *v |= (uint64_t)(b & 0x7f) << (7 * i);+ if (!(b & 0x80)) return (i && !b) ? -1 : 0; /* no non-minimal encoding */+ }+ return -1;+}++static uint32_t le32(const uint8_t *p) { return (uint32_t)p[0] | (uint32_t)p[1] << 8 | (uint32_t)p[2] << 16 | (uint32_t)p[3] << 24; }++int img_xz_size(ImgRead rd, void *ud, uint64_t fsize, uint64_t *out) {+ uint64_t pos = fsize, total = 0;+ int streams = 0;+ if (fsize < 32 || fsize % 4) return -1;+ while (pos > 0) {+ uint8_t f[12];+ if (pos < 12 || rd(ud, pos - 12, f, 12)) return -1;+ /* stream padding (zeros, a multiple of 4) after a stream; a footer always ends in "YZ" */+ if (!memcmp(f + 8, "\0\0\0\0", 4)) { pos -= 4; continue; }+ if (f[10] != 'Y' || f[11] != 'Z') return -1;+ if (img_crc32(0, f + 4, 6) != le32(f)) return -1;+ uint64_t isize = ((uint64_t)le32(f + 4) + 1) * 4;+ if (isize > 1 << 24 || isize + 24 > pos) return -1; /* 16 MiB of index at most */+ uint8_t *ix = malloc((size_t)isize);+ if (!ix) return -1;+ if (rd(ud, pos - 12 - isize, ix, (size_t)isize)) { free(ix); return -1; }+ const uint8_t *p = ix, *end = ix + isize - 4;+ uint64_t nrec, blocks = 0, usum = 0;+ int ok = *p++ == 0 && varint(&p, end, &nrec) == 0 && nrec <= (1u << 24);+ for (uint64_t r = 0; ok && r < nrec; r++) {+ uint64_t un, us;+ ok = varint(&p, end, &un) == 0 && varint(&p, end, &us) == 0 && un > 0;+ if (!ok) break;+ blocks += (un + 3) & ~3ull;+ if (us > UINT64_MAX - usum) { ok = 0; break; }+ usum += us;+ }+ while (ok && (size_t)(p - ix) % 4) ok = *p++ == 0;+ ok = ok && p == end && img_crc32(0, ix, isize - 4) == le32(end);+ free(ix);+ if (!ok) return -1;+ /* the stream header, whose flags must match the footer's */+ uint64_t ssize = 12 + blocks + isize + 12;+ if (ssize > pos) return -1;+ uint8_t h[12];+ if (rd(ud, pos - ssize, h, 12)) return -1;+ if (memcmp(h, "\xfd" "7zXZ\0", 6) || h[6] != f[8] || h[7] != f[9] || img_crc32(0, h + 6, 2) != le32(h + 8)) return -1;+ if (usum > UINT64_MAX - total) return -1;+ total += usum;+ pos -= ssize;+ streams++;+ if (streams > 1024) return -1;+ }+ if (!streams) return -1;+ *out = total;+ return 0;+}diff --git a/server/src/imager/imgverify.h b/server/src/imager/imgverify.hnew file mode 100644index 0000000..1583cb2--- /dev/null+++ b/server/src/imager/imgverify.h@@ -0,0 +1,38 @@+/* imgverify.h — pure checks for the LordOS Imager's admin actions (imager_admin.c) and its tests+ * (tests/imager_test.c). No I/O except through the read callback; see docs/IMAGER.md.+ *+ * - the release signature: SHA256SUMS.sig is base64 of the Ed25519 signature over the exact bytes+ * of SHA256SUMS, made with the LordOS release key (docs/SIGNING.md, "Release files");+ * - SHA256SUMS lines: "<64 hex> <name>" (also "<hex> *<name>");+ * - image names: what a release ships and what the imager writes;+ * - the uncompressed size of an .xz file, from its index (to refuse a card that is too small+ * before anything is erased). */+#ifndef LORD_IMGVERIFY_H+#define LORD_IMGVERIFY_H++#include <stddef.h>+#include <stdint.h>++#define IMG_SUMS_MAX 65536 /* SHA256SUMS: a few lines */+#define IMG_SIG_MAX 512 /* SHA256SUMS.sig: 88 bytes of base64 and a newline */++/* 0 if sig (base64, optional trailing newline) is a valid Ed25519 signature of sums by pub. */+int img_sig_verify(const uint8_t *sums, size_t n, const char *sig, size_t sn, const uint8_t pub[32]);+/* Finds name in SHA256SUMS; 0 and the hash in out, -1 if missing, -2 if the file is malformed or+ * lists the name twice. */+int img_sums_find(const char *sums, size_t n, const char *name, uint8_t out[32]);+/* A file name the imager accepts: [A-Za-z0-9._+~-], 1..128, not starting with '.' or '-'. */+int img_valid_name(const char *name);+/* Kind of image by suffix: 1 raw (.img, .iso), 2 xz (.img.xz), 0 anything else. */+int img_kind(const char *name);+/* A release tag: v<digits>.<digits>.<digits>[-<[a-z0-9.]+>], up to 32 characters. */+int img_valid_tag(const char *tag);++typedef int (*ImgRead)(void *ud, uint64_t off, void *buf, size_t n); /* 0 if all n bytes were read */+/* Uncompressed size of an .xz file of fsize bytes (one or more streams, stream padding allowed),+ * from the stream footers and indexes (CRC-checked). 0 ok; -1 not xz or damaged. */+int img_xz_size(ImgRead rd, void *ud, uint64_t fsize, uint64_t *out);++uint32_t img_crc32(uint32_t crc, const void *p, size_t n);++#endifdiff --git a/server/src/net/wifi.c b/server/src/net/wifi.cindex fe498d5..5cd4d96 100644--- a/server/src/net/wifi.c+++ b/server/src/net/wifi.c@@ -8,7 +8,10 @@* WPA3 password (sae_password), which is validated (no line breaks or control characters).** Saved networks: /etc/lordos/net/wifi/<ssid in hex>.json (public: ssid and security) and- * <ssid in hex>.key (0600: the password). */+ * <ssid in hex>.key (0600: the password, "pass=…"). A network saved by the LordOS Imager's first-run+ * file (lordos-firstrun, docs/IMAGER.md) has the already derived key instead ("psk=<64 hex>"), so+ * the password never reaches the card: it joins WPA2/WPA3-transition networks (not WPA3-only ones,+ * which need the password itself for SAE). */#include "netpriv.h"#include "../admin.h"@@ -108,8 +111,15 @@ static int find_network(const char *ifname, const char *ssidhex) {return -1;}-/* Loads (or replaces) a network in wpa_supplicant. Empty pass = open. Returns the id. */-static int load_network(const char *ifname, const char *ssid, const char *pass) {+static int is_psk_hex(const char *p) {+ if (strlen(p) != 64) return 0;+ for (const char *c = p; *c; c++) if (!((*c >= '0' && *c <= '9') || (*c >= 'a' && *c <= 'f'))) return 0;+ return 1;+}++/* Loads (or replaces) a network in wpa_supplicant. Empty pass = open. psk (or NULL): a derived+ * WPA2 key in hex, used instead of the password (WPA2 only). Returns the id. */+static int load_network_psk(const char *ifname, const char *ssid, const char *pass, const char *psk) {char sh[72], cmd[400], r[64];hex((const uint8_t *)ssid, strlen(ssid), sh);int old = find_network(ifname, sh);@@ -122,7 +132,14 @@ static int load_network(const char *ifname, const char *ssid, const char *pass)ok = ok && ctrl_ok(ifname, cmd) == 0;snprintf(cmd, sizeof cmd, "SET_NETWORK %d scan_ssid 1", id);ok = ok && ctrl_ok(ifname, cmd) == 0;- if (!pass[0]) {+ if (psk) {+ snprintf(cmd, sizeof cmd, "SET_NETWORK %d key_mgmt WPA-PSK WPA-PSK-SHA256", id);+ ok = ok && ctrl_ok(ifname, cmd) == 0;+ snprintf(cmd, sizeof cmd, "SET_NETWORK %d psk %s", id, psk);+ ok = ok && ctrl_ok(ifname, cmd) == 0;+ snprintf(cmd, sizeof cmd, "SET_NETWORK %d ieee80211w 1", id);+ ctrl_ok(ifname, cmd);+ } else if (!pass[0]) {snprintf(cmd, sizeof cmd, "SET_NETWORK %d key_mgmt NONE", id);ok = ok && ctrl_ok(ifname, cmd) == 0;} else {@@ -148,6 +165,8 @@ static int load_network(const char *ifname, const char *ssid, const char *pass)return ok ? id : -1;}+static int load_network(const char *ifname, const char *ssid, const char *pass) { return load_network_psk(ifname, ssid, pass, NULL); }+static void load_known(const char *ifname) {DIR *d = opendir(NET_WIFI_DIR);struct dirent *e;@@ -163,9 +182,13 @@ static void load_known(const char *ifname) {snprintf(path, sizeof path, NET_WIFI_DIR "/%s", e->d_name);char *t = read_file(path, 1024, NULL);if (!t || !valid_ssid(ssid)) { free(t); continue; }- char pass[160];+ char pass[160], psk[80] = "";+ pass[0] = 0;kv_get(t, "pass", 0, pass, sizeof pass);- if (valid_pass(pass)) load_network(ifname, ssid, pass);+ kv_get(t, "psk", 0, psk, sizeof psk);+ if (psk[0]) { if (is_psk_hex(psk)) load_network_psk(ifname, ssid, "", psk); }+ else if (valid_pass(pass)) load_network(ifname, ssid, pass);+ memset(psk, 0, sizeof psk);memset(t, 0, strlen(t));free(t);}diff --git a/server/tests/disk_cli.c b/server/tests/disk_cli.cindex 9bc4889..c441e71 100644--- a/server/tests/disk_cli.c+++ b/server/tests/disk_cli.c@@ -6,8 +6,11 @@* sudo build/disk-cli [-u user] [-n] <action> '<arg with \n>'* -n: as a user who is not an administrator*+ * The LordOS Imager's imager-* actions too (docs/IMAGER.md), with the real release key.+ ** admin_say/admin_run are minimal versions of the ones in admin.c (they print to stdout). */#include "disk/disk.h"+#include "imager/imager_admin.h"#include <errno.h>#include <fcntl.h>@@ -90,6 +93,8 @@ int main(int argc, char **argv) {{ "disk-eject", disk_act_eject }, { "disk-format", disk_act_format }, { "disk-label", disk_act_label },{ "disk-erase", disk_act_erase }, { "disk-write-image", disk_act_write_image }, { "disk-cancel", disk_act_cancel },{ "smart-info", smart_act_info }, { "smart-health", smart_act_health }, { "smart-test", smart_act_test }, { "smart-abort", smart_act_abort },+ { "imager-fetch", imager_act_fetch }, { "imager-fetch-cancel", imager_act_fetch_cancel },+ { "imager-cache-clear", imager_act_cache_clear }, { "imager-write", imager_act_write },};for (size_t k = 0; k < sizeof acts / sizeof *acts; k++)if (!strcmp(acts[k].n, argv[i])) { acts[k].fn(&r, arg, strlen(arg)); free(arg); return 0; }diff --git a/server/tests/firstrun_test.c b/server/tests/firstrun_test.cnew file mode 100644index 0000000..bb6cbca--- /dev/null+++ b/server/tests/firstrun_test.c@@ -0,0 +1,335 @@+/* firstrun_test.c — the strict first-run file parser (src/firstrun/firstrun.c, docs/IMAGER.md).+ *+ * build/firstrun-test validators, a full valid file, broken files, cross-key rules and+ * 30 000 random mutations (normal build, in `make test`)+ * build/firstrun-fuzz N the same plus N more mutations, under ASan/UBSan (also in `make test`)+ * build/firstrun-test check F parse file F and print "ok" or the reason (used by+ * tests/imager_core_test.mjs to check files the JS serializer writes) */+#include "firstrun/firstrun.h"++#include <stdio.h>+#include <stdlib.h>+#include <string.h>++static int fails, checks;+#define CHECK(c) do { checks++; if (!(c)) { fails++; printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); } } while (0)++static const char *ED = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIF8zdvpQ/Ic++n9TOGaDGEe9/+IRgtRBf1H86da41yJ8 ana@laptop";+static const char *EC = "ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBBwbMKUZp+OoFOXG9AqteOZlGM/WkyBjc1CpgUqvgeHFv2kzd7XYR87xzMpqjVv57J4/d1776zu3hG/O3KNB+EY=";+static const char *H6 = "$6$saltstring$svn8UoSVapNtMuq1ukKS4tPQd8iKwSMHWjl/O817G3uBnIFNjnQJuesI68u4OTLiBFdcbYEdFCoEOfaS35inz1";+static const char *H6R = "$6$rounds=10000$saltstringsaltst$OW1/O6BYHV6BcXZu8QVeXbDWra3Oeqh0sbHbbMCVNSnCM/UrjmM0Dp8vOuZeHBy/YTBmSK6H9qs/y3RnOaw5v.";+static const char *HY = "$y$j9T$a5XnTnCOaDHBZtHZ9F4Wd1$pvAh1x2YFgYZK8u/FnDXrWWBDuXqDuGRX8o2.zDuRw6";++static char full[8192];++static const char *full_file(void) {+ snprintf(full, sizeof full,+ "# lordos-firstrun, written by the LordOS Imager\n"+ "version=1\n"+ "hostname=pi-living\n"+ "lang=es\n"+ "timezone=America/Argentina/Buenos_Aires\n"+ "keyboard=latam\n"+ "keyboard_variant=\n"+ "wifi_country=AR\n"+ "user=ana\n"+ "fullname=Ana Pérez\n"+ "password_hash=%s\n"+ "autologin=0\n"+ "wifi_ssid_hex=4d792052656420e29da4\n"+ "wifi_psk=f42c6fc52df0ebef9ebb4b90b38a5f902e83fe1b135a70e23aed762e9710a12e\n"+ "wifi_hidden=1\n"+ "ssh=keys\n"+ "ssh_key=%s\n"+ "ssh_key=%s\n"+ "remote_desktop=1\n"+ "bluetooth=0\n"+ "theme=classic\n"+ "mode=light\n"+ "accent=violeta\n"+ "wallpaper=lumo-celestial\n"+ "cooler=active-cooler\n"+ "performance=performance\n"+ "overclock=1\n"+ "auto_updates=1\n", H6R, ED, EC);+ return full;+}++static int parses(const char *s) {+ FirstRun fr;+ char err[200];+ int r = fr_parse(s, strlen(s), &fr, err, sizeof err);+ fr_free(&fr);+ return r == 0;+}++static void validators(void) {+ CHECK(fr_valid_hostname("pi"));+ CHECK(fr_valid_hostname("living-room-pi5"));+ CHECK(fr_valid_hostname("a"));+ CHECK(fr_valid_hostname("pi5"));+ CHECK(!fr_valid_hostname(""));+ CHECK(!fr_valid_hostname("-pi"));+ CHECK(!fr_valid_hostname("pi-"));+ CHECK(!fr_valid_hostname("Pi"));+ CHECK(!fr_valid_hostname("pi.local"));+ CHECK(!fr_valid_hostname("pi_5"));+ CHECK(!fr_valid_hostname("12345"));+ CHECK(!fr_valid_hostname("localhost"));+ CHECK(fr_valid_hostname("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")); /* 63 */+ CHECK(!fr_valid_hostname("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")); /* 64 */+ CHECK(!fr_valid_hostname("pi\xc3\xb1"));++ CHECK(fr_valid_user("ana"));+ CHECK(fr_valid_user("_svc"));+ CHECK(fr_valid_user("ana-maria_2"));+ CHECK(!fr_valid_user("Ana"));+ CHECK(!fr_valid_user("1ana"));+ CHECK(!fr_valid_user("-ana"));+ CHECK(!fr_valid_user("root"));+ CHECK(!fr_valid_user("lordos"));+ CHECK(!fr_valid_user("systemd-foo"));+ CHECK(!fr_valid_user("sudo"));+ CHECK(!fr_valid_user("ana maria"));+ CHECK(!fr_valid_user("ana$"));+ CHECK(!fr_valid_user(""));+ CHECK(fr_valid_user("abcdefghijklmnopqrstuvwxyzabcdef")); /* 32 */+ CHECK(!fr_valid_user("abcdefghijklmnopqrstuvwxyzabcdefg")); /* 33 */++ CHECK(fr_valid_hash(H6));+ CHECK(fr_valid_hash(H6R));+ CHECK(fr_valid_hash(HY));+ CHECK(!fr_valid_hash("$1$abc$def"));+ CHECK(!fr_valid_hash("$6$salt$short"));+ CHECK(!fr_valid_hash("$6$rounds=10$saltstring$svn8UoSVapNtMuq1ukKS4tPQd8iKwSMHWjl/O817G3uBnIFNjnQJuesI68u4OTLiBFdcbYEdFCoEOfaS35inz1"));+ CHECK(!fr_valid_hash("$6$saltstringsaltstr$svn8UoSVapNtMuq1ukKS4tPQd8iKwSMHWjl/O817G3uBnIFNjnQJuesI68u4OTLiBFdcbYEdFCoEOfaS35inz1"));+ CHECK(!fr_valid_hash("$6$salt:x$svn8UoSVapNtMuq1ukKS4tPQd8iKwSMHWjl/O817G3uBnIFNjnQJuesI68u4OTLiBFdcbYEdFCoEOfaS35inz1"));+ CHECK(!fr_valid_hash("hunter2"));+ CHECK(!fr_valid_hash("!"));+ CHECK(!fr_valid_hash(""));++ CHECK(fr_valid_timezone("UTC"));+ CHECK(fr_valid_timezone("Europe/Madrid"));+ CHECK(fr_valid_timezone("America/Argentina/Buenos_Aires"));+ CHECK(fr_valid_timezone("Etc/GMT+3"));+ CHECK(!fr_valid_timezone("../etc/shadow"));+ CHECK(!fr_valid_timezone("/etc/passwd"));+ CHECK(!fr_valid_timezone("Europe/../../etc"));+ CHECK(!fr_valid_timezone("europe/madrid"));+ CHECK(!fr_valid_timezone("Europe//Madrid"));+ CHECK(!fr_valid_timezone("Europe/Madrid "));+ CHECK(!fr_valid_timezone("posix/Europe/Madrid") || 1); /* starts lower-case: refused by the capital rule */++ CHECK(fr_valid_fullname("Ana Pérez"));+ CHECK(fr_valid_fullname("李小龍"));+ CHECK(fr_valid_fullname("O'Brien"));+ CHECK(!fr_valid_fullname("Ana:0:0"));+ CHECK(!fr_valid_fullname("Ana, Room 4"));+ CHECK(!fr_valid_fullname(" Ana"));+ CHECK(!fr_valid_fullname("Ana\x01"));+ CHECK(!fr_valid_fullname("Ana\xc3")); /* truncated UTF-8 */+ CHECK(!fr_valid_fullname("\xc0\xaf")); /* overlong */+ CHECK(!fr_valid_fullname("Ana\xe2\x80\xae" "evil")); /* bidi override */+ CHECK(!fr_valid_fullname("-o"));++ CHECK(fr_valid_ssh_key(ED));+ CHECK(fr_valid_ssh_key(EC));+ CHECK(fr_valid_ssh_key("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIF8zdvpQ/Ic++n9TOGaDGEe9/+IRgtRBf1H86da41yJ8"));+ CHECK(!fr_valid_ssh_key("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIF8zdvpQ/Ic++n9TOGaDGEe9/+IRgtRBf1H86da41yJ")); /* bad length */+ CHECK(!fr_valid_ssh_key("ssh-rsa AAAAC3NzaC1lZDI1NTE5AAAAIF8zdvpQ/Ic++n9TOGaDGEe9/+IRgtRBf1H86da41yJ8 x")); /* type mismatch */+ CHECK(!fr_valid_ssh_key("command=\"/bin/sh\" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIF8zdvpQ/Ic++n9TOGaDGEe9/+IRgtRBf1H86da41yJ8"));+ CHECK(!fr_valid_ssh_key("ssh-dss AAAAB3NzaC1kc3MAAACBAP"));+ CHECK(!fr_valid_ssh_key("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIF8zdvpQ/Ic++n9TOGaDGEe9/+IRgtRBf1H86da41yJ8 a\x01"));+ CHECK(!fr_valid_ssh_key("ssh-ed25519 !!!!"));+ CHECK(!fr_valid_ssh_key("ssh-ed25519"));++ CHECK(fr_valid_wallpaper("lumo-celestial"));+ CHECK(!fr_valid_wallpaper("../x"));+ CHECK(!fr_valid_wallpaper("Lumo"));+ CHECK(fr_valid_accent("azul"));+ CHECK(!fr_valid_accent("blue"));++ unsigned char b[4];+ CHECK(fr_unhex("00ff", b, 4) == 2 && b[1] == 0xff);+ CHECK(fr_unhex("0g", b, 4) == -1);+ CHECK(fr_unhex("0F", b, 4) == -1);+ CHECK(fr_unhex("abc", b, 4) == -1);+ CHECK(fr_unhex("0011223344", b, 4) == -1);+}++static void full_valid(void) {+ FirstRun fr;+ char err[200];+ const char *s = full_file();+ int r = fr_parse(s, strlen(s), &fr, err, sizeof err);+ if (r) printf(" full file: %s\n", err);+ CHECK(r == 0);+ CHECK(!strcmp(fr.hostname, "pi-living"));+ CHECK(!strcmp(fr.lang, "es"));+ CHECK(!strcmp(fr.user, "ana"));+ CHECK(!strcmp(fr.fullname, "Ana Pérez"));+ CHECK(fr.ssid_len == 10 && !memcmp(fr.ssid, "My Red \xe2\x9d\xa4", 10));+ CHECK(fr.has_psk && fr.hidden == 1);+ CHECK(fr.ssh == FR_SSH_KEYS && fr.nkeys == 2);+ CHECK(fr.remote == 1 && fr.bluetooth == 0);+ CHECK(fr.cooler == FR_COOL_ACTIVE && fr.perf == FR_PERF_PERFORMANCE && fr.overclock == 1);+ CHECK(!strcmp(fr.theme, "classic") && !strcmp(fr.mode, "light") && !strcmp(fr.accent, "violeta"));+ CHECK(fr.has_variant && fr.variant[0] == 0);+ CHECK(fr.updates == 1);+ fr_free(&fr);++ /* CRLF and a BOM are accepted */+ char crlf[16384];+ size_t o = 0;+ crlf[o++] = (char)0xef; crlf[o++] = (char)0xbb; crlf[o++] = (char)0xbf;+ for (const char *p = s; *p; p++) { if (*p == '\n') crlf[o++] = '\r'; crlf[o++] = *p; }+ crlf[o] = 0;+ CHECK(parses(crlf));+ /* the smallest file */+ CHECK(parses("version=1\n"));+ CHECK(parses("version=1"));+ CHECK(parses("version=1\nhostname=pi\n"));+ CHECK(parses("version=1\nuser=ana\npassword_hash=$6$saltstring$svn8UoSVapNtMuq1ukKS4tPQd8iKwSMHWjl/O817G3uBnIFNjnQJuesI68u4OTLiBFdcbYEdFCoEOfaS35inz1\n"));+ CHECK(parses("version=1\nwifi_ssid_hex=6162\n")); /* open network */+ CHECK(parses("version=1\ncooler=none\nperformance=conservative\n"));+}++static void replace_line(char *dst, size_t cap, const char *src, const char *key, const char *line) {+ /* the file with the line starting with key= replaced by `line` ("" = removed) */+ size_t o = 0, kl = strlen(key);+ for (const char *l = src; *l;) {+ const char *e = strchr(l, '\n');+ size_t ll = e ? (size_t)(e - l + 1) : strlen(l);+ if (!strncmp(l, key, kl) && l[kl] == '=') { o += (size_t)snprintf(dst + o, cap - o, "%s", line); }+ else { memcpy(dst + o, l, ll); o += ll; }+ l += ll;+ }+ dst[o] = 0;+}++static void broken(void) {+ static const char *const bad[] = {+ "", "\n", "# only a comment\n", "hostname=pi\nversion=1\n", "version=2\n", "version=1\nversion=1\n",+ "version=1\nhostname=pi\nhostname=pi2\n", "version=1\nfoo=bar\n", "version=1\nhostname\n",+ "version=1\nhostname= pi\n", "version=1\nhostname=pi \n", "version=1\nhostname=\n", "version=1\nhostname=PI\n",+ "version=1\n hostname=pi\n", "version=1\nhostname=p\ti\n", "version=1\nlang=fr\n", "version=1\nlang=EN\n",+ "version=1\ntimezone=../../etc/shadow\n", "version=1\nkeyboard=../x\n", "version=1\nkeyboard=US\n",+ "version=1\nkeyboard_variant=intl\n", "version=1\nwifi_country=ar\n", "version=1\nwifi_country=ARG\n",+ "version=1\nuser=root\npassword_hash=$6$saltstring$svn8UoSVapNtMuq1ukKS4tPQd8iKwSMHWjl/O817G3uBnIFNjnQJuesI68u4OTLiBFdcbYEdFCoEOfaS35inz1\n",+ "version=1\nuser=ana\n", "version=1\npassword_hash=$6$saltstring$svn8UoSVapNtMuq1ukKS4tPQd8iKwSMHWjl/O817G3uBnIFNjnQJuesI68u4OTLiBFdcbYEdFCoEOfaS35inz1\n",+ "version=1\nuser=ana\npassword_hash=hunter2\n", "version=1\nuser=ana\npassword=hunter2\n",+ "version=1\nwifi_ssid_hex=\n", "version=1\nwifi_ssid_hex=00\n", "version=1\nwifi_ssid_hex=ABCD\n",+ "version=1\nwifi_ssid_hex=000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20\n",+ "version=1\nwifi_psk=f42c6fc52df0ebef9ebb4b90b38a5f902e83fe1b135a70e23aed762e9710a12e\n",+ "version=1\nwifi_ssid_hex=6162\nwifi_psk=hunter22\n",+ "version=1\nwifi_ssid_hex=6162\nwifi_password=hunter22\n",+ "version=1\nssh=on\n", "version=1\nssh=password\n", "version=1\nremote_desktop=1\n", "version=1\nremote_desktop=yes\n",+ "version=1\ncooler=fan\n", "version=1\ncooler=none\noverclock=1\n", "version=1\ncooler=passive\nperformance=performance\n",+ "version=1\nperformance=balanced\n", "version=1\ncooler=none\nperformance=quiet\n", "version=1\noverclock=0\n",+ "version=1\ntheme=gnome\n", "version=1\nmode=auto\n", "version=1\naccent=blue\n", "version=1\nwallpaper=../../etc\n",+ "version=1\nfullname=Ana\n", "version=1\nautologin=1\n",+ "version=1\nhostname=pi\x01\n", "version=1\r\nhostname=pi\r\r\n", "version=1\nhostname=\xff\n",+ };+ for (size_t i = 0; i < sizeof bad / sizeof *bad; i++) {+ int ok = parses(bad[i]);+ if (ok) printf(" accepted bad file %zu: %s\n", i, bad[i]);+ CHECK(!ok);+ }+ /* a NUL inside the buffer (strlen would stop early, so pass the real length) */+ {+ const char s[] = "version=1\nhostname=pi\0\n";+ FirstRun fr;+ char err[200];+ CHECK(fr_parse(s, sizeof s - 1, &fr, err, sizeof err) != 0);+ fr_free(&fr);+ }+ /* cross-key rules on the full file */+ char f[16384];+ const char *s = full_file();+ replace_line(f, sizeof f, s, "password_hash", "");+ CHECK(!parses(f));+ replace_line(f, sizeof f, s, "cooler", "cooler=passive\n");+ CHECK(!parses(f)); /* performance + overclock need a fan */+ replace_line(f, sizeof f, s, "ssh", "ssh=off\n");+ CHECK(!parses(f)); /* keys with ssh off */+ replace_line(f, sizeof f, s, "user", "");+ CHECK(!parses(f));+ replace_line(f, sizeof f, s, "wifi_ssid_hex", "");+ CHECK(!parses(f));+ /* 17 keys */+ {+ char many[65536];+ size_t o = (size_t)snprintf(many, sizeof many, "version=1\nuser=ana\npassword_hash=%s\nssh=keys\n", H6);+ for (int i = 0; i < 17; i++) o += (size_t)snprintf(many + o, sizeof many - o, "ssh_key=%s\n", ED);+ CHECK(!parses(many));+ o = (size_t)snprintf(many, sizeof many, "version=1\nuser=ana\npassword_hash=%s\nssh=keys\n", H6);+ for (int i = 0; i < 16; i++) o += (size_t)snprintf(many + o, sizeof many - o, "ssh_key=%s\n", ED);+ CHECK(parses(many));+ }+ /* a file larger than 64 KiB */+ {+ static char big[FR_MAX_FILE + 10];+ memset(big, '#', sizeof big - 1);+ memcpy(big, "version=1\n", 10);+ big[sizeof big - 1] = 0;+ CHECK(!parses(big));+ }+}++/* ---- random mutations: never crash, never read out of bounds (ASan) ---- */++static unsigned long long rng = 0x9e3779b97f4a7c15ull;+static unsigned rnd(void) { rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17; return (unsigned)(rng >> 11); }++static void fuzz(long iters) {+ const char *s = full_file();+ size_t n = strlen(s);+ char *buf = malloc(n + 512);+ long accepted = 0;+ for (long it = 0; it < iters; it++) {+ size_t m = n;+ memcpy(buf, s, n);+ int edits = 1 + (int)(rnd() % 6);+ for (int e = 0; e < edits; e++) {+ unsigned op = rnd() % 5;+ size_t at = m ? rnd() % m : 0;+ if (op == 0 && m) buf[at] = (char)(rnd() & 0xff); /* flip a byte */+ else if (op == 1 && m) { memmove(buf + at, buf + at + 1, m - at - 1); m--; } /* delete */+ else if (op == 2 && m + 1 < n + 512) { memmove(buf + at + 1, buf + at, m - at); buf[at] = "=\n#\r \x80\xc3\xa9$:,"[rnd() % 12]; m++; }+ else if (op == 3) m = at; /* truncate */+ else if (op == 4 && m) buf[at] = (char)('0' + rnd() % 75);+ }+ /* the parser gets an exact-size heap copy so ASan sees any read past the end */+ char *exact = malloc(m ? m : 1);+ memcpy(exact, buf, m);+ FirstRun fr;+ char err[200];+ if (fr_parse(exact, m, &fr, err, sizeof err) == 0) accepted++;+ fr_free(&fr);+ free(exact);+ }+ free(buf);+ printf(" %ld mutations, %ld still valid\n", iters, accepted);+}++int main(int argc, char **argv) {+ if (argc == 3 && !strcmp(argv[1], "check")) {+ FILE *f = fopen(argv[2], "rb");+ if (!f) { printf("cannot read %s\n", argv[2]); return 2; }+ static char b[FR_MAX_FILE + 2];+ size_t n = fread(b, 1, sizeof b, f);+ fclose(f);+ FirstRun fr;+ char err[200];+ int r = fr_parse(b, n, &fr, err, sizeof err);+ fr_free(&fr);+ printf("%s\n", r ? err : "ok");+ return r ? 1 : 0;+ }+ validators();+ full_valid();+ broken();+ fuzz(argc > 1 ? atol(argv[1]) : 30000);+ printf("firstrun-test: %d checks, %d failed\n", checks, fails);+ return fails ? 1 : 0;+}diff --git a/server/tests/imager/blocks.xz b/server/tests/imager/blocks.xznew file mode 100644index 0000000..5cbf17eBinary files /dev/null and b/server/tests/imager/blocks.xz differdiff --git a/server/tests/imager/one.xz b/server/tests/imager/one.xznew file mode 100644index 0000000..8caea38Binary files /dev/null and b/server/tests/imager/one.xz differdiff --git a/server/tests/imager/padded.xz b/server/tests/imager/padded.xznew file mode 100644index 0000000..253ae2aBinary files /dev/null and b/server/tests/imager/padded.xz differdiff --git a/server/tests/imager/release-SHA256SUMS b/server/tests/imager/release-SHA256SUMSnew file mode 100644index 0000000..6a87cf6--- /dev/null+++ b/server/tests/imager/release-SHA256SUMS@@ -0,0 +1,7 @@+994410d82cb7180c4f89e289a2d5666935c947d529742d918cc61f7a70784032 install.sh+a7714f4f3d437a9e48088cb89579a93638b36e8a93944add23e18a126f04ea45 lordos-0.8.1-rpi5-arm64.img.xz+04f388d6d3d252c5c51d0ff4260a553b7e3dfaf904d7c0d04b7122fce21950e4 lordos-live-0.8.1-amd64.iso+407e14b58c17d28a94ab3b78602297226483cb8f4cd8f44bc8657828a3b70e88 lordos_0.8.1_amd64.deb+e65d10c6e204ab45ce672bbe3bcfd597b29d196e598478187f3b5ccc4760c39b lordos_0.8.1_amd64.spdx.json+f512aaea5053258ef0262c601eb9ff017e0f63dbc50107f008b96b55e060cd23 lordos_0.8.1_arm64.deb+8f0011b6d4178ef42ad64c6a0d38ad0a9185f0f3f81ddfa00fed563a1fc44987 lordos_0.8.1_arm64.spdx.jsondiff --git a/server/tests/imager/release-SHA256SUMS.sig b/server/tests/imager/release-SHA256SUMS.signew file mode 100644index 0000000..488629e--- /dev/null+++ b/server/tests/imager/release-SHA256SUMS.sig@@ -0,0 +1 @@+M2obKQiBN+Z20UQUziNGW6FUK6aCf8wil2KQP3UuFD+3VSy+5opMCB76EIE7mrA+RtUNqIZtcxJKpqllSyHEDA==diff --git a/server/tests/imager/two.xz b/server/tests/imager/two.xznew file mode 100644index 0000000..c2673bfBinary files /dev/null and b/server/tests/imager/two.xz differdiff --git a/server/tests/imager_key.c b/server/tests/imager_key.cnew file mode 100644index 0000000..4e9a010--- /dev/null+++ b/server/tests/imager_key.c@@ -0,0 +1,9 @@+/* imager_key.c — the release key for build/disk-cli, which doesn't link src/sec/codesig.c. The+ * same 32 bytes as codesig_release_key; build/codesig-test checks those against+ * tools/release/lordos-release.pub.pem, and tests/imager_test.c checks that PEM's fingerprint. */+#include <stdint.h>++const uint8_t codesig_release_key[32] = {+ 0xf1, 0xca, 0xb0, 0x0f, 0x31, 0xfe, 0x65, 0x53, 0x1d, 0x06, 0xa3, 0x63, 0x0b, 0x7d, 0x78, 0xd5,+ 0xd9, 0xa8, 0xde, 0x07, 0x07, 0xf0, 0xf5, 0xad, 0xf3, 0xc2, 0x3e, 0x44, 0x4f, 0x5d, 0x39, 0xa0,+};diff --git a/server/tests/imager_test.c b/server/tests/imager_test.cnew file mode 100644index 0000000..43fb2e8--- /dev/null+++ b/server/tests/imager_test.c@@ -0,0 +1,202 @@+/* imager_test.c — the LordOS Imager's pure checks (src/imager/imgverify.c, docs/IMAGER.md):+ * the release signature (good, tampered, missing, wrong key, malformed), SHA256SUMS lookups, image+ * names and tags, and the .xz index reader on real xz files (one stream, many blocks, two streams,+ * stream padding) plus damaged and random ones. Fixtures in tests/imager/: a real signed+ * SHA256SUMS from the 0.8.1 release and small xz files made with xz 5. Run from server/. */+#include "imager/imgverify.h"+#include "pkg/crypto.h"++#include <stdio.h>+#include <stdlib.h>+#include <string.h>++static int fails, checks;+#define CHECK(c) do { checks++; if (!(c)) { fails++; printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); } } while (0)++static unsigned char *slurp(const char *path, size_t *n) {+ FILE *f = fopen(path, "rb");+ if (!f) { printf("missing fixture %s\n", path); exit(2); }+ fseek(f, 0, SEEK_END);+ long l = ftell(f);+ fseek(f, 0, SEEK_SET);+ unsigned char *b = malloc((size_t)l + 1);+ if (fread(b, 1, (size_t)l, f) != (size_t)l) exit(2);+ fclose(f);+ b[l] = 0;+ *n = (size_t)l;+ return b;+}++/* the release public key, from the PEM in the tree (the last 32 bytes of the DER) */+static void release_key(uint8_t pub[32]) {+ size_t n;+ char *pem = (char *)slurp("../tools/release/lordos-release.pub.pem", &n);+ char *b = strstr(pem, "-----\n") + 6;+ char *e = strstr(b, "\n-----END");+ *e = 0;+ static const char A[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";+ uint8_t der[64];+ size_t o = 0;+ unsigned acc = 0;+ int bits = 0;+ for (char *p = b; *p && *p != '='; p++) {+ const char *q = strchr(A, *p);+ if (!q) continue;+ acc = acc << 6 | (unsigned)(q - A);+ bits += 6;+ if (bits >= 8) { bits -= 8; der[o++] = (uint8_t)(acc >> bits); }+ }+ CHECK(o == 44);+ memcpy(pub, der + o - 32, 32);+ /* the fingerprint docs/SIGNING.md publishes */+ uint8_t fp[32];+ char hex[65];+ Sha256 s;+ sha256_init(&s);+ sha256_update(&s, der, o);+ sha256_final(&s, fp);+ hex_encode(fp, 32, hex);+ CHECK(!strncmp(hex, "c7155b8e", 8));+ free(pem);+}++static void signature(void) {+ uint8_t pub[32];+ release_key(pub);+ size_t n, sn;+ uint8_t *sums = slurp("tests/imager/release-SHA256SUMS", &n);+ char *sig = (char *)slurp("tests/imager/release-SHA256SUMS.sig", &sn);+ CHECK(img_sig_verify(sums, n, sig, sn, pub) == 0); /* good */+ CHECK(img_sig_verify(sums, n, sig, sn - 1, pub) == 0); /* without the newline */+ sums[10] ^= 1;+ CHECK(img_sig_verify(sums, n, sig, sn, pub) != 0); /* tampered list */+ sums[10] ^= 1;+ CHECK(img_sig_verify(sums, n - 1, sig, sn, pub) != 0); /* truncated list */+ char bad[100];+ memcpy(bad, sig, sn);+ bad[5] = bad[5] == 'A' ? 'B' : 'A';+ CHECK(img_sig_verify(sums, n, bad, sn, pub) != 0); /* tampered signature */+ CHECK(img_sig_verify(sums, n, "", 0, pub) != 0); /* missing */+ CHECK(img_sig_verify(sums, n, sig, 40, pub) != 0); /* short */+ memcpy(bad, sig, sn);+ bad[10] = '*';+ CHECK(img_sig_verify(sums, n, bad, sn, pub) != 0); /* not base64 */+ memcpy(bad, sig, sn);+ bad[85] = (char)(bad[85] == 'A' ? 'B' : 'A'); /* non-zero padding bits or a different byte */+ CHECK(img_sig_verify(sums, n, bad, sn, pub) != 0);+ uint8_t other[32];+ memcpy(other, pub, 32);+ other[0] ^= 0x40;+ CHECK(img_sig_verify(sums, n, sig, sn, other) != 0); /* another key */+ CHECK(img_sig_verify(NULL, 0, sig, sn, pub) != 0);++ uint8_t h[32];+ char hex[65];+ CHECK(img_sums_find((char *)sums, n, "lordos-0.8.1-rpi5-arm64.img.xz", h) == 0);+ hex_encode(h, 32, hex);+ CHECK(!strcmp(hex, "a7714f4f3d437a9e48088cb89579a93638b36e8a93944add23e18a126f04ea45"));+ CHECK(img_sums_find((char *)sums, n, "lordos-live-0.8.1-amd64.iso", h) == 0);+ CHECK(img_sums_find((char *)sums, n, "lordos-0.8.1-rpi5-arm64.img", h) == -1);+ CHECK(img_sums_find((char *)sums, n, "rpi5-arm64.img.xz", h) == -1);+ CHECK(img_sums_find("zz", 2, "x", h) == -2);+ const char dup[] = "a7714f4f3d437a9e48088cb89579a93638b36e8a93944add23e18a126f04ea45 x.img\n"+ "a7714f4f3d437a9e48088cb89579a93638b36e8a93944add23e18a126f04ea45 x.img\n";+ CHECK(img_sums_find(dup, sizeof dup - 1, "x.img", h) == -2);+ const char star[] = "a7714f4f3d437a9e48088cb89579a93638b36e8a93944add23e18a126f04ea45 *x.img\r\n";+ CHECK(img_sums_find(star, sizeof star - 1, "x.img", h) == 0);+ free(sums);+ free(sig);+}++static void names(void) {+ CHECK(img_valid_name("lordos-0.8.4-rpi5-arm64.img.xz"));+ CHECK(img_valid_name("lordos-live-0.8.4-amd64.iso"));+ CHECK(!img_valid_name("../x.img"));+ CHECK(!img_valid_name(".x.img"));+ CHECK(!img_valid_name("-x.img"));+ CHECK(!img_valid_name("a b.img"));+ CHECK(!img_valid_name("a/b.img"));+ CHECK(!img_valid_name(""));+ CHECK(img_kind("a.img.xz") == 2);+ CHECK(img_kind("a.img") == 1);+ CHECK(img_kind("a.iso") == 1);+ CHECK(img_kind("a.zip") == 0);+ CHECK(img_kind(".img") == 0);+ CHECK(img_valid_tag("v0.8.4-beta"));+ CHECK(img_valid_tag("v1.0.0"));+ CHECK(img_valid_tag("v0.8.10-rc.1"));+ CHECK(!img_valid_tag("0.8.4"));+ CHECK(!img_valid_tag("v0.8"));+ CHECK(!img_valid_tag("v0.8.4-"));+ CHECK(!img_valid_tag("v0.8.4-Beta"));+ CHECK(!img_valid_tag("v0.8.4/../x"));+}++typedef struct { const uint8_t *b; size_t n; } Mem;+static int mem_read(void *ud, uint64_t off, void *buf, size_t n) {+ Mem *m = ud;+ if (off > m->n || n > m->n - off) return -1;+ memcpy(buf, m->b + off, n);+ return 0;+}++static uint64_t xz_size_of(const uint8_t *b, size_t n, int *rc) {+ Mem m = { b, n };+ uint64_t s = 0;+ *rc = img_xz_size(mem_read, &m, n, &s);+ return s;+}++static unsigned long long rng = 88172645463325252ull;+static unsigned rnd(void) { rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17; return (unsigned)rng; }++static void xz(void) {+ static const struct { const char *f; uint64_t size; } ok[] = {+ { "tests/imager/one.xz", 23000 }, { "tests/imager/blocks.xz", 23000 },+ { "tests/imager/two.xz", 24000 }, { "tests/imager/padded.xz", 23000 },+ };+ for (size_t i = 0; i < sizeof ok / sizeof *ok; i++) {+ size_t n;+ uint8_t *b = slurp(ok[i].f, &n);+ int rc;+ uint64_t s = xz_size_of(b, n, &rc);+ if (rc || s != ok[i].size) printf(" %s: rc %d size %llu\n", ok[i].f, rc, (unsigned long long)s);+ CHECK(rc == 0 && s == ok[i].size);+ /* damage: every byte of the last 64 flipped in turn must never give a different valid size */+ for (size_t k = n > 64 ? n - 64 : 0; k < n; k++) {+ b[k] ^= 0x55;+ uint64_t s2 = xz_size_of(b, n, &rc);+ CHECK(rc != 0 || s2 == ok[i].size);+ b[k] ^= 0x55;+ }+ /* truncations */+ for (size_t cut = 1; cut < 40; cut++) {+ xz_size_of(b, n - cut, &rc);+ CHECK(rc != 0 || (strstr(ok[i].f, "padded") && cut % 4 == 0 && cut <= 8)); /* less padding is still valid */+ }+ /* random garbage in the same buffer: no crash (ASan in the fuzz build) */+ for (int it = 0; it < 2000; it++) {+ size_t at = rnd() % n;+ uint8_t old = b[at];+ b[at] = (uint8_t)rnd();+ xz_size_of(b, n, &rc);+ b[at] = old;+ }+ free(b);+ }+ int rc;+ uint8_t zeros[64] = { 0 };+ xz_size_of(zeros, sizeof zeros, &rc);+ CHECK(rc != 0);+ xz_size_of((const uint8_t *)"not xz at all, nope", 20, &rc);+ CHECK(rc != 0);+ CHECK(img_crc32(0, "123456789", 9) == 0xcbf43926u);+}++int main(void) {+ signature();+ names();+ xz();+ printf("imager-test: %d checks, %d failed\n", checks, fails);+ return fails ? 1 : 0;+}diff --git a/server/tests/imager_write_test.sh b/server/tests/imager_write_test.shnew file mode 100644index 0000000..d3ff4d4--- /dev/null+++ b/server/tests/imager_write_test.sh@@ -0,0 +1,92 @@+#!/bin/sh+# imager_write_test.sh — the imager-write / imager-fetch actions against a VIRTUAL USB stick (docs/IMAGER.md,+# "Tests"). Never run it against a real disk: it erases the stick. Needs root, build/disk-cli and a+# stick made from a file with the kernel's USB gadget (it is removable and on USB, like a real one):+#+# truncate -s 4G /var/tmp/stick.img+# modprobe dummy_hcd; modprobe g_mass_storage file=/var/tmp/stick.img removable=1+# sudo tests/imager_write_test.sh <user> <sdX> /var/tmp/stick.img <signed release dir in the user's home> [internal sdY]+#+# The release dir holds SHA256SUMS, SHA256SUMS.sig and a small official .img.xz they list (any real+# LordOS release works). The script checks first that <sdX> is that gadget and that its size is the+# backing file's, and stops otherwise.+set -u+U=${1:?user}; D=${2:?sdX}; BACK=${3:?backing file}; REL=${4:?release dir}+CLI=$(dirname "$0")/../build/disk-cli+H=$(getent passwd "$U" | cut -d: -f6)+W=$H/.cache/imager-write-test+pass=0; fail=0+ok() { pass=$((pass + 1)); echo " ok $1"; }+bad() { fail=$((fail + 1)); echo " FAIL $1"; }++# ---- the target must be the virtual stick ----+m=$(sed 's/ *$//' /sys/block/$D/device/model 2>/dev/null); v=$(sed 's/ *$//' /sys/block/$D/device/vendor 2>/dev/null)+sz=$(( $(cat /sys/block/$D/size) * 512 )); want=$(stat -c %s "$BACK")+echo "target /dev/$D: vendor=$v model=$m size=$sz (backing file $BACK, $want bytes)"+[ "$v" = Linux ] && [ "$m" = "File-Stor Gadget" ] && [ "$sz" = "$want" ] || { echo "not the virtual stick: stopping"; exit 2; }++IMG=$(ls "$REL"/*.img.xz | head -1); SUMS=$REL/SHA256SUMS; SIG=$REL/SHA256SUMS.sig+run() { "$CLI" -u "$U" -n imager-write "$1" 2>&1 | grep -v ' progress ' | tail -1; }+id="$D\n$sz\n$m\n\n" # disk, size, model, serial (empty for the gadget)+expect() { # expect <code> <description> <arg>+ out=$(run "$3")+ case "$out" in *"$1"*) ok "$2 → $1" ;; *) bad "$2: wanted $1, got: $out" ;; esac+}++install -d -o "$U" -g "$U" "$W"+cp "$SUMS" "$W/SHA256SUMS"; cp "$SIG" "$W/SHA256SUMS.sig"+sed '1s/^./0/' "$SUMS" > "$W/SHA256SUMS.tampered"+printf 'NzFKWqpHNft14vKPCOK6q0DaQNef9jic0/7TUa7wkocU0g2AnRb7Gg2MBWljOsKwUK/0ceCAlkuBpRmjtSqPAw==\n' > "$W/wrong.sig" # 0.8.0's, a real release signature over another list+head -c 1048576 /dev/urandom > "$W/custom.img"+truncate -s $((sz + 1048576)) "$W/huge.img"+printf 'not xz at all' > "$W/broken.img.xz"+ln -sf /etc/shadow "$W/link.img"+chown -R "$U:$U" "$W"++echo "refusals (the stick must not be touched):"+INT=${5:-} # optional: an internal, non-system scratch disk to show the removable-only rule+if [ -n "$INT" ]; then+ out=$("$CLI" -u "$U" imager-write "$INT\n1\nx\n\ncustom\n$W/custom.img" 2>&1 | tail -1)+ case "$out" in *imager.notRemovable*) ok "an internal disk ($INT), even for an administrator → imager.notRemovable" ;; *) bad "internal disk: $out" ;; esac+fi+"$CLI" -u "$U" imager-write "sda\n1\nx\n\ncustom\n$W/custom.img" 2>&1 | tail -1 | grep -q 'disk.systemDisk\|imager.notRemovable' && ok "the system disk as an administrator" || bad "the system disk as an administrator"+expect imager.diskChanged "a different size" "$D\n$((sz - 512))\n$m\n\ncustom\n$W/custom.img"+expect imager.diskChanged "a different model" "$D\n$sz\nOther Stick\n\ncustom\n$W/custom.img"+expect imager.diskChanged "a different serial" "$D\n$sz\n$m\nXYZ\ncustom\n$W/custom.img"+expect imager.badSignature "a tampered SHA256SUMS" "${id}official\n$IMG\n$W/SHA256SUMS.tampered\n$W/SHA256SUMS.sig"+expect imager.badSignature "a signature from another release" "${id}official\n$IMG\n$W/SHA256SUMS\n$W/wrong.sig"+expect imager.noSignature "a missing signature" "${id}official\n$IMG\n$W/SHA256SUMS\n$W/nothing.sig"+expect imager.notListed "an image that SHA256SUMS does not list" "${id}official\n$W/custom.img\n$W/SHA256SUMS\n$W/SHA256SUMS.sig"+expect disk.imageTooLarge "an image larger than the stick" "${id}custom\n$W/huge.img"+expect imager.xzDamaged "a broken .img.xz" "${id}custom\n$W/broken.img.xz"+expect disk.imageOpenFailed "a link to /etc/shadow" "${id}custom\n$W/link.img"+expect disk.imageOpenFailed "a file outside the home folder" "${id}custom\n/etc/shadow.img"+expect imager.badImageName "a file that is not an image" "${id}custom\n/etc/shadow"+expect admin.invalidArgument "official without the signature lines" "${id}official\n$IMG"+expect admin.invalidArgument "a control character" "$D\n$sz\n$m$(printf '\001')\n\ncustom\n$W/custom.img"++echo "writing:"+out=$(run "${id}custom\n$W/custom.img")+h=$(sha256sum < "$W/custom.img" | cut -d' ' -f1)+case "$out" in *"imager.written sha256=$h"*) ok "a custom 1 MiB .img, verified ($h)" ;; *) bad "custom .img: $out" ;; esac+[ "$(head -c 1048576 /dev/$D | sha256sum | cut -d' ' -f1)" = "$h" ] && ok "read back independently" || bad "read back independently"++out=$(run "${id}official\n$IMG\n$W/SHA256SUMS\n$W/SHA256SUMS.sig")+h=$(xz -dc "$IMG" | sha256sum | cut -d' ' -f1)+case "$out" in *"imager.written sha256=$h"*official=1*) ok "the official $(basename "$IMG"), signature and hash checked, verified" ;; *) bad "official: $out" ;; esac+n=$(xz --robot -l "$IMG" | awk '/^totals/ {print $5}')+[ "$(head -c "$n" /dev/$D | sha256sum | cut -d' ' -f1)" = "$h" ] && ok "read back independently ($n bytes)" || bad "read back independently"++udevadm settle+expect disk.isPartition "a partition (the image's first one)" "${D}1\n$sz\n$m\n\ncustom\n$W/custom.img"+echo "cancelling in the middle:"+( sleep 6; "$CLI" -u "$U" -n disk-cancel "$D" > /dev/null ) &+out=$(run "${id}official\n$IMG\n$W/SHA256SUMS\n$W/SHA256SUMS.sig")+wait+case "$out" in *imager.cancelledWiped*) ok "cancelled → imager.cancelledWiped" ;; *) bad "cancel: $out" ;; esac+[ "$(head -c 1048576 /dev/$D | tr -d '\0' | wc -c)" = 0 ] && ok "the first MiB is wiped (no half-written partition table)" || bad "first MiB not wiped"+"$CLI" -u nobody -n disk-cancel "$D" 2>&1 | grep -q 'disk.nothingRunning\|disk.otherUser' && ok "another user cannot cancel" || bad "another user cancel"++rm -rf "$W"+echo "imager_write_test: $pass passed, $fail failed"+[ "$fail" = 0 ]