Files
dawnline/package/luci-app-dawnline/root/usr/share/ucode/dawnline/nft.uc
T
Aemeath dc0f159447
Build packages / CI (push) Blocked by required conditions
Build packages / Version (push) Waiting to run
CI / Web (format, types, tests, bundles) (push) Blocked by required conditions
CI / ShellCheck (push) Blocked by required conditions
CI / ucode static checks (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 24.10) (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 25.12) (push) Blocked by required conditions
Dawnline 0.14.0
- A device is renamed where its name stands on its card: a click on the
  name, Return or Space on it, or Rename in the ⋯ menu turns it into a
  field with the name selected. Return saves, and the words shimmer until
  the router answers. Esc or a click elsewhere puts the old name back. The
  rename window is gone, and the page no longer redraws under a name being
  edited
- Device names take up to 20 characters: letters of any language, digits,
  spaces and - _ . The router refuses anything else when a device is added
  or renamed, so a name can't carry symbols into configurations, file
  names or the AmneziaVPN key. The portal and the admin turn a character
  like that away as it is typed: the field shakes, its outline goes red
  and a short line says why. Suggested names (a phone's model, "Phone 2")
  are stripped of such characters and cut to fit. Names set before this
  stay as they are
- LAN Bypass: Add a device, in the portal and in the admin, has a switch
  that keeps the device's own local network (printer, TV, NAS) reachable
  while it is connected. It is off by default and stays as chosen; the
  admin's device drawer shows it. With home and internet access the switch
  says which addresses still lead to the home network
- Health warns when a server's home network is on one of the subnets home
  routers come with (192.168.0.x, 192.168.1.x and others). People with
  home access who connect from a network on the same addresses reach your
  home instead of their own, LAN Bypass or not
- The router tells when a device can't connect properly. After the problem
  lasts three minutes, the portal card and the admin drawer name it:
  can't finish connecting (the network may block it), connected but no
  data (an outdated configuration, and the card offers Reconnect), on two
  devices at once, or a connection that keeps dropping. Activity lists
  these under Problems, one line per device per hour, and says when the
  device connects normally again
- The set-up sheet's connection line follows what the device does:
  waiting, can't finish, connected, or connected but no data. The sheet
  closes by itself only once data comes through. On the device itself and
  for a router, the steps regroup to what fixes the problem: "Set it up
  again" when the handshake never finishes, "Add the connection again"
  ("Import the configuration again" for a router) when no data comes
- Set-up in the portal: a QR code too long for a camera to read gives its
  place to a code that opens the set-up link (a LAN Bypass configuration
  or a long AmneziaVPN key can be that long). A TV, box or NAS added from
  a phone gets the steps for setting up from another device. Back from
  "Open on the device" keeps the kind, LAN Bypass and the name typed. The
  packet-size note under the kinds is gone
- The portal on phones keeps its place: nothing jumps when an access row
  opens or folds, a notice comes or goes, or Safari redraws the cards. A
  reload, or coming back from the VPN app, opens where the page was. Cards
  glide to their new height, and an animation interrupted half-way goes on
  from where it is instead of snapping. A double click no longer closes
  the sheet it just opened
- In the admin, a device's drawer has its own MTU and keep-alive (empty
  means the server's), each with a Change dialog. A change touches only
  that device's configuration and restarts nothing on the router. Opening
  the drawer no longer counts as handing out the configuration: "Update
  config" stays until the new configuration is shown as a QR code,
  downloaded or copied ("Show the new configuration"). New keys set the
  device up again, as the portal's Reconnect does
- "Speed now" on a server's Overview is live: one point a second over the
  last two minutes, all there as soon as the Overview opens. The agent
  keeps those two minutes in memory and writes them out only while someone
  is looking
- Disguise values that AmneziaWG refuses or crashes on are stopped before
  they reach the kernel. That covers overlapping H1-H4, Jmin above Jmax,
  broken I1-I5 tags, padding under 12 with header protection, and more.
  Import and restore refuse them. After a hand edit in uci, the server's
  tunnel stays down and Health and the service log say why and what to do.
  Errors are full sentences in the reader's language
- The header protection key no longer shows in the status that read-only
  users can see: the Server page says only that the key is set, and each
  device's configuration still has it. The server no longer turns off
  WireGuard's protection against handshake floods (devices keep
  DisableCookies). A device can't be added with a server's own key
- An AmneziaWG update whose kernel module can't be swapped (another
  AmneziaWG interface holds the old one) no longer fails. It is installed,
  the tunnels come back on the old module, and Health and Components say
  the update starts after a reboot. On apk firmware, an install that apk
  left at the old version counts as failed. A module installed by hand is
  recorded, so after a firmware upgrade Health can tell that it is gone
- Dawnline reads only its own tunnels, each one separately. Another
  AmneziaWG interface on the router no longer slows the agent's
  once-a-second check, has its keys read or breaks Dawnline's reads. A
  portal request reads only that person's server: one process however many
  servers there are
- Fewer false disconnects: a tunnel that netifd sets up again no longer
  logs everyone as leaving and coming back, and a device with a long
  keep-alive stays online between handshakes. One configuration on two
  devices isn't logged as roaming every few seconds, and new keys end the
  old session at once. A tunnel that is missing devices is synced within a
  minute, and traffic across a tunnel restart is no longer undercounted
- Renaming a server no longer restarts its tunnel. If a tunnel's interface
  is edited outside Dawnline (LuCI, uci), the watchdog sets it up again
  with Dawnline's settings and names only the changed options. The routing
  rules for "Internet like a home device" change one at a time, new ones
  first, so traffic never falls between them. Health and the Server page
  warn when the address's AAAA record isn't this router's, or the router
  has no public IPv6: devices that prefer IPv6 fail to connect
- The README screenshots come in English and Russian; the portal's are
  taken from its demo. The demo has a switch beside × in the set-up sheet
  to show each state of the connection line. In Russian, long labels in
  the admin's wide option buttons wrap under their icon. DESIGN.md
  describes the switch, renaming on the card, the shimmer, the shake and
  how the portal scrolls. New tests cover link states, the meter, access,
  Health, firewall rules, network settings and packages
2026-10-22 00:11:50 +03:00

283 lines
12 KiB
Ucode

// Dawnline — the nft table `inet dawnline`: each person's access, enforced
// on the tunnel interfaces before anything else on the router sees the
// traffic, and where tunnel DNS goes. Its shape follows the servers and their
// home networks (rebuild); who is in which set follows people's state and
// changes often (update, one atomic transaction).
import { unlink } from 'fs';
import { sh, ensure_dir, write_file, rand_hex, ip2int, uniq, RUN_DIR } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as net from 'dawnline.net';
import * as loop from 'dawnline.loop';
/** Private IPv4 ranges: internet people never reach them (awg.BYPASS4 is the rest). */
export const PRIVATE4 = [ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '100.64.0.0/10', '169.254.0.0/16', '224.0.0.0/3' ];
/** The sets whose members change at run time (update replaces them together). */
const SETS = [ 'lan_ok', 'lan_all', 'lan_part', 'mesh_pairs', 'inet_ok', 'svc_ok', 'svc_host', 'dns_real' ];
function ip4(a) {
return ip2int(a ?? '') != null;
}
/**
* Per-person runtime membership: which tunnel addresses may reach what.
* `snap` is the network (net.snapshot() when not given).
*/
export function access_sets(m, usage, states, snap) {
// lan_ok: home access (the router itself, the mesh); lan_all: every home
// network; lan_part: device . network for people limited to some networks;
// mesh_pairs: device . device within a circle (or one person's own devices);
// svc_ok: device . service . port; svc_host: device . service with no ports (all of them).
let sets = {};
for (let k in SETS)
sets[k] = [];
snap ??= net.snapshot();
let homes = {}, groups = {};
for (let id, d in m.devices) {
let p = m.people[d.person];
// Off: paused, ended, over quota or out of hours. Addresses go into nft as they are: IPv4 only.
if (!p || d.disabled || !ip4(d.address) || states[p.id] != 'active')
continue;
// Home names: the plain resolver (their internet does not use the tunnel).
if (p.access == 'lan' && p.dns_mode == 'home')
push(sets.dns_real, d.address);
if (p.access == 'internet' || p.access == 'both')
push(sets.inet_ok, d.address);
if (p.access == 'both' || (p.access == 'lan' && !length(p.services))) {
push(sets.lan_ok, d.address);
let srv = m.servers[p.server];
let h = homes[p.id] ??= srv ? core.person_home(srv, p, snap) : { all: true, nets: [] };
if (h.all)
push(sets.lan_all, d.address);
else
for (let n in h.nets)
push(sets.lan_part, `${d.address} . ${n}`);
// Who this device may reach directly: its circle, or at least its owner's devices.
if (srv?.mesh == 'circles') {
let ci = core.person_circle(m, p);
push(groups[ci ? `c:${ci.id}` : `p:${p.id}`] ??= [], d.address);
}
}
else if (p.access == 'lan')
for (let sid in p.services) {
let s = m.services[sid];
if (!s || !ip4(s.address))
continue;
if (!length(s.ports))
push(sets.svc_host, `${d.address} . ${s.address}`);
for (let port in s.ports)
if (match(port, /^[0-9]+$/))
push(sets.svc_ok, `${d.address} . ${s.address} . ${port}`);
}
}
for (let g, addrs in groups)
for (let a in addrs)
for (let b in addrs)
if (a != b)
push(sets.mesh_pairs, `${a} . ${b}`);
return sets;
};
// Duplicate members (two devices with one address) would make the whole load fail.
function set_elems(arr) {
arr = uniq(arr);
return length(arr) ? `elements = { ${join(', ', arr)} }` : '';
}
/** The portal's TCP ports people may reach through the tunnel (never SSH, DNS or LuCI, whatever is stored). */
function portal_ports(m) {
if (!m.settings.portal_enabled)
return [];
let ok = (p) => p >= 1 && p <= 65535 && index([ 22, 53, 80, 443 ], p) < 0;
let ports = filter([ m.settings.portal_port ], ok);
if (core.portal_http(m) && ok(core.portal_http_port(m)))
push(ports, core.portal_http_port(m));
return ports;
}
/**
* What the table is made from besides the model, read from the router: the
* netns's DNS address (loop.client_dns), where the Home-only resolver runs
* (loop.resolver_target), the LAN's DNS and the network snapshot.
*/
function router_ctx() {
return { dns_addr: loop.client_dns(), resolver: loop.resolver_target(), lan_dns: loop.lan_dns(), snap: net.snapshot() };
}
function table(m, sets, ctx) {
ctx ??= router_ctx();
let ifs = [], tun = [];
let dns_addr = ctx.dns_addr;
if (!ip4(dns_addr))
dns_addr = null;
let rt = ctx.resolver;
let snap = ctx.snap;
// Each server's home networks are its own: with several servers, "all
// home" on one never reaches the other's networks (set lan_<id>).
let homes = {};
for (let id, srv in m.servers) {
// Only valid interface names reach here (core.tunnels): they are written into the rules as strings.
let tns = core.tunnels(srv);
for (let t in tns) {
push(ifs, `"${t.ifname}"`);
push(tun, t.subnet);
}
if (length(tns))
homes[id] = net.collapse(net.server_net(srv, snap).nets);
}
tun = net.collapse(tun);
let t = [];
push(t, 'table inet dawnline {');
for (let id, nets in homes)
push(t, ` set home_${id} { type ipv4_addr; flags interval; auto-merge; ${set_elems(nets)} }`);
// Tunnel subnets are never "home", even inside a wider route to the LAN.
push(t, ` set tun_nets { type ipv4_addr; flags interval; auto-merge; ${set_elems(tun)} }`);
push(t, ` set lan_ok { type ipv4_addr; ${set_elems(sets.lan_ok)} }`);
push(t, ` set lan_all { type ipv4_addr; ${set_elems(sets.lan_all)} }`);
push(t, ` set lan_part { type ipv4_addr . ipv4_addr; flags interval; ${set_elems(sets.lan_part)} }`);
push(t, ` set mesh_pairs { type ipv4_addr . ipv4_addr; ${set_elems(sets.mesh_pairs)} }`);
push(t, ` set inet_ok { type ipv4_addr; ${set_elems(sets.inet_ok)} }`);
push(t, ` set svc_ok { type ipv4_addr . ipv4_addr . inet_service; ${set_elems(sets.svc_ok)} }`);
push(t, ` set svc_host { type ipv4_addr . ipv4_addr; ${set_elems(sets.svc_host)} }`);
push(t, ` set dns_real { type ipv4_addr; ${set_elems(sets.dns_real)} }`);
push(t, ' chain pre {');
// Ahead of mangle-priority hooks (transparent proxies mark at -150).
push(t, ' type filter hook prerouting priority -160; policy accept;');
if (length(ifs))
push(t, ` iifname { ${join(', ', ifs)} } jump guard`);
push(t, ' }');
push(t, ' chain guard {');
push(t, ' meta nfproto ipv6 drop');
// Every packet is judged by the rules below, not only the first of a
// connection: a change of access cuts open connections too, instead of
// letting a session or a long UDP flow run on for days. Only what has no
// rule of its own passes on its connection: errors and the like, answers
// to the admin's port forwards, and the router's own pings.
push(t, ' ct state related accept');
push(t, ' ct status dnat accept');
push(t, ' icmp type { echo-request, echo-reply } fib daddr type local accept');
push(t, ' fib daddr type local meta l4proto { tcp, udp } th dport 53 accept');
let pp = portal_ports(m);
if (length(pp))
// Their own portal, also with the VPN on (the address may be this router's).
push(t, ` fib daddr type local tcp dport { ${join(', ', pp)} } accept`);
// The router itself is part of home: for everyone with all of it, and for
// people limited to some networks only on the addresses in those.
push(t, ' fib daddr type local ip saddr @lan_all accept');
push(t, ' fib daddr type local ip saddr . ip daddr @lan_part accept');
push(t, ' fib daddr type local counter drop');
if (dns_addr)
// DNS through the netns (it forwards to the LAN's DNS), for everyone.
push(t, ` ip daddr ${dns_addr} meta l4proto { tcp, udp } th dport 53 accept`);
for (let id, nets in homes)
for (let tn in core.tunnels(m.servers[id]))
push(t, ` iifname "${tn.ifname}" ip daddr @home_${id} ip daddr != @tun_nets ip saddr @lan_all accept`);
push(t, ' ip saddr . ip daddr @lan_part ip daddr != @tun_nets accept');
// Devices with home access are part of home: they reach each other, where the
// server allows it (everyone, or within circles). Within one server: the
// firewall has no forwarding between different servers' zones.
for (let id, srv in m.servers)
for (let tn in core.tunnels(srv))
if (srv.mesh == 'all')
push(t, ` iifname "${tn.ifname}" ip saddr @lan_ok ip daddr @lan_ok accept`);
else if (srv.mesh == 'circles')
push(t, ` iifname "${tn.ifname}" ip saddr . ip daddr @mesh_pairs accept`);
push(t, ' meta l4proto { tcp, udp } ip saddr . ip daddr . th dport @svc_ok accept');
push(t, ' ip saddr . ip daddr @svc_host accept');
push(t, ` ip daddr { ${join(', ', PRIVATE4)} } counter drop`);
push(t, ' ip saddr @inet_ok accept');
push(t, ' counter drop');
push(t, ' }');
// The other way: fw4 lets the server's home zones reach the tunnel; here
// only connections from its home networks to people with home access pass
// (paused, ended and internet-only people are not reachable). The admin's
// own port forwards (DNAT) stay with fw4.
push(t, ' chain inbound {');
push(t, ' type filter hook forward priority filter - 5; policy accept;');
if (length(ifs))
push(t, ` oifname { ${join(', ', ifs)} } iifname != { ${join(', ', ifs)} } ct state new jump to_device`);
push(t, ' }');
push(t, ' chain to_device {');
push(t, ' meta nfproto ipv6 drop');
push(t, ' ct status dnat accept');
for (let id, nets in homes)
for (let tn in core.tunnels(m.servers[id]))
push(t, ` oifname "${tn.ifname}" ip saddr @home_${id} ip saddr != @tun_nets ip daddr @lan_all accept`);
push(t, ' ip daddr . ip saddr @lan_part ip saddr != @tun_nets accept');
push(t, ' counter reject with icmpx admin-prohibited');
push(t, ' }');
// Devices ask the tunnel address; send each query where it belongs.
let to_resolver = rt.mode == 'ns' && ip4(rt.address) ? `dnat ip to ${rt.address}:53` : `redirect to :${+rt.port}`;
let lan_dns = ctx.lan_dns;
if (!ip4(lan_dns))
lan_dns = null;
push(t, ' chain dns {');
push(t, ' type nat hook prerouting priority dstnat - 5; policy accept;');
if (length(ifs))
// Home names (and no LAN DNS at all): the plain resolver, whatever address was asked.
push(t, ` iifname { ${join(', ', ifs)} } ip saddr @dns_real meta l4proto { tcp, udp } th dport 53 ${to_resolver}`);
for (let id, srv in m.servers)
for (let tn in core.tunnels(srv)) {
// Everyone else: the LAN's DNS, through the netns (from the LAN side) when internet goes that way.
let target = srv.lan_like && dns_addr ? `dnat ip to ${dns_addr}:53` : lan_dns ? `dnat ip to ${lan_dns}:53` : to_resolver;
push(t, ` iifname "${tn.ifname}" ip daddr ${tn.address} meta l4proto { tcp, udp } th dport 53 ${target}`);
}
push(t, ' }');
push(t, '}');
return join('\n', t) + '\n';
}
/** Run an nft script (one transaction); null when it loaded, else what nft said. */
export function load(script) {
ensure_dir(RUN_DIR);
// A file of its own: two writers must never load each other's script.
let f = `${RUN_DIR}/nft.${rand_hex(4)}.rules`;
if (!write_file(f, script))
return `couldn't write ${f}`;
let r = sh(`nft -f ${f}`);
unlink(f);
if (r.code == 0)
return null;
// Without the random file name, so the same failure reads the same every time.
return replace(trim(r.out), f, 'rules') || `nft exited with ${r.code}`;
};
/**
* The table as text, for a check (`nft -c -f`) or a test; nothing is loaded.
* `ctx` (a test's) stands for what is read from the router: { dns_addr,
* resolver, lan_dns, snap } (router_ctx).
*/
export function render(m, sets, ctx) {
return table(m, sets, ctx);
};
/** Full table rebuild (structure changes: servers, home networks, DNS paths); null or the error. */
export function rebuild(m, sets) {
return load('table inet dawnline\ndelete table inet dawnline\n' + table(m, sets));
};
/**
* Replace the members of every runtime set at once; null or the error. Fails
* as a whole when the table or one of its sets is missing (not loaded yet,
* or an older shape): the caller then rebuilds.
*/
export function update(sets) {
let s = '';
for (let name in SETS) {
let members = uniq(sets[name]);
s += `flush set inet dawnline ${name}\n`;
if (length(members))
s += `add element inet dawnline ${name} { ${join(', ', members)} }\n`;
}
return load(s);
};
/** Is the table loaded (watchdog). */
export function present() {
return system('nft list table inet dawnline >/dev/null 2>&1') == 0;
};
export function remove() {
system('nft delete table inet dawnline 2>/dev/null');
};