- Access rules fail closed: when the table cannot load, no device is loaded into the tunnels (the firewall alone would let every loaded device reach everything); an older table that survived a failed rebuild keeps its rules and a revoked device still leaves. The agent re-syncs within a minute when the table is gone - A change the router saved but could not put into effect (access rules that did not load, a server that refused its devices) is said in the admin UI instead of a plain "Saved" - The guard judges every packet, not only a connection's first: a change of access, a pause or a limit now cuts open connections too - Each server's home networks are its own: with several servers, "all home" on one no longer reaches the other's networks where firewall zones overlap - People limited to some home networks reach the router only on the addresses in those networks (LuCI and SSH on the main LAN stay closed) - Internet-only people can open their personal portal with the VPN on - Tunnel DNS reaches the resolver and the LAN's DNS from servers that do not forward to those zones on their own (Home-only names on servers without "like a home device", LAN DNS on servers with no home network) - A new personal link offers to remove the devices added through the old one, so a leaked link is really contained - Import and restore refuse an inconsistent file (devices with addresses outside their server, shared addresses, malformed keys, broken references); Health reports one, and the sync leaves such a device out instead of failing its server. A config write that did not reach flash is an error, not a silent success - Backups are kept per kind (nightly ones no longer push out manual or pre-delete ones), nightly and pre-change backups hold the config only, archives are written whole or not at all, and a failed nightly backup is logged. A restore no longer has its history overwritten by the agent's in-memory counters - Settings defaults and ranges come from one place (dawnline.schema) - Portal: anything not shaped like a personal link is answered by a shell before ucode starts (a scan on the root costs nothing); 4 portal processes at once instead of 16; a link may make 40 changes a quarter hour; over plain HTTP the page shows but configurations, new devices and new keys are refused with the HTTPS twin of the link; the connect sheet polls only while the first connection is awaited, with backoff, and stops once the link stopped working - Updates: after Dawnline's own package changes, a shell checks that LuCI reaches it and the agent runs, and puts the kept previous version back when they do not (automatic runs always keep it); the AmneziaWG module reload verifies rmmod and modprobe; installs check free space; on apk a reinstall that changed nothing is an error; uninstall.sh hands the update lock to the removal it calls; an upgrade restarts the service only where it was enabled; the release workflow pins the SDK images by digest and the actions by commit - AmneziaWG: features count only when both the tools and the kernel module have them; a server whose disguise this build cannot run (a 3.1 preset after a rollback to 2.0) is kept down and reported; Components tells 1.0 builds from 2.0 ones; `awg show dump` is parsed by shape; Maximum's DNS-shaped signature packets are made for each server and its keep-alive is a 25-35 s range - CI compiles every ucode file and runs the new tests/ucode unit tests (54 tests on the real libuci) in OpenWrt 24.10 and 25.12 rootfs containers; scripts/compile-ucode.sh does the same wherever ucode runs and scripts/ucode-container.sh locally with docker; lint-ucode checks POSIX regexes and module layering; a tag builds only after CI passes
306 lines
9.7 KiB
Ucode
306 lines
9.7 KiB
Ucode
// Dawnline — the router's network interfaces: what exists, which one is the
|
|
// WAN, and which ones make up a server's "home network".
|
|
//
|
|
// Per server (uci `server` section):
|
|
// auto_wan 1 = use the interface of the default route (detected_wan
|
|
// is kept as a fallback while the WAN is down)
|
|
// wan_device the WAN interface when auto_wan is off
|
|
// auto_lan 1 = include the detected LAN (detected_lan as fallback)
|
|
// lan_device extra interfaces that count as the home network (list)
|
|
//
|
|
// Home access is enforced by destination: the networks routed out of the
|
|
// chosen interfaces form the server's nft `home_<id>` set, and the tunnel's
|
|
// firewall zone gets a forwarding to each of their zones.
|
|
|
|
import { readfile, readlink, lsdir, stat } from 'fs';
|
|
import { cursor } from 'uci';
|
|
import { sh_out, ip2int, int2ip, cidr_any, uniq } from 'dawnline.util';
|
|
|
|
const SYS = '/sys/class/net';
|
|
/** Links Dawnline creates itself (dawnline.loop); never offered as interfaces. */
|
|
export const INTERNAL = { transit: 'dlx0', lan: 'dll0' };
|
|
const VPN_PROTOS = [ 'amneziawg', 'wireguard', 'openvpn', 'openconnect', 'vpnc', 'pptp', 'l2tp', 'gre', 'gretap', 'vti', 'xfrm' ];
|
|
const VPN_NAMES = /^(wg|awg|tun|tap|ovpn|ipsec|vti|xfrm)/;
|
|
// Never the WAN while another default route exists: VPN clients. (PPTP and
|
|
// L2TP stay eligible: some ISPs connect the WAN with them.)
|
|
const NOT_WAN_PROTOS = [ 'amneziawg', 'wireguard', 'openvpn', 'openconnect', 'vpnc' ];
|
|
const NOT_WAN_NAMES = /^(wg|awg|tun|tap|ovpn)/;
|
|
// Kernel placeholder devices that never carry a network on their own.
|
|
const NOISE = /^(ifb|teql|sit|ip6tnl|gre|gretap|erspan|ip6gre|ip6gretap|ip_vti|ip6_vti|tunl|bond)[0-9]*$/;
|
|
const PRIVATE = [ [ '10.0.0.0', 8 ], [ '172.16.0.0', 12 ], [ '192.168.0.0', 16 ], [ '100.64.0.0', 10 ] ];
|
|
|
|
function sysread(dev, f) {
|
|
return trim(readfile(`${SYS}/${dev}/${f}`) ?? '');
|
|
}
|
|
|
|
function ip_json(args) {
|
|
try {
|
|
return json(sh_out(`ip -j ${args} 2>/dev/null`) || '[]') ?? [];
|
|
}
|
|
catch (e) {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
function ubus_json(path, method) {
|
|
try {
|
|
return json(sh_out(`ubus call ${path} ${method} 2>/dev/null`) || 'null');
|
|
}
|
|
catch (e) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/** "a.b.c.d[/len]" → { net, prefix, size } for any prefix 1-32; null for default or junk. */
|
|
function net_of(s) {
|
|
let c = cidr_any(s);
|
|
return c && c.prefix >= 1 ? c : null;
|
|
}
|
|
|
|
function net_str(n) {
|
|
return `${int2ip(n.net)}/${n.prefix}`;
|
|
}
|
|
|
|
/** Drop networks already covered by a wider one. */
|
|
export function collapse(list) {
|
|
let nets = filter(map(uniq(list), net_of), (x) => x != null);
|
|
nets = sort(nets, (a, b) => a.prefix - b.prefix || a.net - b.net);
|
|
let keep = [];
|
|
for (let n in nets) {
|
|
let inside = false;
|
|
for (let k in keep)
|
|
if (n.net >= k.net && n.net < k.net + k.size) {
|
|
inside = true;
|
|
break;
|
|
}
|
|
if (!inside)
|
|
push(keep, n);
|
|
}
|
|
return map(sort(keep, (a, b) => a.net - b.net), net_str);
|
|
};
|
|
|
|
function is_private(cidr) {
|
|
let n = net_of(cidr);
|
|
if (!n)
|
|
return false;
|
|
for (let p in PRIVATE) {
|
|
let base = ip2int(p[0]), size = 1 << (32 - p[1]);
|
|
if (n.net >= base && n.net < base + size)
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/* ---------- snapshot ---------- */
|
|
|
|
let cache = null;
|
|
|
|
/**
|
|
* One consistent view of the router's interfaces, cached for a few seconds
|
|
* (rpcd keeps this module loaded, so the cache must expire).
|
|
*/
|
|
export function snapshot(fresh) {
|
|
if (!fresh && cache && time() - cache.ts < 5)
|
|
return cache;
|
|
|
|
// Networks reachable through each device (main table, IPv4).
|
|
let routes = {}, defaults = [];
|
|
for (let r in ip_json('-4 route show table main')) {
|
|
if (!r.dev)
|
|
continue;
|
|
if (r.dst == 'default') {
|
|
push(defaults, r);
|
|
continue;
|
|
}
|
|
push(routes[r.dev] ??= [], r.dst);
|
|
}
|
|
let addrs = {};
|
|
for (let l in ip_json('-4 addr show'))
|
|
for (let a in l.addr_info ?? [])
|
|
if (a.family == 'inet')
|
|
push(addrs[l.ifname] ??= [], `${a.local}/${a.prefixlen}`);
|
|
|
|
// Logical (netifd) interfaces by device, and firewall zones by network.
|
|
let logical = {};
|
|
for (let i in ubus_json('network.interface', 'dump')?.interface ?? []) {
|
|
let dev = i.l3_device ?? i.device;
|
|
if (dev && !logical[dev])
|
|
logical[dev] = { name: i.interface, proto: i.proto, up: i.up };
|
|
}
|
|
// The WAN: the default route with the lowest metric that does not go into
|
|
// a VPN client (its default route is not where the tunnels listen); only
|
|
// VPN routes: the lowest of them.
|
|
let vpn = (dev) => index(NOT_WAN_PROTOS, logical[dev]?.proto) >= 0 || match(dev, NOT_WAN_NAMES) != null;
|
|
let wan_dev = null, wan_metric = null, wan_vpn = true;
|
|
for (let r in defaults) {
|
|
let v = vpn(r.dev), metric = r.metric ?? 0;
|
|
if (wan_dev == null || (wan_vpn && !v) || (wan_vpn == v && metric < wan_metric)) {
|
|
wan_dev = r.dev;
|
|
wan_metric = metric;
|
|
wan_vpn = v;
|
|
}
|
|
}
|
|
let zone_by_net = {}, zone_by_dev = {}, zones = [];
|
|
let fc = cursor();
|
|
fc.load('firewall');
|
|
fc.foreach('firewall', 'zone', (z) => {
|
|
if (!z.name)
|
|
return;
|
|
push(zones, z.name);
|
|
for (let n in (type(z.network) == 'array' ? z.network : split(z.network ?? '', /\s+/)))
|
|
if (n != '')
|
|
zone_by_net[n] ??= z.name;
|
|
for (let d in (type(z.device) == 'array' ? z.device : split(z.device ?? '', /\s+/)))
|
|
if (d != '')
|
|
zone_by_dev[d] ??= z.name;
|
|
});
|
|
|
|
let devices = {};
|
|
for (let dev in sort(lsdir(SYS) ?? [])) {
|
|
if (dev == 'lo' || dev == INTERNAL.transit || dev == INTERNAL.lan)
|
|
continue;
|
|
let lg = logical[dev];
|
|
let flags = hex(sysread(dev, 'flags') || '0');
|
|
let kind = +(sysread(dev, 'type') || '0');
|
|
let master = readlink(`${SYS}/${dev}/master`);
|
|
master = master ? replace(master, /^.*\//, '') : null;
|
|
let bridge = stat(`${SYS}/${dev}/bridge`) != null;
|
|
let wifi = stat(`${SYS}/${dev}/phy80211`) != null || stat(`${SYS}/${dev}/wireless`) != null;
|
|
let nets = routes[dev] ? collapse(routes[dev]) : [];
|
|
let up = (flags & 1) != 0;
|
|
if (match(dev, NOISE) && !length(nets))
|
|
continue;
|
|
let cat;
|
|
if (wifi)
|
|
cat = 'wifi';
|
|
else if ((lg && index(VPN_PROTOS, lg.proto) >= 0) || kind == 65534 || ((flags & 0x10) && kind != 1) || match(dev, VPN_NAMES))
|
|
cat = 'vpn';
|
|
else if (kind == 1 || bridge)
|
|
cat = 'ethernet';
|
|
else
|
|
cat = 'other';
|
|
devices[dev] = {
|
|
name: dev,
|
|
category: dev == wan_dev ? 'wan' : cat,
|
|
kind: bridge ? 'bridge' : cat,
|
|
up,
|
|
master,
|
|
members: [],
|
|
nets,
|
|
addrs: addrs[dev] ?? [],
|
|
logical: lg?.name,
|
|
proto: lg?.proto,
|
|
zone: zone_by_dev[dev] ?? (lg ? zone_by_net[lg.name] : null),
|
|
};
|
|
}
|
|
for (let dev, d in devices)
|
|
if (d.master && devices[d.master])
|
|
push(devices[d.master].members, dev);
|
|
|
|
// The LAN: netifd's "lan" if present, otherwise the first bridge (then
|
|
// ethernet device) carrying a private network.
|
|
let lan_dev = null;
|
|
for (let dev, lg in logical)
|
|
if (lg.name == 'lan' && devices[dev])
|
|
lan_dev = dev;
|
|
if (!lan_dev)
|
|
for (let pass in [ 'bridge', 'ethernet' ])
|
|
for (let dev, d in devices)
|
|
if (!lan_dev && dev != wan_dev && d.kind == pass && !d.master && length(filter(d.nets, is_private)))
|
|
lan_dev = dev;
|
|
|
|
cache = { ts: time(), devices, wan: wan_dev, lan: lan_dev, zones };
|
|
return cache;
|
|
};
|
|
|
|
/* ---------- per server ---------- */
|
|
|
|
/**
|
|
* What a server actually uses right now:
|
|
* wan: { dev, zone, auto, missing }
|
|
* home: [{ dev, auto, nets, zone, missing }]
|
|
* nets: home networks (collapsed), zones: their firewall zones
|
|
*/
|
|
export function server_net(srv, snap) {
|
|
snap ??= snapshot();
|
|
let devs = snap.devices;
|
|
|
|
let wan_dev = srv.auto_wan ? (snap.wan ?? srv.detected_wan) : srv.wan_device;
|
|
let wan = {
|
|
dev: wan_dev || null,
|
|
auto: !!srv.auto_wan,
|
|
zone: devs[wan_dev]?.zone ?? srv.wan_zone ?? 'wan',
|
|
missing: !!wan_dev && !devs[wan_dev],
|
|
};
|
|
|
|
let picked = [];
|
|
let auto_lan = srv.auto_lan ? (snap.lan ?? srv.detected_lan) : null;
|
|
if (auto_lan)
|
|
push(picked, [ auto_lan, true ]);
|
|
for (let d in srv.lan_devices ?? [])
|
|
if (d != auto_lan)
|
|
push(picked, [ d, false ]);
|
|
|
|
let home = [], nets = [], zones = [];
|
|
for (let p in picked) {
|
|
let dev = p[0];
|
|
// Never the WAN, the tunnel itself, or a bridge port (routing only sees the bridge).
|
|
if (dev == wan.dev || dev == srv.ifname || devs[dev]?.master)
|
|
continue;
|
|
let d = devs[dev];
|
|
// The detected LAN missing for a moment (bridge recreated) keeps its zone,
|
|
// so its forwardings are not removed meanwhile.
|
|
let h = { dev, auto: p[1], nets: d?.nets ?? [], zone: d?.zone ?? (p[1] ? srv.lan_zone : null), missing: !d };
|
|
push(home, h);
|
|
push(nets, ...h.nets);
|
|
if (h.zone)
|
|
push(zones, h.zone);
|
|
}
|
|
// Older configs and routers where nothing could be resolved: the zone set at setup.
|
|
if (!length(home) && srv.auto_lan && srv.lan_zone)
|
|
push(zones, srv.lan_zone);
|
|
return { wan, home, nets: collapse(nets), zones: uniq(zones) };
|
|
};
|
|
|
|
/** Router address on the home network (DNS for tunnel clients). */
|
|
export function home_address(srv, snap) {
|
|
snap ??= snapshot();
|
|
let sn = server_net(srv, snap);
|
|
for (let h in sn.home)
|
|
for (let a in snap.devices[h.dev]?.addrs ?? [])
|
|
return split(a, '/')[0];
|
|
return null;
|
|
};
|
|
|
|
/** WAN IPv4 address of a server's WAN interface. */
|
|
export function wan_address(srv, snap) {
|
|
snap ??= snapshot();
|
|
let a = snap.devices[server_net(srv, snap).wan.dev]?.addrs?.[0];
|
|
return a ? split(a, '/')[0] : null;
|
|
};
|
|
|
|
/** Names of devices at home by address: DHCP leases, then static hosts. */
|
|
export function lan_names() {
|
|
let out = {};
|
|
for (let line in split(readfile('/tmp/dhcp.leases') ?? '', '\n')) {
|
|
let f = split(line, ' ');
|
|
if (length(f) >= 4 && f[3] != '*')
|
|
out[f[2]] = f[3];
|
|
}
|
|
let c = cursor();
|
|
c.foreach('dhcp', 'host', (h) => {
|
|
if (h.ip && h.name)
|
|
out[h.ip] ??= h.name;
|
|
});
|
|
return out;
|
|
};
|
|
|
|
/** Event addresses that belong to devices at home, with their names ({ ip: name }). */
|
|
export function event_hosts(e, names) {
|
|
let out = null;
|
|
for (let ip in match(e.detail ?? '', /[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/g) ?? [])
|
|
if (names[ip[0]])
|
|
(out ??= {})[ip[0]] = names[ip[0]];
|
|
return out;
|
|
};
|