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
Launcher: no-files apps get their own view, and folders only from their id
Federico Pereira198e0403e82d
diff --git a/server/src/apps.c b/server/src/apps.cindex 9ac87b8..21db01a 100644--- a/server/src/apps.c+++ b/server/src/apps.c@@ -403,6 +403,7 @@ static void open_log(void) {typedef struct {SandboxFilesCfg cfg;+ char home[PATH_MAX], runtime[PATH_MAX], wayland[64];char buf[2 * SANDBOX_FILES_MAX][PATH_MAX];int nbuf, nrw, nro;} FilesPlan;@@ -425,96 +426,85 @@ static void plan_add(FilesPlan *p, int rw, const char *fmt, const char *a, constlist[*n] = NULL;}-/* A name that may become a folder of its own under ~/.config, ~/.cache or ~/.local/share:- * plain characters, not hidden, and never one of the folders that hold the user's secrets or- * LordOS's own decisions. */-static int dir_name_ok(const char *c) {- static const char *const deny[] = { "lordos", "ssh", "gnupg", "local", "config", "cache", "pki", "password-store",- "thumbnails", "autostart", "systemd", "environment.d", "dconf", "keyrings", NULL };- size_t n = strlen(c);- if (!n || n > 100 || c[0] == '.' || c[0] == '-') return 0;- for (const char *q = c; *q; q++) if (!isalnum((unsigned char)*q) && !strchr("._-+", *q)) return 0;- for (int i = 0; deny[i]; i++) if (!strcasecmp(c, deny[i])) return 0;+/* The canonical desktop id as a folder name under ~/.config, ~/.cache and ~/.local/share: only+ * if it can't name a folder that belongs to someone else's startup, keys or settings. The id is+ * the only name used: Exec, StartupWMClass and Name are free text of the .desktop file. */+static int own_dir_ok(const char *id) {+ static const char *const deny[] = { "lordos", "ssh", "gnupg", "autostart", "applications", "systemd", "environment.d",+ "keyrings", "dconf", "git", "trash", "mime", "fontconfig", "pulse", "pipewire",+ "wireplumber", "user-dirs.dirs", "mimeapps.list", "gtk-3.0", "gtk-4.0", "fish",+ "bash", "zsh", "nvim", "vim", "emacs", "nano", "mc", "flatpak", "containers",+ "thumbnails", "recently-used.xbel", "icons", "themes", "fonts", NULL };+ size_t n = strlen(id);+ if (!n || n > 100 || id[0] == '.' || id[0] == '-') return 0;+ for (const char *q = id; *q; q++) if (!isalnum((unsigned char)*q) && !strchr("._-+", *q)) return 0;+ if (!strncasecmp(id, "lordos", 6)) return 0;+ for (int i = 0; deny[i]; i++) if (!strcasecmp(id, deny[i])) return 0;return 1;}-/* The app's own names: its .desktop id, the last part of a reverse-DNS id, the program and its- * window class, as written and in lowercase. */-static int app_names(const DesktopApp *a, char out[][160], int max) {- char tmp[6][160];- int nt = 0;- snprintf(tmp[nt++], 160, "%.159s", a->id);- const char *dot = strrchr(a->id, '.');- if (dot && dot[1]) snprintf(tmp[nt++], 160, "%.159s", dot + 1);- if (a->bin[0]) snprintf(tmp[nt++], 160, "%.159s", a->bin);- static const char *const suffixes[] = { "-esr", "-stable", "-bin", NULL };- for (int i = 0; suffixes[i] && a->bin[0]; i++) {- size_t bl = strlen(a->bin), sl = strlen(suffixes[i]);- if (bl > sl && !strcmp(a->bin + bl - sl, suffixes[i])) { snprintf(tmp[nt++], 160, "%.*s", (int)(bl - sl), a->bin); break; }- }- if (a->wmclass[0]) snprintf(tmp[nt++], 160, "%.159s", a->wmclass);- int n = 0;- for (int i = 0; i < nt; i++)- for (int lower = 0; lower < 2; lower++) {- char c[160];- memcpy(c, tmp[i], sizeof c);- c[sizeof c - 1] = 0;- if (lower) for (char *q = c; *q; q++) *q = (char)tolower((unsigned char)*q);- if (!dir_name_ok(c)) continue;- int dup = 0;- for (int k = 0; k < n; k++) dup |= !strcmp(out[k], c);- if (!dup && n < max) memcpy(out[n++], c, sizeof c);- }- return n;+/* A writable grant must never land on a folder the system reads to start or install something,+ * or that holds a security decision (fsops_protected), nor on the shell's startup files. */+static int grant_ok(const char *path) {+ if (fsops_protected(path)) return 0;+ const char *base = strrchr(path, '/');+ base = base ? base + 1 : path;+ static const char *const startup[] = { ".bashrc", ".bash_profile", ".bash_login", ".profile", ".zshrc", ".zprofile",+ ".zshenv", ".zlogin", ".xprofile", ".xsession", ".xsessionrc", ".pam_environment",+ ".gitconfig", ".ssh", ".gnupg", NULL };+ for (int i = 0; startup[i]; i++) if (!strcmp(base, startup[i])) return 0;+ return 1;}static int is_dir(const char *p) { struct stat st; return !lstat(p, &st) && S_ISDIR(st.st_mode); }/* What a restricted app may touch (see sandbox.h). file: the realpath it was opened with, or NULL. */static FilesPlan *files_plan(const DesktopApp *a, const char *file) {- const char *home = getenv("HOME");- if (!home || home[0] != '/') return NULL;+ const char *h = getenv("HOME");FilesPlan *p = calloc(1, sizeof *p);if (!p) return NULL;- p->cfg.runtime_dir = getenv("XDG_RUNTIME_DIR");- char names[12][160];- int nn = app_names(a, names, 12), have_config = 0;+ if (!h || !realpath(h, p->home) || p->home[0] != '/' || !strcmp(p->home, "/")) { free(p); return NULL; }+ const char *home = p->home;+ p->cfg.home = home;+ const char *rt = getenv("XDG_RUNTIME_DIR");+ if (rt && rt[0] == '/' && realpath(rt, p->runtime)) p->cfg.runtime_dir = p->runtime;+ /* the only sockets of the session it keeps: the display and the sound server's normal ones+ * (never pipewire-0-manager, the bus, systemd's, agents' or LordOS's own) */+ const char *wd = getenv("WAYLAND_DISPLAY");+ int ns = 0;+ if (wd && wd[0] && !strchr(wd, '/') && strlen(wd) < sizeof p->wayland) { snprintf(p->wayland, sizeof p->wayland, "%s", wd); p->cfg.sockets[ns++] = p->wayland; }+ else p->cfg.sockets[ns++] = "wayland-0";+ p->cfg.sockets[ns++] = "pipewire-0";+ p->cfg.sockets[ns++] = "pulse/native";+ p->cfg.sockets[ns] = NULL;char path[PATH_MAX];- for (int i = 0; i < nn; i++) {- static const char *const own[] = { "%s/.config/%s", "%s/.local/share/%s", "%s/.local/state/%s", "%s/.cache/%s", "%s/.%s", NULL };+ /* its own folders, named exactly after its canonical id, created if missing */+ if (own_dir_ok(a->id)) {+ static const char *const own[] = { "%s/.config/%s", "%s/.cache/%s", "%s/.local/share/%s", "%s/.local/state/%s", NULL };+ static const char *const parents[] = { "%s/.config", "%s/.cache", "%s/.local", "%s/.local/share", "%s/.local/state", NULL };+ for (int k = 0; parents[k]; k++) { snprintf(path, sizeof path, parents[k], home); mkdir(path, 0700); }for (int k = 0; own[k]; k++) {- snprintf(path, sizeof path, own[k], home, names[i]);- if (!is_dir(path)) continue; /* only what exists (no symlinks out of the home) */- plan_add(p, 1, "%s%s", path, "");- if (k == 0 || k == 4) have_config = 1;+ snprintf(path, sizeof path, own[k], home, a->id);+ mkdir(path, 0700);+ if (is_dir(path) && grant_ok(path)) plan_add(p, 1, "%s%s", path, "");}}- /* programs whose data folder isn't named after them (program name prefix → folder in the- * home and in ~/.cache); created if missing, like the app would */- static const struct { const char *prog, *dir; } alias[] = { { "firefox", "mozilla" }, { "librewolf", "librewolf" },- { "icecat", "mozilla" }, { NULL, NULL } };- for (int k = 0; alias[k].prog && a->bin[0]; k++) {- if (strncmp(a->bin, alias[k].prog, strlen(alias[k].prog))) continue;- snprintf(path, sizeof path, "%s/.%s", home, alias[k].dir);- mkdir(path, 0700);- if (is_dir(path)) { plan_add(p, 1, "%s%s", path, ""); have_config = 1; }- snprintf(path, sizeof path, "%s/.cache/%s", home, alias[k].dir);- mkdir(path, 0700);- if (is_dir(path)) plan_add(p, 1, "%s%s", path, "");- }- /* none yet: its folders under the program's name, so it can save its settings */- if (!have_config && a->bin[0] && dir_name_ok(a->bin)) {- static const char *const make[] = { "%s/.config", "%s/.config/%s", "%s/.local", "%s/.local/share", "%s/.local/share/%s",- "%s/.cache", "%s/.cache/%s", NULL };- for (int k = 0; make[k]; k++) { snprintf(path, sizeof path, make[k], home, a->bin); mkdir(path, 0700); }- plan_add(p, 1, "%s/.config/%s", home, a->bin);- plan_add(p, 1, "%s/.local/share/%s", home, a->bin);- plan_add(p, 1, "%s/.cache/%s", home, a->bin);+ /* apps whose data folder isn't named after their id: a fixed table (canonical id → folder in+ * the home and in ~/.cache), never names taken from the .desktop file */+ static const struct { const char *id, *dir; } alias[] = { { "firefox-esr", "mozilla" }, { "firefox", "mozilla" }, { NULL, NULL } };+ for (int k = 0; alias[k].id; k++) {+ if (strcmp(a->id, alias[k].id)) continue;+ static const char *const where[] = { "%s/.%s", "%s/.cache/%s", NULL };+ for (int w = 0; where[w]; w++) {+ snprintf(path, sizeof path, where[w], home, alias[k].dir);+ mkdir(path, 0700);+ if (is_dir(path) && grant_ok(path)) plan_add(p, 1, "%s%s", path, "");+ }}/* caches shared by every app that hold nothing of the user's (not all of ~/.cache: its* thumbnails are pictures of the user's documents) */static const char *const caches[] = { "fontconfig", "mesa_shader_cache", "mesa_shader_cache_db", "radv_builtin_shaders",- "gstreamer-1.0", "ibus", "at-spi", NULL };+ "gstreamer-1.0", NULL };for (int k = 0; caches[k]; k++) plan_add(p, 1, "%s/.cache/%s", home, caches[k]);/* the desktop's look and settings, read only */static const char *const look[] = { ".config/gtk-3.0", ".config/gtk-4.0", ".config/fontconfig", ".config/dconf",@@ -523,8 +513,8 @@ static FilesPlan *files_plan(const DesktopApp *a, const char *file) {".config/pulse", ".local/share/fonts", ".local/share/icons", ".local/share/themes",".local/share/mime", ".local/share/applications", ".fonts", ".icons", ".themes", NULL };for (int k = 0; look[k]; k++) plan_add(p, 0, "%s/%s", home, look[k]);- /* "Open with": that file or folder only */- if (file) plan_add(p, 1, "%s%s", file, "");+ /* "Open with": that file or folder only (read only if it is one of the protected ones) */+ if (file) plan_add(p, grant_ok(file), "%s%s", file, "");return p;}@@ -594,8 +584,9 @@ static int launch(const char *id, const char *file) {const char *home = getenv("HOME");if (!cwd[0] || chdir(cwd)) { if (home && chdir(home)) {} }app_scope_enter(id); /* its own app-lordos-<id>.scope cgroup (the monitor attributes it) */- if (plan && sandbox_apply_files(&plan->cfg)) {- static const char msg[] = "apps: could not apply the no-files restriction (Landlock): not launched\n";+ /* its own view (namespaces: no session sockets, only its folders), then Landlock */+ if (plan && (sandbox_files_isolate(&plan->cfg) || sandbox_apply_files(&plan->cfg))) {+ static const char msg[] = "apps: could not apply the no-files restriction: not launched\n";if (write(2, msg, sizeof msg - 1) < 0) {}_exit(126);}diff --git a/server/src/sec/sandbox.c b/server/src/sec/sandbox.cindex ed93b3f..ec4f19e 100644--- a/server/src/sec/sandbox.c+++ b/server/src/sec/sandbox.c@@ -12,12 +12,16 @@#include <errno.h>#include <fcntl.h>+#include <limits.h>#include <stddef.h>#include <stdint.h>#include <stdio.h>#include <string.h>#include <sched.h>+#include <signal.h>+#include <sys/mount.h>#include <sys/prctl.h>+#include <sys/wait.h>#include <sys/syscall.h>#include <sys/stat.h>#include <unistd.h>@@ -182,6 +186,10 @@ int sandbox_apply_files(const SandboxFilesCfg *cfg) {struct landlock_ruleset_attr attr;memset(&attr, 0, sizeof attr);attr.handled_access_fs = handled;+#ifdef LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET+ /* abstract unix sockets of programs outside the app (ABI 6): refused too */+ if (abi >= 6) attr.scoped = LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET;+#endifint rs = ll_create(&attr, sizeof attr);if (rs < 0) return -1;/* not "/run" or "/var" as a whole: /run/media/<user> and /var/mail are the user's */@@ -213,6 +221,140 @@ int sandbox_apply_files(const SandboxFilesCfg *cfg) {#endif}+/* ---- the app's own view: user + mount + PID namespace (sandbox.h) ---- */++#ifndef OPEN_TREE_CLONE+#define OPEN_TREE_CLONE 1+#endif+#ifndef MOVE_MOUNT_F_EMPTY_PATH+#define MOVE_MOUNT_F_EMPTY_PATH 0x00000004+#endif++static int write_file(const char *path, const char *text) {+ int fd = open(path, O_WRONLY | O_CLOEXEC);+ if (fd < 0) return -1;+ size_t n = strlen(text);+ int r = write(fd, text, n) == (ssize_t)n ? 0 : -1;+ close(fd);+ return r;+}++/* mkdir -p of the parents of path (inside a tmpfs we just mounted) */+static void mk_parents(const char *path) {+ char p[PATH_MAX];+ snprintf(p, sizeof p, "%s", path);+ for (char *q = p + 1; *q; q++) {+ if (*q != '/') continue;+ *q = 0;+ mkdir(p, 0700);+ *q = '/';+ }+}++/* Binds an open_tree clone on path: creates an empty dir or file of the same kind first. */+static int bind_clone(int tree, const char *path, int is_dir) {+ mk_parents(path);+ if (is_dir) mkdir(path, 0700);+ else { int fd = open(path, O_WRONLY | O_CREAT | O_CLOEXEC, 0600); if (fd >= 0) close(fd); }+ return (int)syscall(SYS_move_mount, tree, "", AT_FDCWD, path, MOVE_MOUNT_F_EMPTY_PATH);+}++static int is_under(const char *path, const char *dir) {+ size_t n = strlen(dir);+ return !strncmp(path, dir, n) && (path[n] == '/' || !path[n]);+}++int sandbox_files_isolate(const SandboxFilesCfg *cfg) {+ if (!cfg->home || cfg->home[0] != '/' || !strcmp(cfg->home, "/")) return -1;+ char map[64];+ unsigned uid = (unsigned)getuid(), gid = (unsigned)getgid();+ if (unshare(CLONE_NEWUSER | CLONE_NEWNS | CLONE_NEWPID)) return -1;+ if (write_file("/proc/self/setgroups", "deny")) return -1;+ snprintf(map, sizeof map, "%u %u 1", uid, uid);+ if (write_file("/proc/self/uid_map", map)) return -1;+ snprintf(map, sizeof map, "%u %u 1", gid, gid);+ if (write_file("/proc/self/gid_map", map)) return -1;+ if (mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL)) return -1;++ /* the PID namespace starts with the next child: it is PID 1 */+ int sync[2];+ if (pipe2(sync, O_CLOEXEC)) return -1;+ pid_t init = fork();+ if (init < 0) return -1;+ if (init > 0) {+ /* tell the caller (through the exit status of nothing: we're an orphan) — wait until PID 1+ * says whether the view could be built, so a failure is logged before we go */+ char ok = 0;+ close(sync[1]);+ if (read(sync[0], &ok, 1) != 1) ok = 0;+ if (!ok) { static const char m[] = "sandbox: could not build the app's view (namespaces); not launched\n"; if (write(2, m, sizeof m - 1) < 0) {} }+ _exit(0);+ }+ close(sync[0]);++ /* PID 1: clones of everything that stays visible, taken before the tmpfs hide the originals */+ struct { int fd, dir; const char *path; int ro; } keep[2 * SANDBOX_FILES_MAX + 10];+ int nk = 0;+ for (int pass = 0; pass < 2; pass++) {+ const char *const *list = pass ? cfg->ro : cfg->rw;+ for (int i = 0; i < SANDBOX_FILES_MAX && list[i]; i++) {+ if (!is_under(list[i], cfg->home) || !strcmp(list[i], cfg->home)) continue; /* outside home: Landlock alone */+ struct stat st;+ if (lstat(list[i], &st) || !(S_ISDIR(st.st_mode) || S_ISREG(st.st_mode))) continue;+ int t = (int)syscall(SYS_open_tree, AT_FDCWD, list[i], OPEN_TREE_CLONE | O_CLOEXEC);+ if (t < 0) continue;+ keep[nk].fd = t; keep[nk].dir = S_ISDIR(st.st_mode); keep[nk].path = list[i]; keep[nk].ro = pass; nk++;+ }+ }+ char sockpath[8][PATH_MAX];+ int nsock = 0;+ for (int i = 0; cfg->runtime_dir && i < 8 && cfg->sockets[i]; i++) {+ snprintf(sockpath[nsock], PATH_MAX, "%s/%s", cfg->runtime_dir, cfg->sockets[i]);+ struct stat st;+ if (lstat(sockpath[nsock], &st) || !S_ISSOCK(st.st_mode)) continue;+ int t = (int)syscall(SYS_open_tree, AT_FDCWD, sockpath[nsock], OPEN_TREE_CLONE | O_CLOEXEC);+ if (t < 0) continue;+ keep[nk].fd = t; keep[nk].dir = 0; keep[nk].path = sockpath[nsock]; keep[nk].ro = 0; nk++;+ nsock++;+ }+ int bad = 0;+ const char *opts = "mode=0700,size=64m";+ bad |= mount("tmpfs", cfg->home, "tmpfs", MS_NOSUID | MS_NODEV, opts);+ if (cfg->runtime_dir) bad |= mount("tmpfs", cfg->runtime_dir, "tmpfs", MS_NOSUID | MS_NODEV, "mode=0700,size=8m");+ bad |= mount("tmpfs", "/tmp", "tmpfs", MS_NOSUID | MS_NODEV, "mode=1777");+ struct stat vt;+ if (!stat("/var/tmp", &vt)) bad |= mount("tmpfs", "/var/tmp", "tmpfs", MS_NOSUID | MS_NODEV, "mode=1777");+ bad |= mount("proc", "/proc", "proc", MS_NOSUID | MS_NODEV | MS_NOEXEC, NULL);+ for (int i = 0; i < nk && !bad; i++) {+ if (bind_clone(keep[i].fd, keep[i].path, keep[i].dir)) { bad = 1; break; }+ if (keep[i].ro) mount(NULL, keep[i].path, NULL, MS_REMOUNT | MS_BIND | MS_RDONLY | MS_NOSUID | MS_NODEV, NULL);+ }+ for (int i = 0; i < nk; i++) close(keep[i].fd);+ char ok = !bad;+ if (write(sync[1], &ok, 1) < 0) {}+ close(sync[1]);+ if (bad) _exit(1);++ pid_t app = fork();+ if (app < 0) _exit(1);+ if (app == 0) { prctl(PR_SET_PDEATHSIG, SIGKILL); return 0; } /* the app: Landlock, then execve */+ /* PID 1 only reaps; it leaves with the app's status. SIGTERM/SIGINT/SIGHUP go to the app. */+ sigset_t all;+ sigfillset(&all);+ sigprocmask(SIG_BLOCK, &all, NULL);+ for (;;) {+ struct timespec tick = { 1, 0 };+ siginfo_t si;+ int sig = sigtimedwait(&all, &si, &tick);+ if (sig == SIGTERM || sig == SIGINT || sig == SIGHUP) kill(app, sig);+ int st;+ pid_t w;+ while ((w = waitpid(-1, &st, WNOHANG)) > 0)+ if (w == app) _exit(WIFEXITED(st) ? WEXITSTATUS(st) : 128 + (WIFSIGNALED(st) ? WTERMSIG(st) : 0));+ if (w < 0 && errno == ECHILD) _exit(0);+ }+}+/* ---- seccomp-bpf: allowlist ---- */#if defined(__x86_64__)diff --git a/server/src/sec/sandbox.h b/server/src/sec/sandbox.hindex b82c707..c37ffd3 100644--- a/server/src/sec/sandbox.h+++ b/server/src/sec/sandbox.h@@ -84,10 +84,28 @@ int sandbox_apply_helper(const SandboxHelperCfg *cfg);* the caller decides). */#define SANDBOX_FILES_MAX 48typedef struct {+ const char *home;const char *runtime_dir;const char *rw[SANDBOX_FILES_MAX + 1]; /* NULL-terminated */const char *ro[SANDBOX_FILES_MAX + 1];+ const char *sockets[8]; /* names inside runtime_dir kept visible (wayland-0...), NULL-terminated */} SandboxFilesCfg;++/* Before sandbox_apply_files: the app's own view of the system, so no unix socket of the session+ * can be reached (Landlock in kernel 6.12 doesn't cover connect() on unix sockets, and the session+ * bus or a terminal multiplexer would run anything outside the restriction). In a new user, mount+ * and PID namespace (unprivileged; uid and gid map to themselves):+ * - the home folder is an empty tmpfs with only rw[] and ro[] bound into it (ro[] read-only);+ * - the runtime dir is an empty tmpfs with only sockets[] bound into it: no session bus, no+ * systemd user manager, no agents, no LordOS sockets;+ * - /tmp and /var/tmp are private tmpfs (no other program's sockets);+ * - /proc is a new procfs of the new PID namespace (no /proc/<pid>/root of the session's+ * processes back into the real one).+ * The calling process forks: the parent _exits (the caller already is an orphan), the child is+ * PID 1 of the new namespace and only reaps; its child returns 0 and goes on to Landlock and+ * execve. -1 (and nothing launched) if the kernel refuses any step: the caller doesn't start the+ * app. Doesn't allocate. */+int sandbox_files_isolate(const SandboxFilesCfg *cfg);int sandbox_apply_files(const SandboxFilesCfg *cfg);/* Landlock ABI of the running kernel (0 = none). */int sandbox_landlock_abi(void);diff --git a/server/tests/fwlinux/files.sh b/server/tests/fwlinux/files.shindex 862ae06..38f13f4 100755--- a/server/tests/fwlinux/files.sh+++ b/server/tests/fwlinux/files.sh@@ -20,40 +20,48 @@ echo secret > ~/Documents/fwlinux-secret.txtecho "opened with" > ~/fwlinux-open/note.txtecho sibling > ~/fwlinux-open/fwlinux-sibling.txtmkdir -p ~/.config/fwprobe ~/.cache/fwprobe-PROBE=/tmp/fwlinux-files-probe-$U.py # outside the home folder: the restricted app must be able to run it+PROBE=~/.config/fwprobe/probe.py # its own config dir: visible to the restricted appcp "$D/files_probe.py" "$PROBE"+SPID=$(pgrep -u "$U" -o -x lord-server || echo 1) # a session process: its /proc/<pid>/root must not be reachable+TSOCK=/tmp/fwlinux-tmp-$U.sock # a socket in the real /tmp (like a terminal multiplexer's)+rm -f "$TSOCK"+python3 -c "import socket,sys,time; s=socket.socket(socket.AF_UNIX); s.bind(sys.argv[1]); s.listen(); time.sleep(60)" "$TSOCK" &+TSOCK_PID=$!cat > "$APPS/fwprobe.desktop" <<DESK[Desktop Entry]Type=ApplicationName=Files restriction probe-Exec=python3 $PROBE %f+Exec=python3 $PROBE --outside-pid=$SPID --tmp-socket=$TSOCK %fMimeType=text/plain;NoDisplay=falseDESK-OUT=/tmp/fwlinux-files-$U.json+OUT=~/.cache/fwprobe/result.jsonprobe() { # probe [file]: launches and waits for the resultrm -f "$OUT"- "$CLI" fwprobe "$@" >/dev/null 2>&1- for i in $(seq 1 50); do [ -s "$OUT" ] && break; sleep 0.1; done+ WAYLAND_DISPLAY=wayland-0 XDG_RUNTIME_DIR=/run/user/$U "$CLI" fwprobe "$@" >/dev/null 2>&1+ for i in $(seq 1 300); do [ -s "$OUT" ] && break; sleep 0.1; done}-val() { python3 -c "import json;print(json.load(open('$OUT')).get('$1','missing'))" 2>/dev/null; }+val() { python3 -c "import json,os;print(json.load(open(os.path.expanduser('$OUT'))).get('$1','missing'))" 2>/dev/null; }+shopt -s extglobexpect() { local key=$1 want=$2 got; got=$(val "$key"); case "$got" in $want*) ok "$key → $got";; *) bad "$key → $got (expected $want)";; esac; }-echo "1. not restricted: the app reads ~/Documents"+echo "1. not restricted: the app reads ~/Documents (and reaches the session bus)"restrict desktop:fwprobe ""probeexpect read_documents okexpect list_home ok+expect connect_session_bus ok+rm -f ~/.cache/fwprobe/escaped ~/.config/autostart/fwlinux.desktop ~/.local/share/applications/fwlinux-evil.desktopecho "2. no-files: only its own folders, the system, /tmp and the runtime dir"restrict desktop:fwprobe no-filesprobe-expect read_documents "Permission denied"-expect list_documents "Permission denied"+expect read_documents "@(Permission denied|No such file)*"+expect list_documents "@(Permission denied|No such file)*"expect list_home "Permission denied"-expect read_firewall_json "Permission denied"-expect write_autostart "Permission denied"-expect read_ssh "Permission denied"+expect read_firewall_json "@(Permission denied|No such file)*"+expect write_autostart "@(Permission denied|No such file)*"+expect read_ssh "@(Permission denied|No such file)*"expect read_system okexpect write_tmp okexpect write_own_config ok@@ -61,18 +69,58 @@ expect write_own_cache okexpect rename_in_own_config okexpect read_desktop_files okexpect write_runtime_dir ok+expect connect_wayland ok+expect connect_pipewire ok+expect connect_session_bus "No such file"+expect connect_systemd_private "No such file"+expect connect_pipewire_manager "No such file"+expect outside_proc_visible "No such file"+expect outside_proc_root "No such file"+expect connect_tmp_socket "No such file"+expect systemd_run_user "exit"+expect gdbus_start_transient_unit "exit"+[ -e ~/.cache/fwprobe/escaped ] && bad "a process escaped through the user manager" || ok "nothing started through the user manager"echo "3. no-files, opened with a file (\"Open with\")"probe ~/fwlinux-open/note.txtexpect read_opened_file okexpect write_opened_file ok-expect read_next_to_opened "Permission denied"-expect read_documents "Permission denied"+expect read_next_to_opened "@(Permission denied|No such file)*"+expect read_documents "@(Permission denied|No such file)*"++echo "4. malicious .desktop files: names chosen to reach other programs' folders"+EVIL=/usr/local/lib/lordos-tests/files_probe.py # a system path: these ids get no folders of their own+sudo install -D -m 644 "$D/files_probe.py" "$EVIL"+for id in fwevil autostart applications; do+ cat > "$APPS/$id.desktop" <<DESK+[Desktop Entry]+Type=Application+Name=ssh+Exec=python3 $EVIL --result-in-opened %f+StartupWMClass=autostart+MimeType=text/plain;+DESK+ restrict "desktop:$id" no-files+ RES=~/fwlinux-open/result-$id.json+ : > "$RES"+ WAYLAND_DISPLAY=wayland-0 XDG_RUNTIME_DIR=/run/user/$U "$CLI" "$id" "$RES" >/dev/null 2>&1+ for i in $(seq 1 300); do [ -s "$RES" ] && break; sleep 0.1; done+ for key in write_autostart read_ssh write_python3_config write_local_share_applications write_bashrc read_documents; do+ got=$(python3 -c "import json,sys;print(json.load(open(sys.argv[1])).get(sys.argv[2],'missing'))" "$RES" "$key" 2>/dev/null)+ case "$got" in "Permission denied"*|"No such file"*|"Read-only"*) ok "$id: $key → $got";; *) bad "$id: $key → $got (expected refused)";; esac+ done+ rm -f "$APPS/$id.desktop"+done+[ -e ~/.config/autostart/fwlinux.desktop ] && bad "an autostart entry was written" || ok "no autostart entry was written"+[ -e ~/.local/share/applications/fwlinux-evil.desktop ] && bad "a .desktop was written" || ok "no .desktop file was written"+sudo rm -rf /usr/local/lib/lordos-tests+rm -rf ~/.config/fwevil ~/.cache/fwevil ~/.local/share/fwevil ~/.local/state/fwevilif command -v gtk4-print-editor >/dev/null && command -v strace >/dev/null && [ -S "/run/user/$U/wayland-0" ]; then- echo "4. a real GTK 4 app (gtk4-print-editor, traced with strace), restricted"- TR=/tmp/fwlinux-gtk-$U.trace+ echo "5. a real GTK 4 app (gtk4-print-editor, traced with strace), restricted"gtk() { # gtk <name> <Exec arguments> [file]: a .desktop for the editor, launched restricted+ TR=$HOME/.cache/$1/strace.txt # its own cache dir: the trace survives its private /tmp+ mkdir -p "$HOME/.cache/$1"cat > "$APPS/$1.desktop" <<DESK[Desktop Entry]Type=Application@@ -90,15 +138,16 @@ DESKPID=$(pgrep -u "$U" -n -x gtk4-print-edit)[ -n "$PID" ] && ok "it starts and stays up under the restriction (pid $PID)" || bad "gtk4-print-editor did not stay up"[ -n "$PID" ] && grep -q "^NoNewPrivs:.*1" /proc/$PID/status && ok "no_new_privs is set (Landlock)" || bad "no_new_privs not set"- grep -E "Documents/fwlinux-secret.txt.*EACCES" "$TR" >/dev/null && ok "its open of ~/Documents/fwlinux-secret.txt → EACCES" || bad "~/Documents was not refused: $(grep fwlinux-secret "$TR" | head -1)"+ grep -E "Documents/fwlinux-secret.txt.*(EACCES|ENOENT)" "$TR" >/dev/null && ok "its open of ~/Documents/fwlinux-secret.txt is refused ($(grep -oE "(EACCES|ENOENT)" "$TR" | head -1))" || bad "~/Documents was not refused: $(grep fwlinux-secret "$TR" | head -1)"[ -n "$PID" ] && kill "$PID" 2>/dev/null; sleep 0.5# b: opened with a file ("Open with" → %f): that file is readablegtk fwgtkopen "%f" "$HOME/fwlinux-open/note.txt"PID=$(pgrep -u "$U" -n -x gtk4-print-edit)grep -E "fwlinux-open/note.txt.*= [0-9]+$" "$TR" >/dev/null && ok "it opens the file passed by Open with" || bad "the passed file was not opened: $(grep note.txt "$TR" | head -1)"[ -n "$PID" ] && kill "$PID" 2>/dev/null- rm -f "$APPS/fwgtkdoc.desktop" "$APPS/fwgtkopen.desktop" "$TR"+ rm -f "$APPS/fwgtkdoc.desktop" "$APPS/fwgtkopen.desktop"+ rm -rf ~/.cache/fwgtkdoc ~/.cache/fwgtkopen ~/.config/fwgtkdoc ~/.config/fwgtkopen ~/.local/share/fwgtkdoc ~/.local/share/fwgtkopen ~/.local/state/fwgtkdoc ~/.local/state/fwgtkopenfirm -f "$APPS/fwprobe.desktop" "$APPS/fwgtk.desktop" ~/Documents/fwlinux-secret.txt "$OUT"-rm -rf ~/fwlinux-open ~/.config/fwprobe ~/.cache/fwprobe+rm -rf ~/fwlinux-open ~/.config/fwprobe ~/.cache/fwprobe ~/.local/share/fwprobe ~/.local/state/fwprobefwlinux_donediff --git a/server/tests/fwlinux/files_probe.py b/server/tests/fwlinux/files_probe.pyindex b0bf5d8..4b36114 100755--- a/server/tests/fwlinux/files_probe.py+++ b/server/tests/fwlinux/files_probe.py@@ -1,15 +1,19 @@#!/usr/bin/python3# files_probe.py — stand-in app for tests/fwlinux/files.sh: launched by the real launcher# (build/launch-cli) through a .desktop, it tries what a restricted app should and shouldn't be-# able to do and writes the results as JSON to /tmp/fwlinux-files-<uid>.json.-import json, os, sys+# able to do and writes the results as JSON to ~/.cache/fwprobe/result.json (its own cache dir,+# the one place a restricted run and the test both see).+# files_probe.py [--outside-pid=N] [--tmp-socket=PATH] [file]+import json, os, socket, subprocess, syshome = os.environ["HOME"]res = {}def t(name, fn):try:fn(); res[name] = "ok"except OSError as e:- res[name] = os.strerror(e.errno) if e.errno else str(e)+ res[name] = os.strerror(e.errno) if e.errno else (e.strerror or str(e))+ except Exception as e:+ res[name] = type(e).__name__def rd(p): open(p, "rb").read(1)def wr(p): open(p, "ab").close()def ls(p): os.listdir(p)@@ -25,9 +29,38 @@ t("write_own_config", lambda: wr(home + "/.config/fwprobe/settings.ini"))t("write_own_cache", lambda: wr(home + "/.cache/fwprobe/cache.bin"))t("rename_in_own_config", lambda: (wr(home + "/.config/fwprobe/a.tmp"), os.rename(home + "/.config/fwprobe/a.tmp", home + "/.config/fwprobe/a")))t("read_desktop_files", lambda: ls(home + "/.local/share/applications"))-t("write_runtime_dir", lambda: wr(os.environ.get("XDG_RUNTIME_DIR", "/run/user/%d" % os.getuid()) + "/fwlinux-probe"))-if len(sys.argv) > 1:- t("read_opened_file", lambda: rd(sys.argv[1]))- t("write_opened_file", lambda: wr(sys.argv[1]))- t("read_next_to_opened", lambda: rd(os.path.join(os.path.dirname(sys.argv[1]), "fwlinux-sibling.txt")))-json.dump(res, open("/tmp/fwlinux-files-%d.json" % os.getuid(), "w"))+rt = os.environ.get("XDG_RUNTIME_DIR", "/run/user/%d" % os.getuid())+t("write_runtime_dir", lambda: wr(rt + "/fwlinux-probe"))+def conn(p):+ s = socket.socket(socket.AF_UNIX); s.settimeout(2); s.connect(p); s.close()+args = [a for a in sys.argv[1:] if not a.startswith("--")]+outside = [a.split("=", 1)[1] for a in sys.argv[1:] if a.startswith("--outside-pid=")]+# the session's sockets: none reachable except the display and the sound server's+t("connect_session_bus", lambda: conn(rt + "/bus"))+t("connect_systemd_private", lambda: conn(rt + "/systemd/private"))+t("connect_pipewire_manager", lambda: conn(rt + "/pipewire-0-manager"))+t("connect_wayland", lambda: conn(rt + "/" + os.environ.get("WAYLAND_DISPLAY", "wayland-0")))+t("connect_pipewire", lambda: conn(rt + "/pipewire-0"))+if outside:+ t("outside_proc_root", lambda: conn("/proc/%s/root%s/bus" % (outside[0], rt)))+ t("outside_proc_visible", lambda: os.stat("/proc/%s" % outside[0]))+for host in [p for p in sys.argv[1:] if p.startswith("--tmp-socket=")]:+ t("connect_tmp_socket", lambda: conn(host.split("=", 1)[1]))+def run(cmd):+ r = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=15)+ if r.returncode: raise OSError(0, "exit %d" % r.returncode)+marker = home + "/.cache/fwprobe/escaped"+t("systemd_run_user", lambda: run(["systemd-run", "--user", "--quiet", "touch", marker]))+t("gdbus_start_transient_unit", lambda: run(["gdbus", "call", "--session", "--dest", "org.freedesktop.systemd1",+ "--object-path", "/org/freedesktop/systemd1", "--method", "org.freedesktop.systemd1.Manager.StartTransientUnit",+ "fwlinux-escape.service", "fail", "[('ExecStart', <[('/usr/bin/touch', ['/usr/bin/touch', '%s'], false)]>)]" % marker, "[]"]))+if args:+ t("read_opened_file", lambda: rd(args[0]))+ t("write_opened_file", lambda: wr(args[0]))+ t("read_next_to_opened", lambda: rd(os.path.join(os.path.dirname(args[0]), "fwlinux-sibling.txt")))+t("write_python3_config", lambda: wr(home + "/.config/python3/x"))+t("write_local_share_applications", lambda: wr(home + "/.local/share/applications/fwlinux-evil.desktop"))+t("write_bashrc", lambda: wr(home + "/.bashrc"))+# --result-in-opened: the results go into the file it was opened with (an app with no own folders)+out = args[0] if "--result-in-opened" in sys.argv and args else home + "/.cache/fwprobe/result.json"+json.dump(res, open(out, "w"))