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
Firewall: one destination's verdict in the SDK, checked against fw_decide
Federico Pereira1433c7d27438
diff --git a/sdk/fwrule.js b/sdk/fwrule.jsindex cb7907d..6c833bb 100644--- a/sdk/fwrule.js+++ b/sdk/fwrule.js@@ -222,3 +222,96 @@ export function comparePrecedence(a, b) {(b.action === 'deny' ? 1 : 0) - (a.action === 'deny' ? 1 : 0) || (b.id || 0) - (a.id || 0);}export const sortByPrecedence = (rules) => [...rules].sort(comparePrecedence);++// ---- one destination's verdict (the Monitor's per-domain switch, 0.8.2) --------------------------+// The same decision fw_decide makes for one connection of an app (rules.c, docs/FIREWALL.md+// "Precedence"), over that app's rules as lord.fw.rules(app) lists them: the restrictions first,+// then the most specific matching rule. Without a rule the mode decides (null here: allowed in the+// silent and off modes). server/tests/fw_domain_cases.txt is run through both this and fw_decide+// (build/fwdest-test and fwrule_input_test.mjs), so the Monitor shows what the kernel will do.+//+// decide(rules, { names: ['api.example.com'], addr: '93.184.216.34', proto: 'tcp', port: 443 },+// ['no-lan']) → { action: 'allow' | 'deny', rule, by: 'rule' | 'restricted' } | null++function addrBytes(a) {+ const c = typeof a === 'string' && a ? parseCidr(a) : null;+ if (!c || !c.ok || c.kind !== 'address') return null;+ return { fam: c.fam, b: c.fam === 4 ? parseV4(c.dst) : parseV6(c.dst) };+}++export function isLan(a) {+ const x = addrBytes(a);+ if (!x) return false;+ const b = x.b;+ if (x.fam === 4) {+ return b[0] === 0 || b[0] === 10 || b[0] === 127 || (b[0] === 100 && (b[1] & 0xc0) === 64) || (b[0] === 169 && b[1] === 254) ||+ (b[0] === 172 && (b[1] & 0xf0) === 16) || (b[0] === 192 && b[1] === 168) || (b[0] & 0xf0) === 224 || b.every((v) => v === 255);+ }+ if (b.slice(0, 15).every((v) => v === 0) && (b[15] === 0 || b[15] === 1)) return true;+ return (b[0] & 0xfe) === 0xfc || (b[0] === 0xfe && (b[1] & 0xc0) === 0x80) || b[0] === 0xff;+}++function cidrHas(rule, x) {+ const c = parseCidr(rule);+ if (!c.ok || !x || c.fam !== x.fam) return false;+ const net = c.fam === 4 ? parseV4(c.dst.split('/')[0]) : parseV6(c.dst.split('/')[0]);+ for (let i = 0; i < c.prefix; i++) if (bitAt(net, i) !== bitAt(x.b, i)) return false;+ return true;+}++function destMatches(r, names, a, lan) {+ const d = parseDest(r.dst);+ if (!d.ok) return false;+ switch (d.kind) {+ case 'any': return true;+ case 'lan': return !!a && lan; // an unknown address is neither (rules.c)+ case 'internet': return !!a && !lan;+ case 'domain': return names.includes(d.domain);+ case 'wildcard': return names.some((n) => n === d.domain || n.endsWith(`.${d.domain}`));+ default: return cidrHas(r.dst, a);+ }+}++export function decide(rules, { names = [], addr = '', proto = 'tcp', port = 0, dir = 'out' } = {}, restricted = []) {+ const a = addrBytes(addr);+ const lan = a ? isLan(addr) : false;+ const has = (f) => restricted.includes(f);+ if (has('no-network') || (dir === 'in' && has('no-incoming')) || (has('no-internet') && !lan) || (has('no-lan') && lan)) {+ return { action: 'deny', rule: null, by: 'restricted' };+ }+ const ns = names.map((n) => normDomain(n)).filter(Boolean);+ const hits = (rules || []).filter((r) => {+ if ((r.dir || 'out') !== dir) return false;+ if (r.proto && r.proto !== proto) return false;+ const p = parsePort(r.port || '');+ if (!p.ok || (p.port && (port < p.lo || port > p.hi))) return false;+ return destMatches(r, ns, a, lan);+ });+ if (!hits.length) return null;+ // as rules.c weighs them: an exact name also counts its labels (a CNAME chain's longest name wins)+ const spec = (r) => { const d = parseDest(r.dst); return d.ok && d.kind === 'domain' ? SC_EXACT + d.domain.split('.').length : specificity(r); };+ const best = [...hits].sort((x, y) => spec(y) - spec(x) || comparePrecedence(x, y))[0];+ return { action: best.action, rule: best, by: 'rule' };+}++// What one click on a destination's switch does: the rule for exactly that name (or address), any+// port and protocol, set to the other verdict; if dropping that rule already gives the other+// verdict, it is removed instead of piling up rules (like the Monitor's per-app switch).+// → { op: 'add', rule } | { op: 'update', id, rule } | { op: 'remove', id } | null+export function toggleOp(rules, { name, addr, proto = 'tcp', port = 0 }, restricted = []) {+ const q = { names: name ? [name] : [], addr, proto, port };+ const now = decide(rules, q, restricted);+ if (now?.by === 'restricted') return null;+ const allowedNow = now ? now.action === 'allow' : true; // no rule: the mode ("ask" is applied as silent)+ const target = allowedNow ? 'deny' : 'allow';+ const dst = name ? normDomain(name) : parseDest(addr).ok ? parseDest(addr).dst : null;+ if (!dst) return null;+ const own = (rules || []).find((r) => (r.dir || 'out') === 'out' && r.dst === dst && !r.port && !r.proto);+ if (own) {+ const without = decide(rules.filter((r) => r !== own), q, restricted);+ const allowedWithout = without ? without.action === 'allow' : true;+ if ((allowedWithout ? 'allow' : 'deny') === target) return { op: 'remove', id: own.id };+ return { op: 'update', id: own.id, rule: { dir: 'out', dst, port: '', proto: '', action: target } };+ }+ return { op: 'add', rule: { dir: 'out', dst, port: '', proto: '', action: target } };+}diff --git a/server/tests/fw_domain_cases.txt b/server/tests/fw_domain_cases.txtnew file mode 100644index 0000000..aadb689--- /dev/null+++ b/server/tests/fw_domain_cases.txt@@ -0,0 +1,41 @@+# One destination's verdict, as the Monitor's per-domain switch shows it (sdk/fwrule.js decide) and+# as the store decides it (fw_decide). Checked by build/fwdest-test (C, also after a JSON round trip+# through the firewall.json text) and by tests/fwrule_input_test.mjs (JS).+# rules (action dst [port] [proto]; ... or -) | names (comma-separated or -) | address | proto port | restrictions (comma-separated or -) | expected: allow | deny | none (no rule: the mode) | restricted+- | example.com | 93.184.216.34 | tcp 443 | - | none+deny example.com | example.com | 93.184.216.34 | tcp 443 | - | deny+deny example.com | www.example.com | 93.184.216.34 | tcp 443 | - | none+deny *.example.com | www.example.com | 93.184.216.34 | tcp 443 | - | deny+deny *.example.com | example.com | 93.184.216.34 | tcp 443 | - | deny+deny *.example.com | otherexample.com | 93.184.216.34 | tcp 443 | - | none+deny *.example.com; allow api.example.com | api.example.com | 93.184.216.34 | tcp 443 | - | allow+deny *.example.com; allow api.example.com | www.example.com | 93.184.216.34 | tcp 443 | - | deny+deny any; allow api.example.com | api.example.com | 93.184.216.34 | udp 443 | - | allow+deny any; allow api.example.com | www.example.com | 93.184.216.34 | udp 443 | - | deny+allow *.example.com; deny *.cdn.example.com | a.cdn.example.com | 203.0.113.9 | tcp 443 | - | deny+allow *.cdn.example.com; deny *.example.com | a.cdn.example.com | 203.0.113.9 | tcp 443 | - | allow+allow example.com; deny example.com | example.com | 93.184.216.34 | tcp 443 | - | deny+deny 93.184.216.0/24 | example.com | 93.184.216.34 | tcp 443 | - | deny+deny 93.184.216.0/24; allow example.com | example.com | 93.184.216.34 | tcp 443 | - | allow+deny 93.184.216.34; allow 93.184.216.0/24 | - | 93.184.216.34 | tcp 443 | - | deny+allow 93.184.216.34; deny 93.184.216.0/24 | - | 93.184.216.34 | tcp 443 | - | allow+deny example.com 80 | example.com | 93.184.216.34 | tcp 443 | - | none+deny example.com 443 tcp; allow example.com | example.com | 93.184.216.34 | tcp 443 | - | deny+deny example.com 443 tcp | example.com | 93.184.216.34 | udp 443 | - | none+deny example.com 8000-8080 | example.com | 93.184.216.34 | tcp 8080 | - | deny+deny internet | example.com | 93.184.216.34 | tcp 443 | - | deny+deny internet | printer.local | 192.168.1.20 | tcp 631 | - | none+deny lan | printer.local | 192.168.1.20 | tcp 631 | - | deny+deny lan; allow 192.168.1.20 | printer.local | 192.168.1.20 | tcp 631 | - | allow+deny internet; allow *.debian.org | deb.debian.org | 151.101.2.132 | tcp 443 | - | allow+- | example.com | 93.184.216.34 | tcp 443 | no-internet | restricted+allow example.com | example.com | 93.184.216.34 | tcp 443 | no-internet | restricted+- | printer.local | 192.168.1.20 | tcp 631 | no-internet | none+- | printer.local | 192.168.1.20 | tcp 631 | no-lan | restricted+- | example.com | 93.184.216.34 | tcp 443 | no-network | restricted+deny 2001:db8::/32 | v6.example.com | 2001:db8::7 | tcp 443 | - | deny+allow 2001:db8::7; deny 2001:db8::/32 | v6.example.com | 2001:db8::7 | tcp 443 | - | allow+deny lan | - | fd00::1 | udp 53 | - | deny+deny *.Example.COM. | WWW.example.com | 93.184.216.34 | tcp 443 | - | deny+deny a.example.com | b.example.com,a.example.com | 93.184.216.34 | tcp 443 | - | deny+deny example.com; allow www.example.com | www.example.com,example.com | 93.184.216.34 | tcp 443 | - | allowdiff --git a/server/tests/fwdest_test.c b/server/tests/fwdest_test.cindex ed53abb..0c926a0 100644--- a/server/tests/fwdest_test.c+++ b/server/tests/fwdest_test.c@@ -3,11 +3,108 @@* text. The same file is checked against the Settings sheet's parser (sdk/fwrule.js) by* tests/fwrule_input_test.mjs, so what the sheet accepts is what lord.fw.addRule stores.*+ * It also runs tests/fw_domain_cases.txt (0.8.2): one destination's verdict through fw_decide, as the+ * Monitor's per-domain switch shows it with sdk/fwrule.js decide(), once from the store and once after+ * a round trip through the firewall.json text (fw_to_json → fw_from_json), the file lord-netperm reads.+ ** build/fwdest-test [cases file] (default: tests/fw_dest_cases.txt, run from server/) */#include "../src/fw/rules.h"#include <stdio.h>+#include <stdlib.h>#include <string.h>+#include <arpa/inet.h>++static char *trim(char *s) {+ while (*s == ' ') s++;+ char *e = s + strlen(s);+ while (e > s && e[-1] == ' ') *--e = 0;+ return s;+}++static const char *verdict(FwStore *st, const char *app, char *names, const char *addr, const char *proto, int port) {+ const char *hosts[8];+ int nh = 0;+ char buf[512];+ snprintf(buf, sizeof buf, "%s", names);+ if (strcmp(buf, "-")) for (char *t = strtok(buf, ","); t && nh < 8; t = strtok(NULL, ",")) hosts[nh++] = t;+ FwQuery q;+ memset(&q, 0, sizeof q);+ q.app = app;+ q.dir = FW_OUT;+ q.proto = !strcmp(proto, "udp") ? FW_PROTO_UDP : FW_PROTO_TCP;+ q.port = (uint16_t)port;+ if (strcmp(addr, "-")) {+ if (inet_pton(AF_INET, addr, q.addr) == 1) q.fam = 4;+ else if (inet_pton(AF_INET6, addr, q.addr) == 1) q.fam = 6;+ }+ q.hosts = hosts;+ q.nhosts = nh;+ FwDecision d = fw_decide(st, &q);+ return d.reason == FW_BY_RESTRICTED ? "restricted" : d.reason == FW_BY_RULE ? (d.verdict == FW_V_DENY ? "deny" : "allow") : "none";+}++static int domain_cases(const char *path) {+ FILE *f = fopen(path, "r");+ if (!f) { perror(path); return 1; }+ char line[1024];+ int n = 0, bad = 0;+ const char *app = "desktop:t";+ while (fgets(line, sizeof line, f)) {+ line[strcspn(line, "\r\n")] = 0;+ if (!line[0] || line[0] == '#') continue;+ char *col[6];+ int k = 0;+ for (char *p = line, *bar; k < 6; p = bar + 1) {+ bar = strchr(p, '|');+ if (bar) *bar = 0;+ col[k++] = trim(p);+ if (!bar) break;+ }+ if (k != 6) { fprintf(stderr, "malformed line\n"); bad++; continue; }+ FwStore *st = fw_store_new();+ if (strcmp(col[0], "-")) {+ for (char *r = strtok(col[0], ";"); r; r = strtok(NULL, ";")) {+ char act[16] = "", dst[300] = "", port[32] = "", proto[8] = "";+ sscanf(r, "%15s %299s %31s %7s", act, dst, port, proto);+ if (!strcmp(port, "tcp") || !strcmp(port, "udp")) { snprintf(proto, sizeof proto, "%s", port); port[0] = 0; }+ FwRule rule;+ memset(&rule, 0, sizeof rule);+ snprintf(rule.app, sizeof rule.app, "%s", app);+ rule.dir = FW_OUT;+ rule.action = !strcmp(act, "deny") ? FW_DENY : FW_ALLOW;+ rule.life = FW_LIFE_FOREVER;+ rule.port_lo = 0;+ rule.port_hi = 65535;+ if (port[0]) { unsigned lo = 0, hi = 0; if (sscanf(port, "%u-%u", &lo, &hi) < 2) hi = lo; rule.port_lo = (uint16_t)lo; rule.port_hi = (uint16_t)hi; }+ rule.proto = !strcmp(proto, "tcp") ? FW_PROTO_TCP : !strcmp(proto, "udp") ? FW_PROTO_UDP : FW_PROTO_ANY;+ if (fw_parse_dest(dst, &rule) || fw_rule_add(st, &rule, NULL)) { fprintf(stderr, "bad rule %s\n", r); bad++; }+ }+ }+ if (strcmp(col[4], "-")) {+ uint32_t fl = 0;+ for (char *r = strtok(col[4], ","); r; r = strtok(NULL, ",")) fl |= fw_flag_from_name(trim(r));+ fw_set_restricted(st, app, fl);+ }+ char proto[8] = "tcp";+ int port = 0;+ sscanf(col[3], "%7s %d", proto, &port);+ const char *got = verdict(st, app, col[1], col[2], proto, port);+ /* the same rules after the firewall.json text */+ size_t len = 0;+ char *j = fw_to_json(st, &len), err[120];+ FwStore *back = fw_store_new();+ const char *again = j && !fw_from_json(back, j, len, err, sizeof err) ? verdict(back, app, col[1], col[2], proto, port) : "(json failed)";+ n++;+ if (strcmp(got, col[5]) || strcmp(again, col[5])) { fprintf(stderr, "✗ domain case %d (%s | %s): want %s, got %s, after JSON %s\n", n, col[1], col[2], col[5], got, again); bad++; }+ free(j);+ fw_store_free(back);+ fw_store_free(st);+ }+ fclose(f);+ printf("fwdest-test: %d domain cases, %d failed\n", n, bad);+ return bad != 0 || n == 0;+}int main(int argc, char **argv) {const char *path = argc > 1 ? argv[1] : "tests/fw_dest_cases.txt";@@ -31,5 +128,6 @@ int main(int argc, char **argv) {}fclose(f);printf("fwdest-test: %d cases, %d failed\n", n, bad);- return bad != 0 || n == 0;+ int dom = argc > 1 ? 0 : domain_cases("tests/fw_domain_cases.txt");+ return bad != 0 || n == 0 || dom;}diff --git a/server/tests/fwrule_input_test.mjs b/server/tests/fwrule_input_test.mjsindex 95caf5b..be62c11 100644--- a/server/tests/fwrule_input_test.mjs+++ b/server/tests/fwrule_input_test.mjs@@ -10,7 +10,7 @@ import path from 'node:path';import { fileURLToPath } from 'node:url';const here = path.dirname(fileURLToPath(import.meta.url));-const { parseDest, parsePort, checkRule, sortByPrecedence, specificity, isDefaultRule } = await import(path.join(here, '../../sdk/fwrule.js'));+const { parseDest, parsePort, checkRule, sortByPrecedence, specificity, isDefaultRule, decide, toggleOp, isLan } = await import(path.join(here, '../../sdk/fwrule.js'));let n = 0, bad = 0;const eq = (name, got, want) => {@@ -82,5 +82,47 @@ const rules = [];eq('sorted', sortByPrecedence(rules).map((r) => r.id), [4, 9, 8, 7, 3, 2, 6, 5, 1]);+// 3. one destination's verdict (the Monitor's per-domain switch): the cases build/fwdest-test runs+// through fw_decide+const ruleOf = (txt, i) => {+ const [action, dst, a = '', b = ''] = txt.trim().split(/\s+/);+ const proto = a === 'tcp' || a === 'udp' ? a : b;+ const port = a === 'tcp' || a === 'udp' ? '' : a;+ const c = parseDest(dst);+ return { id: i + 1, dir: 'out', dst: c.ok ? c.dst : dst, port, proto, action };+};+let cases = 0;+for (const line of fs.readFileSync(path.join(here, 'fw_domain_cases.txt'), 'utf8').split('\n')) {+ if (!line || line[0] === '#') continue;+ const col = line.split('|').map((x) => x.trim());+ // a rule added again with the same destination, ports and protocol replaces the previous one (rules.c)+ const list = [];+ if (col[0] !== '-') col[0].split(';').forEach((r, i) => {+ const x = ruleOf(r, i);+ const same = list.findIndex((y) => y.dst === x.dst && y.port === x.port && y.proto === x.proto);+ if (same >= 0) list[same] = { ...x, id: list[same].id }; else list.push(x);+ });+ const [proto, port] = col[3].split(/\s+/);+ const names = col[1] === '-' ? [] : col[1].split(',');+ const restricted = col[4] === '-' ? [] : col[4].split(',');+ const d = decide(list, { names, addr: col[2] === '-' ? '' : col[2], proto, port: Number(port) }, restricted);+ eq(`domain case ${++cases} ${col[1]} ${col[2]}`, d ? (d.by === 'restricted' ? 'restricted' : d.action) : 'none', col[5]);+}+eq('lan', [isLan('192.168.1.2'), isLan('100.64.0.1'), isLan('8.8.8.8'), isLan('fe80::1'), isLan('2001:db8::1'), isLan('::1')], [true, true, false, true, false, true]);++// the switch: one click flips the verdict, and going back removes the rule instead of adding another+const q = { name: 'ads.example.com', addr: '93.184.216.34', proto: 'tcp', port: 443 };+eq('toggle: none → add deny', toggleOp([], q), { op: 'add', rule: { dir: 'out', dst: 'ads.example.com', port: '', proto: '', action: 'deny' } });+const one = [{ id: 7, dir: 'out', dst: 'ads.example.com', port: '', proto: '', action: 'deny' }];+eq('toggle: own deny → remove', toggleOp(one, q), { op: 'remove', id: 7 });+const blockAll = [{ id: 1, dir: 'out', dst: 'any', port: '', proto: '', action: 'deny' }];+eq('toggle: blocked by default → add allow', toggleOp(blockAll, q).rule.action, 'allow');+const both = [...blockAll, { id: 2, dir: 'out', dst: 'ads.example.com', port: '', proto: '', action: 'allow' }];+eq('toggle: own allow over deny-all → remove', toggleOp(both, q), { op: 'remove', id: 2 });+const wild = [{ id: 3, dir: 'out', dst: '*.example.com', port: '', proto: '', action: 'deny' }, { id: 4, dir: 'out', dst: 'ads.example.com', port: '', proto: '', action: 'deny' }];+eq('toggle: own deny under a deny wildcard → update to allow', toggleOp(wild, q), { op: 'update', id: 4, rule: { dir: 'out', dst: 'ads.example.com', port: '', proto: '', action: 'allow' } });+eq('toggle: no name → the address', toggleOp([], { addr: '203.0.113.5', proto: 'udp', port: 443 }).rule.dst, '203.0.113.5');+eq('toggle: restricted → nothing', toggleOp([], q, ['no-internet']), null);+console.log(`fwrule-input-test: ${n} checks, ${bad} failed`);process.exit(bad ? 1 : 0);