Dawnline 0.14.0
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

- 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
This commit is contained in:
Aemeath committed 2026-10-22 00:11:50 +03:00
1 parent 58492be021
commit dc0f159447
155 files changed
+11062 -1461

No files matched your search

@@ -115,9 +115,9 @@ function peer_of(dmp, d) {
return dmp.peers[d.public_key];
}
/** What the device sends to the router: its configuration's AllowedIPs. */
/** What the device sends to the router: its configuration's AllowedIPs (its own, with lan_bypass). */
function routed(m, srv, p, d) {
return awg.allowed_ips(m, srv, p);
return awg.allowed_ips(m, srv, p, d);
}
/** The home network (interface) of a server that holds an address. */
@@ -204,6 +204,12 @@ function from_device(m, d, t, states, dmp, snap) {
return steps;
}
// A device that keeps its own local network out of the tunnel (lan_bypass;
// Home only is the same either way) sends a private address there, router
// or home address alike: it never reaches this router's rules.
if (d.lan_bypass && p.access != 'lan' && !in_nets(t.ip, allowed))
return stop(steps, via(t.ip));
// The router itself.
if (index(router_addrs(snap), t.ip) >= 0) {
let portal = m.settings.portal_enabled && (t.port == m.settings.portal_port || (core.portal_http(m) && t.port == core.portal_http_port(m)));
@@ -301,17 +307,20 @@ function to_device(m, ip, d, states, dmp, snap) {
return steps;
}
/** `from` and `to`: a device id, or an IPv4 address (optionally :port). */
export function check(m, from, to) {
/**
* `from` and `to`: a device id, or an IPv4 address (optionally :port).
* `ctx` = { states, dmp, snap } (a test's own); read from the router when not
* given. Returns { ok, steps: [{ ok, title, detail }] }.
*/
export function check(m, from, to, ctx) {
let a = parse_target(m, from), b = parse_target(m, to);
if (!a)
die(sprintf(_('"%s" is not a device or an IPv4 address.'), from));
if (!b)
die(sprintf(_('"%s" is not a device or an IPv4 address.'), to));
let usage = core.load_usage();
let states = view.states(m, usage);
let dmp = live.dump(m);
let snap = net.snapshot(true);
let states = ctx?.states ?? view.states(m, core.load_usage());
let dmp = ctx?.dmp ?? live.dump(m);
let snap = ctx?.snap ?? net.snapshot(true);
let steps;
if (a.dev)
steps = from_device(m, a.dev, b, states, dmp, snap);
@@ -1,8 +1,9 @@
// Dawnline — the AmneziaWG core: keys, disguise (obfuscation), client
// configurations (.conf, AmneziaVPN key), the netifd options of a server's
// tunnel, its peers (`awg syncconf`, no restart), live counters, the words for
// why a tunnel is kept down (blocked_text) and what the watchdog and Health
// check about it. Plain WireGuard is AmneziaWG with the disguise off.
// Dawnline — the AmneziaWG core: keys, disguise (obfuscation) and the values
// AmneziaWG refuses, client configurations (.conf, AmneziaVPN key), the
// netifd options of a server's tunnel, its peers (`awg syncconf`, no
// restart), live counters, the words for why a tunnel is kept down
// (blocked_text) and what the watchdog and Health check about it. Plain
// WireGuard is AmneziaWG with the disguise off.
import { readfile, stat, unlink } from 'fs';
import {
@@ -11,6 +12,7 @@ import {
} from 'dawnline.util';
import * as core from 'dawnline.core';
import * as net from 'dawnline.net';
import { ipv6_groups } from 'dawnline.schema';
import * as pkg from 'dawnline.pkg';
import * as builds from 'dawnline.awg_builds';
import { _, L_ } from 'dawnline.i18n';
@@ -29,7 +31,7 @@ const TOOL = '/usr/bin/awg', PROTO = '/lib/netifd/proto/amneziawg.sh';
/** The packages AmneziaWG comes in (the Components tab installs them). */
const PACKAGES = [ 'kmod-amneziawg', 'amneziawg-tools' ];
// A module constant, compiled once (a literal is compiled each time it runs):
// dump() checks it on every line of `awg show all dump`, every second.
// dump() checks it on every line of each tunnel's `awg show <ifname> dump`, every second.
const DIGITS = /^[0-9]+$/;
/** netifd knows the amneziawg protocol (it reads the proto scripts when it starts). */
@@ -138,7 +140,9 @@ function rand_h(used) {
}
}
// caps() answers from here while the tool, the protocol script and the module file are the same.
// caps() answers from here while the tool, the protocol script, the module
// file, the install record and the loaded module are the same (tmpfs: a
// reboot starts over).
const CAPS = `${RUN_DIR}/awg-caps.json`;
/**
@@ -146,15 +150,20 @@ const CAPS = `${RUN_DIR}/awg-caps.json`;
* options it passes on) and the `awg` tool (the keys it accepts) say what the
* tools know, the kernel module's package version what the kernel runs, and
* a feature counts only when both have it (tools 3.1 over a 2.0 module would
* configure header protection that the kernel silently lacks):
* configure header protection that the kernel silently lacks). While an
* update waits for a reboot (its old module stayed loaded) the kernel runs
* the generation from before it, as the install recorded it:
* v2 — S3/S4, I1-I5, header ranges (AWG 1.5/2.0)
* v3 — header protection, trailers, padding, timing (AWG 3.1)
* tools / kmod — their generations ('1.0', '2.0', '3.1'; null unknown)
* mismatch — the two differ
* pending — an installed module waits for a reboot (dawnline.awg_builds)
*/
export function caps() {
let rel = trim(readfile('/proc/sys/kernel/osrelease') ?? '');
let key = `${stat(`/lib/modules/${rel}/amneziawg.ko`)?.mtime ?? 0}/${stat(TOOL)?.mtime ?? 0}/${stat(PROTO)?.mtime ?? 0}`;
let core = builds.module_core();
let key = `${stat(`/lib/modules/${rel}/amneziawg.ko`)?.mtime ?? 0}/${stat(TOOL)?.mtime ?? 0}/${stat(PROTO)?.mtime ?? 0}` +
`/${stat(builds.RECORD)?.mtime ?? 0}/${core ?? 0}`;
let cached = read_json(CAPS, null);
if (cached?.key == key && cached.caps)
return cached.caps;
@@ -163,12 +172,15 @@ export function caps() {
let t2 = index(script, 'awg_s3') >= 0 && index(script, 'awg_i1') >= 0;
let t3 = t2 && index(script, 'awg_header_protection_key') >= 0 && tool != '';
let tools = !stat(TOOL) ? null : t3 ? '3.1' : t2 ? '2.0' : '1.0';
// A module installed by hand has no package: then the tools are believed.
let kmod = builds.gen(pkg.version('kmod-amneziawg'));
// A module installed by hand has no package, so no generation (also when
// a pending update replaces it): then the tools are believed.
let rec = read_json(builds.RECORD, null), boot = builds.boot_id();
let kmod = builds.running_gen(rec, boot, core, pkg.version('kmod-amneziawg'));
let out = {
v2: t2 && (kmod == null || kmod != '1.0'),
v3: t3 && (kmod == null || kmod == '3.1'),
tools, kmod, mismatch: tools != null && kmod != null && tools != kmod,
pending: builds.pending(rec, boot, core),
};
ensure_dir(RUN_DIR);
write_json(CAPS, { key, caps: out }, 0o644);
@@ -241,18 +253,24 @@ function dns_answer() {
* offers Balanced or Maximum instead.
*/
export function obf_preset(name) {
if (name == 'max')
if (name == 'max') {
// 32 random bytes, as `awg genkey` makes them (no process). Without
// one the server would come up with weak or no header protection.
let hpk = genpsk();
if (!valid_key(hpk))
die(_('Key generation failed (no random data).'));
return {
jc: `${rand_int(4, 6)}`, jmin: '10', jmax: '50',
s1: '12', s2: '12', s3: '12', s4: '12',
h1: '1', h2: '2', h3: '3', h4: '4',
i1: dns_query(), i2: dns_answer(),
header_protection_key: sh_out('awg genkey'),
header_protection_key: hpk,
content_padding_addition: '10-100',
rekey_after_time: '100-120', rekey_timeout: '3-7', reject_after_time: '150-180',
keepalive_timeout: '5-15', max_handshake_attempts: '15-20',
random_trailers: 'on', disable_cookies: 'on',
};
}
if (name == 'off')
return { jc: '0', jmin: '0', jmax: '0', s1: '0', s2: '0', h1: '1', h2: '2', h3: '3', h4: '4' };
let o = {};
@@ -278,38 +296,222 @@ export function obf_preset(name) {
return o;
};
/* ---------- disguise values AmneziaWG refuses ---------- */
export function obf_errors(o) {
// Checked with ltrim, not regexes: this module loads with every portal request.
const DEC = '0123456789', HEX = '0123456789abcdefABCDEF';
/** A whole number in digits up to `top`, or null (no spaces: callers trim where the tools drop them). */
function uint(v, top) {
let s = `${v}`;
if (s == '' || length(s) > 10 || ltrim(s, DEC) != '')
return null;
return +s <= top ? +s : null;
}
/** A number or a range as AmneziaWG writes them ("5", "5-15"), each end up to `top`: [ lo, hi ], or null. */
function uint_range(v, top) {
let p = split(trim(`${v}`), '-');
let lo = length(p) <= 2 ? uint(p[0], top) : null;
let hi = length(p) == 2 ? uint(p[1], top) : lo;
return lo != null && hi != null && lo <= hi ? [ lo, hi ] : null;
}
/** Value `k` of disguise values `o` is set. */
function given(o, k) {
return o[k] != null && o[k] != '';
}
/**
* Packet types H1-H4: a number or a range each, apart from the others (the
* kernel refuses an overlap). One not given keeps WireGuard's own type, 1-4.
*/
function headers_unsafe(o, errs) {
let hs = [];
for (let i = 1; i <= 4; i++) {
let r = given(o, `h${i}`) ? uint_range(o[`h${i}`], 4294967295) : [ i, i ];
if (!r)
push(errs, sprintf(_('%s must be a number or a range like 100-200, up to 4294967295.'), OBF_CONF[`h${i}`]));
push(hs, r);
}
for (let i = 0; i < 4; i++)
for (let j = i + 1; j < 4; j++)
if (hs[i] && hs[j] && hs[i][0] <= hs[j][1] && hs[j][0] <= hs[i][1])
push(errs, sprintf(_('%s and %s overlap: each packet type needs values of its own.'), OBF_CONF[`h${i + 1}`], OBF_CONF[`h${j + 1}`]));
}
/**
* One tag of a signature packet as both the kernel and amneziawg-go read it:
* <b 0x..> fixed bytes (an even number of hex digits), <r N>, <rc N>, <rd N>
* (N random bytes, letters, digits; a negative N writes past the packet in
* the kernel, kmod #267) or <t> (the time). <c> is the kernel's alone and
* <d>, <ds>, <dz> amneziawg-go's: devices on the other refuse them.
*/
function itag_ok(tag) {
if (tag == 't')
return true;
let sp = index(tag, ' ');
if (sp < 0)
return false;
let key = substr(tag, 0, sp), val = substr(tag, sp + 1);
if (key == 'b')
return length(val) > 2 && length(val) % 2 == 0 && substr(val, 0, 2) == '0x' && ltrim(substr(val, 2), HEX) == '';
if (key == 'r' || key == 'rc' || key == 'rd')
return (uint(val, 1000) ?? 0) >= 1;
return false;
}
/** What is wrong with signature packet `name` (I1-I5) holding `s`, as a sentence; null when nothing. */
function itag_error(name, s) {
// In a .conf file `#` starts a comment and a line break ends the line: the rest would be lost.
if (index(s, '#') >= 0 || index(s, '\n') >= 0 || index(s, '\r') >= 0)
return sprintf(_('%s may not contain # or a line break.'), name);
// Text between tags is skipped by both parsers.
for (let a = index(s, '<'); a >= 0; a = index(s, '<')) {
let b = index(substr(s, a), '>');
if (b < 0)
return sprintf(_('%s has a tag that is not closed with >.'), name);
let tag = substr(s, a + 1, b - 1);
if (!itag_ok(tag))
return sprintf(_('%s: <%s> is not a tag AmneziaWG apps accept: use <b 0x…> with an even number of hex digits, <r N>, <rc N> or <rd N> with N from 1 to 1000, or <t>.'),
name, length(tag) > 24 ? `${substr(tag, 0, 24)}…` : tag);
s = substr(s, a + b + 1);
}
return null;
}
/** Signature packets I1-I5: their tags, and all of them in one device's configuration (one QR code). */
function itags_unsafe(o, errs) {
let total = 0;
for (let k in [ 'i1', 'i2', 'i3', 'i4', 'i5' ]) {
if (!given(o, k))
continue;
total += length(`${o[k]}`);
let e = itag_error(OBF_CONF[k], `${o[k]}`);
if (e)
push(errs, e);
}
if (total > 2000)
push(errs, sprintf(_('I1-I5 together must be at most 2000 characters, not %d.'), total));
}
/**
* What in disguise values `o` AmneziaWG would refuse, crash on or break
* devices with: what an import, a restore or a hand edit in uci must never
* hand to the kernel (dawnline.backup, dawnline.netifd). Only those rules,
* none of Dawnline's own bounds (obf_errors): a backup the kernel takes stays
* usable. Sentences in the reader's language; [] when the values are safe.
*/
export function obf_unsafe(o) {
o ??= {};
let errs = [];
for (let k, r in OBF_SPEC) {
let v = o[k];
if (v == null || v == '')
continue;
if (!match(v, DIGITS) || +v < r[0] || +v > r[1])
push(errs, `${k}=${v} (${r[0]}-${r[1]})`);
let num = (k) => given(o, k) ? uint(trim(`${o[k]}`), 65535) : 0;
// 16-bit numbers for the tools; Jmin above Jmax sizes junk past its buffer (kmod #225).
for (let k in [ 'jc', 'jmin', 'jmax', 's1', 's2', 's3', 's4' ])
if (num(k) == null)
push(errs, sprintf(_('%s must be a whole number from 0 to 65535.'), OBF_CONF[k]));
if (given(o, 'jmin') && given(o, 'jmax') && num('jmin') != null && num('jmax') != null && num('jmin') > num('jmax'))
push(errs, _('Jmin must not be larger than Jmax.'));
headers_unsafe(o, errs);
// Header protection: a 32-byte key, and every padding at least the 12 bytes of its nonce (the kernel checks).
if (given(o, 'header_protection_key')) {
if (!valid_key(o.header_protection_key))
push(errs, _('The header protection key is not a key.'));
for (let k in [ 's1', 's2', 's3', 's4' ])
if (num(k) != null && num(k) < 12)
push(errs, sprintf(_('%s must be at least 12 with header protection.'), OBF_CONF[k]));
}
if (o.jmin != null && o.jmax != null && +o.jmin > +o.jmax)
push(errs, 'jmin > jmax');
if (o.s1 != null && o.s2 != null && +o.s1 + 56 == +o.s2)
push(errs, 's1 + 56 = s2');
let hs = {};
for (let k in [ 'h1', 'h2', 'h3', 'h4' ]) {
let v = o[k];
if (v == null || v == '')
continue;
if (!match(v, /^[0-9]+(-[0-9]+)?$/))
push(errs, sprintf(_('%s must be a number or range'), k));
else if (hs[v])
push(errs, _('h1-h4 must be distinct'));
hs[v] = true;
// 3.1 timers and counts: 0 alone is the kernel's default; a 0 in a range
// would fire at once. Keys are dropped after 180 seconds whatever is set.
for (let k in [ 'rekey_after_time', 'rekey_timeout', 'reject_after_time', 'keepalive_timeout', 'max_handshake_attempts' ]) {
let r = given(o, k) ? uint_range(o[k], 65535) : [ 0, 0 ];
if (!r || (r[0] == 0 && r[1] > 0))
push(errs, sprintf(_('%s must be a number or a range like 5-15, from 1 to 65535.'), OBF_CONF[k]));
else if (k == 'reject_after_time' && r[1] > 180)
push(errs, _('RejectAfterTime must be at most 180 seconds.'));
}
if (given(o, 'content_padding_addition') && !uint_range(o.content_padding_addition, 65535))
push(errs, sprintf(_('%s must be a number or a range like 10-100, up to 65535.'), OBF_CONF.content_padding_addition));
// What both netifd and the .conf parser read as a switch.
for (let k in [ 'random_trailers', 'disable_cookies' ])
if (given(o, k) && index([ 'on', 'off', '1', '0' ], `${o[k]}`) < 0)
push(errs, sprintf(_('%s must be on or off.'), OBF_CONF[k]));
itags_unsafe(o, errs);
return errs;
};
/**
* What is wrong with the disguise values of a server Dawnline sets up: what
* AmneziaWG refuses (obf_unsafe), and Dawnline's own bounds on top (junk that
* stays under the path MTU, a handshake initiation and response that never
* share a size). Its presets pass it. Sentences in the reader's language; []
* when the values are fine.
*/
export function obf_errors(o) {
o ??= {};
let errs = obf_unsafe(o);
for (let k, r in OBF_SPEC) {
let n = given(o, k) ? uint(trim(`${o[k]}`), 65535) : null;
if (n != null && (n < r[0] || n > r[1]))
push(errs, sprintf(_('%s must be from %d to %d.'), OBF_CONF[k], r[0], r[1]));
}
if (o.s1 != null && o.s2 != null && +o.s1 + 56 == +o.s2)
push(errs, _('S2 must not be S1 + 56: the handshake initiation and response would have the same size.'));
return errs;
};
/**
* Disguise values `o` as anyone who may read the status sees them: all but
* the header protection key, a secret every device of the server shares
* (with it and the server's public key, captured traffic can be unmasked).
* Devices get it in their own configuration (client_config).
*/
export function obf_public(o) {
let out = { ...(o ?? {}) };
delete out.header_protection_key;
return out;
};
export function allowed_ips(m, srv, p) {
if (p.access == 'lan') {
/*
* Everything but a device's own local network, for a device whose local
* network stays outside the tunnel (lan_bypass): every IPv4 address outside
* the private ranges the access table drops for internet people anyway
* (dawnline.nft PRIVATE4: 10/8, 172.16/12, 192.168/16, 100.64/10,
* 169.254/16, 224/3), and every IPv6 address outside fc00::/7, fe80::/10
* and ff00::/8. Fixed lists (tests/ucode/awg.test.uc proves each is exactly
* that complement); what of the private ranges goes through the tunnel after
* all (DNS, home) is added to them.
*/
export const BYPASS4 = [
'0.0.0.0/5', '8.0.0.0/7', '11.0.0.0/8', '12.0.0.0/6', '16.0.0.0/4', '32.0.0.0/3', '64.0.0.0/3', '96.0.0.0/6',
'100.0.0.0/10', '100.128.0.0/9', '101.0.0.0/8', '102.0.0.0/7', '104.0.0.0/5', '112.0.0.0/4', '128.0.0.0/3', '160.0.0.0/5',
'168.0.0.0/8', '169.0.0.0/9', '169.128.0.0/10', '169.192.0.0/11', '169.224.0.0/12', '169.240.0.0/13', '169.248.0.0/14',
'169.252.0.0/15', '169.255.0.0/16', '170.0.0.0/7', '172.0.0.0/12', '172.32.0.0/11', '172.64.0.0/10', '172.128.0.0/9',
'173.0.0.0/8', '174.0.0.0/7', '176.0.0.0/4', '192.0.0.0/9', '192.128.0.0/11', '192.160.0.0/13', '192.169.0.0/16',
'192.170.0.0/15', '192.172.0.0/14', '192.176.0.0/12', '192.192.0.0/10', '193.0.0.0/8', '194.0.0.0/7', '196.0.0.0/6',
'200.0.0.0/5', '208.0.0.0/4',
];
export const BYPASS6 = [ '::/1', '8000::/2', 'c000::/3', 'e000::/4', 'f000::/5', 'f800::/6', 'fe00::/9', 'fec0::/10' ];
/** An IPv6 address BYPASS6 leaves out: in fc00::/7, fe80::/10 or ff00::/8 (the first 16 bits decide). False for anything else. */
function private6(a) {
let g = ipv6_groups(a)?.[0];
return g != null && ((g & 0xfe00) == 0xfc00 || (g & 0xffc0) == 0xfe80 || (g & 0xff00) == 0xff00);
}
/**
* What a device sends into the tunnel (its AllowedIPs; the server's peer
* line stays its address/32). Home only: the person's home networks, the
* tunnel network or the router's address, and the DNS. Internet: everything,
* or with `dev.lan_bypass` everything but the device's own local network
* (BYPASS4, BYPASS6), every DNS server it is given (IPv4 and IPv6) and for
* home access what Home only gets. Without `dev`, as for a device without
* lan_bypass.
*/
export function allowed_ips(m, srv, p, dev) {
if (p.access != 'lan' && !dev?.lan_bypass)
return [ '0.0.0.0/0', '::/0' ];
let home = () => {
let nets = core.person_home(srv, p).nets;
// With devices reaching each other, the whole tunnel network (the router's
// address is in it); otherwise only the router's own address.
@@ -318,13 +520,27 @@ export function allowed_ips(m, srv, p) {
push(nets, srv.subnet);
else if (a)
push(nets, `${a}/32`);
return nets;
};
let dns = core.client_dns(m, srv, p);
if (p.access == 'lan') {
// The resolver address must be reachable through the tunnel too (not the fallback).
let dns = core.client_dns(m, srv, p)[0];
if (dns)
push(nets, `${dns}/32`);
let nets = home();
if (dns[0])
push(nets, `${dns[0]}/32`);
return net.collapse(nets);
}
return [ '0.0.0.0/0', '::/0' ];
// Every DNS server stays in the tunnel: a private one left out would be
// asked on whatever network the device is on (a public one is in the rest).
let nets = [ ...BYPASS4 ], nets6 = [];
for (let a in dns)
if (ip2int(a) != null)
push(nets, `${a}/32`);
else if (private6(a))
push(nets6, `${a}/128`);
if (p.access == 'both')
push(nets, ...home());
return [ ...net.collapse(nets), ...BYPASS6, ...uniq(nets6) ];
};
@@ -372,6 +588,48 @@ function client_obf(srv, dev) {
return o;
}
/**
* The keep-alive `dev` gets (its own or the server's, core.device_keepalive)
* as [ lo, hi ] seconds; null when it is off (0). With 3.1 (header
* protection: its apps take ranges) jittered over ten seconds like the other
* timers, since a fixed beat would be the one regular thing left. The online
* window follows its upper end (dawnline.live).
*/
export function keepalive_range(srv, dev) {
let k = core.device_keepalive(srv, dev);
if (!(k > 0))
return null;
return srv.obf?.header_protection_key ? [ k, k + 10 ] : [ k, k ];
};
/**
* The longest an idle device goes between two handshakes, in seconds; null
* when its keep-alive is off (an idle device then sends nothing at all). Its
* keep-alive packets are what it sends, and the first one after its key's
* rekey time (RekeyAfterTime, WireGuard's 120 s; past 180 s the key is
* refused anyway) starts a handshake (kmod send.c keep_key_fresh): up to one
* keep-alive past that time, or each keep-alive once they are further apart.
*/
export function idle_handshake(srv, dev) {
let ka = keepalive_range(srv, dev);
if (!ka)
return null;
let rekey = min(uint_range(srv.obf?.rekey_after_time ?? '', 65535)?.[1] || 120, 180);
return ka[0] > rekey ? ka[1] : rekey + ka[1];
};
/**
* keepalive_range() as the apps write it ("25-35", "25"); null when off. The
* .conf and the AmneziaVPN key carry the same text (AmneziaVPN hands it on as
* written, ranges included).
*/
function keepalive_text(srv, dev) {
let r = keepalive_range(srv, dev);
if (!r)
return null;
return r[0] == r[1] ? `${r[0]}` : `${r[0]}-${r[1]}`;
}
export function client_config(m, dev) {
let p = m.people[dev.person];
let srv = p ? m.servers[p.server] : null;
@@ -379,7 +637,7 @@ export function client_config(m, dev) {
return null;
let host = core.endpoint_host(m, srv);
let ep = index(host, ':') >= 0 && substr(host, 0, 1) != '[' ? `[${host}]` : host;
let allowed = allowed_ips(m, srv, p);
let allowed = allowed_ips(m, srv, p, dev);
let dns = core.client_dns(m, srv, p);
let mtu = core.device_mtu(srv, dev);
let lines = [ '[Interface]' ];
@@ -401,10 +659,9 @@ export function client_config(m, dev) {
push(lines, `PresharedKey = ${dev.preshared_key}`);
push(lines, `AllowedIPs = ${join(', ', allowed)}`);
push(lines, `Endpoint = ${ep}:${srv.port}`);
// With 3.1 (its apps take ranges) the keep-alive is jittered like the
// other timers; a fixed beat would be the one regular thing left.
if (srv.keepalive > 0)
push(lines, `PersistentKeepalive = ${srv.obf.header_protection_key ? `${srv.keepalive}-${srv.keepalive + 10}` : srv.keepalive}`);
let keepalive = keepalive_text(srv, dev);
if (keepalive)
push(lines, `PersistentKeepalive = ${keepalive}`);
return {
name: dev.name,
person: p.name,
@@ -424,7 +681,7 @@ export function client_config(m, dev) {
client_pub_key: dev.public_key,
psk_key: dev.preshared_key,
server_pub_key: srv.public_key,
persistent_keep_alive: `${srv.keepalive}`,
persistent_keep_alive: keepalive ?? '0',
obfuscation: obf,
},
};
@@ -448,12 +705,63 @@ export function netifd_options(srv) {
};
for (let k in core.OBF_KEYS)
o[`awg_${k}`] = srv.obf[k];
// DisableCookies is the devices' alone (their .conf and key keep it): on
// the server it would turn off WireGuard's own defence against a flood of
// handshakes (cookie replies and a per-address limit, only ever under
// load), and anyone who held a configuration could keep both cores busy.
// Null takes it off an interface that had it.
o.awg_disable_cookies = null;
return o;
};
/** Person states whose devices stay in the tunnel: active, and the limits the portal explains. */
export const SOFT_STATES = [ 'active', 'quota', 'hours' ];
/**
* The devices sync_peers() loads into server `sid`'s tunnel, in the model's
* order (an empty list when none). Pure: the model and the people's states
* (apply.states_for). Health and the agent compare a running tunnel with it.
*/
export function tunnel_devices(m, sid, states) {
let out = [];
let own = m.servers?.[sid]?.public_key;
for (let did, d in m.devices) {
let p = m.people[d.person];
// One malformed line makes syncconf refuse the whole server: such a device
// stays out (Health's Data check names it), and so does one with the
// server's own key, which the kernel silently ignores (it would look
// missing for ever). Over the data limit or outside the allowed hours the
// tunnel stays: the access table blocks everything but the portal, which
// says why (a silent handshake failure would look like a broken VPN).
if (p && p.server == sid && !d.disabled && index(SOFT_STATES, states[p.id]) >= 0 && valid_key(d.public_key) && ip2int(d.address) != null &&
(!own || d.public_key != own))
push(out, d);
}
return out;
};
/**
* How the peers dump() read on `ifname` differ from the devices that belong
* there (tunnel_devices): { loaded, missing, extra }, counted by key, not by
* number (a stale peer standing in for a missing one would make the numbers
* match). Pure.
*/
export function peer_diff(devs, dmp, ifname) {
let want = {};
for (let d in devs)
want[d.public_key] = true;
let loaded = 0, extra = 0, found = 0;
for (let k, p in dmp.peers)
if (p.ifname == ifname) {
loaded++;
if (want[k])
found++;
else
extra++;
}
return { loaded, missing: length(keys(want)) - found, extra };
};
/** Push the peer list of every server to the kernel without restarting it. */
export function sync_peers(m, states) {
ensure_dir(RUN_DIR);
@@ -467,15 +775,7 @@ export function sync_peers(m, states) {
continue;
}
let lines = [ '[Interface]', `PrivateKey = ${srv.private_key}`, `ListenPort = ${srv.port}`, '' ];
for (let did, d in m.devices) {
let p = m.people[d.person];
// One malformed line makes syncconf refuse the whole server: such a device
// stays out (Health's Data check names it). Over the data limit or
// outside the allowed hours the tunnel stays: the access table blocks
// everything but the portal, which says why (a silent handshake failure
// would look like a broken VPN).
if (!p || p.server != id || d.disabled || index(SOFT_STATES, states[p.id]) < 0 || !valid_key(d.public_key) || ip2int(d.address) == null)
continue;
for (let d in tunnel_devices(m, id, states)) {
push(lines, '[Peer]', `PublicKey = ${d.public_key}`);
if (d.preshared_key)
push(lines, `PresharedKey = ${d.preshared_key}`);
@@ -492,39 +792,83 @@ export function sync_peers(m, states) {
return res;
};
/**
* Parse `awg show all dump`. Returns { ok, ifaces: { ifname: {...} }, peers: { pubkey: {...} } }.
* Lines are told apart by their shape, not their length (each AmneziaWG
* generation adds fields to the interface line): an interface line carries
* its private and public key and a port, a peer line the peer's key, a
* preshared key or "(none)" and an endpoint. The tool fails when any one
* interface can't be read, but still prints the others: with `wanted` (the
* ifnames that matter) `ok` means those were all read, so another tunnel's
* trouble is not ours.
/** The interface's index while it exists (a new one each time netifd sets the tunnel up), else null. */
function ifindex(ifname) {
let s = trim(readfile(`/sys/class/net/${ifname}/ifindex`) ?? '');
return s != '' ? +s : null;
}
/*
* One interface's `awg show <ifname> dump` into `out` (see dump()). Lines are
* told apart by their shape, not their length (each AmneziaWG generation adds
* fields to the interface line): an interface line carries its private and
* public key and a port, a peer line the peer's key, a preshared key or
* "(none)" and an endpoint. Unlike `show all`, the lines have no ifname.
*/
export function dump(wanted) {
let r = sh('awg show all dump');
let out = { ok: r.code == 0, ifaces: {}, peers: {} };
for (let line in split(r.out, '\n')) {
let f = split(line, '\t');
if (length(f) < 5 || !valid_key(f[1]))
continue;
let key2 = valid_key(f[2]);
if (key2 && match(f[3] ?? '', DIGITS))
out.ifaces[f[0]] = { public_key: f[2], port: +f[3] };
else if (length(f) >= 9 && (key2 || f[2] == '(none)')) {
let ep = f[3] == '(none)' ? '' : f[3];
out.peers[f[1]] = {
ifname: f[0],
endpoint: ep,
handshake: +f[5],
rx: +f[6],
tx: +f[7],
};
}
function read_iface(out, ifname) {
// Read around the call: a link set up again in between gave counters of either one.
let before = ifindex(ifname);
// Not there (a tunnel netifd could not bring up, AmneziaWG gone after an
// upgrade): no process to learn it. One that appears is read next time.
if (before == null) {
out.reads[ifname] = 'down';
return;
}
if (!out.ok && type(wanted) == 'array')
out.ok = length(filter(wanted, (n) => !out.ifaces[n])) == 0;
let r = sh(`awg show ${q(ifname)} dump`);
let ix = ifindex(ifname);
let iface = null, peers = {};
if (r.code == 0)
for (let line in split(r.out, '\n')) {
let f = split(line, '\t');
if (length(f) < 4 || !valid_key(f[0]))
continue;
let key2 = valid_key(f[1]);
if (key2 && match(f[2], DIGITS))
iface = { public_key: f[1], port: +f[2], ifindex: ix };
else if (length(f) >= 8 && (key2 || f[1] == '(none)'))
peers[f[0]] = {
ifname,
endpoint: f[2] == '(none)' ? '' : f[2],
handshake: +f[4],
rx: +f[5],
tx: +f[6],
};
}
let read = iface != null;
// Gone during the read: its peers and their counters are gone with it.
if (ix == null) {
out.reads[ifname] = 'down';
return;
}
if (!read || ix != before) {
out.reads[ifname] = 'error';
out.ok = false;
return;
}
out.reads[ifname] = 'read';
out.ifaces[ifname] = iface;
for (let k, p in peers)
out.peers[k] = p;
}
/**
* Dawnline's own tunnels, one `awg show <ifname> dump` each for `ifnames`
* (live.tunnel_ifnames): never `all`, so another AmneziaWG interface on the
* router (a client tunnel with long I1-I5, say) neither slows the 1-second
* watcher down nor has its keys read. Returns { ok, reads: { ifname: 'read' |
* 'down' | 'error' }, ifaces: { ifname: { public_key, port, ifindex } },
* peers: { pubkey: { ifname, endpoint, handshake, rx, tx } } }, with only
* what was read in `ifaces` and `peers`:
* down the interface does not exist (/sys/class/net has no such link;
* no process is started for it): its peers and counters are gone
* error it exists but could not be read (or was set up again during the
* read): that says nothing about its peers
* `ok` is false when any of them is 'error' (true for an empty list).
*/
export function dump(ifnames) {
let out = { ok: true, reads: {}, ifaces: {}, peers: {} };
for (let ifn in ifnames ?? [])
read_iface(out, ifn);
return out;
};
@@ -544,6 +888,8 @@ export function server_state(srv) {
* { code: 'ifname', ifname } the interface name is invalid
* { code: 'taken', ifname } network.<ifname> exists and isn't Dawnline's
* { code: 'disguise', need, installed } obf_unsupported()
* { code: 'disguise_invalid' } obf_unsafe() finds values AmneziaWG refuses
* (said again from the server's values when read)
* Files written by older versions hold the English fragment ("has an invalid
* interface name …"), shown as it is.
*/
@@ -559,9 +905,20 @@ export function blocked_note(r) {
if (r.code == 'disguise')
return r.installed ? sprintf(L_('is kept down: its disguise needs AmneziaWG %s (installed: %s)'), r.need, r.installed)
: sprintf(L_('is kept down: its disguise needs AmneziaWG %s (installed: none)'), r.need);
if (r.code == 'disguise_invalid')
return L_('is kept down: its disguise has values AmneziaWG cannot take');
return L_('is kept down');
};
/** What to do about a reason (blocked_note), for the service log's details. */
export function blocked_fix(r) {
if (r?.code == 'disguise')
return L_('Install that AmneziaWG build in Dawnline → Components, or switch the disguise on the Server page.');
if (r?.code == 'disguise_invalid')
return L_('Choose a disguise on the Server page: it replaces the values set by hand.');
return L_('Choose another interface name in the server settings.');
};
/**
* Why the server's tunnel is kept down (`srv.blocked`), as a sentence with
* its name in the reader's language: what the admin UI shows. Null when it
@@ -581,6 +938,9 @@ export function blocked_text(srv) {
return r.installed
? sprintf(_('%s is kept down: its disguise needs AmneziaWG %s (installed: %s).'), srv.name, r.need, r.installed)
: sprintf(_('%s is kept down: its disguise needs AmneziaWG %s (installed: none).'), srv.name, r.need);
// Which values, from the server's own (the reason is kept as a code).
if (r.code == 'disguise_invalid')
return trim(sprintf(_('%s is kept down: its disguise has values AmneziaWG cannot take. %s'), srv.name, join(' ', obf_unsafe(srv.obf))));
return sprintf(_('%s is kept down.'), srv.name);
};
@@ -637,7 +997,7 @@ export function probes(m, ctx) {
push(out, {
id: `up_${srv.id}`, src: 'awg', name: `${srv.name} · AmneziaWG`, who: srv.name, ok: false, repair: null,
problem: blocked_note(why), back: L_('AmneziaWG is running again'),
detail: () => L_('Choose another interface name in the server settings.'),
detail: () => blocked_fix(why),
});
continue;
}
@@ -1,8 +1,12 @@
// Dawnline — where AmneziaWG comes from: the awg-openwrt projects publish
// builds per OpenWrt release and target (the kernel module must match the
// firmware). Used by the updater and the Components RPCs.
// firmware), and the record of what was installed on which kernel and boot
// (an update whose module could not be swapped starts with the next boot:
// until then caps() and Health go by the module that still runs). Used by
// the updater, the Components RPCs, dawnline.awg and Health. Installing
// itself is dawnline.upd_awg.
import { readfile } from 'fs';
import { readfile, stat } from 'fs';
import { connect } from 'ubus';
import { ensure_dir, read_json, write_json, DATA_DIR } from 'dawnline.util';
import * as pkg from 'dawnline.pkg';
@@ -36,19 +40,52 @@ export function firmware() {
/** What was installed, for whom: /etc/dawnline/awg.json (survives a sysupgrade with the data). */
export const RECORD = `${DATA_DIR}/awg.json`;
/** This boot (a new one loads the module on disk), or null when the kernel does not say. */
export function boot_id() {
return trim(readfile('/proc/sys/kernel/random/boot_id') ?? '') || null;
};
/**
* The size in memory of the loaded kernel module, or null when none is
* loaded. sysfs has no version for it, but builds differ in size: a module
* reloaded by hand ends a wait for a reboot (pending()).
*/
export function module_core() {
let n = int(trim(readfile('/sys/module/amneziawg/coresize') ?? ''));
return n > 0 ? n : null;
};
/**
* Remember which build was installed on which kernel. After a firmware
* upgrade the module is gone (it was built for that kernel): Health can then
* say so and offer the build for the new one (dawnline.health).
* say so and offer the build for the new one (dawnline.health). `run` comes
* from an install: prev_gen and prev_core, the module that ran before it
* (module_now()), and reloaded, false while that one stays loaded until the
* next boot. null for a module Dawnline did not install (adopt()).
*/
export function record(source, tag, packages) {
export function record(source, tag, packages, run) {
ensure_dir(DATA_DIR, 0o700);
write_json(RECORD, {
osrelease: trim(readfile('/proc/sys/kernel/osrelease') ?? ''),
source, tag, packages, installed: time(),
source, tag, packages, installed: time(), boot: boot_id(),
prev_gen: run?.prev_gen ?? null, prev_core: run?.prev_core ?? null, reloaded: run?.reloaded ?? null,
}, 0o600);
};
/**
* A record for a module Dawnline did not install (install.sh, by hand, or
* before Dawnline kept records), so kernel_changed() notices the next
* firmware upgrade: the kernel it is for, source null, `installed` the time
* Dawnline first saw it. Only when there is no record and the module is
* loaded or on disk for the running kernel. The agent calls it when it starts.
*/
export function adopt() {
let rel = trim(readfile('/proc/sys/kernel/osrelease') ?? '');
if (stat(RECORD) || (!stat('/sys/module/amneziawg') && (rel == '' || !stat(`/lib/modules/${rel}/amneziawg.ko`))))
return;
record(null, null, null, null);
};
/**
* The firmware the recorded AmneziaWG build was for, when it is not this one
* (and the module is gone): { was, now, tag, source }, else null.
@@ -88,6 +125,42 @@ export function gen(version) {
return '2.0';
};
/**
* An installed update that waits for a reboot: the install could not swap
* the kernel module (the old one stayed loaded), this is still the boot it
* ran in, and the module loaded is still the one from before it (core:
* module_core() now). Pure: rec is the record or null.
*/
export function pending(rec, boot, core) {
return rec?.reloaded === false && rec.boot != null && rec.boot == boot && core != null && rec.prev_core == core;
};
/**
* The AmneziaWG generation of the kernel module that runs: the one from
* before the install while it waits for a reboot (pending(); null when that
* module had no package), else the installed package's version (gen()).
* Pure, with the record, this boot and module_core() passed in.
*/
export function running_gen(rec, boot, core, version) {
return pending(rec, boot, core) ? rec.prev_gen : gen(version);
};
/**
* The kernel module loaded now, taken before an install changes packages:
* { core, gen, pending }. core is null when none is loaded; gen is what it
* runs (running_gen(), from `version`, the kmod-amneziawg package installed
* now); pending, an earlier update that still waits for a reboot.
*/
export function module_now(version) {
let rec = read_json(RECORD, null), boot = boot_id(), core = module_core();
return { core, gen: core == null ? null : running_gen(rec, boot, core, version), pending: pending(rec, boot, core) };
};
/** The installed AmneziaWG update waits for a reboot (pending(), for Health and Components). */
export function waits_for_reboot() {
return pending(read_json(RECORD, null), boot_id(), module_core());
};
/** The installed AmneziaWG packages: { name: version | null }. */
export function installed() {
let r = {};
@@ -1,7 +1,8 @@
// Dawnline — backups (tar.gz of the config and its data files), restoring
// them, and the JSON export / import. Whatever comes back in is checked first:
// only Dawnline's own regular files, and servers that cannot take over one of
// the router's own interfaces or networks.
// the router's own interfaces or networks, or hand the kernel disguise values
// AmneziaWG refuses.
import { readfile, stat, unlink, lsdir, rename } from 'fs';
import { cursor } from 'uci';
@@ -9,6 +10,7 @@ import {
q, sh, ensure_dir, read_json, write_json, write_file, file_exists, rand_hex, lock, unlock, DATA_DIR, RUN_DIR, VERSION
} from 'dawnline.util';
import * as core from 'dawnline.core';
import * as awg from 'dawnline.awg';
import * as live from 'dawnline.live';
import * as apply from 'dawnline.apply';
import * as net from 'dawnline.net';
@@ -39,9 +41,10 @@ const MAX_UNPACKED = 16 * 1024 * 1024;
/**
* What is wrong with a configuration about to replace the current one
* (cursor `c` holds it): each server must have a valid, unique interface
* name that is not one of the router's own interfaces, a free subnet and a
* unique port, and the people and devices must be consistent
* (core.model_errors). [] when it can be used.
* name that is not one of the router's own interfaces, a free subnet, a
* unique port and disguise values AmneziaWG takes (awg.obf_unsafe), and the
* people and devices must be consistent (core.model_errors). [] when it can
* be used.
*/
export function config_errors(c) {
let m = core.load(c);
@@ -52,7 +55,7 @@ export function config_errors(c) {
let internal = values(net.INTERNAL);
let ifnames = {}, ports = {}, subnets = [];
for (let id, srv in m.servers) {
for (let e in core.server_errors(m, srv, [ ...foreign, ...subnets ]))
for (let e in [ ...core.server_errors(m, srv, [ ...foreign, ...subnets ]), ...awg.obf_unsafe(srv.obf) ])
push(errs, sprintf(_('Server %s: %s'), srv.name, e));
if (ifnames[srv.ifname])
push(errs, sprintf(_('Server %s: interface %s is also used by %s.'), srv.name, srv.ifname, ifnames[srv.ifname]));
@@ -4,7 +4,7 @@
import { cursor } from 'uci';
import {
valid_name, valid_key, valid_host, valid_iface, valid_date, slugify, host_label, ucut, name_rule, parse_cidr, cidr_overlaps, int2ip, ip2int,
valid_name, valid_device_name, DEVICE_NAME_MAX, valid_key, valid_host, valid_iface, valid_date, slugify, host_label, ucut, name_rule, parse_cidr, cidr_overlaps, int2ip, ip2int,
rand_hex, rand_bytes, date_end, month_key, read_json, DATA_DIR, RUN_DIR, uniq
} from 'dawnline.util';
import { _, N_ } from 'dawnline.i18n';
@@ -199,6 +199,13 @@ export function load(c) {
created: toint(r.created, 0),
created_by: r.created_by ?? 'admin',
disabled: bool(r.disabled, false),
// The device's own link values (admin only): 0 / null = the server's
// (device_mtu, device_keepalive). Out of range is kept as read, so
// model_errors can name it; the configuration then uses the server's.
mtu: toint(r.mtu, 0),
keepalive: r.keepalive == null || r.keepalive == '' ? null : toint(r.keepalive, null),
// Its own local network stays outside the tunnel (awg.allowed_ips).
lan_bypass: bool(r.lan_bypass, false),
};
m.devices[id] = d;
if (m.people[d.person])
@@ -367,18 +374,40 @@ export function alloc_address(m, srv) {
*/
const AUTO_MTU = 1380;
const MOBILE_MTU = 1280;
/** What an MTU set by hand may be (the server's and a device's alike). */
export const MTU_RANGE = [ 1280, 1500 ];
/** What a keep-alive set by hand may be, in seconds (0 = off). */
export const KEEPALIVE_RANGE = [ 0, 600 ];
function in_range(n, r) {
return type(n) == 'int' && n >= r[0] && n <= r[1];
}
/** The server's tunnel MTU: the one set, or automatic for its disguise. */
export function tunnel_mtu(srv) {
return srv.mtu || max(MOBILE_MTU, AUTO_MTU - toint(srv.obf?.s4, 0));
};
/** The MTU a device's configuration carries: the tunnel's, at most 1280 for phones and tablets. */
/**
* The MTU a device's configuration carries: the device's own when the admin
* set one, else the tunnel's, at most 1280 for phones and tablets.
*/
export function device_mtu(srv, dev) {
if (in_range(dev.mtu, MTU_RANGE))
return dev.mtu;
let mtu = tunnel_mtu(srv);
return index(MOBILE_KINDS, dev.kind) >= 0 ? min(mtu, MOBILE_MTU) : mtu;
};
/**
* The keep-alive a device's configuration carries, in seconds (0 = off): the
* device's own when the admin set one, else the server's. Both ends never
* have to agree on it (the server's peers carry none), so it is the device's.
*/
export function device_keepalive(srv, dev) {
return in_range(dev?.keepalive, KEEPALIVE_RANGE) ? dev.keepalive : srv.keepalive;
};
export function endpoint_host(m, srv) {
return srv.endpoint || m.settings.portal_host || '';
};
@@ -649,6 +678,8 @@ export function update_person(c, m, id, a) {
* Add a device for a person. `opts.keys` = { private_key?, public_key,
* preshared_key } from dawnline.awg (or a public key the browser generated).
* `opts.by` is 'admin' or 'portal'; the portal is held to the device limit.
* `opts.lan_bypass` true keeps the device's own local network outside the
* tunnel (awg.allowed_ips).
*/
export function create_device(c, m, person_id, name, kind, opts) {
opts ??= {};
@@ -659,8 +690,8 @@ export function create_device(c, m, person_id, name, kind, opts) {
if (!srv)
fail(_('The person has no server.'));
name = trim(name ?? '');
if (!valid_name(name))
fail(_('Enter a device name (up to 48 characters).'));
if (!valid_device_name(name))
fail(sprintf(_('Enter a device name: up to %d letters, digits, spaces and - _ .'), DEVICE_NAME_MAX));
if (index(KINDS, kind) < 0)
kind = 'other';
if (opts.by == 'portal' && length(p.devices) >= p.device_limit)
@@ -677,10 +708,15 @@ export function create_device(c, m, person_id, name, kind, opts) {
for (let o, d in m.devices)
if (d.public_key == k.public_key)
fail(_('This key is already in use.'));
// A server's own key (it is in every configuration): the kernel would silently ignore such a peer.
for (let sid, s in m.servers)
if (s.public_key == k.public_key)
fail(_('This key is already in use.'));
let id = `d_${rand_hex(4)}`;
let dev = { id, person: person_id, name, kind, address: addr, public_key: k.public_key, private_key: k.private_key ?? '',
preshared_key: k.preshared_key ?? '', created: time(), created_by: opts.by ?? 'admin', disabled: false };
preshared_key: k.preshared_key ?? '', created: time(), created_by: opts.by ?? 'admin', disabled: false,
mtu: 0, keepalive: null, lan_bypass: opts.lan_bypass === true };
c.set(CONFIG, id, 'device');
c.set(CONFIG, id, 'person', person_id);
c.set(CONFIG, id, 'name', name);
@@ -691,6 +727,8 @@ export function create_device(c, m, person_id, name, kind, opts) {
c.set(CONFIG, id, f, dev[f]);
c.set(CONFIG, id, 'created', `${dev.created}`);
c.set(CONFIG, id, 'created_by', dev.created_by);
if (dev.lan_bypass)
c.set(CONFIG, id, 'lan_bypass', '1');
// Keep the in-memory model consistent for callers that continue.
m.devices[id] = dev;
@@ -703,8 +741,8 @@ export function rename_device(c, m, id, name) {
if (!d)
fail(_('Unknown device.'));
name = trim(name ?? '');
if (!valid_name(name))
fail(_('Enter a device name (up to 48 characters).'));
if (!valid_device_name(name))
fail(sprintf(_('Enter a device name: up to %d letters, digits, spaces and - _ .'), DEVICE_NAME_MAX));
for (let o in m.people[d.person]?.devices ?? [])
if (o != id && lc(m.devices[o].name) == lc(name))
fail(sprintf(_('"%s" already exists.'), name));
@@ -712,6 +750,45 @@ export function rename_device(c, m, id, name) {
d.name = name;
};
/**
* The admin's link settings of a device: `a` = { mtu?, keepalive?,
* lan_bypass? }, only keys present change; '' takes a number back to the
* server's (0 is a keep-alive of its own: off). Each is in the device's
* configuration alone (the server's peers carry neither), so a change asks
* that device to import again and touches nothing on the router. Returns the
* names of the options that changed.
*/
export function set_device_link(c, m, id, a) {
let d = m.devices[id];
if (!d)
fail(_('Unknown device.'));
let changed = [];
let put = (k, v, was) => {
if (v == was)
return;
if (v == null)
c.delete(CONFIG, id, k);
else
c.set(CONFIG, id, k, `${v}`);
push(changed, k);
};
let number = (v, r, msg) => {
let s = trim(`${v}`);
if (s == '')
return null;
if (!match(s, /^[0-9]{1,4}$/) || +s < r[0] || +s > r[1])
fail(msg);
return +s;
};
if (a.mtu != null)
put('mtu', number(a.mtu, MTU_RANGE, _('MTU must be 1280-1500.')), d.mtu || null);
if (a.keepalive != null)
put('keepalive', number(a.keepalive, KEEPALIVE_RANGE, _('Keep-alive must be 0-600 seconds.')), d.keepalive);
if (a.lan_bypass != null)
put('lan_bypass', a.lan_bypass === true ? 1 : null, d.lan_bypass ? 1 : null);
return changed;
};
export function delete_device(c, m, id) {
let d = m.devices[id];
if (!d)
@@ -781,10 +858,12 @@ export function server_errors(m, srv, others_subnets) {
* an address outside their server's subnet, the server's own address, a
* prefix on it or one shared with another device (the access sets are keyed
* by address, and one bad peer line makes `awg syncconf` refuse the whole
* server), malformed keys, people and devices pointing at servers, people,
* circles or services that do not exist, and two people with one link. [] when
* it is consistent. Import, restore and Health check it; the runtime sync
* skips what it would reject (dawnline.awg, dawnline.nft).
* server), malformed keys, an MTU or keep-alive of their own out of range,
* people and devices pointing at servers, people, circles or services that do
* not exist, and two people with one link. [] when it is consistent. Import,
* restore and Health check it; the runtime sync skips what it would reject
* (dawnline.awg, dawnline.nft), and a configuration takes the server's value
* for a link value out of range (device_mtu, device_keepalive).
*/
export function model_errors(m) {
let errs = [];
@@ -816,6 +895,11 @@ export function model_errors(m) {
say(_('Device %s of %s: the private key is not a key.'));
if (d.preshared_key != '' && !valid_key(d.preshared_key))
say(_('Device %s of %s: the preshared key is not a key.'));
// Its own link values (0 / null: the server's); one out of range is never used.
if (d.mtu && !in_range(d.mtu, MTU_RANGE))
say(_('Device %s of %s: MTU %d is not between 1280 and 1500.'), d.mtu);
if (d.keepalive != null && !in_range(d.keepalive, KEEPALIVE_RANGE))
say(_('Device %s of %s: keep-alive %d is not between 0 and 600 seconds.'), d.keepalive);
let n = ip2int(d.address);
if (n == null) {
if (d.address)
@@ -825,6 +909,9 @@ export function model_errors(m) {
continue;
}
let srv = m.servers[p.server];
// AmneziaWG ignores a peer with the interface's own key (dawnline.awg tunnel_devices leaves it out).
if (srv?.public_key && d.public_key == srv.public_key)
say(_("Device %s of %s: the public key is the server's own."));
let t = srv ? parse_cidr(srv.subnet) : null;
if (t && (n < t.first || n > t.last))
say(_("Device %s of %s: address %s is outside %s's tunnel %s."), d.address, srv.name, srv.subnet);
@@ -39,11 +39,15 @@ function own(m, id, opts) {
return d;
}
/** New device with fresh keys (or the browser's public key): { id, config }. */
/**
* New device with fresh keys (or the browser's public key): { id, config }.
* `opts.lan_bypass` true keeps its own local network outside the tunnel.
*/
export function add(person, name, kind, opts) {
opts ??= {};
let by = opts.by ?? 'admin';
let id = store.transact((c, m) => core.create_device(c, m, person, name, kind, { by, keys: awg.new_keys(opts.public_key || null) }));
let id = store.transact((c, m) => core.create_device(c, m, person, name, kind,
{ by, keys: awg.new_keys(opts.public_key || null), lan_bypass: opts.lan_bypass === true }));
let s = apply.sync();
let m = core.load();
live.add_event({ type: 'device_added', person, device: id, detail: m.devices[id].name, by });
@@ -52,14 +56,21 @@ export function add(person, name, kind, opts) {
};
/**
* Rename and/or turn a device off or on (`ch` = { name?, disabled? }); only
* the admin turns devices off. Returns the runtime sync.
* Rename and/or turn a device off or on, or change how it connects (`ch` =
* { name?, disabled?, mtu?, keepalive?, lan_bypass? }, see
* core.set_device_link); only the admin turns devices off or changes the
* rest. Returns the runtime sync ({} after a change of the link values alone:
* they are in the device's configuration, nothing on the router changes).
*/
export function update(id, ch, opts) {
opts ??= {};
let by = opts.by ?? 'admin';
if (ch.disabled != null && by != 'admin')
die(_('Only the admin can turn devices off.'));
let link = ch.mtu != null || ch.keepalive != null || ch.lan_bypass != null;
if (link && by != 'admin')
die(_('Only the admin can change how a device connects.'));
let linked = [];
let d0 = store.transact((c, m) => {
let d = own(m, id, opts);
let was = { ...d };
@@ -71,18 +82,28 @@ export function update(id, ch, opts) {
else
c.delete(core.CONFIG, id, 'disabled');
}
if (link)
linked = core.set_device_link(c, m, id, ch);
return was;
});
let r = apply.sync();
let r = ch.name != null || ch.disabled != null ? apply.sync() : {};
if (ch.disabled != null && !!ch.disabled != !!d0.disabled)
live.add_event({ type: 'device_changed', person: d0.person, device: id, detail: ch.disabled ? 'turned off' : 'turned on', by });
else if (ch.name != null && ch.name != d0.name)
live.add_event({ type: 'device_changed', person: d0.person, device: id, detail: `renamed from ${d0.name}`, by });
// The option names, as person_changed lists a person's.
if (length(linked))
live.add_event({ type: 'device_changed', person: d0.person, device: id, detail: join(', ', linked), by });
return r;
};
/** New keys for a device: returns its new configuration. */
export function rotate(id, opts) {
/*
* New keys for a device: returns its new configuration, marked as issued (it
* goes to the set-up sheet; the device then waits for it as "Not set up yet",
* not as "settings changed"). Only through reconnect: new keys always mean
* setting the device up again.
*/
function rotate(id, opts) {
opts ??= {};
let by = opts.by ?? 'admin';
store.transact((c, m) => {
@@ -104,14 +125,15 @@ export function rotate(id, opts) {
if (s?.warning)
cfg.warning = s.warning;
return cfg;
};
}
/**
* Set a device up from scratch (a new phone, the app reinstalled, settings
* the admin changed): new keys, so the configuration it holds stops working
* with the sync, and it counts as not set up until it connects with the new
* one. The usage keeps the old keys' last handshake: awg.handshake_since hides
* it. Returns the new configuration, as rotate.
* the admin changed; the portal's Reconnect and the admin's New keys): new
* keys, so the configuration it holds stops working with the sync, and it
* counts as not set up until it connects with the new one. The usage keeps
* the old keys' last handshake: awg.handshake_since hides it. Returns the new
* configuration (with `warning` when the sync did not fully take).
*/
export function reconnect(id, opts) {
opts ??= {};
@@ -223,23 +223,138 @@ export function wan_kind(wan) {
return length(filter(PRIVATE, (c) => in_cidr(wc, c))) ? 'private' : 'public';
};
const HEX = '0123456789abcdef';
// An IPv6 address as its 32 hex digits, so two spellings of one address
// compare equal (2001:DB8::1, 2001:db8:0::1, as typed or as a tool prints
// it); null when it is none. No regex: the router's addresses and a name's
// AAAA records go through it on every look.
function ip6_full(s) {
if (type(s) != 'string')
return null;
let halves = split(lc(s), '::');
if (length(halves) > 2)
return null;
let head = halves[0] != '' ? split(halves[0], ':') : [];
let tail = length(halves) == 2 && halves[1] != '' ? split(halves[1], ':') : [];
let gap = 8 - length(head) - length(tail);
if (length(halves) == 2 ? gap < 1 : gap != 0)
return null;
let groups = [ ...head ];
for (let i = 0; i < gap; i++)
push(groups, '0');
push(groups, ...tail);
let out = '';
for (let g in groups) {
if (length(g) < 1 || length(g) > 4 || ltrim(g, HEX) != '')
return null;
out += substr(`0000${g}`, length(g));
}
return out;
}
/**
* The router's public IPv6 addresses in `ip -6 -j addr show scope global`
* output (`links`), on any interface: a DDNS client may publish the LAN's
* address from the delegated prefix, which reaches the router too. Unique
* local addresses (fc00::/7: OpenWrt gives the LAN one even without IPv6
* from the ISP) and failed duplicates do not count: nothing reaches them from
* outside. [] when there is none.
*/
export function own_ipv6(links) {
let out = [];
for (let l in (type(links) == 'array' ? links : []))
for (let a in l?.addr_info ?? []) {
let k = ip6_full(a?.local);
if (k && a.family == 'inet6' && !a.dadfailed && substr(k, 0, 2) != 'fc' && substr(k, 0, 2) != 'fd')
push(out, a.local);
}
return out;
};
// The router's public IPv6 addresses (own_ipv6), or null when `ip` could not tell.
function router_ipv6() {
let out = sh_out('ip -6 -j addr show scope global');
if (out == null)
return null;
try {
let links = json(out || '[]');
return type(links) == 'array' ? own_ipv6(links) : null;
}
catch (e) {
// No JSON (an `ip` without -j): unknown, so the AAAA records get no verdict.
return null;
}
}
// What the facts are made from, read on the router.
function endpoint_reads(srv, host) {
let ips = host ? lookup.resolve(host) : [];
// The router's IPv6 only when the name has some to compare with.
return {
ips, wan: srv ? (net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone)) : lookup.wan_ipv4('wan'),
router6: length(filter(ips, (a) => ip2int(a) == null)) ? router_ipv6() : null,
};
}
/**
* What a public address points at, for Health and the "as you type" check on
* the server page: { host, ips, ips4, ips6, wan, kind (wan_kind), cloudflare,
* here (an IPv4 of it is this router's WAN), v6_only }.
* here (an IPv4 of it is this router's WAN), v6_only, router6 (the router's
* public IPv6 addresses, own_ipv6; null when unknown, or not read because the
* name has no IPv6), foreign6 (its IPv6 addresses that are none of those, all
* of them when the router has none; null while router6 is), here6 (it has
* IPv6 addresses and each is one of the router's) }. `reads` (a test's)
* stands for what is read on the router: { ips, wan, router6 }.
*/
export function endpoint_facts(srv, host) {
let ips = host ? lookup.resolve(host) : [];
let wan = srv ? (net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone)) : lookup.wan_ipv4('wan');
export function endpoint_facts(srv, host, reads) {
let r = reads ?? endpoint_reads(srv, host);
let ips = r.ips ?? [], wan = r.wan ?? null;
let ips4 = filter(ips, (a) => ip2int(a) != null), ips6 = filter(ips, (a) => ip2int(a) == null);
let own = r.router6 != null ? map(r.router6, ip6_full) : null;
let foreign6 = own != null ? filter(ips6, (a) => index(own, ip6_full(a)) < 0) : null;
return {
host, ips, ips4, ips6, wan: wan ?? null, kind: wan_kind(wan),
host, ips, ips4, ips6, wan, kind: wan_kind(wan),
cloudflare: length(filter(ips, (a) => cloudflare_ip(a))) > 0,
here: wan != null && index(ips4, wan) >= 0,
v6_only: !length(ips4) && length(ips6) > 0,
router6: r.router6 ?? null, foreign6,
here6: foreign6 != null && length(ips6) > 0 && !length(foreign6),
};
};
/*
* The name's IPv6 addresses that do not reach this router from outside, in
* words, or null (each is a public one of the router, or those are unknown).
* A name with IPv4 too: devices that prefer IPv6 take these and fail, the
* others connect.
*/
function aaaa_words(f) {
let bad = f.foreign6 ?? [], n = length(bad);
if (!n)
return null;
if (!length(f.router6))
return sprintf(N_(n, '%s AAAA → %s, but this router has no public IPv6 address: devices that prefer IPv6 will fail to connect. Remove this AAAA record or set up IPv6 on the router.',
'%s AAAA → %s, but this router has no public IPv6 address: devices that prefer IPv6 will fail to connect. Remove these AAAA records or set up IPv6 on the router.'),
f.host, join(', ', bad));
return sprintf(N_(n, '%s AAAA → %s is not a public address of this router: devices that prefer IPv6 will fail to connect. Fix or remove this AAAA record.',
'%s AAAA → %s are not public addresses of this router: devices that prefer IPv6 will fail to connect. Fix or remove these AAAA records.'),
f.host, join(', ', bad));
}
// An IPv6-only name none of whose addresses is a public one of the router: no device connects. Null otherwise.
function v6_only_unreached(f) {
let n = length(f.foreign6 ?? []);
if (!n || n < length(f.ips6))
return null;
if (!length(f.router6))
return sprintf(_('%s → %s: IPv6 only, but this router has no public IPv6 address: no device can connect. Check your DNS / DDNS, or set up IPv6 on the router.'),
f.host, join(', ', f.ips6));
return sprintf(N_(n, '%s → %s: IPv6 only, and not a public address of this router: no device can connect. Check your DNS / DDNS.',
'%s → %s: IPv6 only, and not public addresses of this router: no device can connect. Check your DNS / DDNS.'),
f.host, join(', ', f.ips6));
}
/**
* The facts in words, in the language of the call: { status: ok|warn|error, text }
* (text a whole sentence). `proto_note` names what must get through ("UDP 4500").
@@ -252,18 +367,28 @@ export function endpoint_words(f, proto_note) {
if (f.cloudflare)
return { status: 'error', text: sprintf(_("%s → %s (Cloudflare). %s reaches the router only if this name is DNS-only there, or use the router's IP."),
f.host, join(', ', f.ips), proto_note) };
if (f.v6_only)
let v6 = aaaa_words(f);
if (f.v6_only) {
let none = v6_only_unreached(f);
if (none != null || v6 != null)
return { status: 'warn', text: none ?? v6 };
return { status: f.kind == 'public' ? 'warn' : 'ok', text: f.kind == 'public'
? sprintf(_("%s → %s: IPv6 only, so only devices with IPv6 connect (the router's IPv4 %s has no name)."), f.host, join(', ', f.ips6), f.wan)
: sprintf(_('%s → %s: IPv6 only, so only devices with IPv6 connect.'), f.host, join(', ', f.ips6)) };
}
let v4 = null;
if (f.kind == 'cgnat' || f.kind == 'private')
return { status: 'warn', text: f.kind == 'cgnat'
v4 = f.kind == 'cgnat'
? sprintf(_('The WAN address %s is CGNAT (shared by the ISP): %s cannot be forwarded to this router from outside unless the ISP gives a public address or IPv6.'), f.wan, proto_note)
: sprintf(_('The WAN address %s is private: this router is behind another one. Forward %s on it, or devices cannot connect.'), f.wan, proto_note) };
if (f.wan && !f.here)
return { status: 'warn', text: sprintf(_('%s points at %s, not this router (WAN %s). Check your DNS / DDNS.'), f.host, join(', ', f.ips4), f.wan) };
: sprintf(_('The WAN address %s is private: this router is behind another one. Forward %s on it, or devices cannot connect.'), f.wan, proto_note);
else if (f.wan && !f.here)
v4 = sprintf(_('%s points at %s, not this router (WAN %s). Check your DNS / DDNS.'), f.host, join(', ', f.ips4), f.wan);
// Two separate facts, each a sentence of its own: the IPv4 one first.
if (v4 != null || v6 != null)
return { status: 'warn', text: join(' ', filter([ v4, v6 ], (x) => x != null)) };
// Without the router's WAN address only the facts: names and addresses, no words.
return { status: 'ok', text: f.here ? sprintf(_('%s points at this router (%s).'), f.host, f.wan) : `${f.host} → ${join(', ', f.ips)}` };
return { status: 'ok', text: f.here ? sprintf(_('%s points at this router (%s).'), f.host, join(', ', [ f.wan, ...(f.here6 ? f.ips6 : []) ]))
: `${f.host} → ${join(', ', f.ips)}` };
};
/** What a public address resolves to and whether that reaches this router (for a core's protocol). */
@@ -332,9 +457,53 @@ function awg_check() {
}
if (!st.handler)
return check('awg', title, 'error', no_proto(), 'netrestart', _('The network doesn’t know AmneziaWG yet'));
// The install could not swap the loaded module: the old one runs until the next boot (dawnline.awg_builds).
if (builds.waits_for_reboot())
return check('awg', title, 'warn', _('The AmneziaWG update is installed and starts after a reboot.'), null,
_('The AmneziaWG update waits for a reboot'));
return check('awg', title, 'ok', _('Kernel module, awg tool and the netifd protocol are present.'));
}
/**
* The /24s home routers come with out of the box. A home network on one of
* them is very likely the same as the network a person connects from, and
* home access then takes those addresses into the tunnel: their own printer or
* TV is out of reach while connected, LAN Bypass or not.
*/
const COMMON_HOME = [
'192.168.0.0/24', '192.168.1.0/24', '192.168.2.0/24', '192.168.3.0/24', '192.168.8.0/24', '192.168.10.0/24',
'192.168.31.0/24', '192.168.50.0/24', '192.168.88.0/24', '192.168.100.0/24', '192.168.178.0/24',
'10.0.0.0/24', '10.1.1.0/24',
];
/** The home networks in `nets` that overlap a common out-of-the-box subnet. */
export function common_home(nets) {
return filter(nets ?? [], (n) => {
let a = parse_cidr(n);
return a && length(filter(COMMON_HOME, (c) => cidr_overlaps(a, parse_cidr(c))));
});
};
/**
* Whether the server's home networks are on a common subnet, while anyone on
* it has home access (otherwise nothing of home goes into the tunnel). A
* warning on Health only: advice, not a fault, so no notice elsewhere.
*/
function home_check(m, id, srv, label) {
let reach = filter(values(m.people), (p) => p.server == id && (p.access == 'lan' || p.access == 'both'));
let nets = net.server_net(srv).nets;
if (!length(reach) || !length(nets))
return null;
let bad = common_home(nets);
let c = check(`homenet_${id}`, _('Home network addresses') + label, length(bad) ? 'warn' : 'ok',
length(bad)
? sprintf(_('%s is one of the most common home subnets. On a network with the same addresses, people with home access reach your home instead of their own: their printer or TV there is out of reach while connected, with LAN Bypass too. A rarer subnet for your home network avoids it, for example 10.37.12.0/24.'), join(', ', bad))
: sprintf(_('%s is not a common home subnet: the networks people connect from rarely use the same addresses.'), join(', ', nets)),
null);
c.problem = null;
return c;
}
/** Checks of a server's AmneziaWG tunnel. */
function awg_checks(m, id, srv, label, fwc, dmp, rep) {
let out = [];
@@ -350,26 +519,15 @@ function awg_checks(m, id, srv, label, fwc, dmp, rep) {
!st ? sprintf(_('%s does not exist.'), srv.ifname) :
length(codes) ? sprintf(_('%s is down: %s.'), srv.ifname, join(', ', codes)) : sprintf(_('%s is down.'), srv.ifname),
up ? null : (st ? 'ifup:' + srv.ifname : 'apply'), down));
if (up) {
// By key, not by count: a stale peer standing in for a missing one would
// make the numbers match.
let states = apply.states_for(m, core.load_usage());
let wanted = {}, expected = 0;
for (let did, d in m.devices) {
let p = m.people[d.person];
if (p?.server == id && !d.disabled && index(awg.SOFT_STATES, states[d.person]) >= 0) {
wanted[d.public_key] = true;
expected++;
}
}
let loaded = {}, actual = 0;
for (let k, p in dmp.peers)
if (p.ifname == srv.ifname) {
loaded[k] = true;
actual++;
}
let missing = length(filter(keys(wanted), (k) => !loaded[k]));
let extra = length(filter(keys(loaded), (k) => !wanted[k]));
// The devices the sync loads, by the same choice the agent compares with every minute.
if (up && dmp.reads[srv.ifname] == 'error')
push(out, check(`peers_${id}`, _('AmneziaWG devices loaded') + label, 'warn',
_('The tunnel could not be read, so its devices could not be checked.'), null,
_('The devices in AmneziaWG could not be checked') + label));
else if (up) {
let devs = awg.tunnel_devices(m, id, apply.states_for(m, core.load_usage()));
let diff = awg.peer_diff(devs, dmp, srv.ifname);
let expected = length(devs), missing = diff.missing, extra = diff.extra, actual = diff.loaded;
let same = !missing && !extra;
push(out, check(`peers_${id}`, _('AmneziaWG devices loaded') + label, same ? 'ok' : 'warn',
same ? sprintf(N_(actual, '%d device is loaded in the tunnel.', '%d devices are loaded in the tunnel.'), actual) :
@@ -406,6 +564,9 @@ function awg_checks(m, id, srv, label, fwc, dmp, rep) {
push(out, check(`subnet_${id}`, _('AmneziaWG subnet is unique') + label, length(overlaps) ? 'error' : 'ok',
length(overlaps) ? sprintf(_('%s overlaps %s.'), srv.subnet, join(', ', overlaps)) : sprintf(_('%s does not overlap other networks.'), srv.subnet),
null, _('AmneziaWG subnet overlaps another network') + label));
let home = home_check(m, id, srv, label);
if (home)
push(out, home);
return out;
}
@@ -0,0 +1,433 @@
// Dawnline — how each device's link behaves, from the counters the agent's
// watcher reads every second (dawnline.awg.dump): a device that knocks but
// never finishes connecting, one whose configuration is in use on two devices,
// one whose traffic the router drops, one whose connection keeps breaking.
//
// The agent keeps one history per device in memory (fresh(), observe(): a few
// events of the last HISTORY seconds, not one entry per tick), classifies it
// (classify(), pure) and shows a state only once it held HOLD seconds
// (settle()). It writes what is shown to dawnline.live.LINK on a change; the
// read side (live.dump's `link`, view.device_view) is dawnline.live's, so the
// portal never loads this module. Who is online stays live.PRESENCE's.
//
// The same history tells the set-up sheet, at once and without HOLD, what a
// device that is being set up does right now (setup_state(), setup()): it
// knocks without finishing, data flows, or it connected but nothing it sends
// comes through. The agent writes that to dawnline.live.SETUP on a change.
//
// What the counters mean (kmod 3.1, receive.c and send.c):
// * an accepted handshake initiation adds exactly INITIATION bytes to the
// peer's rx: the S1 prefix and any trailer are cut off and the header
// protection is undone in place before update_rx_stats(skb->len). The
// router answers it; its own handshake time moves only when the first
// packet under the new keys arrives.
// * a keepalive adds KEEPALIVE plus its content padding; a handshake
// response (the router initiated) RESPONSE; data 32 + its padded length.
// Plain data is a multiple of 16, so 148, 296 and 444 never are data.
// * a data packet the router then drops (its source is not the device's
// address: an old configuration after renumbering; this is what moves
// the interface's rx_frame_errors) adds nothing to rx, but the router
// still answers it with a keepalive within KeepaliveTimeout (about 10 s).
/** Seconds of events kept per device. */
export const HISTORY = 600;
/** A state is shown once it held this long (a flapping mobile link passes). */
export const HOLD = 180;
/** A device is classified at least this often when nothing happened (its spans age). */
export const CHECK_EVERY = 15;
/** Bytes an accepted initiation adds to rx (sizeof(struct message_handshake_initiation)). */
export const INITIATION = 148;
/** Bytes a handshake response adds to rx (the router initiated). */
export const RESPONSE = 92;
/** Bytes an empty data packet adds to rx, before content padding. */
export const KEEPALIVE = 32;
// Random trailers without content padding: a keepalive grows up to a full packet.
const TRAILER_MAX = 1500;
// Initiations a device sends at most in one second (retries are 5 s apart).
const KNOCKS_PER_TICK = 3;
/** trying: at least TRY_KNOCKS accepted initiations within TRY_SPAN seconds while not online. */
export const TRY_SPAN = 120;
export const TRY_KNOCKS = 3;
/*
* Churning: at least CHURN_COUNT handshakes within CHURN_SPAN seconds, with
* CHURN_COUNT - 1 of the gaps under CHURN_GAP seconds. A device that is
* there renews its keys every 100-120 s (RekeyAfterTime), more only when
* its packets get nothing back (KeepaliveTimeout + RekeyTimeout, ~15 s).
*/
export const CHURN_SPAN = 300;
export const CHURN_COUNT = 4;
export const CHURN_GAP = 45;
/** shared: while churning, the endpoint (ip:port) went back to an earlier one this often. */
export const SHARE_RETURNS = 2;
/*
* dropped: online with a handshake within DROP_HS seconds, nothing but
* handshakes and keepalives received for DROP_SPAN seconds, and the router
* sent something at least DROP_ANSWERS times in that span with nothing
* coming in (its keepalives answering packets it dropped), under DROP_TX
* bytes in all (a real download is far more).
*/
export const DROP_SPAN = 180;
export const DROP_HS = 240;
export const DROP_ANSWERS = 6;
export const DROP_TX = 65536;
/** Every state classify() can give. */
export const STATES = [ 'trying', 'shared', 'dropped', 'unstable' ];
/*
* The set-up sheet's trying: at least SETUP_KNOCKS accepted initiations
* within SETUP_SPAN seconds, none of them followed by a handshake. A device
* retries every 5 s, so it shows with the second (5-6 s in) and goes about
* 15 s after the last.
*/
export const SETUP_SPAN = 20;
export const SETUP_KNOCKS = 2;
/*
* nodata: online for SETUP_QUIET seconds since the handshake its session
* began with, nothing but handshakes and keepalives in since, and the router
* answered at least once with nothing coming in (a keepalive for data it
* dropped, about 10 s after it: an old address in the configuration). An
* idle device gets no answers, so it never shows.
*/
export const SETUP_QUIET = 15;
// Per list, the newest entries kept (a device whose endpoint flips every second).
const KEEP = 64;
function keep(list, entry) {
push(list, entry);
if (length(list) > KEEP)
shift(list);
}
/**
* A new, empty history for a device first seen at `now`. Fields: rx, tx
* (the counters last read, null before the first read), hs (the newest
* handshake), ep (the endpoint), data (when rx last carried data), hsev
* (handshake times), epev ([ ts, ip:port, the one before ] endpoint
* changes), knocks (times
* of accepted initiations), ans ([ ts, bytes ] the router sent with nothing
* received), state/since (what is shown), pend (a state waiting for HOLD),
* raw (the last classification), checked (when it was made); for the set-up
* sheet (setup()): on (online at the last read), sess (the handshake its
* online stretch began with, 0 while away), setup ({ state, since } or null)
* and due (when setup_state() may change with time alone, 0 for never).
*/
export function fresh(now) {
return {
start: now, rx: null, tx: null, hs: 0, ep: null, data: 0,
hsev: [], epev: [], knocks: [], ans: [],
state: null, since: 0, pend: null, raw: null, checked: 0,
on: false, sess: 0, setup: null, due: 0,
};
};
/**
* The largest rx a keepalive adds for a server's disguise: KEEPALIVE plus
* the top of its ContentPaddingAddition, or a full packet with random
* trailers and no content padding (the apps get the server's values).
*/
export function keepalive_max(srv) {
let o = srv?.obf ?? {};
let cpa = split(`${o.content_padding_addition ?? ''}`, '-');
let hi = +(cpa[length(cpa) - 1]);
if (o.content_padding_addition != null && o.content_padding_addition != '' && hi > 0)
return KEEPALIVE + hi;
if (o.random_trailers == 'on' || o.random_trailers == '1')
return KEEPALIVE + TRAILER_MAX;
return KEEPALIVE;
};
/** keepalive_max() for each device's server: { device id: bytes }. */
export function keepalive_sizes(m) {
let out = {};
for (let id, d in m.devices)
out[id] = keepalive_max(m.servers[m.people[d.person]?.server]);
return out;
};
/** An rx increment made of accepted initiations only. */
export function knock(drx) {
return drx > 0 && drx % INITIATION == 0 && drx <= KNOCKS_PER_TICK * INITIATION;
};
/**
* An rx increment that carried no data: nothing, or one keepalive of up to
* `ka` bytes (keepalive_max); in the second a handshake completed (`shook`)
* also the handshake messages that came with it. Outside that second a
* handshake message is never counted in: with a padded keepalive their
* sums would cover every small packet (a DNS query, an ACK) up to some
* 670 bytes, and a device with light traffic would look like one whose
* data never comes through.
*/
export function bare(drx, ka, shook) {
if (drx <= 0)
return true;
if (!shook)
return drx >= KEEPALIVE && drx <= ka;
if (drx > KNOCKS_PER_TICK * INITIATION + RESPONSE + ka)
return false;
for (let k = 0; k <= KNOCKS_PER_TICK; k++)
for (let r = 0; r <= 1; r++) {
let rest = drx - k * INITIATION - r * RESPONSE;
if (rest == 0 || (rest >= KEEPALIVE && rest <= ka))
return true;
}
return false;
};
/**
* Fold one read of the device's peer ({ endpoint, handshake, rx, tx } from
* awg.dump) at `now` into its history `h`; `ka` is its keepalive_max().
* Returns true when something worth classifying again happened (a
* handshake, a new endpoint, a knock, an answer, data after a quiet span).
* Counters that went down (the peer re-added, its tunnel set up again)
* start a new baseline.
*/
export function observe(h, peer, now, ka) {
let changed = false;
let shook = peer.handshake > h.hs;
if (shook) {
keep(h.hsev, peer.handshake);
h.hs = peer.handshake;
changed = true;
}
if (peer.endpoint != h.ep) {
if (h.ep != null && peer.endpoint != '') {
keep(h.epev, [ now, peer.endpoint, h.ep ]);
changed = true;
}
h.ep = peer.endpoint;
}
if (h.rx == null || peer.rx < h.rx || peer.tx < h.tx) {
h.rx = peer.rx;
h.tx = peer.tx;
return changed;
}
let drx = peer.rx - h.rx, dtx = peer.tx - h.tx;
h.rx = peer.rx;
h.tx = peer.tx;
if (drx > 0) {
if (!shook && knock(drx)) {
keep(h.knocks, now);
changed = true;
}
else if (!bare(drx, ka, shook)) {
if (now - h.data >= DROP_SPAN)
changed = true;
h.data = now;
}
}
else if (dtx > 0) {
keep(h.ans, [ now, dtx ]);
changed = true;
}
return changed;
};
/** The device's peer is not in its tunnel: the next read starts a new baseline. */
export function gone(h) {
h.rx = null;
h.tx = null;
};
/** Forget events older than HISTORY seconds. */
export function prune(h, now) {
let cut = now - HISTORY;
h.hsev = filter(h.hsev, (t) => t > cut);
h.knocks = filter(h.knocks, (t) => t > cut);
h.epev = filter(h.epev, (e) => e[0] > cut);
h.ans = filter(h.ans, (e) => e[0] > cut);
};
/** Endpoint changes within the span that went back to an endpoint seen before in it (A → B → A → B: 2). */
function returns(h, now) {
let seen = null, n = 0;
for (let e in h.epev)
if (now - e[0] < CHURN_SPAN) {
if (seen == null) {
seen = {};
seen[e[2]] = true;
}
if (seen[e[1]])
n++;
seen[e[1]] = true;
}
return n;
}
function churning(h, now) {
let hs = filter(h.hsev, (t) => now - t < CHURN_SPAN);
if (length(hs) < CHURN_COUNT)
return false;
let short = 0;
for (let i = 1; i < length(hs); i++)
if (hs[i] - hs[i - 1] < CHURN_GAP)
short++;
return short >= CHURN_COUNT - 1;
}
function dropped(h, now) {
if (now - h.start < DROP_SPAN || now - h.data < DROP_SPAN || !(h.hs > 0 && now - h.hs < DROP_HS))
return false;
let n = 0, bytes = 0;
for (let a in h.ans)
if (now - a[0] < DROP_SPAN) {
n++;
bytes += a[1];
}
return n >= DROP_ANSWERS && bytes < DROP_TX;
}
/**
* What the history says about the device at `now` (`on`: it is online, as
* the watcher decides it): null (nothing wrong, or nothing to tell), or
* 'trying' not online, but its initiations reach the router and are
* answered, and it never finishes connecting (the network
* may block it, or its configuration is out of date: a
* stale preshared key looks the same)
* 'shared' connecting over and over from two or more alternating
* endpoints (ip:port): one configuration on two devices
* 'unstable' connecting over and over from one place: the connection
* keeps breaking
* 'dropped' connected, but nothing it sends gets through: the router
* drops it (an old address in its configuration)
*/
export function classify(h, now, on) {
if (!on) {
let n = 0;
for (let t in h.knocks)
if (now - t < TRY_SPAN)
n++;
return n >= TRY_KNOCKS ? 'trying' : null;
}
if (churning(h, now))
return returns(h, now) >= SHARE_RETURNS ? 'shared' : 'unstable';
return dropped(h, now) ? 'dropped' : null;
};
/**
* Turn a classification into what is shown (h.state, h.since): a state, or
* a change of state, shows once classify() gave it for HOLD seconds (since
* = when it began); nothing wrong shows at once when the device is online
* (it works), else after HOLD as well. Returns the change, { from, to }
* (either may be null), or null when what is shown stays.
*/
export function settle(h, raw, now, on) {
if (raw == h.state) {
h.pend = null;
return null;
}
let since = now;
if (raw != null || !on) {
if (h.pend == null || h.pend.state != raw) {
h.pend = { state: raw, since: now };
return null;
}
if (now - h.pend.since < HOLD)
return null;
since = h.pend.since;
}
let from = h.state;
h.state = raw;
h.since = raw != null ? since : 0;
h.pend = null;
return { from, to: raw };
};
/**
* What the device's link does at `now` for the set-up sheet (pure; `on`: it
* is online, as the watcher decides it): { state, due }. state is
* 'trying' its initiations reach the router and are answered, and no
* handshake follows (SETUP_KNOCKS within SETUP_SPAN): the
* network blocks the answers, or the configuration is not this
* device's any more
* 'flowing' online, and data came in during this session (since h.sess)
* 'nodata' online for SETUP_QUIET seconds, nothing but handshakes and
* keepalives came in, and the router answered packets it
* dropped: an old address in the configuration
* null none of these (waiting, idle, or away)
* due: when the state may change with time alone (a knock ages out, the
* quiet span ends), 0 for never: anything else comes with a read.
*/
export function setup_state(h, now, on) {
let n = 0;
for (let i = length(h.knocks) - 1; i >= 0; i--) {
let t = h.knocks[i];
if (t <= h.hs || now - t >= SETUP_SPAN)
break;
if (++n == SETUP_KNOCKS)
return { state: 'trying', due: t + SETUP_SPAN };
}
if (!on || !h.sess)
return { state: null, due: 0 };
if (h.data >= h.sess)
return { state: 'flowing', due: 0 };
if (now - h.sess < SETUP_QUIET)
return { state: null, due: h.sess + SETUP_QUIET };
let a = h.ans[length(h.ans) - 1];
return { state: a != null && a[0] >= h.sess ? 'nodata' : null, due: 0 };
};
/**
* Bring h.setup to setup_state() after a read at `now` (`moved`: what
* observe() returned). Most reads cost a few compares: the state is worked
* out again only when something happened, the device came or went, data
* came in while it is not 'flowing', or its `due` time came. Returns true
* when h.setup changed ({ state, since: when it began } or null).
*/
export function setup(h, now, on, moved) {
// A session begins with the handshake that brought the device online.
if (!on)
h.sess = 0;
else if (!h.sess)
h.sess = h.hs;
let came = on != h.on;
h.on = on;
let cur = h.setup?.state;
if (!moved && !came && !(h.due && now >= h.due) && !(h.data == now && cur != 'flowing'))
return false;
let s = setup_state(h, now, on);
h.due = s.due;
if (s.state == cur)
return false;
h.setup = s.state != null ? { state: s.state, since: now } : null;
return true;
};
/** setup() of every device: { device id: { state, since } }, devices with none left out. */
export function setups(hist) {
let out = {};
for (let id, h in hist)
if (h.setup != null)
out[id] = h.setup;
return out;
};
/** What is shown for every device: { device id: { state, since } }, devices with nothing to show left out. */
export function shown(hist) {
let out = {};
for (let id, h in hist)
if (h.state != null)
out[id] = { state: h.state, since: h.since };
return out;
};
/**
* The activity event for a change settle() made, or null: device_failing
* (detail: the new state) when a state shows, device_recovered (detail:
* the state it had) when it clears while the device is online. One that
* clears while the device is away (it stopped trying, it was paused) logs
* nothing: nobody saw it work.
*/
export function event_for(change, dev, on) {
if (!change)
return null;
if (change.to != null)
return { type: 'device_failing', person: dev.person, device: dev.id, detail: change.to };
if (on && change.from != null)
return { type: 'device_recovered', person: dev.person, device: dev.id, detail: change.from };
return null;
};
@@ -11,11 +11,14 @@ import {
iface_status as util_iface_status, RUN_DIR, DATA_DIR
} from 'dawnline.util';
import * as awg from 'dawnline.awg';
import * as core from 'dawnline.core';
import * as schema from 'dawnline.schema';
// Online while the WireGuard session lives: it is dropped 180 s after its
// handshake, and a device that is there renews it every 2 min (a little slack
// for a renewal that needs a retry). One that left goes offline 1-3 min later.
// The shortest window: a device whose keep-alive is longer gets more
// (online_window), or it would flap between its handshakes.
export const ONLINE_WINDOW = 190;
/** A restore put other counters on flash: the agent reloads from there (dawnline.backup writes it). */
export const USAGE_RELOAD = `${RUN_DIR}/usage.reload`;
@@ -31,6 +34,8 @@ export const CATEGORY = {
person_added: 'people', person_removed: 'people', person_changed: 'people',
paused: 'people', resumed: 'people', expiring: 'people', expired_kept: 'people',
server_down: 'problems', server_up: 'problems', portal_blocked: 'problems',
// A device's link (dawnline.link): failing in a named way, and working again.
device_failing: 'problems', device_recovered: 'problems',
};
export const CATEGORIES = [ 'connections', 'people', 'problems' ];
@@ -95,24 +100,90 @@ export const PRESENCE = `${RUN_DIR}/presence.json`;
const BEAT = `${RUN_DIR}/agent.beat`;
const BEAT_STALE = 180;
/** The agent runs (its heartbeat is fresh): what its watcher wrote counts. */
function agent_running() {
let beat = +(read_json(BEAT, 0) ?? 0);
return beat > 0 && time() - beat <= BEAT_STALE;
}
/** What the watcher sees, or null when the agent isn't running. */
export function presence() {
let beat = +(read_json(BEAT, 0) ?? 0);
if (!beat || time() - beat > BEAT_STALE)
return null;
return read_json(PRESENCE, null);
return agent_running() ? read_json(PRESENCE, null) : null;
};
/**
* Peers of every tunnel: { ok, ifaces, peers: { public key: { ifname, endpoint,
* handshake, rx, tx } }, presence }. See dawnline.awg.
* Written by the agent's watcher when what it shows changes (dawnline.link):
* { device id: { state: 'trying' | 'shared' | 'dropped' | 'unstable', since } },
* only devices whose link fails in one of these ways (link.classify()).
*/
export function dump(m) {
// Only Dawnline's own tunnels decide `ok`: another AmneziaWG interface on
// the router that cannot be read is not our trouble.
let mine = m ? map(filter(values(m.servers), (s) => s.private_key && s.enabled), (s) => s.ifname) : null;
let d = awg.dump(mine);
d.presence = presence();
export const LINK = `${RUN_DIR}/link.json`;
/**
* Written by the agent's watcher when it changes (dawnline.link.setup, at
* once, without LINK's hold): what each device's link does right now, for the
* set-up sheet: { device id: { state: 'trying' | 'flowing' | 'nodata', since } },
* devices with none of these left out.
*/
export const SETUP = `${RUN_DIR}/setup.json`;
/**
* The interfaces of the servers that run: enabled, with keys and an
* interface that is Dawnline's (core.tunnels: never another tunnel that
* took the name); with `sid`, only that server's. What dawnline.awg.dump()
* reads; an empty list when none.
*/
export function tunnel_ifnames(m, sid) {
let out = [];
for (let id, srv in m.servers)
if (srv.enabled && (sid == null || id == sid))
for (let t in core.tunnels(srv))
push(out, t.ifname);
return out;
};
/**
* How long after its last handshake a device still counts as online, in
* seconds: ONLINE_WINDOW, or 30 s more than an idle device with its
* keep-alive goes between handshakes (awg.idle_handshake) when that is
* longer. A device that sends nothing renews its session only with its
* keep-alive: with one of about 95-120 s, or over 160 s, the fixed window
* would see it leave and come back between two handshakes. Keep-alive off:
* ONLINE_WINDOW.
*/
export function online_window(srv, dev) {
let h = srv ? awg.idle_handshake(srv, dev) : null;
return h != null ? max(ONLINE_WINDOW, h + 30) : ONLINE_WINDOW;
};
/** online_window() of every device (with `sid`, of that server's): { device id: seconds }. */
export function online_windows(m, sid) {
let out = {};
for (let id, d in m.devices) {
let s = m.people[d.person]?.server;
if (sid == null || s == sid)
out[id] = online_window(m.servers[s], d);
}
return out;
};
/**
* Dawnline's tunnels as dawnline.awg.dump() reads them (only those, each on
* its own: { ok, reads, ifaces, peers: { public key: { ifname, endpoint,
* handshake, rx, tx } } }), plus `presence`, the agent watcher's, `windows`,
* each device's online_window() (online() without the agent), `link`, the
* watcher's LINK ({} without the agent: its states would be stale), and
* `setup`, its SETUP (null without the agent: nobody tells data from a bare
* handshake then, view.device_view goes by the handshake). With `sid` only
* that server's tunnel is read (one person's page needs no other: one `awg`
* process, not one per server).
*/
export function dump(m, sid) {
let d = awg.dump(tunnel_ifnames(m, sid));
let up = agent_running();
d.presence = up ? read_json(PRESENCE, null) : null;
d.windows = online_windows(m, sid);
d.link = up ? (read_json(LINK, null) ?? {}) : {};
d.setup = up ? (read_json(SETUP, null) ?? {}) : null;
return d;
};
@@ -121,7 +192,7 @@ export function online(dmp, id, peer) {
let p = dmp?.presence?.online;
if (p)
return !!(peer && p[id]);
return !!(peer && peer.handshake > 0 && time() - peer.handshake < ONLINE_WINDOW);
return !!(peer && peer.handshake > 0 && time() - peer.handshake < (dmp?.windows?.[id] ?? ONLINE_WINDOW));
};
// "203.0.113.7:41821", "[2001:db8::1]:41821". A module constant, compiled once:
@@ -218,34 +289,36 @@ function offline(rec) {
/**
* Fold the current kernel counters into `usage`. Counters restart from zero
* when a peer is re-added or the interface restarts; a drop is treated as a
* reset. Returns the per-device live view keyed by device id.
* when a peer is re-added or its tunnel is set up again; a drop is treated
* as a reset, and so is a new link (each record keeps the interface index
* its counters were read on: new counters that already passed the old ones
* would be counted short). Returns the per-device live view keyed by device id.
*
* A device missing from the dump had its counters reset only when its tunnel
* was actually read: an interface the tool couldn't read says nothing, and
* forgetting the last counters there would count them again on the next good
* read. A failed read with nothing in it changes nothing at all.
* was read or is down (dawnline.awg.dump's `reads`): one the tool couldn't
* read says nothing, and forgetting the last counters there would count them
* again on the next good read.
*/
export function collect(m, usage, d) {
d ??= dump(m);
let ts = time();
let live = {};
if (d.ok === false && !length(d.peers)) {
for (let id in keys(m.devices))
live[id] = offline(usage.devices[id]);
return live;
}
for (let id, dev in m.devices) {
let rec = usage.devices[id] ??= { raw: [ 0, 0 ] };
let peer = d.peers[dev.public_key];
if (!peer) {
let ifname = m.servers[m.people[dev.person]?.server]?.ifname;
if (d.ok !== false || d.ifaces[ifname] != null)
if (d.reads[ifname] != 'error')
rec.raw = [ 0, 0 ];
live[id] = offline(rec);
continue;
}
let raw = rec.raw ?? [ 0, 0 ];
let link = d.ifaces[peer.ifname]?.ifindex;
if (link != null && rec.ifindex != null && link != rec.ifindex)
raw = [ 0, 0 ];
if (link != null)
rec.ifindex = link;
let drx = peer.rx >= raw[0] ? peer.rx - raw[0] : peer.rx;
let dtx = peer.tx >= raw[1] ? peer.tx - raw[1] : peer.tx;
rec.raw = [ peer.rx, peer.tx ];
@@ -266,7 +339,7 @@ export function collect(m, usage, d) {
delete rec.ips[ips[i]];
}
live[id] = {
online: peer.handshake > 0 && ts - peer.handshake < ONLINE_WINDOW,
online: peer.handshake > 0 && ts - peer.handshake < online_window(m.servers[m.people[dev.person]?.server], dev),
handshake: peer.handshake || rec.handshake || 0,
endpoint: endpoint_ip(peer.endpoint) || rec.endpoint || '',
present: true,
@@ -373,7 +446,10 @@ export function add_event(e) {
add_events([ e ]);
};
/** Like add_event, but folds into the previous event of the same kind and person within `window` s. */
/**
* Like add_event, but folds into the previous event of the same kind, person
* and device (when it has one) within `window` s.
*/
export function add_event_merged(e, window) {
let pol = policy();
if (index(pol.categories, category_of(e.type)) < 0)
@@ -382,7 +458,7 @@ export function add_event_merged(e, window) {
let ev = load_events();
let last = ev[length(ev) - 1];
let ts = time();
if (last && last.type == e.type && last.person == e.person && ts - last.ts < (window ?? 120)) {
if (last && last.type == e.type && last.person == e.person && last.device == e.device && ts - last.ts < (window ?? 120)) {
let parts = uniq([ ...split(last.detail ?? '', ', '), ...split(e.detail ?? '', ', ') ]);
last.detail = join(', ', filter(parts, (x) => x != ''));
last.ts = ts;
@@ -397,6 +397,23 @@ function load_ns_rules(p) {
return slow ? { fast: false, slow, err: load(false) } : { fast: true };
}
/**
* The policy rules plan `p` wants (pure), in order: [{ pref, iif, to, table }]
* (to null: all). Per server interface: DNS to the netns address through the
* netns, home networks and the tunnel network by main, the rest into the netns.
*/
export function rules(p) {
let out = [];
let rule = (pref, iif, to, table) => push(out, { pref, iif, to, table });
for (let s in p?.servers ?? []) {
rule(PREF_LOOP_DNS, s.ifname, `${p.address}/32`, `${p.table}`);
for (let n in s.direct)
rule(PREF_MAIN, s.ifname, n, 'main');
rule(PREF_LOOP, s.ifname, null, `${p.table}`);
}
return out;
};
/** Our policy rules: in our priority band and bound to a Dawnline tunnel interface. */
function current_rules(ifnames) {
let out = [];
@@ -411,31 +428,58 @@ function current_rules(ifnames) {
}
function rule_key(pref, iif, to, table) {
// `ip -j rule` shows a /32 destination without its length.
if (to && index(to, '/') < 0)
to += '/32';
return `${pref} ${iif} ${to ?? 'all'} ${table}`;
// A rule of ours with a source (none of rules() has one) is told apart, so it is removed.
function rule_key(pref, from, iif, to, table) {
// `ip -j rule` shows a /32 source or destination without its length.
let full = (n) => n && index(n, '/') < 0 ? `${n}/32` : n;
return `${pref} ${full(from) ?? 'all'} ${iif} ${full(to) ?? 'all'} ${table}`;
}
function sync_rules(p, ifnames) {
let want = [];
for (let s in p?.servers ?? []) {
push(want, [ PREF_LOOP_DNS, s.ifname, `${p.address}/32`, `${p.table}` ]);
for (let n in s.direct)
push(want, [ PREF_MAIN, s.ifname, n, 'main' ]);
push(want, [ PREF_LOOP, s.ifname, null, `${p.table}` ]);
/**
* A source or destination as `ip -j rule` has it ("10.9.0.2", or with its
* length), or null for all: a rule without a source shows `"src": "all"`
* (iproute2 prints "from all"), one without a destination no `dst`.
*/
function rule_net(addr, len) {
return addr && addr != 'all' ? `${addr}${len != null ? '/' + len : ''}` : null;
}
/** The command that removes one of current_rules(). */
function rule_del(r) {
let from = rule_net(r.src, r.srclen), to = rule_net(r.dst, r.dstlen);
return `ip -4 rule del priority ${r.priority}${from ? ' from ' + from : ''} iif ${q(r.iif)}${to ? ' to ' + to : ''} lookup ${r.table}`;
}
/**
* The commands that turn rules `current` (ours, as `ip -j -4 rule show`
* prints them) into rules(p) (pure): the missing ones added first, then the
* ones no longer wanted removed, so a device's traffic never falls between
* two rules while others change. [] when they are as wanted.
*/
export function rule_cmds(p, current) {
let have = {}, want = {}, cmds = [], twice = [];
for (let r in current) {
let k = rule_key(r.priority, rule_net(r.src, r.srclen), r.iif, rule_net(r.dst, r.dstlen), r.table);
if (have[k])
push(twice, rule_del(r));
have[k] = r;
}
let have = map(current_rules(ifnames), (r) => rule_key(r.priority, r.iif, r.dst ? `${r.dst}${r.dstlen != null ? '/' + r.dstlen : ''}` : null, r.table));
let wantk = map(want, (w) => rule_key(w[0], w[1], w[2] ?? null, w[3]));
if (join('\n', sort(have)) == join('\n', sort(wantk)))
return [];
let cmds = [];
for (let r in current_rules(ifnames))
push(cmds, `ip -4 rule del priority ${r.priority} iif ${q(r.iif)}${r.dst ? ' to ' + r.dst + (r.dstlen != null ? '/' + r.dstlen : '') : ''} lookup ${r.table}`);
for (let w in want)
push(cmds, `ip -4 rule add priority ${w[0]} iif ${q(w[1])}${w[2] ? ' to ' + w[2] : ''} lookup ${w[3]}`);
for (let w in rules(p)) {
let k = rule_key(w.pref, null, w.iif, w.to, w.table);
if (!have[k] && !want[k])
push(cmds, `ip -4 rule add priority ${w.pref} iif ${q(w.iif)}${w.to ? ' to ' + w.to : ''} lookup ${w.table}`);
want[k] = true;
}
for (let k, r in have)
if (!want[k])
push(cmds, rule_del(r));
// The same rule twice (one deletion removes one of them).
push(cmds, ...twice);
return cmds;
};
function sync_rules(p, ifnames) {
return rule_cmds(p, current_rules(ifnames));
}
function tunnel_ifnames() {
@@ -455,9 +499,7 @@ export function remove(ifnames) {
// Read while the link is there: the entry is ours when it carries the netns's MAC.
let held = last?.dev ? used_addresses(last.dev)[last.address] : null;
let stale = type(held) == 'string' && index([ last.mac, our_mac() ], held) >= 0;
let cmds = [];
for (let r in current_rules(ifnames))
push(cmds, `ip -4 rule del priority ${r.priority} iif ${q(r.iif)}${r.dst ? ' to ' + r.dst + (r.dstlen != null ? '/' + r.dstlen : '') : ''} lookup ${r.table}`);
let cmds = map(current_rules(ifnames), rule_del);
if (last?.table)
push(cmds, `ip -4 route flush table ${last.table}`);
if (exists(TX_ROOT))
@@ -0,0 +1,149 @@
// Dawnline — the live meter (the Overview's Speed now): each server's
// throughput, one point a second over the last two minutes.
//
// The meter RPC (dawnline.rpc.status) calls want() and read(); the agent's
// watcher makes a point from every read it already does (sample(), point())
// and keeps the last two minutes in memory (keep()) whether anyone looks or
// not, so a look gets them all at once. It writes them to FILE (save()) only
// while WANT is younger than WANT_FOR seconds: the first second of a look,
// then with each new point. When WANT goes stale it removes FILE: with nobody
// looking the watcher pays a little arithmetic and one stat() a second, and
// writes nothing. FILE holds server ids and byte rates only, no keys, names
// or personal codes. Who is online and the per-minute rates are not here
// (dawnline.live, the agent's tick).
//
// Bytes are the peers' counters (dawnline.awg.dump): tx includes the
// disguise (S prefixes, padding, junk), rx the packets as they were
// received without their prefix, so both are close to what is on the wire.
import { writefile, stat, unlink } from 'fs';
import { read_json, write_file, ensure_dir, RUN_DIR } from 'dawnline.util';
/** Touched by every meter RPC: the watcher samples while it is fresh. */
export const WANT = `${RUN_DIR}/meter.want`;
/** The points, written by the watcher each second while WANT is fresh. */
export const FILE = `${RUN_DIR}/meter.json`;
/** Seconds after the last meter RPC the watcher keeps sampling. */
export const WANT_FOR = 10;
/** Points kept: two minutes, one a second. */
export const POINTS = 120;
/** Ask the watcher to sample for the next WANT_FOR seconds (the meter RPC). */
export function want() {
ensure_dir(RUN_DIR);
writefile(WANT, `${time()}`);
};
/** Someone asked for the meter within WANT_FOR seconds of `now`. */
export function wanted(now) {
let st = stat(WANT);
return st != null && now - st.mtime < WANT_FOR && st.mtime - now < WANT_FOR;
};
/**
* What the watcher wrote, for the RPC: { now, want: WANT_FOR, keep: POINTS,
* ts (newest point, 0 for none), points } with only the points newer than
* `since` when it is given (a page that polls asks for what it lacks).
* No points when nobody asked within WANT_FOR seconds or the agent is not
* running: FILE is gone (the agent removes it as it stops and starts), or,
* from one that died while someone looked, its newest point is over
* WANT_FOR seconds old (ts then stops moving).
*/
export function read(since) {
let f = read_json(FILE, null);
let ts = +(f?.ts ?? 0);
let pts = type(f?.points) == 'array' && time() - ts <= WANT_FOR ? f.points : [];
if (since > 0)
pts = filter(pts, (p) => p.ts > since);
return { now: time(), want: WANT_FOR, keep: POINTS, ts: ts, points: pts };
};
/** Monotonic seconds, with the fraction: the gap between two samples. */
function mono() {
let c = clock(true);
return c[0] + c[1] / 1e9;
}
/**
* One sample at `now` from the dump the watcher just read (`d`): { t, ts,
* servers: [ server id ] (those whose tunnel was read), dev: { device id:
* [ rx, tx, server id ] } (its peer's counters, on those servers) }. Nothing
* but the dump is read.
*/
export function sample(m, d, now) {
let s = { t: mono(), ts: now, servers: [], dev: {} };
let read = {};
for (let sid, srv in m.servers)
if (d.reads[srv.ifname] == 'read') {
read[sid] = true;
push(s.servers, sid);
}
for (let id, dev in m.devices) {
let peer = d.peers[dev.public_key];
let sid = m.people[dev.person]?.server;
if (peer && read[sid])
s.dev[id] = [ peer.rx, peer.tx, sid ];
}
return s;
};
/** A counter's change, 0 when it went down (a tunnel set up again starts from zero). */
function delta(a, b) {
return (b ?? 0) >= (a ?? 0) ? (b ?? 0) - (a ?? 0) : 0;
}
/**
* The point between samples `a` and `b`, null when they are not a second or
* so apart (the first sample, a stalled watcher): { ts, servers: { server
* id: [ rx, tx ] } }, bytes per second of its devices together (rx what came
* from them, tx what went to them, as a server's per-minute `rate`), for
* every server whose tunnel `b` read ([ 0, 0 ] when nothing moved). A device
* is counted from its second sample on, on the server it was on in both.
*/
export function point(a, b) {
let dt = b.t - a.t;
if (!(dt > 0.2 && dt < 5))
return null;
let sum = {};
for (let sid in b.servers)
sum[sid] = [ 0, 0 ];
for (let id, v in b.dev) {
let o = a.dev[id];
if (!o || o[2] != v[2])
continue;
sum[v[2]][0] += delta(o[0], v[0]);
sum[v[2]][1] += delta(o[1], v[1]);
}
let p = { ts: b.ts, servers: {} };
for (let sid, v in sum)
p.servers[sid] = [ int(v[0] / dt), int(v[1] / dt) ];
return p;
};
/**
* Keep point `p` in `ring` ([ [ ts, the point as JSON ] ], newest last; each
* point is turned into text once, when it is made, not again every second for
* as long as it is kept): at most POINTS of them, none older than POINTS
* seconds before `p` (the watcher may have stalled in between) and none from
* its second or later (the clock went back).
*/
export function keep(ring, p) {
while (length(ring) && ring[length(ring) - 1][0] >= p.ts)
pop(ring);
push(ring, [ p.ts, sprintf('%J', p) ]);
while (length(ring) > POINTS || ring[0][0] <= p.ts - POINTS)
shift(ring);
};
/** Write the points kept in `ring` (keep()) to FILE. */
export function save(ring) {
let ts = length(ring) ? ring[length(ring) - 1][0] : 0;
ensure_dir(RUN_DIR);
write_file(FILE, `{"ts":${ts},"points":[${join(',', map(ring, (r) => r[1]))}]}`, 0o644);
};
/** Nobody looks any more: FILE goes (the next look gets the points kept then). */
export function stop() {
if (stat(FILE))
unlink(FILE);
};
@@ -4,6 +4,7 @@
// tunnel of your own, one from an imported config) is left alone and the
// server is reported instead. Why a server is kept down is kept in
// core.BLOCKED as a code with its values (awg.blocked_text says it).
// drift() tells the watchdog when one of them was edited outside Dawnline.
import { cursor } from 'uci';
import { stat, unlink, writefile } from 'fs';
@@ -30,6 +31,14 @@ export function owner(ifname, c) {
return c.get('network', ifname, '_dawnline') ?? '';
};
/** What sync() writes into network.<ifname> apart from the markers: what netifd sets the tunnel up from. */
function options(srv) {
let o = awg.netifd_options(srv);
o.disabled = srv.enabled ? null : '1';
o.auto = srv.enabled ? null : '0';
return o;
}
/** Bring network config in line with the servers; true when it changed. */
export function sync(m) {
let c = cursor();
@@ -70,13 +79,15 @@ export function sync(m) {
'Dawnline never changes interfaces it did not create. Choose another interface name for this server.');
continue;
}
// Disguise values AmneziaWG refuses or crashes on (a hand edit in uci;
// import and restore refuse them) never reach setconf and the kernel.
// A disguise this build cannot run (a 3.1 preset after a rollback to
// 2.0): the kernel would drop those options silently and run a tunnel
// no device can reach. Down, and said so, until the build or the
// disguise is changed.
let why = tools ? awg.obf_unsupported(srv.obf) : null;
let why = !tools ? null : length(awg.obf_unsafe(srv.obf)) ? { code: 'disguise_invalid' } : awg.obf_unsupported(srv.obf);
if (why) {
block(srv, why, 'Install that AmneziaWG build in Dawnline → Components, or switch the disguise on the Server page.');
block(srv, why, awg.blocked_fix(why));
continue;
}
delete srv.blocked;
@@ -85,17 +96,16 @@ export function sync(m) {
continue;
// Per server: with several, each changed one has to be brought up again.
let mine = uci_section(c, 'network', ifn, 'interface');
let set = (opt, val) => {
if (uci_put(c, 'network', ifn, opt, val))
for (let k, v in options(srv))
if (uci_put(c, 'network', ifn, k, v))
mine = true;
};
for (let k, v in awg.netifd_options(srv))
set(k, v);
set('disabled', srv.enabled ? null : '1');
set('auto', srv.enabled ? null : '0');
set('_dawnline', id);
// The markers are saved, but netifd does not read them: a renamed server
// keeps its tunnel and every session in it.
if (uci_put(c, 'network', ifn, '_dawnline', id))
changed = true;
// For the log once the server is gone.
set('_dawnline_name', srv.name);
if (uci_put(c, 'network', ifn, '_dawnline_name', srv.name))
changed = true;
if (mine) {
changed = true;
push(touched, ifn);
@@ -125,6 +135,9 @@ export function sync(m) {
if (changed) {
c.commit('network');
ack_config([ 'network' ]);
}
// Only the markers changed: nothing for netifd to read (it ignores them, and so does a reload).
if (length(touched) || length(stale)) {
system('ubus call network reload');
for (let ifn in touched)
if (m.servers[c.get('network', ifn, '_dawnline')]?.enabled)
@@ -134,3 +147,29 @@ export function sync(m) {
}
return changed;
};
/**
* For the watchdog: what of each running server's interface differs from
* what sync() writes, by option name (a LuCI or uci edit of network.<ifname>,
* which would otherwise last until the next apply): { server id: [ names ] },
* an empty list when it is as Dawnline set it. Only enabled servers whose
* section exists and is theirs (a missing one is the tunnel probe's); the
* markers are not compared, netifd does not read them. A dry run on a
* cursor of its own: nothing is saved. Meaningful while amneziawg-tools is
* installed (sync() leaves the interfaces alone without it).
*/
export function drift(m) {
let c = cursor();
c.load('network');
let out = {};
for (let id, srv in m.servers) {
if (!srv.enabled || !length(core.tunnels(srv)) || owner(srv.ifname, c) != id || c.get('network', srv.ifname) != 'interface')
continue;
let diff = [];
for (let k, v in options(srv))
if (uci_put(c, 'network', srv.ifname, k, v))
push(diff, k);
out[id] = diff;
}
return out;
};
@@ -10,7 +10,8 @@ import * as core from 'dawnline.core';
import * as net from 'dawnline.net';
import * as loop from 'dawnline.loop';
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' ];
/** 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' ];
@@ -18,8 +19,11 @@ function ip4(a) {
return ip2int(a ?? '') != null;
}
/** Per-person runtime membership: which tunnel addresses may reach what. */
export function access_sets(m, usage, states) {
/**
* 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);
@@ -27,7 +31,7 @@ export function access_sets(m, usage, states) {
let sets = {};
for (let k in SETS)
sets[k] = [];
let snap = net.snapshot();
snap ??= net.snapshot();
let homes = {}, groups = {};
for (let id, d in m.devices) {
let p = m.people[d.person];
@@ -91,13 +95,23 @@ function portal_ports(m) {
return ports;
}
function table(m, sets) {
/**
* 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 = loop.client_dns();
let dns_addr = ctx.dns_addr;
if (!ip4(dns_addr))
dns_addr = null;
let rt = loop.resolver_target();
let snap = net.snapshot();
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 = {};
@@ -194,7 +208,7 @@ function table(m, sets) {
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 = loop.lan_dns();
let lan_dns = ctx.lan_dns;
if (!ip4(lan_dns))
lan_dns = null;
push(t, ' chain dns {');
@@ -228,9 +242,13 @@ export function load(script) {
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. */
export function render(m, sets) {
return table(m, sets);
/**
* 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. */
@@ -47,13 +47,28 @@ export function version(name) {
return found ? trim(found[2]) : null;
};
/**
* The package a control text names: { name, version }, each null when it
* does not say. Pure: an ipk's control file (ipk true), else `apk adbdump`
* of an apk, whose first name and version are the package's own (its files
* are "- name:" entries further down).
*/
export function control_info(text, ipk) {
if (ipk)
return { name: match(text, /(^|\n)Package: *([^\n]+)/)?.[2], version: match(text, /(^|\n)Version: *([^\n]+)/)?.[2] };
return { name: match(text, /\n *name: *([^\n]+)/)?.[1], version: match(text, /\n *version: *([^\n]+)/)?.[1] };
};
/** The package inside a file: { name, version }, each null when the file does not say. */
export function file_info(path) {
if (match(path, /\.ipk$/))
return control_info(run(`tar -xzOf ${q(path)} ./control.tar.gz | tar -xzO ./control`).out, true);
return control_info(run(`apk adbdump ${q(path)}`).out, false);
};
/** The version inside a package file, or null. */
export function file_version(path) {
if (match(path, /\.ipk$/)) {
let o = run(`tar -xzOf ${q(path)} ./control.tar.gz | tar -xzO ./control`).out;
return match(o, /(^|\n)Version: *([^\n]+)/)?.[2];
}
return match(run(`apk adbdump ${q(path)}`).out, /\n *version: *([^\n]+)/)?.[1];
return file_info(path).version;
};
/**
@@ -105,22 +120,54 @@ function preflight(files, need_kb, log) {
log?.(' ' + sprintf(_('%d MB free on the overlay'), int(free / 1024)));
}
/** Package files (from a release): force also reinstalls the same version or goes back to an older one. */
/** Dawnline's own package: a file of it tells whether apk really reinstalled it. */
const SELF = 'luci-app-dawnline', SELF_MARKER = '/usr/share/ucode/dawnline/util.uc';
/**
* The packages an apk install did not leave at their file's version: apk
* takes a given file as it is (an older version too, a rollback) but leaves
* an installed version alone, whatever the file. Pure: want [{ name,
* version, file }] from the files (file_info()), have { name: installed
* version }. [] when every package took.
*/
export function mismatched(want, have) {
return filter(want, (w) => w.name == null || w.version == null || have?.[w.name] != w.version);
};
/**
* Package files (from a release): true when every one is installed. force
* also reinstalls the same version or goes back to an older one (opkg; apk
* takes a file as it is: Dawnline's own package is checked by a file of it,
* any other by its installed version).
*/
export function install_files(files, force, log) {
preflight(files, 0, log);
let args = join(' ', map(files, q));
if (!is_apk())
return logged(`opkg install ${force ? '--force-reinstall --force-downgrade ' : ''}${args}`, log).code == 0;
// apk leaves an installed version alone, whatever the file: a reinstall
// that changed nothing is a failure, not a silent "done".
let marker = '/usr/share/ucode/dawnline/util.uc';
let before = force ? stat(marker)?.mtime : null;
let ok = logged(`apk add --allow-untrusted ${args}`, log).code == 0;
if (ok && force && before != null && stat(marker)?.mtime == before) {
log?.(' ' + _('apk did not reinstall the version that is already installed'));
die(_("apk doesn't reinstall an installed version. Install a different release, or run install.sh on the router"));
let want = map(files, (f) => ({ ...file_info(f), file: f }));
let own = length(filter(want, (w) => w.name == SELF)) > 0;
// Dawnline's own reinstall that changed nothing is a failure, not a silent "done".
let before = own && force ? stat(SELF_MARKER)?.mtime : null;
if (logged(`apk add --allow-untrusted ${args}`, log).code != 0)
return false;
if (own) {
if (force && before != null && stat(SELF_MARKER)?.mtime == before) {
log?.(' ' + _('apk did not reinstall the version that is already installed'));
die(_("apk doesn't reinstall an installed version. Install a different release, or run install.sh on the router"));
}
return true;
}
return ok;
// Any other package took when it is at its file's version (the same
// version again counts: apk keeps the installed one).
let have = {};
for (let w in want)
if (w.name != null)
have[w.name] = version(w.name);
let bad = mismatched(want, have);
for (let w in bad)
log?.(' ' + sprintf(_('apk did not install %s %s (installed: %s)'), w.name ?? w.file, w.version ?? '?', have[w.name] ?? '-'));
return !length(bad);
};
/** Packages by name from the feeds. */
@@ -3,7 +3,7 @@
// GET /<code> the app shell
// GET /<code>/assets/<file> its script, styles and fonts
// GET /<code>/api/state
// POST /<code>/api/devices { name, kind, public_key? }
// POST /<code>/api/devices { name, kind, public_key?, lan_bypass? }
// GET /<code>/api/devices/<id>/config
// POST /<code>/api/devices/<id> { action: rename|rotate|delete, name? }
//
@@ -368,7 +368,8 @@ function tz_offset() {
function state(r) {
let m = r.m, person = r.person;
let usage = core.load_usage();
let v = view.person_view(m, person, usage, live.dump(m), view.states(m, usage));
// Only their server's tunnel: one `awg` process per request, however many servers there are.
let v = view.person_view(m, person, usage, live.dump(m, person.server ?? ''), view.states(m, usage));
v.state = person_state(m, person, usage);
// Day by day this month, for the page's chart (the admin's views have no use for it).
v.month_days = view.month_days(usage.people?.[person.id]);
@@ -384,6 +385,9 @@ function state(r) {
awg_disguise: srv ? !awg.obf_neutral(srv.obf) : false,
// Which apps (and versions) connect: off, balanced (2.0), max (3.1); legacy = the old junk-only presets.
preset: !srv || awg.obf_neutral(srv.obf) ? 'off' : index([ 'balanced', 'max' ], srv.preset) >= 0 ? srv.preset : 'legacy',
// The home networks a device with LAN Bypass still sends into the tunnel (home and internet access):
// its own local network on the same addresses is out of reach (Add a device says so).
home: srv && person.access == 'both' ? core.person_home(srv, person).nets : [],
},
can_add: length(person.devices) < person.device_limit,
locked: index(LOCKED, v.state) >= 0,
@@ -419,7 +423,8 @@ function api_add(r) {
if (!devices.ready())
fail(r, '503 Service Unavailable', not_ready());
rate_action(r);
let res = guard(r, () => devices.add(r.person.id, b.name, b.kind, { by: 'portal', public_key: b.public_key }));
// lan_bypass: JSON true keeps the device's own local network out of the tunnel; anything else is off.
let res = guard(r, () => devices.add(r.person.id, b.name, b.kind, { by: 'portal', public_key: b.public_key, lan_bypass: b.lan_bypass === true }));
reload(r);
send_json(r, '200 OK', { id: res.id, config: res.config, state: state(r) });
}
@@ -56,7 +56,9 @@ function person_update(a) {
let s = apply.sync();
let m = core.load();
let u = core.load_usage();
return { person: view.person_view(m, m.people[a.id], u, live.dump(m), view.states(m, u), { admin: true }), was: before?.access, warning: s.warning };
// One person: only their server's tunnel is read.
let p = m.people[a.id];
return { person: view.person_view(m, p, u, live.dump(m, p.server ?? ''), view.states(m, u), { admin: true }), was: before?.access, warning: s.warning };
}
function person_pause(a) {
@@ -138,20 +140,28 @@ function person_usage(a) {
function device_create(a) {
devices.need_awg();
return devices.add(a.person, a.name, a.kind, { by: 'admin' });
return devices.add(a.person, a.name, a.kind, { by: 'admin', lan_bypass: a.lan_bypass === true });
}
/**
* A device's configuration. Only `issue` (true: the admin shows its QR code,
* downloads or copies it) counts as handing it out; a look at the device
* marks nothing, so its "settings changed" stays until it really gets them.
*/
function device_config(a) {
let m = core.load();
let d = m.devices[a.id];
if (!d)
die(_('Unknown device.'));
awg.mark_issued(m, d.id);
if (a.issue === true)
awg.mark_issued(m, d.id);
return awg.client_config(m, d);
}
/** Name, on/off and the link values (mtu, keepalive: strings, '' = the server's; lan_bypass: true or false). */
function device_update(a) {
return devices.update(a.id, { name: a.name, disabled: a.disabled }, { by: 'admin' });
return devices.update(a.id, { name: a.name, disabled: a.disabled, mtu: a.mtu, keepalive: a.keepalive,
lan_bypass: a.lan_bypass == null ? null : a.lan_bypass === true }, { by: 'admin' });
}
export const methods = {
@@ -169,9 +179,10 @@ export const methods = {
person_links: { args: { id: '' }, call: wrap(person_links) },
person_delete: { args: { id: '' }, call: wrap(person_delete) },
person_usage: { args: { id: '', days: 30 }, call: wrap(person_usage) },
device_create: { args: { person: '', name: '', kind: '' }, call: wrap(device_create) },
device_config: { args: { id: '' }, call: wrap(device_config) },
device_update: { args: { id: '', name: '', disabled: false }, call: wrap(device_update) },
device_create: { args: { person: '', name: '', kind: '', lan_bypass: false }, call: wrap(device_create) },
device_config: { args: { id: '', issue: false }, call: wrap(device_config) },
device_update: { args: { id: '', name: '', disabled: false, mtu: '', keepalive: '', lan_bypass: false }, call: wrap(device_update) },
device_delete: { args: { id: '' }, call: wrap((a) => devices.remove(a.id, { by: 'admin' })) },
device_rotate: { args: { id: '' }, call: wrap((a) => devices.rotate(a.id, { by: 'admin' })) },
// New keys: the device is set up again, as with the portal's Reconnect.
device_rotate: { args: { id: '' }, call: wrap((a) => devices.reconnect(a.id, { by: 'admin' })) },
};
@@ -596,6 +596,10 @@ function server_ports(a) {
function server_obfuscation(a) {
let preset = str(a.preset) || default_method();
let o = awg.obf_preset(check_method(preset));
// A cheap self-check: new values pass what a restore would be held to.
let errs = awg.obf_errors(o);
if (length(errs))
die(join(' ', errs));
let srv = store.transact((c, m) => {
let srv = m.servers[a.id];
if (!srv)
@@ -1,5 +1,6 @@
// Dawnline rpcd methods: the live revision, the Overview status (servers,
// people, totals, map, recent activity), the activity log and traffic history.
// people, totals, map, recent activity), the live meter, the activity log and
// traffic history.
import { readfile } from 'fs';
import { _ } from 'dawnline.i18n';
@@ -13,6 +14,7 @@ import * as loop from 'dawnline.loop';
import * as awg from 'dawnline.awg';
import * as lookup from 'dawnline.lookup';
import * as health from 'dawnline.health';
import * as meter from 'dawnline.meter';
import { wrap, str, clamp_days } from 'dawnline.rpc.common';
/** The router's public IPv4 (null when none or private). */
@@ -127,7 +129,8 @@ function server_view(m, srv, usage, dmp, rates, days) {
blocked: awg.blocked_text(srv),
// Home networks (interfaces) for the per-person picker.
home: map(net.server_net(srv).home, (h) => ({ dev: h.dev, nets: h.nets })),
peers, online, obf: srv.obf,
// The header protection key is a secret every device shares: whether there is one.
peers, online, obf: awg.obf_public(srv.obf), hpk: !!srv.obf.header_protection_key,
// Bytes per second, one point a minute: [ts, rx, tx] (rx = from devices).
rate: rates[srv.id] ?? [],
// Daily traffic of the people on this server (its Overview chart).
@@ -137,7 +140,8 @@ function server_view(m, srv, usage, dmp, rates, days) {
/*
* Everything the pages show at once. Readable by read-only users: no personal
* codes or links here (person_links has them).
* codes or links here (person_links has them), and no keys but public ones
* (device_config has the rest).
*/
function status(a) {
let m = core.load();
@@ -282,8 +286,21 @@ function rev() {
return { rev: +(live.presence()?.rev ?? 0), version: VERSION };
}
/*
* The live meter (Overview): each call keeps the agent's watcher writing out
* the points it keeps for meter.WANT_FOR seconds more (a first call finds
* none yet: the watcher writes the last two minutes within a second) and
* returns them (dawnline.meter.read), those newer than `since` when given. Read-only users may look: server ids
* and bytes per second only, no keys or personal codes.
*/
function meter_points(a) {
meter.want();
return meter.read(+a.since || 0);
}
export const methods = {
rev: { call: wrap(rev) },
meter: { args: { since: 0 }, call: wrap(meter_points) },
status: { args: { days: 30 }, call: wrap(status) },
events: { args: { limit: 300, person: '', since: 0 }, call: wrap(events_list) },
logs_clear: { args: { person: '', device: '', category: '', older_days: '' }, call: wrap(logs_clear) },
@@ -1,6 +1,8 @@
// Dawnline updater: AmneziaWG — the builds published for this firmware by
// each source, installing or switching a build (verified against GitHub's
// sha256), the Russian LuCI translation, and rolling back to a kept build.
// Every install and rollback is recorded (dawnline.awg_builds), with whether
// the new kernel module runs or waits for the next boot.
// ctx is the updater's job context (see usr/libexec/dawnline/updater).
import { stat } from 'fs';
@@ -89,6 +91,8 @@ export function check(ctx) {
current = id;
let mine = current ? sources[current] : null;
let c = cur && mine?.version ? pkg.cmp(cur, mine.version) : null;
// An update that waits for a reboot: Components says so after a check.
let pending = builds.waits_for_reboot();
let st = c == null ? '' : c < 0 ? 'outdated' : c > 0 ? 'dev' : 'latest';
ctx.log(cur == null ? _('AmneziaWG is not installed')
: !current ? sprintf(_('AmneziaWG %s: no source publishes this build for this firmware any more'), cur)
@@ -99,13 +103,19 @@ export function check(ctx) {
update: cur == null || st == 'outdated',
// An update that changes the generation (2.0 → 3.1) breaks older apps: never automatic.
gen_change: cur != null && mine?.version != null && builds.gen(cur) != builds.gen(mine.version),
note: !length(filter(values(sources), (x) => x.version)) ? sprintf(_('No AmneziaWG build for OpenWrt %s yet'), substr(fw.tag, 1)) : null };
pending,
note: !length(filter(values(sources), (x) => x.version)) ? sprintf(_('No AmneziaWG build for OpenWrt %s yet'), substr(fw.tag, 1))
: pending ? _('The AmneziaWG update is installed and starts after a reboot.') : null };
};
/** Tunnels on a new kernel module: every AmneziaWG interface is brought down and up again. */
function reload_module(ctx, before, after) {
if (!before['kmod-amneziawg'] || before['kmod-amneziawg'] == after['kmod-amneziawg'])
return;
/**
* Tunnels on a new kernel module: every AmneziaWG interface is brought down,
* the module swapped and the interfaces brought up again. False when the old
* module stays loaded: the tunnels come back on it (the tools talk to an
* older module at its own netlink version) and the installed one starts
* with the next boot, which caps() and Health then wait for.
*/
function reload_module(ctx) {
let ifaces = [];
let c = cursor();
c.load('network');
@@ -119,33 +129,58 @@ function reload_module(ctx, before, after) {
iface_intent(i, 'update', c.get('network', i, '_dawnline_name') ?? i);
sh(`ifdown '${i}'`);
}
// Both steps must really happen: the new tools against the old module (or
// no module at all) leave every tunnel down while the job says "done".
ctx.run('rmmod amneziawg');
if (stat('/sys/module/amneziawg'))
die(_('The old AmneziaWG kernel module is still loaded (another AmneziaWG interface may use it): reboot the router to finish the update'));
ctx.run('modprobe amneziawg');
if (!stat('/sys/module/amneziawg'))
die(_("The new AmneziaWG kernel module doesn't load on this firmware: the tunnels stay down until it does (see the log above)"));
ctx.run('rmmod amneziawg');
let swapped = !stat('/sys/module/amneziawg');
if (swapped) {
ctx.run('modprobe amneziawg');
if (!stat('/sys/module/amneziawg'))
die(_("The new AmneziaWG kernel module doesn't load on this firmware: the tunnels stay down until it does (see the log above)"));
}
for (let i in ifaces)
sh(`ifup '${i}'`);
return swapped;
}
/** After packages changed: the module loaded, netifd knowing the protocol, Dawnline set up again. */
function settle(ctx, before, after) {
if (!before['kmod-amneziawg'] && after['kmod-amneziawg']) {
/**
* After packages changed: the module loaded, netifd knowing the protocol,
* Dawnline set up again. was: the module loaded before (builds.module_now()).
* Returns whether the module that runs is the installed one; false while the
* old one stays loaded until the next boot.
*/
function settle(ctx, before, after, was) {
let b = before['kmod-amneziawg'], a = after['kmod-amneziawg'];
let fresh = true;
// A new module package, one over a module loaded by hand, or an earlier
// update that still waits for a boot (Reinstall tries again).
if (a && (a != b || was.pending) && (b || was.core != null))
fresh = reload_module(ctx);
else if (a && !b) {
ctx.phase(_('Loading the kernel module'));
if (ctx.run('modprobe amneziawg').code != 0 && !stat('/sys/module/amneziawg'))
die(_("AmneziaWG is installed, but its kernel module doesn't load on this firmware"));
}
else
reload_module(ctx, before, after);
// netifd reads its protocol handlers when it starts.
if (index(ctx.run('ubus call network get_proto_handlers').out, '"amneziawg"') < 0) {
ctx.phase(_('Restarting the network so it knows AmneziaWG (connections drop for a few seconds)'));
ctx.run('/etc/init.d/network restart');
}
ctx.after('apply');
return fresh;
}
/**
* The packages are in: settle them and record the build (source, tag) with
* the module that ran before (was). An old module that stays loaded is no
* failure: the job says so, and Health until the next boot.
*/
function finish(ctx, out, source, tag, was) {
out.after = builds.installed();
out.reloaded = settle(ctx, out.before, out.after, was);
builds.record(source, tag, out.after, { prev_gen: was.gen, prev_core: was.core, reloaded: out.reloaded });
if (!out.reloaded)
ctx.log(_('The old kernel module stays loaded (another AmneziaWG interface may use it): the AmneziaWG update is installed and starts after a reboot.'));
return out;
}
/** The first source that publishes every package for this firmware. */
@@ -165,6 +200,7 @@ function pick(fw) {
/** arg: [auto|slava|grey][:ru] | rollback */
export function install(ctx, arg) {
let before = builds.installed();
let was = builds.module_now(before['kmod-amneziawg']);
let out = { from: before['amneziawg-tools'], to: null, before };
let fw = builds.firmware();
if (!fw)
@@ -182,9 +218,7 @@ export function install(ctx, arg) {
if (!pkg.install_files(k.files, true, ctx.log))
die(_('Package installation failed'));
upd.forget('amneziawg');
out.after = builds.installed();
settle(ctx, before, out.after);
return out;
return finish(ctx, out, k.build, fw.tag, was);
}
let parts = split(arg ?? '', ':');
let id = parts[0] || 'auto';
@@ -236,8 +270,5 @@ export function install(ctx, arg) {
die(_('Package installation failed'));
if (!want_ru && pkg.version(builds.RU))
pkg.remove([ builds.RU ], ctx.log);
out.after = builds.installed();
settle(ctx, before, out.after);
builds.record(id, fw.tag, out.after);
return out;
return finish(ctx, out, id, fw.tag, was);
};
@@ -5,7 +5,7 @@
import { open, readfile, writefile, rename, mkdir, stat, unlink, popen, lsdir } from 'fs';
import { _ } from 'dawnline.i18n';
export const VERSION = '0.13.0';
export const VERSION = '0.14.0';
/** GitHub repository with Dawnline releases (updates and the installer). */
export const REPO = 'tickcount/luci-app-dawnline';
export const RUN_DIR = '/var/run/dawnline';
@@ -561,6 +561,76 @@ export function name_rule() {
// with one fails these checks (a regex looks only up to it).
const ASCII_ALNUM = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const B64 = `${ASCII_ALNUM}+/`;
/**
* The longest name a device takes, in characters: ordinary words fill a portal card's line about as far as its
* status ("Return to save, Esc to cancel"), and fit the server list in the AmneziaVPN app. Names set before the rule stay as they are; it holds when a name is set.
*/
export const DEVICE_NAME_MAX = 20;
// What a device's name may hold of ASCII: letters, digits, spaces and - _ . It goes into configurations, file
// names and the AmneziaVPN key: nothing there to escape.
const DEVICE_NAME_CHARS = `${ASCII_ALNUM} ._-`;
// Past ASCII, letters of any language are welcome; these blocks are not: symbols, punctuation, arrows, maths,
// emoji and invisibles (code point ranges, both ends in; web/src/shared/format.ts NAME_SYMBOLS is the same list,
// and the page asks Unicode besides that a character is a letter or a digit).
const NAME_SYMBOLS = [
[ 0x80, 0xbf ], [ 0xd7, 0xd7 ], [ 0xf7, 0xf7 ], [ 0x2000, 0x2bff ], [ 0x3000, 0x303f ], [ 0xd800, 0xf8ff ],
[ 0xfe00, 0xfe0f ], [ 0xfe30, 0xfe4f ], [ 0xfeff, 0xfeff ], [ 0xfff0, 0xffff ], [ 0x1f000, 0x1fbff ],
[ 0xe0000, 0xe007f ]
];
function name_symbol(cp) {
for (let r in NAME_SYMBOLS)
if (cp >= r[0] && cp <= r[1])
return true;
return false;
}
/**
* A device's name (trimmed by the caller): 1-DEVICE_NAME_MAX characters, not blank, each one of
* DEVICE_NAME_CHARS or past ASCII outside NAME_SYMBOLS. Read by code points: broken UTF-8, and an
* ASCII character spelled long (0xC0 0xAF for "/"), are refused.
*/
export function valid_device_name(s) {
if (type(s) != 'string' || length(trim(s)) == 0 || ulength(s) > DEVICE_NAME_MAX)
return false;
let i = 0, n = length(s);
while (i < n) {
let b = ord(s, i), cp, len;
if (b < 0x80) {
if (index(DEVICE_NAME_CHARS, substr(s, i, 1)) < 0)
return false;
i++;
continue;
}
if ((b & 0xe0) == 0xc0) {
len = 2;
cp = b & 0x1f;
}
else if ((b & 0xf0) == 0xe0) {
len = 3;
cp = b & 0x0f;
}
else if ((b & 0xf8) == 0xf0) {
len = 4;
cp = b & 0x07;
}
else
return false;
if (i + len > n)
return false;
for (let k = 1; k < len; k++) {
let c = ord(s, i + k);
if ((c & 0xc0) != 0x80)
return false;
cp = (cp << 6) | (c & 0x3f);
}
if (cp < 0xc0 || cp > 0x10ffff || name_symbol(cp))
return false;
i += len;
}
return true;
};
// 32 bytes are 43 base64 characters: the last holds four bits of the key and two zero bits.
const KEY_LAST = 'AEIMQUYcgkosw048';
@@ -568,7 +638,7 @@ const KEY_LAST = 'AEIMQUYcgkosw048';
* A (Amnezia)WireGuard key: 32 bytes in base64, 43 characters and "=", the
* same as /^[A-Za-z0-9+\/]{42}[AEIMQUYcgkosw048]=$/ without its 1.7 ms
* compile on the WR3000P: the agent's watcher checks two keys per line of
* `awg show all dump` every second. This takes about 0.03 ms.
* `awg show <ifname> dump` every second. This takes about 0.03 ms.
*/
export function valid_key(s) {
return type(s) == 'string' && length(s) == 44 && substr(s, 43) == '=' &&
@@ -58,6 +58,7 @@ export function device_view(m, d, usage, dmp) {
m._reconnect ??= awg.reconnects();
let hs = awg.handshake_since(peer?.handshake || u?.handshake || 0, m._reconnect[d.id]);
let p = m.people[d.person];
let srv = m.servers[p?.server];
// The same label /tmp/hosts carries (core.device_labels), so what is shown resolves.
let label = '';
if (m.settings.hostnames && p) {
@@ -65,6 +66,7 @@ export function device_view(m, d, usage, dmp) {
m._labels[p.id] ??= core.device_labels(m, p);
label = m._labels[p.id][d.id] ?? 'device';
}
let online = hs > 0 && live.online(dmp, d.id, peer);
let v = {
id: d.id,
name: d.name,
@@ -73,7 +75,7 @@ export function device_view(m, d, usage, dmp) {
disabled: d.disabled,
created: d.created,
created_by: d.created_by,
online: hs > 0 && live.online(dmp, d.id, peer),
online,
handshake: hs,
endpoint: live.endpoint_ip(peer?.endpoint) || u?.endpoint || '',
active: !!peer,
@@ -84,6 +86,21 @@ export function device_view(m, d, usage, dmp) {
browser_key: d.private_key == '',
// Its configuration changed since it was last shown or downloaded.
config_stale: config_stale(m, d),
// How it connects: its own local network outside the tunnel, its own MTU
// and keep-alive (0 / null: the server's) and what its configuration carries.
lan_bypass: d.lan_bypass,
mtu: d.mtu,
keepalive: d.keepalive,
mtu_used: srv ? core.device_mtu(srv, d) : null,
keepalive_used: srv ? core.device_keepalive(srv, d) : null,
// Its link failing in a named way, as the agent's watcher shows it
// (dawnline.link): { state, since }, or null.
link: dmp.link?.[d.id] ?? null,
// What its link does right now, for the set-up sheet (dawnline.link
// setup_state): { state: 'trying' | 'flowing' | 'nodata', since }, or null.
// Without the agent nobody tells data from a bare handshake: a session
// that lives counts as data flowing, so the sheet still sees it arrive.
setup: dmp.setup != null ? (dmp.setup[d.id] ?? null) : online ? { state: 'flowing', since: hs } : null,
};
return v;
};
@@ -44,7 +44,23 @@ function restart_services() {
function probes(m) {
let out = [];
// The tunnels check themselves: AmneziaWG (packages, kernel module, netifd) and each server's interface.
push(out, ...awg.probes(m, { udp_listening: health.udp_listening, reapply: () => apply.apply(), owner: (ifn) => netifd.owner(ifn) }));
let tunnels = awg.probes(m, { udp_listening: health.udp_listening, reapply: () => apply.apply(), owner: (ifn) => netifd.owner(ifn) });
push(out, ...tunnels);
// A tunnel's interface edited outside Dawnline (LuCI, uci) keeps that until
// the next apply: set up again with Dawnline's settings. Only while
// AmneziaWG itself works (its target comes first, and is fixed first).
if (filter(tunnels, (p) => p.id == 'awg')[0]?.ok)
for (let id, diff in netifd.drift(m)) {
let srv = m.servers[id];
push(out, {
id: `cfg_${id}`, src: 'awg', name: `${srv.name} · interface settings`, who: srv.name, ok: !length(diff),
problem: sprintf(L_('interface %s was changed outside Dawnline'), srv.ifname),
back: sprintf(L_("interface %s has Dawnline's settings again"), srv.ifname),
// Option names only: their values hold the server's private key.
detail: () => sprintf(L_('Changed: %s.'), join(', ', diff)),
repair: { what: L_('setting it up again'), run: () => apply.apply() },
});
}
if (length(m.servers))
push(out, {
id: 'nft', src: 'dawnline', name: 'Access rules', who: L_('Access rules'), ok: nft.present(),
@@ -184,6 +200,14 @@ function names() {
};
}
/** A target's chip name in the language of the call: names(), a server's interface settings, else as stored. */
function chip_name(m, n, id, stored) {
if (n[id])
return n[id];
let srv = substr(id, 0, 4) == 'cfg_' ? m.servers[substr(id, 4)] : null;
return srv ? sprintf(_('%s · interface settings'), srv.name) : stored;
}
/**
* For the Health page: the watchdog's state and the newest log entries. Target
* and repair names in the language of the call; the log as it was written.
@@ -195,11 +219,11 @@ export function view(m) {
// The agent itself: fine while it ticks (cron restarts it after 5 minutes without).
let targets = [ { id: 'agent', name: n.agent, ok: beat > 0 && time() - beat < 180, tries: 0 } ];
for (let id, x in (type(st.targets) == 'object' ? st.targets : {}))
push(targets, { id, name: n[id] ?? x.name, ok: !!x.ok, tries: x.tries ?? 0 });
push(targets, { id, name: chip_name(m, n, id, x.name), ok: !!x.ok, tries: x.tries ?? 0 });
return {
watchdog: {
enabled: m.settings.watchdog, last: st.last ?? null, beat: beat || null, now: time(),
targets, repairs: map(st.repairs ?? [], (r) => ({ ...r, name: n[r.id] ?? r.name })),
targets, repairs: map(st.repairs ?? [], (r) => ({ ...r, name: chip_name(m, n, r.id, r.name) })),
},
log: slog_read(200),
};