Skip to content

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.

lord-netperm: enforce no camera, no USB and no Bluetooth for Linux apps

Federico Pereiraab6056072853
diff --git a/server/Makefile b/server/Makefile
index 5ae95f4..2a207d3 100644
--- a/server/Makefile
+++ b/server/Makefile
@@ -148,6 +148,14 @@ build/gen/np_bpf.h: build/np.bpf.o build/bpf2c
build/lord-netperm: $(NP_SRC) $(wildcard src/netperm/*.h) $(wildcard src/fw/*.h) src/sec/json.h $(NP_GEN)
@mkdir -p build
$(CC) $(CPPFLAGS) $(NP_CPP) $(CFLAGS) $(WARN) -std=c11 -o $@ $(NP_SRC)
+# tests/npverify_test.c: the BTF reader, and (as root) every program through the kernel verifier
+ifeq ($(BPF),1)
+test: build/npverify-test
+build/npverify-test: tests/npverify_test.c src/netperm/bpfsys.c $(wildcard src/netperm/*.h) $(NP_GEN)
+ @mkdir -p build
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/npverify_test.c src/netperm/bpfsys.c
+ ./$@ || { rm -f $@; exit 1; }
+endif
test: build/npcompile-test
build/npcompile-test: tests/npcompile_test.c src/netperm/npcompile.c src/netperm/npdns.c src/fw/rules.c src/fw/dnsmap.c src/fw/fwmap.c src/sec/json.c $(wildcard src/netperm/*.h) $(wildcard src/fw/*.h)
@mkdir -p build
diff --git a/server/src/netperm/bpfsys.c b/server/src/netperm/bpfsys.c
index 4dba42e..4ef03bd 100644
--- a/server/src/netperm/bpfsys.c
+++ b/server/src/netperm/bpfsys.c
@@ -68,6 +68,11 @@ int bpfs_map_delete(int fd, const void *key) {
}
int bpfs_prog_load(uint32_t type, uint32_t attach, const NpProgDesc *d, int (*map_fd)(const char *), char *log, size_t loglen) {
+ return bpfs_prog_load_btf(type, attach, 0, "LordOS", d, map_fd, log, loglen);
+}
+
+int bpfs_prog_load_btf(uint32_t type, uint32_t attach, uint32_t btf_id, const char *license, const NpProgDesc *d,
+ int (*map_fd)(const char *), char *log, size_t loglen) {
if (!d || !d->ninsns || d->ninsns > 1000000) { errno = EINVAL; return -1; }
struct bpf_insn *ins = malloc(d->ninsns * sizeof *ins);
if (!ins) return -1;
@@ -86,7 +91,8 @@ int bpfs_prog_load(uint32_t type, uint32_t attach, const NpProgDesc *d, int (*ma
a.expected_attach_type = attach;
a.insns = (uint64_t)(uintptr_t)ins;
a.insn_cnt = d->ninsns;
- a.license = (uint64_t)(uintptr_t)"LordOS";
+ a.license = (uint64_t)(uintptr_t)license;
+ a.attach_btf_id = btf_id;
set_name(a.prog_name, d->name);
int fd = sys_bpf(BPF_PROG_LOAD, &a);
if (fd < 0 && log && loglen > 1) {
@@ -152,6 +158,56 @@ void bpfs_ring_close(BpfRing *r) {
r->cons = r->prod = NULL;
}
+/* ---- kernel BTF: only enough to find a function by name ---- */
+
+static uint32_t rd32(const unsigned char *p) { uint32_t v; memcpy(&v, p, 4); return v; }
+
+uint32_t bpfs_btf_func_id(const char *path, const char *name) {
+ int fd = open(path ? path : "/sys/kernel/btf/vmlinux", O_RDONLY | O_CLOEXEC);
+ if (fd < 0) return 0;
+ /* sysfs reports size 0 for this file: read until EOF, up to 64 MB */
+ size_t cap = 8u << 20, len = 0;
+ unsigned char *buf = malloc(cap);
+ while (buf) {
+ if (len == cap) {
+ if (cap >= (64u << 20)) { free(buf); buf = NULL; break; }
+ unsigned char *nb = realloc(buf, cap * 2);
+ if (!nb) { free(buf); buf = NULL; break; }
+ buf = nb; cap *= 2;
+ }
+ ssize_t n = read(fd, buf + len, cap - len);
+ if (n < 0 && errno == EINTR) continue;
+ if (n <= 0) break;
+ len += (size_t)n;
+ }
+ close(fd);
+ if (!buf) return 0;
+ uint32_t found = 0;
+ if (len < 24 || buf[0] != 0x9f || buf[1] != 0xeb) goto out; /* magic 0xeB9F, little endian */
+ uint32_t hl = rd32(buf + 4), toff = rd32(buf + 8), tlen = rd32(buf + 12), soff = rd32(buf + 16), slen = rd32(buf + 20);
+ if (hl < 24 || hl > len || toff > len - hl || tlen > len - hl - toff || soff > len - hl || slen > len - hl - soff) goto out;
+ const unsigned char *t = buf + hl + toff, *strs = buf + hl + soff;
+ size_t nl = strlen(name), pos = 0;
+ for (uint32_t id = 1; pos + 12 <= tlen; id++) {
+ uint32_t noff = rd32(t + pos), info = rd32(t + pos + 4);
+ uint32_t kind = (info >> 24) & 0x1f, vlen = info & 0xffff;
+ size_t extra;
+ switch (kind) {
+ case 1: case 14: case 17: extra = 4; break; /* INT, VAR, DECL_TAG */
+ case 3: extra = 12; break; /* ARRAY */
+ case 4: case 5: case 15: case 19: extra = 12u * vlen; break;/* STRUCT, UNION, DATASEC, ENUM64 */
+ case 6: case 13: extra = 8u * vlen; break; /* ENUM, FUNC_PROTO */
+ case 2: case 7: case 8: case 9: case 10: case 11: case 12: case 16: case 18: extra = 0; break;
+ default: goto out; /* a kind we don't know: give up */
+ }
+ if (kind == 12 && noff < slen && slen - noff > nl && !memcmp(strs + noff, name, nl + 1)) { found = id; break; }
+ pos += 12 + extra;
+ }
+out:
+ free(buf);
+ return found;
+}
+
uint64_t bpfs_cgroup_id(int dirfd, const char *name) {
_Alignas(8) unsigned char buf[sizeof(struct file_handle) + sizeof(uint64_t)];
struct file_handle *fh = (struct file_handle *)(void *)buf;
diff --git a/server/src/netperm/bpfsys.h b/server/src/netperm/bpfsys.h
index 9a65532..add4cb7 100644
--- a/server/src/netperm/bpfsys.h
+++ b/server/src/netperm/bpfsys.h
@@ -33,6 +33,16 @@ int bpfs_map_delete(int fd, const void *key);
/* Loads a program with its relocations resolved (map_fd(name) gives the fd, -1 if it doesn't
* exist). log (optional) receives the verifier log if it fails. Returns the fd or -1. */
int bpfs_prog_load(uint32_t type, uint32_t attach, const NpProgDesc *d, int (*map_fd)(const char *), char *log, size_t loglen);
+/* The same with the attach target's BTF id (LSM programs: the kernel function of the hook) and
+ * the license string. The kernel only loads LSM programs with a GPL-compatible license: the
+ * programs are ours (MIT), and MIT code may also be distributed under the GPL, so those go as
+ * "Dual MIT/GPL"; the others as "LordOS". */
+int bpfs_prog_load_btf(uint32_t type, uint32_t attach, uint32_t btf_id, const char *license, const NpProgDesc *d,
+ int (*map_fd)(const char *), char *log, size_t loglen);
+/* Id of a function (BTF_KIND_FUNC) in the kernel's own type information (/sys/kernel/btf/vmlinux,
+ * or the file given, for tests), 0 if it isn't there or the file is malformed. Only reads; checks
+ * every offset. */
+uint32_t bpfs_btf_func_id(const char *path, const char *name);
int bpfs_link_create(int prog_fd, int target_fd, uint32_t attach);
/* Ring buffer: mmap of the consumer page (rw) and of the producer + data (ro). */
diff --git a/server/src/netperm/netperm.c b/server/src/netperm/netperm.c
index 84835a9..19e80e1 100644
--- a/server/src/netperm/netperm.c
+++ b/server/src/netperm/netperm.c
@@ -4,7 +4,9 @@
* - no arguments, executes nothing, no network of its own (it creates no AF_INET/AF_INET6
* sockets: the systemd service also forbids it with RestrictAddressFamilies);
* - loads the BPF programs it carries inside (np.bpf.c → build/gen/np_bpf.h) into the cgroup of
- * lordos.service, which contains the subtrees of all sessions;
+ * lordos.service, which contains the subtrees of all sessions: the network ones and, with the
+ * same per-app policy, the device program ("no camera", "no USB") and the Bluetooth socket
+ * program ("no Bluetooth"; it needs the kernel's function list, /sys/kernel/btf/vmlinux);
* - reads the rules of each user with a session from ~/.config/lordos/firewall.json (fixed,
* validated path) and compiles them into maps (npcompile.c);
* - learns names only from the system resolver (npdns.c);
@@ -17,6 +19,7 @@
#include "netperm/bpfsys.h"
#include "netperm/npcompile.h"
#include "netperm/npdns.h"
+#include "netperm/npload.h"
#include "netperm/npproto.h"
#include "fw/fwmap.h"
#include "errcode.h"
@@ -53,7 +56,7 @@
#define SCOPE_LEVEL (SVC_LEVEL + 2) /* lordos-session-<uid>/<scope> */
#define USER_LEVEL 3 /* user.slice/user-<uid>.slice/user@<uid>.service */
#define NAMES_APP "lordos" /* dnsmap key for what the resolver says */
-#define MAX_SESS 64
+#define MAX_SESS NP_MAX_SESS
#define MAX_CLIENTS 64
#define CLIENT_OUT (256u << 10)
@@ -77,6 +80,8 @@ typedef struct {
int nsc, cap;
int dirty_counts;
uint64_t user_cg; /* id of user@<uid>.service, or 0 if it isn't there (nor attached) */
+ uint64_t exempt[8]; /* the user's audio services in np_exempt (see sync_exempt) */
+ int nexempt;
int ulinks[16], nulinks; /* the programs attached to user@<uid>.service */
} Session;
@@ -98,7 +103,8 @@ typedef struct {
static struct {
int bpf_ok;
char bpf_err[200]; /* a code line (errcode.h): the firewall page shows it translated */
- int m_cfg, m_apps, m_union, m_lpm4, m_lpm6, m_seen, m_counts, m_events;
+ int m_np_cfg, m_np_apps, m_np_union, m_np_lpm4, m_np_lpm6, m_np_seen, m_np_counts, m_np_events, m_np_exempt;
+ int dev_ok, bt_ok; /* the device / Bluetooth programs loaded */
int links[16], nlinks;
int progs[16], nprogs;
uint32_t attach[16];
@@ -196,14 +202,15 @@ static void load_rules(Session *s) {
#ifdef NP_HAVE_BPF /* the program loader's relocations (bpf_setup) */
static int map_fd(const char *name) {
- if (!strcmp(name, "np_cfg")) return G.m_cfg;
- if (!strcmp(name, "np_apps")) return G.m_apps;
- if (!strcmp(name, "np_union")) return G.m_union;
- if (!strcmp(name, "np_lpm4")) return G.m_lpm4;
- if (!strcmp(name, "np_lpm6")) return G.m_lpm6;
- if (!strcmp(name, "np_seen")) return G.m_seen;
- if (!strcmp(name, "np_counts")) return G.m_counts;
- if (!strcmp(name, "np_events")) return G.m_events;
+ if (!strcmp(name, "np_cfg")) return G.m_np_cfg;
+ if (!strcmp(name, "np_apps")) return G.m_np_apps;
+ if (!strcmp(name, "np_union")) return G.m_np_union;
+ if (!strcmp(name, "np_lpm4")) return G.m_np_lpm4;
+ if (!strcmp(name, "np_lpm6")) return G.m_np_lpm6;
+ if (!strcmp(name, "np_seen")) return G.m_np_seen;
+ if (!strcmp(name, "np_counts")) return G.m_np_counts;
+ if (!strcmp(name, "np_events")) return G.m_np_events;
+ if (!strcmp(name, "np_exempt")) return G.m_np_exempt;
return -1;
}
#endif
@@ -226,8 +233,8 @@ static size_t inst_key(uint32_t idx, const NpNode *n, unsigned char *k) {
}
static int lpm_put(uint32_t idx, const NpNode *n) {
- if (n->fam == 4) { NpLpm4Key k; np_key4(idx, n, &k); return bpfs_map_update(G.m_lpm4, &k, &n->list, BPF_ANY); }
- NpLpm6Key k; np_key6(idx, n, &k); return bpfs_map_update(G.m_lpm6, &k, &n->list, BPF_ANY);
+ if (n->fam == 4) { NpLpm4Key k; np_key4(idx, n, &k); return bpfs_map_update(G.m_np_lpm4, &k, &n->list, BPF_ANY); }
+ NpLpm6Key k; np_key6(idx, n, &k); return bpfs_map_update(G.m_np_lpm6, &k, &n->list, BPF_ANY);
}
static void lpm_del(uint32_t idx, const unsigned char *ik) {
@@ -236,8 +243,8 @@ static void lpm_del(uint32_t idx, const unsigned char *ik) {
n.fam = ik[4];
n.prefix = ik[5];
memcpy(n.addr, ik + 6, 16);
- if (n.fam == 4) { NpLpm4Key k; np_key4(idx, &n, &k); bpfs_map_delete(G.m_lpm4, &k); }
- else { NpLpm6Key k; np_key6(idx, &n, &k); bpfs_map_delete(G.m_lpm6, &k); }
+ if (n.fam == 4) { NpLpm4Key k; np_key4(idx, &n, &k); bpfs_map_delete(G.m_np_lpm4, &k); }
+ else { NpLpm6Key k; np_key6(idx, &n, &k); bpfs_map_delete(G.m_np_lpm6, &k); }
}
/* Installs a node if it changed. 0 ok. */
@@ -278,14 +285,14 @@ static void sync_scope(Session *s, Scope *sc) {
prune(sc->idx, gen);
sc->has_domains = c.has_domains;
sc->app_v = c.app;
- if (bpfs_map_update(G.m_apps, &sc->cgid, &c.app, BPF_ANY)) logf_("np_apps: %s", strerror(errno));
+ if (bpfs_map_update(G.m_np_apps, &sc->cgid, &c.app, BPF_ANY)) logf_("np_apps: %s", strerror(errno));
np_compiled_free(&c);
}
static void drop_scope(Scope *sc) {
if (!G.bpf_ok) return;
- bpfs_map_delete(G.m_apps, &sc->cgid);
- bpfs_map_delete(G.m_counts, &sc->cgid);
+ bpfs_map_delete(G.m_np_apps, &sc->cgid);
+ bpfs_map_delete(G.m_np_counts, &sc->cgid);
prune(sc->idx, 0);
}
@@ -310,12 +317,41 @@ static void sync_union(Session *s) {
if (u.flags) {
u.trusted = 1; /* whatever the union doesn't restrict is allowed without notice */
u.mode = NP_M_SILENT;
- if (bpfs_map_update(G.m_union, &s->user_cg, &u, BPF_ANY)) logf_("np_union: %s", strerror(errno));
+ if (bpfs_map_update(G.m_np_union, &s->user_cg, &u, BPF_ANY)) logf_("np_union: %s", strerror(errno));
} else {
- bpfs_map_delete(G.m_union, &s->user_cg);
+ bpfs_map_delete(G.m_np_union, &s->user_cg);
}
}
+/* The user's audio services stay out of the device and Bluetooth union (np.bpf.c, find_dev_app):
+ * PipeWire opens the cameras for its video nodes and WirePlumber the Bluetooth audio sockets, for
+ * the whole session. Their cgroups (user@<uid>.service/session.slice/<unit>) change id when they
+ * restart, so this runs on every pass. Fixed unit names, nothing from the user. */
+static void sync_exempt(Session *s) {
+ static const char *const units[] = { "pipewire.service", "pipewire-pulse.service", "wireplumber.service", "filter-chain.service" };
+ uint64_t now[8];
+ int n = 0;
+ if (s->user_cg) {
+ char path[200];
+ snprintf(path, sizeof path, CG_ROOT "/" CG_USER "/user-%u.slice/user@%u.service/session.slice", s->uid, s->uid);
+ int dfd = open(path, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
+ for (size_t i = 0; dfd >= 0 && i < sizeof units / sizeof units[0] && n < 8; i++) {
+ uint64_t id = bpfs_cgroup_id(dfd, units[i]);
+ if (id) now[n++] = id;
+ }
+ if (dfd >= 0) close(dfd);
+ }
+ for (int i = 0; i < s->nexempt; i++) {
+ int keep = 0;
+ for (int k = 0; k < n; k++) keep |= now[k] == s->exempt[i];
+ if (!keep) bpfs_map_delete(G.m_np_exempt, &s->exempt[i]);
+ }
+ uint32_t one = 1;
+ for (int k = 0; k < n; k++) bpfs_map_update(G.m_np_exempt, &now[k], &one, BPF_ANY);
+ memcpy(s->exempt, now, sizeof now);
+ s->nexempt = n;
+}
+
static void drop_user_links(Session *s) {
for (int i = 0; i < s->nulinks; i++) close(s->ulinks[i]);
s->nulinks = 0;
@@ -339,7 +375,7 @@ static void sync_user_scope(Session *s) {
}
if (id == s->user_cg) { if (ufd >= 0) close(ufd); return; }
drop_user_links(s);
- if (s->user_cg) { bpfs_map_delete(G.m_union, &s->user_cg); bpfs_map_delete(G.m_counts, &s->user_cg); }
+ if (s->user_cg) { bpfs_map_delete(G.m_np_union, &s->user_cg); bpfs_map_delete(G.m_np_counts, &s->user_cg); }
s->user_cg = 0;
if (!id || ufd < 0) { if (ufd >= 0) close(ufd); return; }
for (int i = 0; i < G.nprogs && s->nulinks < (int)(sizeof s->ulinks / sizeof s->ulinks[0]); i++) {
@@ -405,13 +441,15 @@ static void scan_session(Session *s) {
}
sync_user_scope(s); /* attaches/re-attaches user@ and recompiles the union */
sync_union(s);
+ if (G.bpf_ok) sync_exempt(s);
}
static void drop_session(int k) {
Session *s = &G.sess[k];
for (int i = 0; i < s->nsc; i++) drop_scope(&s->sc[i]);
drop_user_links(s);
- if (s->user_cg) { bpfs_map_delete(G.m_union, &s->user_cg); bpfs_map_delete(G.m_counts, &s->user_cg); }
+ if (s->user_cg) { bpfs_map_delete(G.m_np_union, &s->user_cg); bpfs_map_delete(G.m_np_counts, &s->user_cg); }
+ if (G.bpf_ok) for (int i = 0; i < s->nexempt; i++) bpfs_map_delete(G.m_np_exempt, &s->exempt[i]);
if (s->wd >= 0) inotify_rm_watch(G.ifd, s->wd);
free(s->sc);
fw_store_free(s->store);
@@ -499,7 +537,8 @@ static void send_uid(unsigned uid, int type, const char *json, size_t n, int dro
static void status_json(char *b, size_t n) {
char err[260];
json_quote(err, sizeof err, G.bpf_ok ? "" : G.bpf_err);
- snprintf(b, n, "{\"bpf\":%s,\"dns\":\"%s\",\"error\":%s}", G.bpf_ok ? "true" : "false", G.dns ? npdns_source(G.dns) : "none", err);
+ snprintf(b, n, "{\"bpf\":%s,\"devices\":%s,\"bluetooth\":%s,\"dns\":\"%s\",\"error\":%s}", G.bpf_ok ? "true" : "false",
+ G.bpf_ok && G.dev_ok ? "true" : "false", G.bpf_ok && G.bt_ok ? "true" : "false", G.dns ? npdns_source(G.dns) : "none", err);
}
static void accept_client(void) {
@@ -565,6 +604,18 @@ static void on_event(void *u, const void *data, uint32_t len) {
memcpy(&ev, data, sizeof ev);
Session *s;
Scope *sc = scope_by_cgid(ev.cgid, &s);
+ if (ev.dir == NP_D_DEV || ev.dir == NP_D_BT) {
+ /* a device open or a Bluetooth socket: only in the journal (the Monitor's counters and
+ * connection log are about the network) */
+ Session *us = sc ? s : session_by_user_cg(ev.cgid);
+ unsigned minor = (unsigned)ev.addr[0] | (unsigned)ev.addr[1] << 8 | (unsigned)ev.addr[2] << 16 | (unsigned)ev.addr[3] << 24;
+ if (!us) return;
+ if (ev.dir == NP_D_DEV)
+ logf_("uid %u %s: denied opening device %u:%u (%s)", us->uid, sc ? sc->app : "user@ (union of restricted apps)", ev.port, minor, fw_flag_name(ev.flag));
+ else
+ logf_("uid %u %s: denied a Bluetooth socket (%s)", us->uid, sc ? sc->app : "user@ (union of restricted apps)", fw_flag_name(ev.flag));
+ return;
+ }
char addr[INET6_ADDRSTRLEN] = "";
if (ev.fam == 4) inet_ntop(AF_INET, ev.addr, addr, sizeof addr);
else if (ev.fam == 6) inet_ntop(AF_INET6, ev.addr, addr, sizeof addr);
@@ -597,7 +648,7 @@ static void push_counts(void) {
int changed = s->dirty_counts;
for (int k = 0; k < s->nsc; k++) {
NpCount c = { 0, 0 };
- if (G.bpf_ok) bpfs_map_lookup(G.m_counts, &s->sc[k].cgid, &c);
+ if (G.bpf_ok) bpfs_map_lookup(G.m_np_counts, &s->sc[k].cgid, &c);
if (c.allowed != s->sc[k].allowed || c.denied != s->sc[k].denied) changed = 1;
s->sc[k].allowed = c.allowed;
s->sc[k].denied = c.denied;
@@ -644,7 +695,7 @@ static void on_dns(void *u, const uint8_t *pkt, size_t len) {
if (np_compile_host(store_of(s), sc->app, r->addr[a].fam, r->addr[a].addr, (const char (*)[FW_NAME_MAX])names, n, &node, &tr) != 1) continue;
if (install(sc->idx, sc->gen, &node)) continue;
np_u8 *has = node.fam == 4 ? &sc->app_v.has4 : &sc->app_v.has6;
- if (!*has) { *has = 1; bpfs_map_update(G.m_apps, &sc->cgid, &sc->app_v, BPF_ANY); }
+ if (!*has) { *has = 1; bpfs_map_update(G.m_np_apps, &sc->cgid, &sc->app_v, BPF_ANY); }
}
}
}
@@ -653,43 +704,60 @@ static void on_dns(void *u, const uint8_t *pkt, size_t len) {
/* ---- BPF ------------------------------------------------------------------------------------- */
+#ifdef NP_HAVE_BPF
+/* Major of /dev/hidraw* (dynamic): the "hidraw" line of /proc/devices, or 0. */
+static uint32_t hidraw_major(void) {
+ FILE *f = fopen("/proc/devices", "re");
+ char line[128];
+ unsigned m = 0, v;
+ char name[64];
+ int chr = 0;
+ while (f && fgets(line, sizeof line, f)) {
+ if (!strncmp(line, "Character devices:", 18)) { chr = 1; continue; }
+ if (!strncmp(line, "Block devices:", 14)) chr = 0;
+ if (chr && sscanf(line, "%u %63s", &v, name) == 2 && !strcmp(name, "hidraw")) m = v;
+ }
+ if (f) fclose(f);
+ return m;
+}
+#endif
+
static int bpf_setup(void) {
#ifndef NP_HAVE_BPF
lerr_set(G.bpf_err, sizeof G.bpf_err, "fw.bpfNotBuilt", NULL);
return -1;
#else
- G.m_cfg = bpfs_map_create(BPF_MAP_TYPE_ARRAY, 4, sizeof(NpCfg), 1, 0, "np_cfg");
- G.m_apps = bpfs_map_create(BPF_MAP_TYPE_HASH, 8, sizeof(NpApp), NP_MAX_APPS, 0, "np_apps");
- G.m_union = bpfs_map_create(BPF_MAP_TYPE_HASH, 8, sizeof(NpApp), MAX_SESS, 0, "np_union");
- G.m_lpm4 = bpfs_map_create(BPF_MAP_TYPE_LPM_TRIE, sizeof(NpLpm4Key), sizeof(NpList), NP_MAX_LPM, BPF_F_NO_PREALLOC, "np_lpm4");
- G.m_lpm6 = bpfs_map_create(BPF_MAP_TYPE_LPM_TRIE, sizeof(NpLpm6Key), sizeof(NpList), NP_MAX_LPM, BPF_F_NO_PREALLOC, "np_lpm6");
- G.m_seen = bpfs_map_create(BPF_MAP_TYPE_LRU_HASH, sizeof(NpSeenKey), 8, NP_MAX_SEEN, 0, "np_seen");
- G.m_counts = bpfs_map_create(BPF_MAP_TYPE_HASH, 8, sizeof(NpCount), NP_MAX_APPS, 0, "np_counts");
- G.m_events = bpfs_map_create(BPF_MAP_TYPE_RINGBUF, 0, 0, NP_RINGBUF, 0, "np_events");
- if (G.m_cfg < 0 || G.m_apps < 0 || G.m_union < 0 || G.m_lpm4 < 0 || G.m_lpm6 < 0 || G.m_seen < 0 || G.m_counts < 0 || G.m_events < 0) {
+#define NP_MKMAP(n, t, k, v, m, f) G.m_##n = bpfs_map_create(t, k, v, m, f, #n);
+ NP_MAPS(NP_MKMAP)
+#undef NP_MKMAP
+ if (G.m_np_exempt < 0 || G.m_np_cfg < 0 || G.m_np_apps < 0 || G.m_np_union < 0 || G.m_np_lpm4 < 0 || G.m_np_lpm6 < 0 || G.m_np_seen < 0 || G.m_np_counts < 0 || G.m_np_events < 0) {
lerr_set(G.bpf_err, sizeof G.bpf_err, "fw.bpfMaps", "errno", lerr_errno(errno), NULL);
return -1;
}
- if (bpfs_ring_open(&G.ring, G.m_events, NP_RINGBUF)) {
+ if (bpfs_ring_open(&G.ring, G.m_np_events, NP_RINGBUF)) {
lerr_set(G.bpf_err, sizeof G.bpf_err, "fw.bpfRing", "errno", lerr_errno(errno), NULL);
return -1;
}
- static const struct { const char *sec; uint32_t type, attach; } want[] = {
- { "cgroup/connect4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT },
- { "cgroup/connect6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT },
- { "cgroup/sendmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG },
- { "cgroup/sendmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG },
- { "cgroup/bind4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND },
- { "cgroup/bind6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND },
- { "cgroup/sock_create", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE },
- };
static char log[1 << 20];
int np = 0;
- for (size_t w = 0; w < sizeof want / sizeof want[0]; w++) {
+ for (int w = 0; w < NP_NSPECS; w++) {
+ const NpProgSpec *want = np_prog_specs;
const NpProgDesc *d = NULL;
for (int i = 0; i < NP_NPROGS; i++) if (!strcmp(np_progs[i].section, want[w].sec)) d = &np_progs[i];
if (!d) { lerr_set(G.bpf_err, sizeof G.bpf_err, "fw.bpfMissing", "program", want[w].sec, NULL); return -1; }
- int fd = bpfs_prog_load(want[w].type, want[w].attach, d, map_fd, log, sizeof log);
+ uint32_t btf_id = 0;
+ if (want[w].btf && !(btf_id = bpfs_btf_func_id(NULL, want[w].btf))) {
+ logf_("%s: %s is not in the kernel's BTF: \"no Bluetooth\" is not enforced", want[w].sec, want[w].btf);
+ continue;
+ }
+ int fd = bpfs_prog_load_btf(want[w].type, want[w].attach, btf_id, np_prog_license(&want[w]), d, map_fd, log, sizeof log);
+ if (fd < 0 && want[w].opt) {
+ int e = errno;
+ size_t ll = strlen(log);
+ fprintf(stderr, "%s\n", ll > 3000 ? log + ll - 3000 : log);
+ logf_("%s: the kernel refused it (%s); that restriction is not enforced", want[w].sec, strerror(e));
+ continue;
+ }
if (fd < 0) {
int e = errno;
size_t ll = strlen(log);
@@ -697,14 +765,17 @@ static int bpf_setup(void) {
lerr_set(G.bpf_err, sizeof G.bpf_err, "fw.bpfRejected", "program", want[w].sec, "errno", lerr_errno(e), NULL);
return -1;
}
+ if (want[w].attach == BPF_CGROUP_DEVICE) G.dev_ok = 1;
+ if (want[w].attach == BPF_LSM_CGROUP) G.bt_ok = 1;
G.attach[np] = want[w].attach;
G.progs[np++] = fd;
}
G.nprogs = np;
- NpCfg cfg = { SCOPE_LEVEL, 1, USER_LEVEL };
+ NpCfg cfg = { SCOPE_LEVEL, 1, USER_LEVEL, hidraw_major() };
uint32_t zero = 0;
- if (bpfs_map_update(G.m_cfg, &zero, &cfg, BPF_ANY)) { lerr_set(G.bpf_err, sizeof G.bpf_err, "fw.bpfConfig", "errno", lerr_errno(errno), NULL); return -1; }
- logf_("%d BPF programs loaded", np);
+ if (bpfs_map_update(G.m_np_cfg, &zero, &cfg, BPF_ANY)) { lerr_set(G.bpf_err, sizeof G.bpf_err, "fw.bpfConfig", "errno", lerr_errno(errno), NULL); return -1; }
+ logf_("%d BPF programs loaded (devices: %s, Bluetooth sockets: %s, hidraw major %u)", np, G.dev_ok ? "yes" : "no",
+ G.bt_ok ? "yes" : "no", cfg.hidraw_major);
return 0;
#endif
}
@@ -810,7 +881,7 @@ int main(int argc, char **argv) {
epoll_ctl(G.ep, EPOLL_CTL_ADD, G.ifd, &ev);
ev.data.u64 = 3;
epoll_ctl(G.ep, EPOLL_CTL_ADD, G.tfd, &ev);
- if (G.bpf_ok) { ev.data.u64 = 4; epoll_ctl(G.ep, EPOLL_CTL_ADD, G.m_events, &ev); }
+ if (G.bpf_ok) { ev.data.u64 = 4; epoll_ctl(G.ep, EPOLL_CTL_ADD, G.m_np_events, &ev); }
G.root_wd = -1;
G.sys_wd = inotify_add_watch(G.ifd, CG_ROOT "/system.slice", IN_CREATE | IN_ONLYDIR);
attach_service();
diff --git a/server/src/netperm/np.bpf.c b/server/src/netperm/np.bpf.c
index eb8f973..6c9ab09 100644
--- a/server/src/netperm/np.bpf.c
+++ b/server/src/netperm/np.bpf.c
@@ -9,6 +9,11 @@
* cgroup/sendmsg4, sendmsg6 unconnected UDP (sendto with an address)
* cgroup/bind4, bind6 "no incoming connections" and inbound rules (local port != 0)
* cgroup/sock_create "no network": not even creating an AF_INET/AF_INET6 socket
+ * cgroup/dev "no camera" and "no USB": opening video devices, raw USB devices
+ * (/dev/bus/usb), hidraw, ttyACM and ttyUSB (by major); every other
+ * device stays allowed
+ * cgroup/lsm_socket_create "no Bluetooth": socket(AF_BLUETOOTH) (a per-cgroup LSM program,
+ * BPF_LSM_CGROUP: the inet sock_create hook never sees that family)
*
* The same programs are also attached to the user@<uid>.service of each LordOS session, to
* close the `systemd-run --user` escape (the process ends up there, outside lordos.service). A
@@ -45,9 +50,11 @@ char np_lpm6[4] SEC("maps");
char np_seen[4] SEC("maps");
char np_counts[4] SEC("maps");
char np_events[4] SEC("maps");
+char np_exempt[4] SEC("maps");
#define AF_INET 2
#define AF_INET6 10
+#define AF_BLUETOOTH 31
#define IPPROTO_TCP 6
#define IPPROTO_UDP 17
@@ -75,6 +82,28 @@ NP_INLINE NpApp *find_app(NpCfg *cfg, np_u64 *cgid) {
return 0;
}
+/* The same for the device and Bluetooth restrictions, with one difference: under user@<uid> the
+ * user's own audio services (PipeWire, WirePlumber: np_exempt, a service at level
+ * cfg->user_level + 2) are left out of the union, so a restricted app running doesn't take the
+ * camera or Bluetooth audio away from the whole session. */
+NP_INLINE NpApp *find_dev_app(NpCfg *cfg, np_u64 *cgid) {
+ np_u64 id = bpf_get_current_ancestor_cgroup_id((int)cfg->level);
+ if (id) {
+ NpApp *app = bpf_map_lookup_elem(&np_apps, &id);
+ if (app) { *cgid = id; return app; }
+ }
+ if (cfg->user_level) {
+ np_u64 svc = bpf_get_current_ancestor_cgroup_id((int)cfg->user_level + 2);
+ if (svc && bpf_map_lookup_elem(&np_exempt, &svc)) return 0;
+ np_u64 uid = bpf_get_current_ancestor_cgroup_id((int)cfg->user_level);
+ if (uid) {
+ NpApp *app = bpf_map_lookup_elem(&np_union, &uid);
+ if (app) { *cgid = uid; return app; }
+ }
+ }
+ return 0;
+}
+
NP_INLINE void count(np_u64 cgid, int deny) {
NpCount *c = bpf_map_lookup_elem(&np_counts, &cgid);
if (!c) {
@@ -240,3 +269,62 @@ SEC("cgroup/sock_create") int np_sock_create(struct bpf_sock *sk) {
handle(0, a, 0, proto_of(sk->protocol), NP_D_OUT, 1); /* counts and reports (denies because of the restriction) */
return 0;
}
+
+/* A denied device open or Bluetooth socket: reported once per 5 s (np_seen). Not counted: the
+ * Monitor's allowed/denied counters are about connections. */
+NP_INLINE void report_dev(np_u64 cgid, int dir, np_u32 major, np_u32 minor, np_u32 flag) {
+ NpSeenKey sk;
+ __builtin_memset(&sk, 0, sizeof sk);
+ sk.cgid = cgid;
+ sk.addr[0] = (np_u8)minor; sk.addr[1] = (np_u8)(minor >> 8); sk.addr[2] = (np_u8)(minor >> 16); sk.addr[3] = (np_u8)(minor >> 24);
+ sk.port = (np_u16)major;
+ sk.dir = (np_u8)dir; sk.verdict = 1;
+ np_u64 now = bpf_ktime_get_ns();
+ np_u64 *last = bpf_map_lookup_elem(&np_seen, &sk);
+ if (last && now - *last <= NP_REPEAT_NS) return;
+ bpf_map_update_elem(&np_seen, &sk, &now, BPF_ANY);
+ NpEvent ev;
+ __builtin_memset(&ev, 0, sizeof ev);
+ ev.cgid = cgid;
+ ev.ts = now;
+ for (int i = 0; i < 4; i++) ev.addr[i] = sk.addr[i];
+ ev.port = (np_u16)major;
+ ev.proto = NP_P_OTHER; ev.dir = (np_u8)dir; ev.verdict = NP_V_DENY;
+ ev.reason = NP_BY_RESTRICTED; ev.record = 1;
+ ev.flag = flag;
+ bpf_ringbuf_output(&np_events, &ev, sizeof ev, 0);
+}
+
+/* "no camera" / "no USB": the device controller of cgroup v2 is this kind of program. It runs on
+ * open() and mknod() of a device node; 1 = allow, 0 = EPERM. Programs attached higher up (systemd's
+ * DeviceAllow) still apply: the kernel allows only what all of them allow. Only the devices of
+ * np_dev_restriction are ever denied, and only to a restricted app. */
+SEC("cgroup/dev") int np_dev(struct bpf_cgroup_dev_ctx *ctx) {
+ np_u32 zero = 0;
+ NpCfg *cfg = bpf_map_lookup_elem(&np_cfg, &zero);
+ if (!cfg || !cfg->on) return 1;
+ np_u32 need = np_dev_restriction(ctx->access_type & 0xffff, ctx->major, cfg->hidraw_major);
+ if (!need) return 1;
+ np_u64 cgid = 0;
+ NpApp *app = find_dev_app(cfg, &cgid);
+ if (!app || !(app->flags & need)) return 1;
+ report_dev(cgid, NP_D_DEV, ctx->major, ctx->minor, need);
+ return 0;
+}
+
+/* "no Bluetooth": socket(AF_BLUETOOTH, ...) of a restricted app. A cgroup LSM program on the
+ * socket_create hook (BPF_LSM_CGROUP, kernel >= 6.0 with the bpf LSM active); ctx are the hook's
+ * arguments (family, type, protocol, kern). kern = 1 is the kernel's own socket: never touched. */
+SEC("cgroup/lsm_socket_create") int np_bt_socket(unsigned long long *ctx) {
+ int family = (int)ctx[0];
+ int kern = (int)ctx[3];
+ if (family != AF_BLUETOOTH || kern) return 1;
+ np_u32 zero = 0;
+ NpCfg *cfg = bpf_map_lookup_elem(&np_cfg, &zero);
+ if (!cfg || !cfg->on) return 1;
+ np_u64 cgid = 0;
+ NpApp *app = find_dev_app(cfg, &cgid);
+ if (!app || !(app->flags & NP_R_NO_BLUETOOTH)) return 1;
+ report_dev(cgid, NP_D_BT, 0, 0, NP_R_NO_BLUETOOTH);
+ return 0;
+}
diff --git a/server/src/netperm/np_shared.h b/server/src/netperm/np_shared.h
index 912e438..9997cf6 100644
--- a/server/src/netperm/np_shared.h
+++ b/server/src/netperm/np_shared.h
@@ -15,6 +15,13 @@
* np_seen LRU NpSeenKey → u64 ns to report only new connections
* np_counts HASH cgroup id → NpCount allowed / denied
* np_events RINGBUF NpEvent towards lord-netperm
+ * np_exempt HASH cgroup id (u64) → u32 the user's audio services (PipeWire,
+ * WirePlumber) under user@<uid>: the device and
+ * Bluetooth union doesn't apply to them
+ *
+ * Besides the network, the same per-app policy carries three device restrictions (docs/FIREWALL.md,
+ * "Linux apps"): "no camera" and "no USB" (cgroup/dev, by device major) and "no Bluetooth"
+ * (socket(AF_BLUETOOTH), cgroup/lsm_socket_create).
*/
#ifndef LORD_NP_SHARED_H
#define LORD_NP_SHARED_H
@@ -48,9 +55,22 @@ typedef uint64_t np_u64;
#define NP_R_NO_LAN (1u << 1)
#define NP_R_NO_NETWORK (1u << 2)
#define NP_R_NO_INCOMING (1u << 3)
+#define NP_R_NO_CAMERA (1u << 4)
+#define NP_R_NO_USB (1u << 7)
+#define NP_R_NO_BLUETOOTH (1u << 8)
+#define NP_R_NET_MASK (NP_R_NO_INTERNET | NP_R_NO_LAN | NP_R_NO_NETWORK | NP_R_NO_INCOMING)
+#define NP_R_DEV_MASK (NP_R_NO_CAMERA | NP_R_NO_USB | NP_R_NO_BLUETOOTH)
+
+/* Character device majors (Documentation/admin-guide/devices.txt; hidraw is dynamic and comes
+ * from /proc/devices, in NpCfg). */
+#define NP_MAJOR_V4L 81 /* /dev/video*, /dev/v4l-subdev*, /dev/radio*, /dev/vbi* */
+#define NP_MAJOR_TTYACM 166 /* USB modems and boards (/dev/ttyACM*) */
+#define NP_MAJOR_TTYUSB 188 /* USB serial adapters (/dev/ttyUSB*) */
+#define NP_MAJOR_USBDEV 189 /* raw USB devices (/dev/bus/usb/BBB/DDD, libusb) */
+#define NP_DEV_CHAR 2 /* BPF_DEVCG_DEV_CHAR */
enum { NP_P_ANY = 0, NP_P_TCP = 1, NP_P_UDP = 2, NP_P_OTHER = 3 }; /* like FwProto (+ other) */
-enum { NP_D_OUT = 0, NP_D_IN = 1 };
+enum { NP_D_OUT = 0, NP_D_IN = 1, NP_D_DEV = 2, NP_D_BT = 3 }; /* events: DEV = a device open, BT = a Bluetooth socket */
enum { NP_V_ALLOW = 0, NP_V_DENY = 1 };
enum { NP_K_RULE = 0, NP_K_ANY = 1, NP_K_LAN = 2, NP_K_INET = 3 }; /* NpEnt.kind */
enum { NP_M_SILENT = 0, NP_M_OFF = 2 }; /* "ask" is treated as silent */
@@ -88,6 +108,7 @@ typedef struct {
np_u32 level; /* depth of the apps' scopes (bpf_get_current_ancestor_cgroup_id) */
np_u32 on; /* 0: everything is allowed without looking at anything */
np_u32 user_level; /* depth of user@<uid>.service; 0: don't look at the user@ union */
+ np_u32 hidraw_major; /* /dev/hidraw* (dynamic major), 0 if the kernel has none */
} NpCfg;
typedef struct {
@@ -115,6 +136,17 @@ typedef struct {
np_u32 rule_id, flag;
} NpRes;
+/* Which restriction covers opening a character device (cgroup/dev): NP_R_NO_CAMERA for video
+ * devices, NP_R_NO_USB for raw USB, hidraw and USB serial; 0 for everything else (always
+ * allowed: the program only takes away what the user restricted). */
+NP_INLINE np_u32 np_dev_restriction(np_u32 type, np_u32 major, np_u32 hidraw_major) {
+ if (type != NP_DEV_CHAR) return 0;
+ if (major == NP_MAJOR_V4L) return NP_R_NO_CAMERA;
+ if (major == NP_MAJOR_USBDEV || major == NP_MAJOR_TTYACM || major == NP_MAJOR_TTYUSB) return NP_R_NO_USB;
+ if (hidraw_major && major == hidraw_major) return NP_R_NO_USB;
+ return 0;
+}
+
/* LAN, same as fw_addr_is_lan (addresses are in network order). */
NP_INLINE int np_is_lan4(const np_u8 *a) {
np_u8 b0 = a[0], b1 = a[1];
diff --git a/server/src/netperm/npcompile.c b/server/src/netperm/npcompile.c
index 3aaf1f3..4bd2bdb 100644
--- a/server/src/netperm/npcompile.c
+++ b/server/src/netperm/npcompile.c
@@ -191,7 +191,12 @@ int np_compile_app(FwStore *s, const char *app, uint32_t idx, DnsMap *names, con
if (load_rules(s, app, &R)) return -1;
NpApp *a = &out->app;
a->idx = idx;
- a->flags = fw_restricted(s, app) & (NP_R_NO_INTERNET | NP_R_NO_LAN | NP_R_NO_NETWORK | NP_R_NO_INCOMING);
+ /* network, and for apps outside lord-server also the device ones (camera, USB, Bluetooth).
+ * "lordos" is lord-server itself: it opens the camera and the FIDO key for the apps after
+ * their permission and restriction checks (js_media.c, the broker), so the kernel doesn't
+ * take its devices away. */
+ uint32_t keep = NP_R_NET_MASK | (strcmp(app, "lordos") ? NP_R_DEV_MASK : 0);
+ a->flags = fw_restricted(s, app) & keep;
a->trusted = (np_u8)(fw_is_trusted(s, app) != 0);
a->mode = fw_mode(s) == FW_MODE_OFF ? NP_M_OFF : NP_M_SILENT;
diff --git a/server/src/netperm/npload.h b/server/src/netperm/npload.h
new file mode 100644
index 0000000..3a358ee
--- /dev/null
+++ b/server/src/netperm/npload.h
@@ -0,0 +1,52 @@
+/* npload.h — what lord-netperm loads into the kernel: its maps and which kind of program each
+ * section of np.bpf.c is. Shared by netperm.c and tests/npverify_test.c (which loads every
+ * program into the running kernel, so the verifier checks exactly what the service loads). */
+#ifndef LORD_NP_LOAD_H
+#define LORD_NP_LOAD_H
+
+#include <linux/bpf.h>
+#include <stdint.h>
+
+#include "netperm/np_shared.h"
+
+#define NP_MAX_SESS 64
+
+/* name, type, key size, value size, max entries, flags */
+#define NP_MAPS(X) \
+ X(np_cfg, BPF_MAP_TYPE_ARRAY, 4, sizeof(NpCfg), 1, 0) \
+ X(np_apps, BPF_MAP_TYPE_HASH, 8, sizeof(NpApp), NP_MAX_APPS, 0) \
+ X(np_union, BPF_MAP_TYPE_HASH, 8, sizeof(NpApp), NP_MAX_SESS, 0) \
+ X(np_lpm4, BPF_MAP_TYPE_LPM_TRIE, sizeof(NpLpm4Key), sizeof(NpList), NP_MAX_LPM, BPF_F_NO_PREALLOC) \
+ X(np_lpm6, BPF_MAP_TYPE_LPM_TRIE, sizeof(NpLpm6Key), sizeof(NpList), NP_MAX_LPM, BPF_F_NO_PREALLOC) \
+ X(np_seen, BPF_MAP_TYPE_LRU_HASH, sizeof(NpSeenKey), 8, NP_MAX_SEEN, 0) \
+ X(np_counts, BPF_MAP_TYPE_HASH, 8, sizeof(NpCount), NP_MAX_APPS, 0) \
+ X(np_events, BPF_MAP_TYPE_RINGBUF, 0, 0, NP_RINGBUF, 0) \
+ X(np_exempt, BPF_MAP_TYPE_HASH, 8, 4, NP_MAX_SESS * 8, 0)
+
+/* Each program: its section, kind and attach point. btf: the kernel function an LSM program
+ * hooks (its id comes from /sys/kernel/btf/vmlinux). opt: 1 = the device and Bluetooth
+ * programs; if the kernel refuses one (no bpf LSM, an old kernel) the network ones still work. */
+typedef struct {
+ const char *sec;
+ uint32_t type, attach;
+ const char *btf;
+ int opt;
+} NpProgSpec;
+
+static const NpProgSpec np_prog_specs[] = {
+ { "cgroup/connect4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, NULL, 0 },
+ { "cgroup/connect6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, NULL, 0 },
+ { "cgroup/sendmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, NULL, 0 },
+ { "cgroup/sendmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, NULL, 0 },
+ { "cgroup/bind4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, NULL, 0 },
+ { "cgroup/bind6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, NULL, 0 },
+ { "cgroup/sock_create", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, NULL, 0 },
+ { "cgroup/dev", BPF_PROG_TYPE_CGROUP_DEVICE, BPF_CGROUP_DEVICE, NULL, 1 },
+ { "cgroup/lsm_socket_create", BPF_PROG_TYPE_LSM, BPF_LSM_CGROUP, "bpf_lsm_socket_create", 1 },
+};
+#define NP_NSPECS (int)(sizeof np_prog_specs / sizeof np_prog_specs[0])
+
+/* The license the kernel sees: LSM programs must declare a GPL-compatible one (see bpfsys.h). */
+static inline const char *np_prog_license(const NpProgSpec *p) { return p->type == BPF_PROG_TYPE_LSM ? "Dual MIT/GPL" : "LordOS"; }
+
+#endif
diff --git a/server/tests/fwlinux/bluetooth.sh b/server/tests/fwlinux/bluetooth.sh
new file mode 100755
index 0000000..be2ec57
--- /dev/null
+++ b/server/tests/fwlinux/bluetooth.sh
@@ -0,0 +1,36 @@
+#!/bin/bash
+# bluetooth.sh — "no Bluetooth" for Linux apps: socket(AF_BLUETOOTH) refused by lord-netperm's
+# per-cgroup LSM program (docs/FIREWALL.md, "Linux apps"). Applies immediately to new sockets.
+# BlueZ over D-Bus is a separate path (see the documentation).
+#
+# bash server/tests/fwlinux/bluetooth.sh
+. "$(dirname "$0")/lib.sh"
+[ -S /run/lordos/netperm.sock ] || { echo "lord-netperm is not running"; exit 2; }
+APP=desktop:fwbt
+SC=$(scope fwbt)
+SOCK='
+import socket, errno
+try:
+ s = socket.socket(31, socket.SOCK_RAW, 1); s.close(); print("ok") # AF_BLUETOOTH, BTPROTO_HCI
+except OSError as e:
+ print(errno.errorcode.get(e.errno, str(e.errno)))
+'
+INET='
+import socket
+socket.socket(); socket.socket(socket.AF_UNIX); print("ok")
+'
+bt() { in_scope "$SC" python3 -c "$SOCK" 2>&1 | tail -1; }
+expect() { local want=$1 got=$2 what=$3; case "$got" in $want*) ok "$what → $got";; *) bad "$what → $got (expected $want)";; esac; }
+base=$(python3 -c "$SOCK" | tail -1) # without restriction (ok, or EAFNOSUPPORT without the module)
+echo "1. not restricted"
+restrict $APP ""
+expect "$base" "$(bt)" "socket(AF_BLUETOOTH)"
+echo "2. no-bluetooth"
+restrict $APP no-bluetooth
+expect EPERM "$(bt)" "socket(AF_BLUETOOTH)"
+expect ok "$(in_scope "$SC" python3 -c "$INET" 2>&1 | tail -1)" "inet and unix sockets still work"
+expect "$base" "$(python3 -c "$SOCK" | tail -1)" "outside the app's scope"
+echo "3. lifted"
+restrict $APP ""
+expect "$base" "$(bt)" "socket(AF_BLUETOOTH)"
+fwlinux_done
diff --git a/server/tests/fwlinux/devices.sh b/server/tests/fwlinux/devices.sh
new file mode 100755
index 0000000..fc7b0e2
--- /dev/null
+++ b/server/tests/fwlinux/devices.sh
@@ -0,0 +1,63 @@
+#!/bin/bash
+# devices.sh — "no camera" and "no USB" for Linux apps: lord-netperm's cgroup/dev program
+# (docs/FIREWALL.md, "Linux apps"). Needs a video device (v4l2loopback is enough) and
+# v4l2-ctl. Applies immediately: the next open() of an app that is already running.
+#
+# bash server/tests/fwlinux/devices.sh [/dev/videoN]
+. "$(dirname "$0")/lib.sh"
+VID=${1:-$(ls /dev/video* 2>/dev/null | head -1)}
+USB=$(find /dev/bus/usb -type c 2>/dev/null | head -1)
+[ -c "$VID" ] || { echo "no video device"; exit 2; }
+[ -S /run/lordos/netperm.sock ] || { echo "lord-netperm is not running"; exit 2; }
+APP=desktop:fwdev
+SC=$(scope fwdev)
+OPEN='
+import os, sys, errno
+try:
+ fd = os.open(sys.argv[1], os.O_RDONLY | os.O_NONBLOCK); os.close(fd); print("ok")
+except OSError as e:
+ print(errno.errorcode.get(e.errno, str(e.errno)))
+'
+op() { in_scope "$SC" python3 -c "$OPEN" "$1" 2>&1 | tail -1; }
+expect() { local want=$1 got=$2 what=$3; case "$got" in $want*) ok "$what → $got";; *) bad "$what → $got (expected $want)";; esac; }
+
+echo "1. not restricted: the camera and USB open"
+restrict $APP ""
+expect ok "$(op "$VID")" "open $VID"
+got=$(in_scope "$SC" v4l2-ctl -d "$VID" --info 2>&1 | grep -c "Driver name")
+[ "$got" = 1 ] && ok "v4l2-ctl --info works" || bad "v4l2-ctl --info failed"
+[ -n "$USB" ] && expect ok "$(op "$USB")" "open $USB"
+
+echo "2. no-camera: the video device is refused, USB still opens"
+restrict $APP no-camera
+expect EPERM "$(op "$VID")" "open $VID"
+got=$(in_scope "$SC" v4l2-ctl -d "$VID" --info 2>&1 | tail -1)
+case "$got" in *"ermission denied"*|*"not permitted"*) ok "v4l2-ctl --info refused ($got)";; *) bad "v4l2-ctl --info → $got";; esac
+[ -n "$USB" ] && expect ok "$(op "$USB")" "open $USB"
+expect ok "$(op /dev/null)" "open /dev/null (other devices stay allowed)"
+expect ok "$(op /dev/urandom)" "open /dev/urandom"
+got=$(python3 -c "$OPEN" "$VID" | tail -1)
+expect ok "$got" "the same open outside the app's scope"
+
+echo "3. no-usb: raw USB is refused, the camera opens"
+restrict $APP no-usb
+[ -n "$USB" ] && expect EPERM "$(op "$USB")" "open $USB"
+expect ok "$(op "$VID")" "open $VID"
+
+echo "4. lifted again: works at once (no restart)"
+restrict $APP ""
+expect ok "$(op "$VID")" "open $VID"
+
+echo "5. escape with systemd-run --user while the restricted app runs"
+restrict $APP no-camera
+in_scope "$SC" sleep 6 &
+sleep 1.5 # lord-netperm sees the scope and builds the union
+got=$(systemd-run --user --quiet --wait --pipe python3 -c "$OPEN" "$VID" 2>&1 | tail -1)
+expect EPERM "$got" "systemd-run --user (user@ union)"
+PWCG=/sys/fs/cgroup/user.slice/user-$U.slice/user@$U.service/session.slice/pipewire.service
+if [ -d "$PWCG" ]; then # the user's PipeWire keeps the camera for the whole session
+ got=$(sudo bash -c 'echo $$ > "$0/cgroup.procs"; exec setpriv --reuid='"$U"' --regid='"$G"' --init-groups python3 -c "$1" "$2"' "$PWCG" "$OPEN" "$VID" 2>&1 | tail -1)
+ expect ok "$got" "a process in pipewire.service (exempt from the union)"
+fi
+wait
+fwlinux_done
diff --git a/server/tests/fwlinux/lib.sh b/server/tests/fwlinux/lib.sh
new file mode 100755
index 0000000..6a9a15e
--- /dev/null
+++ b/server/tests/fwlinux/lib.sh
@@ -0,0 +1,64 @@
+# lib.sh — shared by the per-restriction end-to-end tests of Linux apps (docs/FIREWALL.md, "Linux
+# apps"). Run them in the test VM as the session user, with passwordless sudo, a LordOS session
+# (lord-sessiond) and lord-netperm running. Each script builds an app scope by hand, the way the
+# launcher's root-owned scopes look (system.slice/lordos.service/lordos-session-<uid>/
+# app-lordos-<id>.scope), writes ~/.config/lordos/firewall.json and puts it back at the end.
+set -u
+U=$(id -u)
+G=$(id -g)
+SESS=/sys/fs/cgroup/system.slice/lordos.service/lordos-session-$U
+FW=~/.config/lordos/firewall.json
+pass=0; fail=0
+ok() { pass=$((pass+1)); echo " ok: $*"; }
+bad() { fail=$((fail+1)); echo " BAD: $*"; }
+[ -d "$SESS" ] || { echo "no LordOS session for uid $U ($SESS)"; exit 2; }
+mkdir -p ~/.config/lordos
+FW_BACKUP=$(mktemp); FW_HAD=0
+[ -f "$FW" ] && { cp "$FW" "$FW_BACKUP"; FW_HAD=1; }
+SCOPES=""
+
+# scope <id>: creates app-lordos-<id>.scope (root-owned, like the real ones) and prints its path
+scope() {
+ local sc=$SESS/app-lordos-$1.scope
+ sudo mkdir -p "$sc"
+ SCOPES="$SCOPES $sc"
+ echo "$sc"
+}
+
+# netperm_reload: asks lord-netperm to reread firewall.json (the only message it takes)
+netperm_reload() {
+ [ -S /run/lordos/netperm.sock ] || return 0
+ python3 - <<'PY'
+import socket, struct, time
+s = socket.socket(socket.AF_UNIX); s.connect('/run/lordos/netperm.sock')
+s.sendall(struct.pack('<IB', 1, 1)); time.sleep(0.4); s.close()
+PY
+}
+
+# restrict <app> <flag,flag...>: only that app restricted ("" = nothing restricted)
+restrict() {
+ local app=$1 flags=$2 list=""
+ [ -n "$flags" ] && list=$(echo "$flags" | sed 's/[^,][^,]*/"&"/g')
+ if [ -n "$flags" ]; then
+ echo '{"v":1,"mode":"silent","trusted":[],"restricted":{"'"$app"'":['"$list"']},"rules":[]}' > "$FW"
+ else
+ echo '{"v":1,"mode":"silent","trusted":[],"restricted":{},"rules":[]}' > "$FW"
+ fi
+ netperm_reload
+}
+
+# in_scope <scope dir> <command...>: runs the command as the user inside the scope
+in_scope() {
+ local sc=$1; shift
+ sudo env XDG_RUNTIME_DIR=/run/user/$U DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$U/bus HOME="$HOME" \
+ bash -c 'echo $$ > "$0/cgroup.procs"; exec setpriv --reuid='"$U"' --regid='"$G"' --init-groups "$@"' "$sc" "$@"
+}
+
+fwlinux_done() {
+ if [ $FW_HAD = 1 ]; then cp "$FW_BACKUP" "$FW"; else rm -f "$FW"; fi
+ netperm_reload
+ rm -f "$FW_BACKUP"
+ for sc in $SCOPES; do sudo rmdir "$sc" 2>/dev/null; done
+ echo "$(basename "$0" .sh): $pass passed, $fail failed"
+ [ $fail = 0 ]
+}
diff --git a/server/tests/npcompile_test.c b/server/tests/npcompile_test.c
index ae142ba..61f2bdc 100644
--- a/server/tests/npcompile_test.c
+++ b/server/tests/npcompile_test.c
@@ -416,7 +416,45 @@ static void bench(void) {
fw_store_free(s);
}
+/* The device and Bluetooth restrictions (cgroup/dev, cgroup/lsm_socket_create): which majors each
+ * one covers, that they reach the compiled policy of Linux apps but never lord-server's own
+ * ("lordos"), and that they don't change any network decision. */
+static void device_cases(void) {
+ const uint32_t HID = 242;
+ CHECK(np_dev_restriction(NP_DEV_CHAR, 81, HID) == NP_R_NO_CAMERA); /* /dev/video* */
+ CHECK(np_dev_restriction(NP_DEV_CHAR, 189, HID) == NP_R_NO_USB); /* /dev/bus/usb */
+ CHECK(np_dev_restriction(NP_DEV_CHAR, 166, HID) == NP_R_NO_USB); /* ttyACM */
+ CHECK(np_dev_restriction(NP_DEV_CHAR, 188, HID) == NP_R_NO_USB); /* ttyUSB */
+ CHECK(np_dev_restriction(NP_DEV_CHAR, HID, HID) == NP_R_NO_USB); /* hidraw */
+ CHECK(np_dev_restriction(NP_DEV_CHAR, HID, 0) == 0); /* no hidraw in the kernel */
+ CHECK(np_dev_restriction(1, 81, HID) == 0); /* a block device 81: not a camera */
+ static const uint32_t free_majors[] = { 1, 4, 5, 10, 13, 116, 226, 180, 246, 0 }; /* mem, tty, misc, input, sound, dri... */
+ for (int i = 0; free_majors[i]; i++) CHECK(np_dev_restriction(NP_DEV_CHAR, free_majors[i], HID) == 0);
+ /* the FW_R_* bits are the same */
+ CHECK(NP_R_NO_CAMERA == FW_R_NO_CAMERA && NP_R_NO_USB == FW_R_NO_USB && NP_R_NO_BLUETOOTH == FW_R_NO_BLUETOOTH);
+
+ FwStore *s = fw_store_new();
+ DnsMap *names = dnsmap_new(0);
+ fw_set_restricted(s, "desktop:cam", FW_R_NO_CAMERA | FW_R_NO_USB | FW_R_NO_BLUETOOTH | FW_R_NO_FILES | FW_R_NO_MIC);
+ fw_set_restricted(s, "lordos", FW_R_NO_CAMERA | FW_R_NO_USB | FW_R_NO_BLUETOOTH | FW_R_NO_INTERNET);
+ NpCompiled c = compile(s, "desktop:cam", names, 1000);
+ CHECK(c.app.flags == (NP_R_NO_CAMERA | NP_R_NO_USB | NP_R_NO_BLUETOOTH)); /* files/mic aren't the kernel's */
+ uint8_t a[16];
+ FwDecision ref;
+ NpRes got;
+ int fam = ip("203.0.113.10", a);
+ CHECK(same(s, names, &c, "desktop:cam", FW_OUT, FW_PROTO_TCP, fam, a, 443, 1000, &ref, &got));
+ CHECK(got.verdict == NP_V_ALLOW); /* the network is untouched */
+ np_compiled_free(&c);
+ c = compile(s, "lordos", names, 1000);
+ CHECK(c.app.flags == NP_R_NO_INTERNET); /* lord-server keeps its devices */
+ np_compiled_free(&c);
+ fw_store_free(s);
+ dnsmap_free(names);
+}
+
int main(void) {
+ device_cases();
fixed_cases();
dns_sources();
int diffs = 0, queries = 0;
diff --git a/server/tests/npverify_test.c b/server/tests/npverify_test.c
new file mode 100644
index 0000000..09c4a86
--- /dev/null
+++ b/server/tests/npverify_test.c
@@ -0,0 +1,116 @@
+/* npverify_test.c — lord-netperm's BPF programs against the real kernel verifier, and the BTF
+ * reader (src/netperm/bpfsys.c) it uses to find the LSM hook.
+ *
+ * build/npverify-test (in `make test`; as root it also loads every program)
+ *
+ * Without root: only the BTF reader, on blobs built here (good, truncated, unknown kind). As root
+ * (sudo, in the test VM): creates the same maps as lord-netperm (npload.h), loads every program
+ * of build/gen/np_bpf.h with the kind and attach point the service uses, and fails with the
+ * verifier's log if the kernel refuses one; then finds bpf_lsm_socket_create in the running
+ * kernel's BTF. Nothing is attached: no cgroup, process or device is touched. */
+#include "netperm/bpfsys.h"
+#include "netperm/npload.h"
+#include "np_bpf.h"
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+static int fails, checks;
+#define CHECK(c) do { checks++; if (!(c)) { fails++; fprintf(stderr, "%s:%d: failed: %s\n", __FILE__, __LINE__, #c); } } while (0)
+
+/* ---- a small BTF blob: INT "int", FUNC_PROTO, FUNC "my_hook", STRUCT with one member ---- */
+static size_t put32(unsigned char *b, size_t o, uint32_t v) { memcpy(b + o, &v, 4); return o + 4; }
+
+static size_t make_btf(unsigned char *b, int bad_kind, int truncate) {
+ static const char strs[] = "\0int\0my_hook\0s\0m"; /* offsets: int=1 my_hook=5 s=13 m=15 */
+ unsigned char t[256];
+ size_t o = 0;
+ o = put32(t, o, 1); o = put32(t, o, 1u << 24); o = put32(t, o, 4); o = put32(t, o, 32); /* [1] INT int */
+ o = put32(t, o, 0); o = put32(t, o, 13u << 24 | 1); o = put32(t, o, 1); o = put32(t, o, 0); o = put32(t, o, 1); /* [2] FUNC_PROTO (int) */
+ o = put32(t, o, 13); o = put32(t, o, 4u << 24 | 1); o = put32(t, o, 4); /* [3] STRUCT s { int m; } */
+ o = put32(t, o, 15); o = put32(t, o, 1); o = put32(t, o, 0);
+ if (bad_kind) { o = put32(t, o, 0); o = put32(t, o, 30u << 24); o = put32(t, o, 0); } /* an unknown kind */
+ o = put32(t, o, 5); o = put32(t, o, 12u << 24); o = put32(t, o, 2); /* FUNC my_hook */
+ size_t n = 0;
+ b[n++] = 0x9f; b[n++] = 0xeb; b[n++] = 1; b[n++] = 0;
+ n = put32(b, n, 24); n = put32(b, n, 0); n = put32(b, n, (uint32_t)o); n = put32(b, n, (uint32_t)o); n = put32(b, n, sizeof strs);
+ memcpy(b + n, t, o); n += o;
+ memcpy(b + n, strs, sizeof strs); n += sizeof strs;
+ return truncate ? n - 20 : n;
+}
+
+static uint32_t btf_lookup(const unsigned char *b, size_t n, const char *name) {
+ char path[] = "/tmp/npverify-btf-XXXXXX";
+ int fd = mkstemp(path);
+ if (fd < 0) return 0;
+ if (write(fd, b, n) != (ssize_t)n) { close(fd); unlink(path); return 0; }
+ close(fd);
+ uint32_t id = bpfs_btf_func_id(path, name);
+ unlink(path);
+ return id;
+}
+
+static void btf_reader(void) {
+ unsigned char b[512];
+ size_t n = make_btf(b, 0, 0);
+ CHECK(btf_lookup(b, n, "my_hook") == 4); /* ids start at 1: the FUNC is the 4th type */
+ CHECK(btf_lookup(b, n, "int") == 0); /* an INT, not a function */
+ CHECK(btf_lookup(b, n, "my_hoo") == 0);
+ CHECK(btf_lookup(b, n, "my_hook_x") == 0);
+ n = make_btf(b, 1, 0);
+ CHECK(btf_lookup(b, n, "my_hook") == 0); /* unknown kind before it: gives up */
+ n = make_btf(b, 0, 1);
+ CHECK(btf_lookup(b, n, "my_hook") == 0); /* sections past the end of the file */
+ n = make_btf(b, 0, 0);
+ b[1] = 0x12;
+ CHECK(btf_lookup(b, n, "my_hook") == 0); /* bad magic */
+ CHECK(bpfs_btf_func_id("/nonexistent/btf", "my_hook") == 0);
+}
+
+/* ---- the kernel verifier ---- */
+static int maps[16];
+static const char *map_names[16];
+static int nmaps;
+static int map_fd(const char *name) {
+ for (int i = 0; i < nmaps; i++) if (!strcmp(map_names[i], name)) return maps[i];
+ return -1;
+}
+
+static void kernel_verifier(void) {
+#define NP_MKMAP(n, t, k, v, m, f) map_names[nmaps] = #n; maps[nmaps] = bpfs_map_create(t, k, v, m, f, #n); CHECK(maps[nmaps] >= 0); nmaps++;
+ NP_MAPS(NP_MKMAP)
+#undef NP_MKMAP
+ static char log[1 << 20];
+ CHECK(NP_NPROGS == NP_NSPECS); /* np.bpf.c and the table agree */
+ for (int w = 0; w < NP_NSPECS; w++) {
+ const NpProgSpec *p = &np_prog_specs[w];
+ const NpProgDesc *d = NULL;
+ for (int i = 0; i < NP_NPROGS; i++) if (!strcmp(np_progs[i].section, p->sec)) d = &np_progs[i];
+ CHECK(d != NULL);
+ if (!d) continue;
+ uint32_t btf = 0;
+ if (p->btf) {
+ btf = bpfs_btf_func_id(NULL, p->btf);
+ CHECK(btf != 0);
+ if (!btf) { fprintf(stderr, " %s: %s is not in the kernel's BTF\n", p->sec, p->btf); continue; }
+ }
+ int fd = bpfs_prog_load_btf(p->type, p->attach, btf, np_prog_license(p), d, map_fd, log, sizeof log);
+ if (fd < 0) {
+ size_t ll = strlen(log);
+ fprintf(stderr, " %s refused (%s):\n%s\n", p->sec, strerror(errno), ll > 4000 ? log + ll - 4000 : log);
+ } else printf("npverify-test: %-28s verified (%u instructions)\n", p->sec, d->ninsns);
+ CHECK(fd >= 0);
+ if (fd >= 0) close(fd);
+ }
+}
+
+int main(void) {
+ btf_reader();
+ if (geteuid() == 0) kernel_verifier();
+ else printf("npverify-test: kernel verifier skipped: needs root (sudo build/npverify-test)\n");
+ printf("npverify-test: %d/%d passed\n", checks - fails, checks);
+ return fails ? 1 : 0;
+}