Files
dawnline/package/luci-app-dawnline/root/usr/share/ucode/dawnline/apply.uc
T
Aemeath 31a2065f05 Dawnline 0.6.0
- 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
2026-10-18 15:32:27 +03:00

271 lines
9.3 KiB
Ucode

// Dawnline — reconciliation. Turns /etc/config/dawnline into router state:
// * network interfaces (dawnline.netifd) and the devices loaded live into
// them (dawnline.awg)
// * firewall zones, forwardings, WAN rules and reply routes (dawnline.fw)
// * the nft table `inet dawnline` enforcing each person's access (dawnline.nft)
// * hostnames in /tmp/hosts/dawnline
// * the "like a home device" path and the Home-only resolver (dawnline.loop)
// Only objects created by Dawnline are ever modified.
//
// apply(), sync() and sync_loop() run under one lock ('apply') and read the
// model inside it, so a rebuild and a runtime update never interleave and the
// last one to run always works from the newest configuration. The config lock
// (dawnline.store) is never taken while 'apply' is held.
import { readfile, writefile, stat, unlink } from 'fs';
import { ensure_dir, write_file, write_json, with_lock, ip2int, slog, RUN_DIR } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as net from 'dawnline.net';
import * as loop from 'dawnline.loop';
import * as awg from 'dawnline.awg';
import * as nft from 'dawnline.nft';
import * as fw from 'dawnline.fw';
import * as netifd from 'dawnline.netifd';
import * as migrate from 'dawnline.migrate';
const HOSTS_FILE = '/tmp/hosts/dawnline';
/** The network signature the last apply() worked from (the agent compares against it). */
export const NET_SIG = `${RUN_DIR}/net.sig`;
// The last access-table error that was logged (each distinct failure once).
const NFT_ERR = `${RUN_DIR}/nft.err`;
function log(who, msg, level, detail) {
slog('dawnline', level ?? 'info', msg, detail, who);
}
/* ---------- hostnames ---------- */
function host_label(s) {
let l = replace(lc(s), /[^a-z0-9]+/g, '-');
l = replace(l, /^-+|-+$/g, '');
return substr(l, 0, 40) || 'device';
}
export function sync_hosts(m) {
let lines = [];
if (m.settings.hostnames)
for (let id, d in m.devices) {
let p = m.people[d.person];
if (p && ip2int(d.address) != null)
push(lines, `${d.address} ${host_label(d.name)}.${p.id}.${m.settings.domain}`);
}
let ls = loop.status();
if (ls.active)
push(lines, `${ls.address} dawnline.${m.settings.domain}`);
let body = length(lines) ? join('\n', lines) + '\n' : '';
// dnsmasq runs as its own user; rpcd's umask would leave the file 0600.
let readable = ((stat(HOSTS_FILE)?.perm?.other_read) ?? false);
if ((readfile(HOSTS_FILE) ?? '') == body && (body == '' || readable))
return false;
ensure_dir('/tmp/hosts');
if (body == '')
unlink(HOSTS_FILE);
else {
writefile(HOSTS_FILE, body);
system(`chmod 644 ${HOSTS_FILE}`);
}
system('killall -HUP dnsmasq 2>/dev/null');
return true;
};
/* ---------- access table ---------- */
export function states_for(m, usage) {
let st = {};
for (let id, p in m.people)
st[id] = core.person_state(m, p, usage);
return st;
};
/** Per-person runtime membership (dawnline.nft). */
export function access_sets(m, usage, states) {
return nft.access_sets(m, usage, states);
};
/**
* Log an access-table failure once per distinct error (with what it means
* for the devices: none loaded while the table is missing, the previous rules
* kept when an older one survived the failed rebuild); the error, or null.
*/
function nft_result(err, present) {
let was = readfile(NFT_ERR);
if (err == null) {
if (was != null)
unlink(NFT_ERR);
return null;
}
if (was != err) {
log('Access rules', present
? "couldn't be updated — the previous rules stay, and changes to access wait until they load"
: "couldn't load — no device is loaded into the tunnels until they do", 'error', err);
ensure_dir(RUN_DIR);
writefile(NFT_ERR, err);
}
return err;
}
/**
* The table in place: rebuilt with `full`, otherwise members only, rebuilt
* when that fails (no table yet at boot, or an older shape). Null, or the
* error when the rebuild fails too.
*/
function load_table(m, sets, full) {
let err = full ? nft.rebuild(m, sets) : nft.update(sets);
if (err != null && !full)
err = nft.rebuild(m, sets);
return nft_result(err, err != null && nft.present());
}
/** Full table rebuild (structure changes: servers, LAN subnets); true when it loaded. */
export function rebuild_nft(m, sets) {
let err = nft.rebuild(m, sets);
return nft_result(err, err != null && nft.present()) == null;
};
/** Atomically replace set contents only. */
export function update_sets(sets) {
return nft.update(sets) == null;
};
export function remove_nft() {
nft.remove();
};
/** For the watchdog (dawnline.fw). */
export function firewall_drift(m) {
return fw.drift(m);
};
/* ---------- runtime sync ---------- */
/**
* What an admin should hear when a sync did not fully take: the access table
* failed, or a server did not accept its devices. Null when all went in.
*/
function sync_warning(m, table, peers) {
let out = [];
if (table != null)
push(out, nft.present()
? `Access rules couldn't be updated (${table}): the previous rules stay, so this change isn't in effect yet.`
: `Access rules couldn't load (${table}): no device is loaded into the tunnels until they do.`);
for (let id, r in peers)
if (r != 'ok' && r != 'down')
push(out, `Couldn't load devices into ${m.servers[id]?.name ?? id}: ${r}.`);
return length(out) ? join(' ', out) + ' Open Diagnostics → Health.' : null;
}
/*
* With the lock held: access sets first, then devices into the tunnels.
* Fail closed: without the table the firewall would let every loaded device
* reach everything, so while it is missing no device is loaded at all. An
* older table that survived a failed rebuild keeps limiting them with the
* sets it has, and the devices still follow people's states (a revoked one
* leaves).
*/
function locked_sync(m, usage, full) {
let states = states_for(m, usage);
let sets = nft.access_sets(m, usage, states);
let table = load_table(m, sets, full);
let peers = awg.sync_peers(m, table == null || nft.present() ? states : {});
sync_hosts(m);
ensure_dir(RUN_DIR);
write_json(`${RUN_DIR}/states.json`, states, 0o644);
return { peers, states, table, warning: sync_warning(m, table, peers) };
}
/**
* Runtime sync: devices into the tunnels (AmneziaWG peers), access sets,
* hostnames. Cheap; safe to call often. The model is always read again under
* the lock (`m` is accepted for older callers and not used); `usage` is the
* caller's (the agent holds the live counters). The result carries `warning`
* (a sentence for the admin) when the sync did not fully take.
*/
export function sync(m, usage) {
return with_lock('apply', () => locked_sync(core.load(), usage ?? core.load_usage()));
};
/** Is the access table loaded (the agent's tick re-syncs when it is not). */
export function table_present() {
return nft.present();
};
/**
* Everything on the router that Dawnline's state is derived from: WAN and
* LAN, the home networks and zones of each server, the netns address and the
* LAN's DNS. The agent re-applies when it changes (LAN renumbered, interface
* added, bridge recreated, DHCP DNS changed, ...).
*/
export function net_signature(m) {
let snap = net.snapshot(true);
let srvs = {};
for (let id, srv in m.servers)
srvs[id] = net.server_net(srv, snap);
let lan = snap.devices[snap.lan];
return sprintf('%J', { wan: snap.wan, lan: snap.lan, addrs: lan?.addrs, servers: srvs, dns: loop.lan_dns(), loop: loop.client_dns() });
};
/**
* Keep the "like a home device" path and the resolver in step (agent tick).
* Cheap when nothing changed; rebuilds the access table when the netns
* address appears, moves or goes away (the guard allows DNS to it).
*/
export function sync_loop(m, usage, force) {
let p = with_lock('apply', () => {
let mm = core.load();
let before = `${loop.client_dns()} ${loop.resolver_target().mode}`;
let lp = loop.ensure(mm, force);
loop.sync_resolver(mm);
fw.sync_reply_routes(mm);
if (`${loop.client_dns()} ${loop.resolver_target().mode}` != before)
locked_sync(mm, usage ?? core.load_usage(), true);
return lp;
});
loop.remember(p);
return p;
};
/* ---------- entry points ---------- */
/** Full reconcile: router configuration + runtime state. */
export function apply(opts) {
opts ??= {};
migrate.run();
let r = with_lock('apply', () => {
let m = core.load();
let usage = core.load_usage();
let network = netifd.sync(m);
let firewall = fw.sync(m);
let lp = loop.ensure(m, true);
loop.sync_resolver(m);
fw.sync_reply_routes(m);
let s = locked_sync(m, usage, true);
ensure_dir(RUN_DIR);
write_file(NET_SIG, net_signature(m), 0o644);
return { network, firewall, lp, peers: s.peers, warning: s.warning };
});
loop.remember(r.lp);
return { network: r.network, firewall: r.firewall, like_home: r.lp.error ? { error: r.lp.error } : !r.lp.off, peers: r.peers, warning: r.warning };
};
/** Remove everything Dawnline created (used by the uninstaller). */
export function teardown() {
with_lock('apply', () => {
let m = core.load();
loop.remove();
unlink(loop.RESOLVER.conf);
m.servers = {};
m.settings.portal_enabled = false;
netifd.sync(m);
fw.sync(m);
fw.sync_reply_routes(m);
nft.remove();
unlink(HOSTS_FILE);
unlink(NET_SIG);
system('killall -HUP dnsmasq 2>/dev/null');
});
migrate.uhttpd();
// The agent's heartbeat check.
if (system('grep -qs /usr/libexec/dawnline/heartbeat /etc/crontabs/root') == 0)
system("sed -i '\\#/usr/libexec/dawnline/heartbeat#d' /etc/crontabs/root; /etc/init.d/cron restart >/dev/null 2>&1");
};