LuCI admin (people, devices, limits, disguise, health, updates, backups) and a personal self-service portal, built as ipk (OpenWrt 24.10) and apk (OpenWrt 25.12) with the OpenWrt SDK. Successor of openwrt-liminal. - install.sh: checks the router, installs AmneziaWG for its firmware, then the release package verified against sha256sums.txt - CI: Prettier, types, tests, committed bundles, ShellCheck, ucode checks; tagged releases build both packages and publish them - Web bundles minified with esbuild (JS and CSS) - README with framed screenshots
This commit is contained in:
commit
a3910f8b97
105 files changed
+22278
No files matched your search
@@ -0,0 +1,621 @@
|
||||
// Dawnline — reconciliation. Turns /etc/config/dawnline into router state:
|
||||
// * network interfaces (proto amneziawg), peers applied live with `awg syncconf`
|
||||
// * firewall zones, forwardings and WAN rules (named sections dawnline_*)
|
||||
// * nft table `inet dawnline` enforcing each person's access
|
||||
// * hostnames in /tmp/hosts/dawnline
|
||||
// * the "like a home device" path and the Home-only resolver (dawnline.loop)
|
||||
// Only objects created by Dawnline are ever modified.
|
||||
|
||||
import { cursor } from 'uci';
|
||||
import { readfile, writefile, stat, unlink } from 'fs';
|
||||
import {
|
||||
q, sh, sh_out, sh_bg, ensure_dir, write_file, write_json, read_json, parse_cidr, int2ip, uniq,
|
||||
lock, unlock, RUN_DIR
|
||||
} from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as net from 'dawnline.net';
|
||||
import * as loop from 'dawnline.loop';
|
||||
|
||||
const HOSTS_FILE = '/tmp/hosts/dawnline';
|
||||
/*
|
||||
* Our own answers leave by the main table: the portal's (TCP) and each
|
||||
* tunnel's (UDP). Proxies on the router (tproxy with an fwmark rule) may mark
|
||||
* the router's own traffic to internet addresses and divert it locally, which
|
||||
* swallows replies to outside clients. These rules sit before such fwmark
|
||||
* rules and only match our listening ports.
|
||||
*/
|
||||
const PREF_REPLY = 90;
|
||||
|
||||
function log(msg) {
|
||||
system(`logger -t dawnline ${q(msg)}`);
|
||||
}
|
||||
|
||||
/* ---------- helpers ---------- */
|
||||
|
||||
/** Set an option only when it differs; returns true if something changed. */
|
||||
function put(c, conf, sec, opt, val) {
|
||||
let cur = c.get(conf, sec, opt);
|
||||
if (val == null || val == '' || (type(val) == 'array' && !length(val))) {
|
||||
if (cur != null) {
|
||||
c.delete(conf, sec, opt);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (type(val) == 'array') {
|
||||
if (type(cur) == 'array' && join('\n', cur) == join('\n', val))
|
||||
return false;
|
||||
}
|
||||
else if (cur == `${val}`)
|
||||
return false;
|
||||
c.set(conf, sec, opt, type(val) == 'array' ? val : `${val}`);
|
||||
return true;
|
||||
}
|
||||
|
||||
function ensure_section(c, conf, sec, stype) {
|
||||
if (c.get(conf, sec) == stype)
|
||||
return false;
|
||||
if (c.get(conf, sec) != null)
|
||||
c.delete(conf, sec);
|
||||
c.set(conf, sec, stype);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* After committing a config ourselves (and applying it), record its new
|
||||
* checksum so a later `reload_config` does not treat it as changed and
|
||||
* restart unrelated services that reload on any network change.
|
||||
*/
|
||||
function ack_config(confs) {
|
||||
let md5f = '/var/run/config.md5';
|
||||
if (!stat(md5f))
|
||||
return;
|
||||
let lines = split(trim(readfile(md5f) ?? ''), '\n');
|
||||
for (let conf in confs) {
|
||||
let path = `/var/run/config.check/${conf}`;
|
||||
let sum = sh_out(`uci show ${q(conf)} | md5sum | cut -d' ' -f1`);
|
||||
if (!sum)
|
||||
continue;
|
||||
let found = false;
|
||||
for (let i = 0; i < length(lines); i++)
|
||||
if (substr(lines[i], -length(path) - 2) == ` ${path}`) {
|
||||
lines[i] = `${sum} ${path}`;
|
||||
found = true;
|
||||
}
|
||||
if (!found)
|
||||
push(lines, `${sum} ${path}`);
|
||||
}
|
||||
writefile(md5f, join('\n', lines) + '\n');
|
||||
}
|
||||
|
||||
/* ---------- network ---------- */
|
||||
|
||||
function sync_network(m) {
|
||||
let c = cursor();
|
||||
c.load('network');
|
||||
let changed = false, touched = [];
|
||||
let want = {};
|
||||
|
||||
for (let id, srv in m.servers) {
|
||||
if (!srv.private_key)
|
||||
continue;
|
||||
let ifn = srv.ifname;
|
||||
want[ifn] = true;
|
||||
let addr = core.server_address(srv);
|
||||
let pc = parse_cidr(srv.subnet);
|
||||
let before = changed;
|
||||
changed = ensure_section(c, 'network', ifn, 'interface') || changed;
|
||||
changed = put(c, 'network', ifn, 'proto', 'amneziawg') || changed;
|
||||
changed = put(c, 'network', ifn, 'private_key', srv.private_key) || changed;
|
||||
changed = put(c, 'network', ifn, 'listen_port', srv.port) || changed;
|
||||
changed = put(c, 'network', ifn, 'addresses', [ `${addr}/${pc.prefix}` ]) || changed;
|
||||
changed = put(c, 'network', ifn, 'mtu', srv.mtu) || changed;
|
||||
changed = put(c, 'network', ifn, 'disabled', srv.enabled ? null : '1') || changed;
|
||||
changed = put(c, 'network', ifn, 'auto', srv.enabled ? null : '0') || changed;
|
||||
changed = put(c, 'network', ifn, '_dawnline', id) || changed;
|
||||
for (let k in core.OBF_KEYS)
|
||||
changed = put(c, 'network', ifn, `awg_${k}`, srv.obf[k]) || changed;
|
||||
if (changed != before)
|
||||
push(touched, ifn);
|
||||
}
|
||||
|
||||
// Remove interfaces Dawnline created for servers that no longer exist.
|
||||
let stale = [];
|
||||
c.foreach('network', 'interface', (s) => {
|
||||
if (s._dawnline && !want[s['.name']])
|
||||
push(stale, s['.name']);
|
||||
});
|
||||
for (let ifn in stale) {
|
||||
system(`ifdown ${q(ifn)} 2>/dev/null`);
|
||||
c.delete('network', ifn);
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (changed) {
|
||||
c.commit('network');
|
||||
ack_config([ 'network' ]);
|
||||
system('ubus call network reload');
|
||||
for (let ifn in touched)
|
||||
if (m.servers[c.get('network', ifn, '_dawnline')]?.enabled)
|
||||
system(`ifup ${q(ifn)}`);
|
||||
log(`network updated (${join(', ', touched) || 'removed ' + join(', ', stale)})`);
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
/* ---------- firewall ---------- */
|
||||
|
||||
const LOOP_ZONE = 'dl_loop';
|
||||
|
||||
function sync_firewall(m) {
|
||||
let c = cursor();
|
||||
c.load('firewall');
|
||||
let changed = false, want = {};
|
||||
|
||||
let sec = (name, stype, opts) => {
|
||||
want[name] = true;
|
||||
changed = ensure_section(c, 'firewall', name, stype) || changed;
|
||||
for (let k, v in opts)
|
||||
changed = put(c, 'firewall', name, k, v) || changed;
|
||||
};
|
||||
|
||||
let snap = net.snapshot(true);
|
||||
let portal_zone = null, want_loop = false;
|
||||
for (let id, srv in m.servers) {
|
||||
if (!srv.private_key)
|
||||
continue;
|
||||
let z = `dawnline_${id}`;
|
||||
let sn = net.server_net(srv, snap);
|
||||
portal_zone ??= sn.wan.zone;
|
||||
sec(`${z}_zone`, 'zone', {
|
||||
name: srv.ifname, network: [ srv.ifname ],
|
||||
input: 'ACCEPT', output: 'ACCEPT', forward: 'REJECT',
|
||||
});
|
||||
// Access per person is enforced by the inet dawnline table; the zone
|
||||
// only needs to be allowed to reach each home-network zone and WAN.
|
||||
for (let i, zone in sn.zones)
|
||||
if (zone != sn.wan.zone && zone != srv.ifname)
|
||||
sec(i == 0 ? `${z}_lan` : `${z}_lan_${replace(zone, /[^A-Za-z0-9_]/g, '_')}`, 'forwarding', { src: srv.ifname, dest: zone });
|
||||
sec(`${z}_wan`, 'forwarding', { src: srv.ifname, dest: sn.wan.zone });
|
||||
if (srv.lan_like) {
|
||||
sec(`${z}_loop`, 'forwarding', { src: srv.ifname, dest: LOOP_ZONE });
|
||||
want_loop = true;
|
||||
}
|
||||
sec(`${z}_port`, 'rule', {
|
||||
name: `Dawnline-${srv.ifname}`, src: sn.wan.zone, proto: 'udp',
|
||||
dest_port: srv.port, target: 'ACCEPT', enabled: srv.enabled ? null : '0',
|
||||
});
|
||||
}
|
||||
|
||||
// The link into the netns that re-enters the router from the LAN.
|
||||
if (want_loop) {
|
||||
sec('dawnline_loop', 'zone', {
|
||||
name: LOOP_ZONE, device: [ net.INTERNAL.transit ],
|
||||
input: 'REJECT', output: 'ACCEPT', forward: 'REJECT',
|
||||
});
|
||||
// The Home-only resolver in the netns reaches its upstream DNS this way.
|
||||
sec('dawnline_loop_wan', 'forwarding', { src: LOOP_ZONE, dest: portal_zone ?? 'wan' });
|
||||
}
|
||||
|
||||
if (m.settings.portal_enabled) {
|
||||
let wan = portal_zone ?? 'wan';
|
||||
sec('dawnline_portal', 'rule', {
|
||||
name: 'Dawnline-Portal', src: wan, proto: 'tcp',
|
||||
dest_port: m.settings.portal_port, target: 'ACCEPT',
|
||||
});
|
||||
// IP addresses in links: plain HTTP next to the HTTPS port, and 80 forwarded to it.
|
||||
if (core.portal_http(m)) {
|
||||
sec('dawnline_portal_http', 'rule', {
|
||||
name: 'Dawnline-Portal-HTTP', src: wan, proto: 'tcp',
|
||||
dest_port: core.portal_http_port(m), target: 'ACCEPT',
|
||||
});
|
||||
if (core.portal_http_public(m) == 80)
|
||||
sec('dawnline_portal_80', 'redirect', {
|
||||
name: 'Dawnline-Portal-80', src: wan, proto: 'tcp',
|
||||
src_dport: 80, dest_port: core.portal_http_port(m), target: 'DNAT',
|
||||
});
|
||||
}
|
||||
// Links use 443: from outside it lands on the portal (LuCI stays closed there).
|
||||
if (core.portal_public_port(m) == 443 && m.settings.portal_port != 443)
|
||||
sec('dawnline_portal_443', 'redirect', {
|
||||
name: 'Dawnline-Portal-443', src: wan, proto: 'tcp',
|
||||
src_dport: 443, dest_port: m.settings.portal_port, target: 'DNAT',
|
||||
});
|
||||
}
|
||||
|
||||
let stale = [];
|
||||
c.foreach('firewall', null, (s) => {
|
||||
if (match(s['.name'], /^dawnline_/) && !want[s['.name']])
|
||||
push(stale, s['.name']);
|
||||
});
|
||||
for (let s in stale) {
|
||||
c.delete('firewall', s);
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (changed) {
|
||||
c.commit('firewall');
|
||||
ack_config([ 'firewall' ]);
|
||||
system('fw4 -q reload');
|
||||
log('firewall updated');
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
/* ---------- nft access table ---------- */
|
||||
|
||||
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' ];
|
||||
|
||||
/** Per-person runtime membership: which tunnel addresses may reach what. */
|
||||
export function access_sets(m, usage, states) {
|
||||
let sets = { lan_ok: [], inet_ok: [], svc_ok: [], dns_real: [] };
|
||||
for (let id, d in m.devices) {
|
||||
let p = m.people[d.person];
|
||||
if (!p || d.disabled || !d.address || states[p.id] != 'active')
|
||||
continue;
|
||||
// Plain DNS for whoever's internet does not go through the router.
|
||||
// Home names: the plain resolver (their internet does not use the tunnel).
|
||||
if (p.access == 'lan' && p.dns_mode == 'home')
|
||||
push(sets.dns_real, d.address);
|
||||
if (p.access == 'internet' || p.access == 'both')
|
||||
push(sets.inet_ok, d.address);
|
||||
if (p.access == 'both' || (p.access == 'lan' && !length(p.services)))
|
||||
push(sets.lan_ok, d.address);
|
||||
else if (p.access == 'lan')
|
||||
for (let sid in p.services) {
|
||||
let s = m.services[sid];
|
||||
if (!s || !s.address)
|
||||
continue;
|
||||
for (let port in s.ports)
|
||||
if (match(port, /^[0-9]+$/))
|
||||
push(sets.svc_ok, `${d.address} . ${s.address} . ${port}`);
|
||||
}
|
||||
}
|
||||
return sets;
|
||||
};
|
||||
|
||||
function set_elems(arr) {
|
||||
return length(arr) ? `elements = { ${join(', ', arr)} }` : '';
|
||||
}
|
||||
|
||||
function nft_table(m, sets) {
|
||||
let ifs = [], lan = [];
|
||||
let dns_addr = loop.client_dns();
|
||||
let rt = loop.resolver_target();
|
||||
let snap = net.snapshot();
|
||||
for (let id, srv in m.servers)
|
||||
if (srv.private_key) {
|
||||
push(ifs, `"${srv.ifname}"`);
|
||||
push(lan, ...net.server_net(srv, snap).nets);
|
||||
}
|
||||
lan = net.collapse(lan);
|
||||
let t = [];
|
||||
push(t, 'table inet dawnline {');
|
||||
push(t, ` set lan_nets { type ipv4_addr; flags interval; auto-merge; ${set_elems(lan)} }`);
|
||||
push(t, ` set lan_ok { type ipv4_addr; ${set_elems(sets.lan_ok)} }`);
|
||||
push(t, ` set inet_ok { type ipv4_addr; ${set_elems(sets.inet_ok)} }`);
|
||||
push(t, ` set svc_ok { type ipv4_addr . ipv4_addr . inet_service; ${set_elems(sets.svc_ok)} }`);
|
||||
push(t, ` set dns_real { type ipv4_addr; ${set_elems(sets.dns_real)} }`);
|
||||
push(t, ' chain pre {');
|
||||
// Ahead of mangle-priority hooks (transparent proxies mark at -150).
|
||||
push(t, ' type filter hook prerouting priority -160; policy accept;');
|
||||
if (length(ifs))
|
||||
push(t, ` iifname { ${join(', ', ifs)} } jump guard`);
|
||||
push(t, ' }');
|
||||
push(t, ' chain guard {');
|
||||
push(t, ' meta nfproto ipv6 drop');
|
||||
push(t, ' ct state established,related accept');
|
||||
push(t, ' icmp type echo-request fib daddr type local accept');
|
||||
push(t, ' fib daddr type local meta l4proto { tcp, udp } th dport 53 accept');
|
||||
push(t, ' fib daddr type local ip saddr @lan_ok accept');
|
||||
push(t, ' fib daddr type local counter drop');
|
||||
if (dns_addr)
|
||||
// DNS through the netns (it forwards to the LAN's DNS), for everyone.
|
||||
push(t, ` ip daddr ${dns_addr} meta l4proto { tcp, udp } th dport 53 accept`);
|
||||
push(t, ' ip daddr @lan_nets ip saddr @lan_ok accept');
|
||||
push(t, ' meta l4proto { tcp, udp } ip saddr . ip daddr . th dport @svc_ok accept');
|
||||
push(t, ` ip daddr { ${join(', ', PRIVATE4)} } counter drop`);
|
||||
push(t, ' ip saddr @inet_ok accept');
|
||||
push(t, ' counter drop');
|
||||
push(t, ' }');
|
||||
// Devices ask the tunnel address; send each query where it belongs.
|
||||
let to_resolver = rt.mode == 'ns' ? `dnat ip to ${rt.address}:53` : `redirect to :${rt.port}`;
|
||||
let lan_dns = loop.lan_dns();
|
||||
push(t, ' chain dns {');
|
||||
push(t, ' type nat hook prerouting priority dstnat - 5; policy accept;');
|
||||
if (length(ifs))
|
||||
// Home names (and no LAN DNS at all): the plain resolver, whatever address was asked.
|
||||
push(t, ` iifname { ${join(', ', ifs)} } ip saddr @dns_real meta l4proto { tcp, udp } th dport 53 ${to_resolver}`);
|
||||
for (let id, srv in m.servers) {
|
||||
let a = srv.private_key ? core.server_address(srv) : null;
|
||||
if (!a)
|
||||
continue;
|
||||
// Everyone else: the LAN's DNS, through the netns (from the LAN side) when internet goes that way.
|
||||
let target = srv.lan_like && dns_addr ? `dnat ip to ${dns_addr}:53` : lan_dns ? `dnat ip to ${lan_dns}:53` : to_resolver;
|
||||
push(t, ` iifname "${srv.ifname}" ip daddr ${a} meta l4proto { tcp, udp } th dport 53 ${target}`);
|
||||
}
|
||||
push(t, ' }');
|
||||
push(t, '}');
|
||||
return join('\n', t) + '\n';
|
||||
}
|
||||
|
||||
function nft_load(script) {
|
||||
ensure_dir(RUN_DIR);
|
||||
let f = `${RUN_DIR}/nft.rules`;
|
||||
writefile(f, script);
|
||||
let r = sh(`nft -f ${f}`);
|
||||
if (r.code != 0)
|
||||
log(`nft failed: ${trim(r.out)}`);
|
||||
return r.code == 0;
|
||||
}
|
||||
|
||||
/** Full table rebuild (structure changes: servers, LAN subnets). */
|
||||
export function rebuild_nft(m, sets) {
|
||||
let s = 'table inet dawnline\ndelete table inet dawnline\n' + nft_table(m, sets);
|
||||
return nft_load(s);
|
||||
};
|
||||
|
||||
/** Atomically replace set contents only. */
|
||||
export function update_sets(sets) {
|
||||
let s = '';
|
||||
for (let name in [ 'lan_ok', 'inet_ok', 'svc_ok', 'dns_real' ]) {
|
||||
s += `flush set inet dawnline ${name}\n`;
|
||||
if (length(sets[name]))
|
||||
s += `add element inet dawnline ${name} { ${join(', ', sets[name])} }\n`;
|
||||
}
|
||||
return nft_load(s);
|
||||
};
|
||||
|
||||
export function remove_nft() {
|
||||
system('nft delete table inet dawnline 2>/dev/null');
|
||||
};
|
||||
|
||||
/* ---------- AmneziaWG peers ---------- */
|
||||
|
||||
/** Push the peer list of every server to the kernel without restarting it. */
|
||||
export function sync_peers(m, states) {
|
||||
ensure_dir(RUN_DIR);
|
||||
let res = {};
|
||||
for (let id, srv in m.servers) {
|
||||
if (!srv.private_key || !srv.enabled)
|
||||
continue;
|
||||
if (system(`awg show ${q(srv.ifname)} public-key >/dev/null 2>&1`) != 0) {
|
||||
res[id] = 'down';
|
||||
continue;
|
||||
}
|
||||
let lines = [ '[Interface]', `PrivateKey = ${srv.private_key}`, `ListenPort = ${srv.port}`, '' ];
|
||||
for (let did, d in m.devices) {
|
||||
let p = m.people[d.person];
|
||||
if (!p || p.server != id || d.disabled || states[p.id] != 'active' || !d.public_key || !d.address)
|
||||
continue;
|
||||
push(lines, '[Peer]', `PublicKey = ${d.public_key}`);
|
||||
if (d.preshared_key)
|
||||
push(lines, `PresharedKey = ${d.preshared_key}`);
|
||||
push(lines, `AllowedIPs = ${d.address}/32`, '');
|
||||
}
|
||||
let f = `${RUN_DIR}/${srv.ifname}.conf`;
|
||||
write_file(f, join('\n', lines));
|
||||
let r = sh(`awg syncconf ${q(srv.ifname)} ${f}`);
|
||||
unlink(f);
|
||||
res[id] = r.code == 0 ? 'ok' : trim(r.out);
|
||||
if (r.code != 0)
|
||||
log(`awg syncconf ${srv.ifname}: ${trim(r.out)}`);
|
||||
}
|
||||
return res;
|
||||
};
|
||||
|
||||
/* ---------- hostnames ---------- */
|
||||
|
||||
function host_label(s) {
|
||||
let l = replace(lc(s), /[^a-z0-9]+/g, '-');
|
||||
l = replace(l, /^-+|-+$/g, '');
|
||||
return substr(l, 0, 40) || 'device';
|
||||
}
|
||||
|
||||
export function sync_hosts(m) {
|
||||
let lines = [];
|
||||
if (m.settings.hostnames)
|
||||
for (let id, d in m.devices) {
|
||||
let p = m.people[d.person];
|
||||
if (p && d.address)
|
||||
push(lines, `${d.address} ${host_label(d.name)}.${p.id}.${m.settings.domain}`);
|
||||
}
|
||||
let ls = loop.status();
|
||||
if (ls.active)
|
||||
push(lines, `${ls.address} dawnline.${m.settings.domain}`);
|
||||
let body = length(lines) ? join('\n', lines) + '\n' : '';
|
||||
// dnsmasq runs as its own user; rpcd's umask would leave the file 0600.
|
||||
let readable = ((stat(HOSTS_FILE)?.perm?.other_read) ?? false);
|
||||
if ((readfile(HOSTS_FILE) ?? '') == body && (body == '' || readable))
|
||||
return false;
|
||||
ensure_dir('/tmp/hosts');
|
||||
if (body == '')
|
||||
unlink(HOSTS_FILE);
|
||||
else {
|
||||
writefile(HOSTS_FILE, body);
|
||||
system(`chmod 644 ${HOSTS_FILE}`);
|
||||
}
|
||||
system('killall -HUP dnsmasq 2>/dev/null');
|
||||
return true;
|
||||
};
|
||||
|
||||
/* ---------- entry points ---------- */
|
||||
|
||||
export function states_for(m, usage) {
|
||||
let st = {};
|
||||
for (let id, p in m.people)
|
||||
st[id] = core.person_state(m, p, usage);
|
||||
return st;
|
||||
};
|
||||
|
||||
/** Runtime sync: peers + access sets + hostnames. Cheap; safe to call often. */
|
||||
export function sync(m, usage) {
|
||||
m ??= core.load();
|
||||
usage ??= core.load_usage();
|
||||
let states = states_for(m, usage);
|
||||
let l = lock('apply');
|
||||
let peers = sync_peers(m, states);
|
||||
let sets = access_sets(m, usage, states);
|
||||
if (!update_sets(sets))
|
||||
rebuild_nft(m, sets);
|
||||
sync_hosts(m);
|
||||
unlock(l);
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(`${RUN_DIR}/states.json`, states, 0o644);
|
||||
return { peers, states };
|
||||
};
|
||||
|
||||
/**
|
||||
* Everything on the router that Dawnline's state is derived from: WAN and
|
||||
* LAN, the home networks and zones of each server, the netns address and the
|
||||
* LAN's DNS. The agent re-applies when it changes (LAN renumbered, interface
|
||||
* added, bridge recreated, DHCP DNS changed, ...).
|
||||
*/
|
||||
export function net_signature(m) {
|
||||
let snap = net.snapshot(true);
|
||||
let srvs = {};
|
||||
for (let id, srv in m.servers)
|
||||
srvs[id] = net.server_net(srv, snap);
|
||||
let lan = snap.devices[snap.lan];
|
||||
return sprintf('%J', { wan: snap.wan, lan: snap.lan, addrs: lan?.addrs, servers: srvs, dns: loop.lan_dns(), loop: loop.client_dns() });
|
||||
};
|
||||
|
||||
const PORTAL_CGI = '/usr/share/dawnline/portal/www/cgi-bin/portal';
|
||||
const LAN_CGI = '/www/cgi-bin/dawnline-portal';
|
||||
const LAN_CGI_URL = '/cgi-bin/dawnline-portal';
|
||||
|
||||
/*
|
||||
* At home the portal's hostname usually points at the router itself, where
|
||||
* LuCI's web server owns 443. Paths it does not know (the portal's) go to the
|
||||
* portal CGI through its error page, so the same link works inside and out.
|
||||
*/
|
||||
function sync_uhttpd(m) {
|
||||
let want = m.settings.portal_enabled && core.portal_public_port(m) == 443 && m.settings.portal_port != 443;
|
||||
let c = cursor();
|
||||
c.load('uhttpd');
|
||||
let cur = c.get('uhttpd', 'main', 'error_page');
|
||||
let changed = false;
|
||||
if (want) {
|
||||
if (!stat(LAN_CGI))
|
||||
system(`ln -sf ${PORTAL_CGI} ${LAN_CGI}`);
|
||||
if (cur == null && c.get('uhttpd', 'main')) {
|
||||
c.set('uhttpd', 'main', 'error_page', LAN_CGI_URL);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (cur == LAN_CGI_URL) {
|
||||
c.delete('uhttpd', 'main', 'error_page');
|
||||
changed = true;
|
||||
}
|
||||
if (stat(LAN_CGI))
|
||||
unlink(LAN_CGI);
|
||||
}
|
||||
if (changed) {
|
||||
c.commit('uhttpd');
|
||||
system('/etc/init.d/uhttpd reload >/dev/null 2>&1');
|
||||
log(want ? 'portal answers on 443 at home too' : 'portal removed from the LuCI web server');
|
||||
}
|
||||
}
|
||||
|
||||
/** One `ipproto <p> sport <port> lookup main` rule per listening port and family. */
|
||||
function sync_reply_routes(m) {
|
||||
let want = [];
|
||||
if (m.settings.portal_enabled) {
|
||||
push(want, `tcp ${+m.settings.portal_port}`);
|
||||
if (core.portal_http(m))
|
||||
push(want, `tcp ${core.portal_http_port(m)}`);
|
||||
}
|
||||
for (let id, srv in m.servers)
|
||||
if (srv.private_key && srv.enabled && +srv.port)
|
||||
push(want, `udp ${+srv.port}`);
|
||||
want = uniq(want);
|
||||
for (let fam in [ '-4', '-6' ]) {
|
||||
let have = [];
|
||||
for (let line in split(sh_out(`ip ${fam} rule show priority ${PREF_REPLY} 2>/dev/null`) ?? '', '\n')) {
|
||||
let mm = match(line, /ipproto (tcp|udp) sport (\d+) lookup main/);
|
||||
if (mm)
|
||||
push(have, `${mm[1]} ${mm[2]}`);
|
||||
}
|
||||
for (let h in have)
|
||||
if (index(want, h) < 0)
|
||||
sh(`ip ${fam} rule del priority ${PREF_REPLY} ipproto ${split(h, ' ')[0]} sport ${split(h, ' ')[1]} lookup main 2>/dev/null`);
|
||||
for (let w in want)
|
||||
if (index(have, w) < 0)
|
||||
sh(`ip ${fam} rule add priority ${PREF_REPLY} ipproto ${split(w, ' ')[0]} sport ${split(w, ' ')[1]} lookup main`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep the "like a home device" path and the resolver in step (agent tick).
|
||||
* Cheap when nothing changed; rebuilds the access table when the netns
|
||||
* address appears, moves or goes away (the guard allows DNS to it).
|
||||
*/
|
||||
export function sync_loop(m, usage, force) {
|
||||
m ??= core.load();
|
||||
let before = `${loop.client_dns()} ${loop.resolver_target().mode}`;
|
||||
let p = loop.ensure(m, force);
|
||||
loop.sync_resolver(m);
|
||||
sync_reply_routes(m);
|
||||
if (`${loop.client_dns()} ${loop.resolver_target().mode}` != before) {
|
||||
usage ??= core.load_usage();
|
||||
rebuild_nft(m, access_sets(m, usage, states_for(m, usage)));
|
||||
sync_hosts(m);
|
||||
}
|
||||
return p;
|
||||
};
|
||||
|
||||
/** Every personal code is a word code; older random ones are replaced (their links stop working). */
|
||||
function ensure_word_codes() {
|
||||
let c = cursor();
|
||||
c.load('dawnline');
|
||||
let changed = false;
|
||||
c.foreach('dawnline', 'person', (s) => {
|
||||
if (s.code != null && !match(s.code, core.WORD_CODE)) {
|
||||
c.set('dawnline', s['.name'], 'code', core.new_code());
|
||||
c.delete('dawnline', s['.name'], 'words');
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
if (changed) {
|
||||
c.commit('dawnline');
|
||||
system('chmod 600 /etc/config/dawnline');
|
||||
log('personal links moved to word codes');
|
||||
}
|
||||
}
|
||||
|
||||
/** Full reconcile: router configuration + runtime state. */
|
||||
export function apply(opts) {
|
||||
opts ??= {};
|
||||
ensure_word_codes();
|
||||
let m = core.load();
|
||||
let usage = core.load_usage();
|
||||
let l = lock('reconcile');
|
||||
let net = sync_network(m);
|
||||
let fw = sync_firewall(m);
|
||||
sync_uhttpd(m);
|
||||
let lp = loop.ensure(m, true);
|
||||
loop.sync_resolver(m);
|
||||
sync_reply_routes(m);
|
||||
let states = states_for(m, usage);
|
||||
rebuild_nft(m, access_sets(m, usage, states));
|
||||
unlock(l);
|
||||
let r = sync(m, usage);
|
||||
return { network: net, firewall: fw, like_home: lp.error ? { error: lp.error } : !lp.off, peers: r.peers };
|
||||
};
|
||||
|
||||
/** Remove everything Dawnline created (used by the uninstaller). */
|
||||
export function teardown() {
|
||||
let m = core.load();
|
||||
loop.remove();
|
||||
unlink(loop.RESOLVER.conf);
|
||||
m.servers = {};
|
||||
m.settings.portal_enabled = false;
|
||||
sync_network(m);
|
||||
sync_firewall(m);
|
||||
sync_uhttpd(m);
|
||||
sync_reply_routes(m);
|
||||
remove_nft();
|
||||
unlink(HOSTS_FILE);
|
||||
system('killall -HUP dnsmasq 2>/dev/null');
|
||||
};
|
||||
@@ -0,0 +1,937 @@
|
||||
// Dawnline — data model: reads /etc/config/dawnline, validates and mutates it,
|
||||
// allocates addresses, generates keys and renders client configurations.
|
||||
|
||||
import { cursor } from 'uci';
|
||||
import { readfile } from 'fs';
|
||||
import {
|
||||
q, sh, sh_out, valid_name, valid_key, valid_host, valid_date, slugify,
|
||||
parse_cidr, cidr_str, cidr_overlaps, int2ip, ip2int, in_cidr, rand_token, rand_hex, rand_int, rand_bytes,
|
||||
date_end, month_key, read_json, write_json, ensure_dir, lock, unlock, DATA_DIR, RUN_DIR, uniq
|
||||
} from 'dawnline.util';
|
||||
import * as net from 'dawnline.net';
|
||||
import * as loop from 'dawnline.loop';
|
||||
|
||||
export const CONFIG = 'dawnline';
|
||||
export const ACCESS = [ 'lan', 'internet', 'both' ];
|
||||
export const KINDS = [ 'computer', 'phone', 'tablet', 'router', 'other' ];
|
||||
export const OBF_KEYS = [ 'jc', 'jmin', 'jmax', 's1', 's2', 's3', 's4', 'h1', 'h2', 'h3', 'h4', 'i1', 'i2', 'i3', 'i4', 'i5',
|
||||
// AmneziaWG 3.x
|
||||
'header_protection_key', 'content_padding_addition', 'rekey_after_time', 'rekey_timeout', 'reject_after_time',
|
||||
'keepalive_timeout', 'max_handshake_attempts', 'random_trailers', 'disable_cookies' ];
|
||||
|
||||
/** Names in .conf files (and AmneziaVPN keys); netifd uses `awg_<key>`. */
|
||||
export const OBF_CONF = {
|
||||
jc: 'Jc', jmin: 'Jmin', jmax: 'Jmax', s1: 'S1', s2: 'S2', s3: 'S3', s4: 'S4',
|
||||
h1: 'H1', h2: 'H2', h3: 'H3', h4: 'H4', i1: 'I1', i2: 'I2', i3: 'I3', i4: 'I4', i5: 'I5',
|
||||
header_protection_key: 'HeaderProtectionKey', content_padding_addition: 'ContentPaddingAddition',
|
||||
rekey_after_time: 'RekeyAfterTime', rekey_timeout: 'RekeyTimeout', reject_after_time: 'RejectAfterTime',
|
||||
keepalive_timeout: 'KeepaliveTimeout', max_handshake_attempts: 'MaxHandshakeAttempts',
|
||||
random_trailers: 'RandomTrailers', disable_cookies: 'DisableCookies',
|
||||
};
|
||||
|
||||
function toint(v, dflt) {
|
||||
if (v == null || v == '')
|
||||
return dflt;
|
||||
let n = +v;
|
||||
return n != n ? dflt : int(n);
|
||||
}
|
||||
|
||||
function num(v, dflt) {
|
||||
if (v == null || v == '')
|
||||
return dflt;
|
||||
let n = +v;
|
||||
return n != n ? dflt : n;
|
||||
}
|
||||
|
||||
function bool(v, dflt) {
|
||||
if (v == null || v == '')
|
||||
return dflt;
|
||||
return v == '1' || v == 'true' || v == 'yes' || v == 'on';
|
||||
}
|
||||
|
||||
function list(v) {
|
||||
if (v == null)
|
||||
return [];
|
||||
return type(v) == 'array' ? v : split(trim(v), /[[:space:],]+/);
|
||||
}
|
||||
|
||||
/* ---------- load ---------- */
|
||||
|
||||
export function open_cursor() {
|
||||
let c = cursor();
|
||||
c.load(CONFIG);
|
||||
return c;
|
||||
};
|
||||
|
||||
export function load(c) {
|
||||
c ??= open_cursor();
|
||||
let s = c.get_all(CONFIG, 'settings') ?? {};
|
||||
let m = {
|
||||
settings: {
|
||||
portal_enabled: bool(s.portal_enabled, false),
|
||||
portal_port: toint(s.portal_port, 8443),
|
||||
// Also answer on 443 from the internet (mobile networks often drop TLS on other ports).
|
||||
portal_443: bool(s.portal_443, true),
|
||||
portal_host: s.portal_host ?? '',
|
||||
// More addresses for the same links (the main one is portal_host).
|
||||
portal_alt: filter(type(s.portal_alt) == 'array' ? s.portal_alt : s.portal_alt ? [ s.portal_alt ] : [], (x) => x != ''),
|
||||
portal_cert: s.portal_cert ?? '',
|
||||
portal_key: s.portal_key ?? '',
|
||||
portal_title: s.portal_title ?? 'Dawnline',
|
||||
// Where unknown portal links go instead of a bare 404 (empty = 404).
|
||||
portal_redirect: s.portal_redirect ?? '',
|
||||
paused_all: bool(s.paused_all, false),
|
||||
default_device_limit: toint(s.default_device_limit, 3),
|
||||
geo_enabled: bool(s.geo_enabled, true),
|
||||
geo_provider: s.geo_provider == 'ipapi.co' ? 'ipapi.co' : 'ipwho.is',
|
||||
hostnames: bool(s.hostnames, true),
|
||||
domain: s.domain ?? 'lan',
|
||||
log_connections: bool(s.log_connections, true),
|
||||
// Second DNS for "home names" devices, used by the device when the tunnel is down.
|
||||
home_dns_fallback: s.home_dns_fallback == 'none' ? '' : (s.home_dns_fallback ?? '1.1.1.1'),
|
||||
// Raw retention values; dawnline.live policy() interprets them.
|
||||
retention: {
|
||||
log_keep_days: s.log_keep_days, log_max: s.log_max, log_category: s.log_category,
|
||||
log_connections: s.log_connections, log_persist: s.log_persist,
|
||||
usage_keep_days: s.usage_keep_days, usage_keep_months: s.usage_keep_months,
|
||||
},
|
||||
},
|
||||
servers: {},
|
||||
people: {},
|
||||
devices: {},
|
||||
services: {},
|
||||
};
|
||||
|
||||
c.foreach(CONFIG, 'server', (r) => {
|
||||
let id = r['.name'];
|
||||
let srv = {
|
||||
id,
|
||||
name: r.name ?? id,
|
||||
ifname: r.ifname ?? id,
|
||||
port: toint(r.port, 51820),
|
||||
subnet: r.subnet ?? '',
|
||||
endpoint: r.endpoint ?? '',
|
||||
mtu: toint(r.mtu, 1380),
|
||||
dns: list(r.dns),
|
||||
keepalive: toint(r.keepalive, 25),
|
||||
private_key: r.private_key ?? '',
|
||||
public_key: r.public_key ?? '',
|
||||
preset: r.preset ?? 'standard',
|
||||
lan_zone: r.lan_zone ?? 'lan',
|
||||
wan_zone: r.wan_zone ?? 'wan',
|
||||
auto_wan: bool(r.auto_wan, true),
|
||||
wan_device: r.wan_device ?? '',
|
||||
auto_lan: bool(r.auto_lan, true),
|
||||
lan_devices: list(r.lan_device),
|
||||
detected_wan: r.detected_wan ?? '',
|
||||
detected_lan: r.detected_lan ?? '',
|
||||
lan_like: bool(r.lan_like, true),
|
||||
enabled: bool(r.enabled, true),
|
||||
obf: {},
|
||||
};
|
||||
for (let k in OBF_KEYS)
|
||||
if (r[k] != null && r[k] != '')
|
||||
srv.obf[k] = `${r[k]}`;
|
||||
m.servers[id] = srv;
|
||||
});
|
||||
|
||||
c.foreach(CONFIG, 'person', (r) => {
|
||||
let id = r['.name'];
|
||||
m.people[id] = {
|
||||
id,
|
||||
server: r.server ?? '',
|
||||
name: r.name ?? id,
|
||||
access: index(ACCESS, r.access) >= 0 ? r.access : 'internet',
|
||||
device_limit: toint(r.device_limit, m.settings.default_device_limit),
|
||||
code: r.code ?? '',
|
||||
expires: r.expires ?? '',
|
||||
quota_gb: num(r.quota_gb, 0),
|
||||
quota_period: r.quota_period == 'total' ? 'total' : 'month',
|
||||
paused: bool(r.paused, false),
|
||||
hours: r.hours ?? '',
|
||||
expire_action: index([ 'pause', 'notify', 'remove' ], r.expire_action) >= 0 ? r.expire_action : 'pause',
|
||||
// Home-only access: keep the device's own DNS, or use home names (Dawnline's resolver).
|
||||
dns_mode: r.dns_mode == 'home' ? 'home' : 'device',
|
||||
expire_warn: toint(r.expire_warn, 3),
|
||||
bonus_gb: num(r.bonus_gb, 0),
|
||||
bonus_month: r.bonus_month ?? '',
|
||||
services: list(r.service),
|
||||
note: r.note ?? '',
|
||||
created: toint(r.created, 0),
|
||||
devices: [],
|
||||
};
|
||||
});
|
||||
|
||||
c.foreach(CONFIG, 'device', (r) => {
|
||||
let id = r['.name'];
|
||||
let d = {
|
||||
id,
|
||||
person: r.person ?? '',
|
||||
name: r.name ?? id,
|
||||
kind: index(KINDS, r.kind) >= 0 ? r.kind : 'other',
|
||||
address: r.address ?? '',
|
||||
public_key: r.public_key ?? '',
|
||||
private_key: r.private_key ?? '',
|
||||
preshared_key: r.preshared_key ?? '',
|
||||
created: toint(r.created, 0),
|
||||
created_by: r.created_by ?? 'admin',
|
||||
disabled: bool(r.disabled, false),
|
||||
};
|
||||
m.devices[id] = d;
|
||||
if (m.people[d.person])
|
||||
push(m.people[d.person].devices, id);
|
||||
});
|
||||
|
||||
c.foreach(CONFIG, 'service', (r) => {
|
||||
let id = r['.name'];
|
||||
m.services[id] = {
|
||||
id,
|
||||
name: r.name ?? id,
|
||||
address: r.address ?? '',
|
||||
ports: list(r.port),
|
||||
};
|
||||
});
|
||||
|
||||
return m;
|
||||
};
|
||||
|
||||
/* ---------- derived state ---------- */
|
||||
|
||||
/** Parse "07:00-23:00" → [startMin, endMin] or null. */
|
||||
export function parse_hours(s) {
|
||||
let m = match(s ?? '', /^([0-9]{1,2}):([0-9]{2})-([0-9]{1,2}):([0-9]{2})$/);
|
||||
if (!m)
|
||||
return null;
|
||||
let a = +m[1] * 60 + +m[2], b = +m[3] * 60 + +m[4];
|
||||
if (a >= 1440 || b > 1440 || a == b)
|
||||
return null;
|
||||
return [ a, b ];
|
||||
};
|
||||
|
||||
function within_hours(h, ts) {
|
||||
let t = localtime(ts);
|
||||
let cur = t.hour * 60 + t.min;
|
||||
return h[0] < h[1] ? (cur >= h[0] && cur < h[1]) : (cur >= h[0] || cur < h[1]);
|
||||
}
|
||||
|
||||
/** Bytes used in the person's quota period. */
|
||||
export function person_usage(p, usage) {
|
||||
let u = usage?.people?.[p.id];
|
||||
if (!u)
|
||||
return 0;
|
||||
if (p.quota_period == 'total')
|
||||
return (u.total?.[0] ?? 0) + (u.total?.[1] ?? 0);
|
||||
let mm = u.months?.[month_key()];
|
||||
return mm ? mm[0] + mm[1] : 0;
|
||||
};
|
||||
|
||||
/** Quota in bytes for the current period (base + this month's bonus), 0 = unlimited. */
|
||||
export function person_quota(p) {
|
||||
if (!(p.quota_gb > 0))
|
||||
return 0;
|
||||
let gb = p.quota_gb;
|
||||
if (p.bonus_gb > 0 && p.bonus_month == month_key())
|
||||
gb += p.bonus_gb;
|
||||
return gb * 1073741824;
|
||||
};
|
||||
|
||||
export function person_expired(p, ts) {
|
||||
if (p.expires == '')
|
||||
return false;
|
||||
let end = date_end(p.expires);
|
||||
return end != null && (ts ?? time()) > end;
|
||||
};
|
||||
|
||||
/**
|
||||
* Effective state of a person: 'active', or why they are off:
|
||||
* 'paused' (admin), 'paused_all', 'expired', 'quota', 'hours', 'no_server'.
|
||||
*/
|
||||
export function person_state(m, p, usage, ts) {
|
||||
ts ??= time();
|
||||
let srv = m.servers[p.server];
|
||||
if (!srv || !srv.enabled)
|
||||
return 'no_server';
|
||||
if (p.paused)
|
||||
return 'paused';
|
||||
if (m.settings.paused_all)
|
||||
return 'paused_all';
|
||||
// "notify" keeps access after the end date (shown in Overview and People).
|
||||
if (person_expired(p, ts) && p.expire_action != 'notify')
|
||||
return 'expired';
|
||||
let quota = person_quota(p);
|
||||
if (quota > 0 && person_usage(p, usage) >= quota)
|
||||
return 'quota';
|
||||
let h = parse_hours(p.hours);
|
||||
if (h && !within_hours(h, ts))
|
||||
return 'hours';
|
||||
return 'active';
|
||||
};
|
||||
|
||||
export function load_usage() {
|
||||
return read_json(`${RUN_DIR}/usage.json`, null) ?? read_json(`${DATA_DIR}/usage.json`, { devices: {}, people: {} });
|
||||
};
|
||||
|
||||
/* ---------- keys ---------- */
|
||||
|
||||
export function genkey() {
|
||||
return sh_out('awg genkey');
|
||||
};
|
||||
|
||||
export function pubkey(priv) {
|
||||
if (!valid_key(priv))
|
||||
return null;
|
||||
return sh_out(`printf %s ${q(priv)} | awg pubkey`);
|
||||
};
|
||||
|
||||
export function genpsk() {
|
||||
return sh_out('awg genpsk');
|
||||
};
|
||||
|
||||
/* ---------- networks ---------- */
|
||||
|
||||
/** IPv4 subnets of the router's LAN zone (from netifd), as CIDR strings. */
|
||||
/** Router address inside the server subnet (first host). */
|
||||
export function server_address(srv) {
|
||||
let c = parse_cidr(srv.subnet);
|
||||
return c ? int2ip(c.first) : null;
|
||||
};
|
||||
|
||||
export function alloc_address(m, srv) {
|
||||
let c = parse_cidr(srv.subnet);
|
||||
if (!c)
|
||||
return null;
|
||||
let used = {};
|
||||
used[c.first] = true;
|
||||
for (let id, d in m.devices) {
|
||||
let p = m.people[d.person];
|
||||
if (p && p.server == srv.id) {
|
||||
let n = ip2int(d.address);
|
||||
if (n != null)
|
||||
used[n] = true;
|
||||
}
|
||||
}
|
||||
for (let n = c.first + 1; n <= c.last; n++)
|
||||
if (!used[n])
|
||||
return int2ip(n);
|
||||
return null;
|
||||
};
|
||||
|
||||
/* ---------- obfuscation ---------- */
|
||||
|
||||
const OBF_SPEC = { jc: [ 0, 10 ], jmin: [ 64, 1024 ], jmax: [ 64, 1024 ], s1: [ 0, 64 ], s2: [ 0, 64 ], s3: [ 0, 64 ], s4: [ 0, 32 ] };
|
||||
|
||||
function rand_h(used) {
|
||||
for (let i = 0; i < 50; i++) {
|
||||
let v = rand_int(5, 2147483647);
|
||||
if (!used[v]) {
|
||||
used[v] = true;
|
||||
return `${v}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What the installed AmneziaWG can do, from the netifd protocol script (the
|
||||
* options it passes on) and the `awg` tool (the keys it accepts):
|
||||
* v2 — S3/S4, I1-I5, header ranges (AWG 1.5/2.0)
|
||||
* v3 — header protection, trailers, padding, timing (AWG 3.1)
|
||||
*/
|
||||
export function awg_caps() {
|
||||
let script = readfile('/lib/netifd/proto/amneziawg.sh') ?? '';
|
||||
let tool = sh_out("grep -a -o -m1 'HeaderProtectionKey' /usr/bin/awg 2>/dev/null") ?? '';
|
||||
let v2 = index(script, 'awg_s3') >= 0 && index(script, 'awg_i1') >= 0;
|
||||
let v3 = v2 && index(script, 'awg_header_protection_key') >= 0 && tool != '';
|
||||
return { v2, v3 };
|
||||
};
|
||||
|
||||
/** First junk packet shaped like a DNS answer (AmneziaVPN's own default for 3.1). */
|
||||
const DNS_MIMIC = '<r 2><b 0x858000010001000000000669636c6f756403636f6d0000010001c00c000100010000105a00044d583737>';
|
||||
|
||||
/**
|
||||
* Generate obfuscation parameters for a method:
|
||||
* off plain WireGuard-compatible packets
|
||||
* standard junk packets and random headers (any AmneziaWG client)
|
||||
* strong more and larger junk (any AmneziaWG client)
|
||||
* max AmneziaWG 3.1: protected headers, random trailers, padding,
|
||||
* jittered timers and a DNS-like first packet — the values
|
||||
* AmneziaVPN itself uses for 3.1 servers
|
||||
*/
|
||||
export function obf_preset(name) {
|
||||
if (name == 'max')
|
||||
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_MIMIC,
|
||||
header_protection_key: genkey(),
|
||||
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 strong = name == 'strong';
|
||||
let o = {};
|
||||
o.jc = `${strong ? rand_int(6, 10) : rand_int(3, 6)}`;
|
||||
let jmin = rand_int(64, strong ? 128 : 96);
|
||||
o.jmin = `${jmin}`;
|
||||
o.jmax = `${jmin + rand_int(strong ? 200 : 32, strong ? 600 : 160)}`;
|
||||
let s1 = rand_int(15, 64), s2 = rand_int(15, 64);
|
||||
while (s1 + 56 == s2)
|
||||
s2 = rand_int(15, 64);
|
||||
o.s1 = `${s1}`;
|
||||
o.s2 = `${s2}`;
|
||||
let used = {};
|
||||
for (let k in [ 'h1', 'h2', 'h3', 'h4' ])
|
||||
o[k] = rand_h(used);
|
||||
return o;
|
||||
};
|
||||
|
||||
export function obf_errors(o) {
|
||||
let errs = [];
|
||||
for (let k, r in OBF_SPEC) {
|
||||
let v = o[k];
|
||||
if (v == null || v == '')
|
||||
continue;
|
||||
if (!match(v, /^[0-9]+$/) || +v < r[0] || +v > r[1]) {
|
||||
if (!(v == '0' && (k == 'jmin' || k == 'jmax')))
|
||||
push(errs, `${k}=${v} (${r[0]}-${r[1]})`);
|
||||
}
|
||||
}
|
||||
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, `${k} must be a number or range`);
|
||||
else if (hs[v])
|
||||
push(errs, 'h1-h4 must be distinct');
|
||||
hs[v] = true;
|
||||
}
|
||||
return errs;
|
||||
};
|
||||
|
||||
/* ---------- client configuration ---------- */
|
||||
|
||||
export function endpoint_host(m, srv) {
|
||||
return srv.endpoint || m.settings.portal_host || '';
|
||||
};
|
||||
|
||||
/**
|
||||
* DNS for a server's clients: the router's tunnel address, which never
|
||||
* changes after setup. The router forwards each query where it belongs (the
|
||||
* LAN's DNS, from the LAN side; or the plain resolver), so configurations on
|
||||
* devices keep working when the LAN, its DNS or the netns address change.
|
||||
*/
|
||||
export function dns_list(m, srv) {
|
||||
if (!srv)
|
||||
return [];
|
||||
if (length(srv.dns))
|
||||
return srv.dns;
|
||||
let a = server_address(srv);
|
||||
return a ? [ a ] : [];
|
||||
};
|
||||
|
||||
/**
|
||||
* DNS written into a device's configuration. Home-only people keep their
|
||||
* device's DNS unless they chose home names; then the first server is
|
||||
* Dawnline's plain resolver (reached through the tunnel) and the second the
|
||||
* fallback the device uses when the tunnel is down.
|
||||
*/
|
||||
export function client_dns(m, srv, p) {
|
||||
if (p?.access != 'lan')
|
||||
return dns_list(m, srv);
|
||||
if (p.dns_mode != 'home')
|
||||
return [];
|
||||
let a = server_address(srv);
|
||||
let out = a ? [ a ] : [];
|
||||
if (m.settings.home_dns_fallback && m.settings.home_dns_fallback != a)
|
||||
push(out, m.settings.home_dns_fallback);
|
||||
return out;
|
||||
};
|
||||
|
||||
export function allowed_ips(m, srv, p) {
|
||||
if (p.access == 'lan') {
|
||||
let nets = net.server_net(srv).nets;
|
||||
let a = server_address(srv);
|
||||
if (a)
|
||||
push(nets, `${a}/32`);
|
||||
// The resolver address must be reachable through the tunnel too (not the fallback).
|
||||
let dns = client_dns(m, srv, p)[0];
|
||||
if (dns)
|
||||
push(nets, `${dns}/32`);
|
||||
return net.collapse(nets);
|
||||
}
|
||||
return [ '0.0.0.0/0', '::/0' ];
|
||||
};
|
||||
|
||||
/** Everything a client needs; `conf` is the .conf text. */
|
||||
export function client_config(m, dev) {
|
||||
let p = m.people[dev.person];
|
||||
let srv = p ? m.servers[p.server] : null;
|
||||
if (!srv)
|
||||
return null;
|
||||
let host = endpoint_host(m, srv);
|
||||
let ep = match(host, /:/) && !match(host, /^\[/) ? `[${host}]` : host;
|
||||
let allowed = allowed_ips(m, srv, p);
|
||||
let dns = client_dns(m, srv, p);
|
||||
let lines = [ '[Interface]' ];
|
||||
push(lines, `PrivateKey = ${dev.private_key || '<private key stays on your device>'}`);
|
||||
push(lines, `Address = ${dev.address}/32`);
|
||||
if (length(dns))
|
||||
push(lines, `DNS = ${join(', ', dns)}`);
|
||||
push(lines, `MTU = ${srv.mtu}`);
|
||||
for (let k in OBF_KEYS)
|
||||
if (srv.obf[k] != null && srv.obf[k] != '')
|
||||
push(lines, `${OBF_CONF[k]} = ${srv.obf[k]}`);
|
||||
push(lines, '', '[Peer]');
|
||||
push(lines, `PublicKey = ${srv.public_key}`);
|
||||
if (dev.preshared_key)
|
||||
push(lines, `PresharedKey = ${dev.preshared_key}`);
|
||||
push(lines, `AllowedIPs = ${join(', ', allowed)}`);
|
||||
push(lines, `Endpoint = ${ep}:${srv.port}`);
|
||||
if (srv.keepalive > 0)
|
||||
push(lines, `PersistentKeepalive = ${srv.keepalive}`);
|
||||
return {
|
||||
name: dev.name,
|
||||
person: p.name,
|
||||
server: srv.name,
|
||||
filename: `${substr(replace(lc(p.id + '-' + dev.name), /[^a-z0-9]+/g, '-'), 0, 15)}.conf`,
|
||||
conf: join('\n', lines) + '\n',
|
||||
has_private_key: dev.private_key != '',
|
||||
amnezia: {
|
||||
host,
|
||||
port: srv.port,
|
||||
mtu: `${srv.mtu}`,
|
||||
dns,
|
||||
allowed_ips: allowed,
|
||||
client_ip: dev.address,
|
||||
client_priv_key: dev.private_key,
|
||||
client_pub_key: dev.public_key,
|
||||
psk_key: dev.preshared_key,
|
||||
server_pub_key: srv.public_key,
|
||||
persistent_keep_alive: `${srv.keepalive}`,
|
||||
obfuscation: srv.obf,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
/* ---------- issued configurations ---------- */
|
||||
|
||||
const ISSUED = `${DATA_DIR}/issued.json`;
|
||||
|
||||
function fnv32(str) {
|
||||
let h = 2166136261;
|
||||
for (let i = 0; i < length(str); i++)
|
||||
h = ((h ^ ord(str, i)) * 16777619) & 0xffffffff;
|
||||
return sprintf('%08x', h);
|
||||
}
|
||||
|
||||
/** What a device holds, minus its private key: changes when it must import again. */
|
||||
export function config_fingerprint(m, dev) {
|
||||
let c = dev ? client_config(m, dev) : null;
|
||||
return c ? fnv32(join('\n', filter(split(c.conf, '\n'), (l) => !match(l, /^PrivateKey/)))) : null;
|
||||
};
|
||||
|
||||
/** Device id → fingerprint of the configuration last shown or downloaded. */
|
||||
export function issued() {
|
||||
return read_json(ISSUED, {});
|
||||
};
|
||||
|
||||
/** Remember that a device was just given its current configuration. */
|
||||
export function mark_issued(m, id) {
|
||||
let fp = config_fingerprint(m, m.devices[id]);
|
||||
if (!fp)
|
||||
return;
|
||||
let l = lock('issued');
|
||||
let all = issued();
|
||||
if (all[id] != fp) {
|
||||
all[id] = fp;
|
||||
for (let k in keys(all))
|
||||
if (!m.devices[k])
|
||||
delete all[k];
|
||||
ensure_dir(DATA_DIR, 0o700);
|
||||
write_json(ISSUED, all, 0o600);
|
||||
}
|
||||
unlock(l);
|
||||
};
|
||||
|
||||
/* ---------- mutations (caller commits) ---------- */
|
||||
|
||||
function fail(msg) {
|
||||
die(msg);
|
||||
}
|
||||
|
||||
/*
|
||||
* Personal codes are three pronounceable words of three syllables each
|
||||
* (kamiro-telosu-bavine): easy to read out or type, ~2^55 combinations, and
|
||||
* guessing is rate-limited by the portal. The code is the whole link path.
|
||||
*/
|
||||
export const WORD_CODE = /^[a-z]{6}-[a-z]{6}-[a-z]{6}$/;
|
||||
const SYL_C = 'bdfgklmnprstvz', SYL_V = 'aeiou';
|
||||
const CODE_AVOID = [ 'suka', 'pido', 'muda', 'zalup', 'dura', 'gavn' ];
|
||||
|
||||
function pick(alphabet) {
|
||||
let n = length(alphabet), lim = 256 - 256 % n;
|
||||
for (;;) {
|
||||
let b = ord(rand_bytes(1), 0);
|
||||
if (b < lim)
|
||||
return substr(alphabet, b % n, 1);
|
||||
}
|
||||
}
|
||||
|
||||
export function new_code() {
|
||||
for (;;) {
|
||||
let words = [];
|
||||
for (let w = 0; w < 3; w++) {
|
||||
let s = '';
|
||||
for (let i = 0; i < 3; i++)
|
||||
s += pick(SYL_C) + pick(SYL_V);
|
||||
push(words, s);
|
||||
}
|
||||
let code = join('-', words);
|
||||
if (!length(filter(CODE_AVOID, (x) => index(code, x) >= 0)))
|
||||
return code;
|
||||
}
|
||||
};
|
||||
|
||||
export function create_person(c, m, a) {
|
||||
if (!valid_name(a.name))
|
||||
fail('Enter a name (up to 48 characters).');
|
||||
// The id is a UCI section name: letters, digits and underscores only (a dash
|
||||
// makes uci drop the section). Repeated names get _2, _3, …
|
||||
let base = replace(a.slug ?? slugify(a.name), /-/g, '_');
|
||||
if (!match(base, /^[a-z0-9_]{1,32}$/))
|
||||
fail('The id may use lowercase letters, digits and underscores.');
|
||||
let taken = (id) => m.people[id] || m.servers[id] || m.devices[id] || m.services[id] || id == 'settings';
|
||||
let slug = base;
|
||||
for (let n = 2; taken(slug); n++) {
|
||||
if (n > 99)
|
||||
fail(`"${base}" is already taken.`);
|
||||
slug = `${substr(base, 0, 28)}_${n}`;
|
||||
}
|
||||
let srv_id = a.server ?? keys(m.servers)[0];
|
||||
if (!m.servers[srv_id])
|
||||
fail('Set up a server first.');
|
||||
let access = a.access ?? 'internet';
|
||||
if (index(ACCESS, access) < 0)
|
||||
fail('Access must be lan, internet or both.');
|
||||
let limit = toint(a.device_limit, m.settings.default_device_limit);
|
||||
if (limit < 1 || limit > 32)
|
||||
fail('Device limit must be between 1 and 32.');
|
||||
if (a.expires && !valid_date(a.expires))
|
||||
fail('End date must be YYYY-MM-DD.');
|
||||
let quota = num(a.quota_gb, 0);
|
||||
if (quota < 0 || quota > 100000)
|
||||
fail('Monthly data must be a positive number of GB.');
|
||||
|
||||
c.set(CONFIG, slug, 'person');
|
||||
c.set(CONFIG, slug, 'server', srv_id);
|
||||
c.set(CONFIG, slug, 'name', trim(a.name));
|
||||
c.set(CONFIG, slug, 'access', access);
|
||||
c.set(CONFIG, slug, 'device_limit', `${limit}`);
|
||||
c.set(CONFIG, slug, 'code', new_code());
|
||||
c.set(CONFIG, slug, 'created', `${time()}`);
|
||||
if (a.expires)
|
||||
c.set(CONFIG, slug, 'expires', a.expires);
|
||||
if (quota > 0) {
|
||||
c.set(CONFIG, slug, 'quota_gb', `${quota}`);
|
||||
c.set(CONFIG, slug, 'quota_period', a.quota_period == 'total' ? 'total' : 'month');
|
||||
}
|
||||
return slug;
|
||||
};
|
||||
|
||||
/**
|
||||
* Immediate edit of a person from the admin page. Only keys present in `a`
|
||||
* change; '' clears optional values (end date, data limit, hours).
|
||||
*/
|
||||
export function update_person(c, m, id, a) {
|
||||
let p = m.people[id];
|
||||
if (!p)
|
||||
fail('Unknown person.');
|
||||
let set = (k, v) => (v == null || v == '') ? c.delete(CONFIG, id, k) : c.set(CONFIG, id, k, `${v}`);
|
||||
if (a.name != null) {
|
||||
if (!valid_name(a.name))
|
||||
fail('Enter a name (up to 48 characters).');
|
||||
set('name', trim(a.name));
|
||||
}
|
||||
if (a.access != null) {
|
||||
if (index(ACCESS, a.access) < 0)
|
||||
fail('Access must be lan, internet or both.');
|
||||
set('access', a.access);
|
||||
}
|
||||
if (a.device_limit != null) {
|
||||
let n = toint(a.device_limit, 0);
|
||||
if (n < 1 || n > 32)
|
||||
fail('Device limit must be between 1 and 32.');
|
||||
if (n < length(p.devices))
|
||||
fail(`${p.name} already has ${length(p.devices)} devices. Remove one first to lower the limit to ${n}.`);
|
||||
set('device_limit', n);
|
||||
}
|
||||
if (a.expires != null) {
|
||||
if (a.expires != '' && !valid_date(a.expires))
|
||||
fail('End date must be YYYY-MM-DD.');
|
||||
set('expires', a.expires);
|
||||
}
|
||||
if (a.expire_action != null) {
|
||||
if (index([ 'pause', 'notify', 'remove' ], a.expire_action) < 0)
|
||||
fail('Unknown end action.');
|
||||
set('expire_action', a.expire_action == 'pause' ? '' : a.expire_action);
|
||||
}
|
||||
if (a.dns_mode != null) {
|
||||
if (index([ 'device', 'home' ], a.dns_mode) < 0)
|
||||
fail('Unknown DNS choice.');
|
||||
set('dns_mode', a.dns_mode == 'device' ? '' : a.dns_mode);
|
||||
}
|
||||
if (a.expire_warn != null) {
|
||||
let n = toint(a.expire_warn, -1);
|
||||
if (n < 0 || n > 60)
|
||||
fail('Warning must be 0-60 days.');
|
||||
set('expire_warn', n == 3 ? '' : n);
|
||||
}
|
||||
if (a.quota_gb != null) {
|
||||
let q = num(a.quota_gb, -1);
|
||||
if (a.quota_gb != '' && (q < 0 || q > 100000))
|
||||
fail('Data limit must be a positive number of GB.');
|
||||
set('quota_gb', q > 0 ? q : '');
|
||||
}
|
||||
if (a.quota_period != null)
|
||||
set('quota_period', a.quota_period == 'total' ? 'total' : '');
|
||||
if (a.bonus_gb != null) {
|
||||
let b = num(a.bonus_gb, -1);
|
||||
if (b < 0 || b > 100000)
|
||||
fail('Extra data must be a positive number of GB.');
|
||||
set('bonus_gb', b > 0 ? b : '');
|
||||
set('bonus_month', b > 0 ? month_key() : '');
|
||||
}
|
||||
if (a.hours != null) {
|
||||
if (a.hours != '' && !parse_hours(a.hours))
|
||||
fail('Hours must look like 07:00-23:00.');
|
||||
set('hours', a.hours);
|
||||
}
|
||||
if (a.note != null)
|
||||
set('note', substr(trim(a.note), 0, 500));
|
||||
if (type(a.services) == 'array') {
|
||||
for (let sid in a.services)
|
||||
if (!m.services[sid])
|
||||
fail(`Unknown service ${sid}.`);
|
||||
if (length(a.services))
|
||||
c.set(CONFIG, id, 'service', a.services);
|
||||
else
|
||||
c.delete(CONFIG, id, 'service');
|
||||
}
|
||||
if (a.paused != null)
|
||||
set('paused', a.paused ? '1' : '');
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a device for a person. `opts.by` is 'admin' or 'portal'; the portal
|
||||
* enforces the device limit. `opts.public_key` keeps the private key on the
|
||||
* client (browser-generated keys).
|
||||
*/
|
||||
export function create_device(c, m, person_id, name, kind, opts) {
|
||||
opts ??= {};
|
||||
let p = m.people[person_id];
|
||||
if (!p)
|
||||
fail('Unknown person.');
|
||||
let srv = m.servers[p.server];
|
||||
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 (index(KINDS, kind) < 0)
|
||||
kind = 'other';
|
||||
if (opts.by == 'portal' && length(p.devices) >= p.device_limit)
|
||||
fail(`Device limit reached (${p.device_limit}).`);
|
||||
for (let id in p.devices)
|
||||
if (lc(m.devices[id].name) == lc(name))
|
||||
fail(`"${name}" already exists.`);
|
||||
let addr = alloc_address(m, srv);
|
||||
if (!addr)
|
||||
fail('No free addresses left in the server subnet.');
|
||||
|
||||
let priv = '', pub;
|
||||
if (opts.public_key) {
|
||||
if (!valid_key(opts.public_key))
|
||||
fail('Invalid public key.');
|
||||
pub = opts.public_key;
|
||||
}
|
||||
else {
|
||||
priv = genkey();
|
||||
pub = pubkey(priv);
|
||||
}
|
||||
if (!pub)
|
||||
fail('Key generation failed (is amneziawg-tools installed?).');
|
||||
for (let id, d in m.devices)
|
||||
if (d.public_key == pub)
|
||||
fail('This key is already in use.');
|
||||
|
||||
let id = `d_${rand_hex(4)}`;
|
||||
c.set(CONFIG, id, 'device');
|
||||
c.set(CONFIG, id, 'person', person_id);
|
||||
c.set(CONFIG, id, 'name', name);
|
||||
c.set(CONFIG, id, 'kind', kind);
|
||||
c.set(CONFIG, id, 'address', addr);
|
||||
c.set(CONFIG, id, 'public_key', pub);
|
||||
if (priv)
|
||||
c.set(CONFIG, id, 'private_key', priv);
|
||||
c.set(CONFIG, id, 'preshared_key', genpsk());
|
||||
c.set(CONFIG, id, 'created', `${time()}`);
|
||||
c.set(CONFIG, id, 'created_by', opts.by ?? 'admin');
|
||||
|
||||
// Keep the in-memory model consistent for callers that continue.
|
||||
m.devices[id] = { id, person: person_id, name, kind, address: addr, public_key: pub, private_key: priv,
|
||||
preshared_key: c.get(CONFIG, id, 'preshared_key'), created: time(), created_by: opts.by ?? 'admin', disabled: false };
|
||||
push(p.devices, id);
|
||||
return id;
|
||||
};
|
||||
|
||||
export function rename_device(c, m, id, name) {
|
||||
let d = m.devices[id];
|
||||
if (!d)
|
||||
fail('Unknown device.');
|
||||
name = trim(name ?? '');
|
||||
if (!valid_name(name))
|
||||
fail('Enter a device name (up to 48 characters).');
|
||||
for (let o in m.people[d.person]?.devices ?? [])
|
||||
if (o != id && lc(m.devices[o].name) == lc(name))
|
||||
fail(`"${name}" already exists.`);
|
||||
c.set(CONFIG, id, 'name', name);
|
||||
d.name = name;
|
||||
};
|
||||
|
||||
export function delete_device(c, m, id) {
|
||||
let d = m.devices[id];
|
||||
if (!d)
|
||||
fail('Unknown device.');
|
||||
c.delete(CONFIG, id);
|
||||
let p = m.people[d.person];
|
||||
if (p)
|
||||
p.devices = filter(p.devices, (x) => x != id);
|
||||
delete m.devices[id];
|
||||
};
|
||||
|
||||
export function rotate_device(c, m, id) {
|
||||
let d = m.devices[id];
|
||||
if (!d)
|
||||
fail('Unknown device.');
|
||||
let priv = genkey(), pub = pubkey(priv);
|
||||
if (!pub)
|
||||
fail('Key generation failed.');
|
||||
c.set(CONFIG, id, 'private_key', priv);
|
||||
c.set(CONFIG, id, 'public_key', pub);
|
||||
c.set(CONFIG, id, 'preshared_key', genpsk());
|
||||
};
|
||||
|
||||
export function delete_person(c, m, id) {
|
||||
let p = m.people[id];
|
||||
if (!p)
|
||||
fail('Unknown person.');
|
||||
for (let d in p.devices)
|
||||
c.delete(CONFIG, d);
|
||||
c.delete(CONFIG, id);
|
||||
};
|
||||
|
||||
/** Validate a server definition (as loaded) against the rest of the router. */
|
||||
export function server_errors(m, srv, others_subnets) {
|
||||
let errs = [];
|
||||
if (!match(srv.ifname, /^[a-z][a-z0-9_]{0,11}$/))
|
||||
push(errs, 'Interface name: 1-12 lowercase letters, digits or _.');
|
||||
if (srv.port < 1 || srv.port > 65535)
|
||||
push(errs, 'Port must be 1-65535.');
|
||||
let c = parse_cidr(srv.subnet);
|
||||
if (!c)
|
||||
push(errs, 'Subnet must look like 10.77.0.0/24.');
|
||||
else
|
||||
for (let o in others_subnets ?? []) {
|
||||
let oc = parse_cidr(o);
|
||||
if (oc && cidr_overlaps(c, oc))
|
||||
push(errs, `Subnet overlaps ${o}.`);
|
||||
}
|
||||
if (srv.endpoint != '' && !valid_host(srv.endpoint))
|
||||
push(errs, 'Endpoint must be a hostname or IP address.');
|
||||
push(errs, ...obf_errors(srv.obf));
|
||||
return errs;
|
||||
};
|
||||
|
||||
/** Someone else already forwards this TCP port from outside (a port forward we must not take over). */
|
||||
export function wan_port_taken(port) {
|
||||
let c = cursor();
|
||||
c.load('firewall');
|
||||
let taken = false;
|
||||
c.foreach('firewall', 'redirect', (r) => {
|
||||
if (match(r['.name'], /^dawnline_/) || r.enabled == '0' || (r.target ?? 'DNAT') != 'DNAT')
|
||||
return;
|
||||
for (let p in split(`${r.src_dport ?? ''}`, /[ ,]+/)) {
|
||||
let m = match(p, /^(\d+)(?:[-:](\d+))?$/);
|
||||
if (m && +m[1] <= port && port <= +(m[2] ?? m[1]))
|
||||
taken = true;
|
||||
}
|
||||
});
|
||||
return taken;
|
||||
};
|
||||
|
||||
export function wan443_taken() {
|
||||
return wan_port_taken(443);
|
||||
};
|
||||
|
||||
/** Every address the links use, the main one first. */
|
||||
export function portal_hosts(m) {
|
||||
let out = [];
|
||||
for (let h in [ m.settings.portal_host, ...m.settings.portal_alt ])
|
||||
if (h && index(out, h) < 0)
|
||||
push(out, h);
|
||||
return out;
|
||||
};
|
||||
|
||||
/** IP addresses have no certificate: the portal also answers plain HTTP for them. */
|
||||
export function portal_http(m) {
|
||||
return length(filter(portal_hosts(m), (h) => ip2int(h) != null)) > 0;
|
||||
};
|
||||
|
||||
/** Where the portal listens for plain HTTP (next to its HTTPS port). */
|
||||
export function portal_http_port(m) {
|
||||
return m.settings.portal_port + 1;
|
||||
};
|
||||
|
||||
/** The port in plain-HTTP links: 80 when standard ports are on and free. */
|
||||
export function portal_http_public(m) {
|
||||
return m.settings.portal_443 && !wan_port_taken(80) ? 80 : portal_http_port(m);
|
||||
};
|
||||
|
||||
/** The port in personal links: 443 when the portal also answers there. */
|
||||
export function portal_public_port(m) {
|
||||
let s = m.settings;
|
||||
if (s.portal_port == 443 || !s.portal_443 || wan443_taken())
|
||||
return s.portal_port;
|
||||
return 443;
|
||||
};
|
||||
|
||||
/** The link on one address: https for names, plain http for IP addresses. */
|
||||
export function portal_link(m, p, host) {
|
||||
if (!host || !m.servers[p.server] || !match(p.code ?? '', WORD_CODE))
|
||||
return null;
|
||||
if (ip2int(host) != null) {
|
||||
let hp = portal_http_public(m);
|
||||
return `http://${host}${hp == 80 ? '' : `:${hp}`}/${p.code}`;
|
||||
}
|
||||
let pp = portal_public_port(m);
|
||||
return `https://${host}${pp == 443 ? '' : `:${pp}`}/${p.code}`;
|
||||
};
|
||||
|
||||
/** The main link (QR, invite card, Copy link). */
|
||||
export function portal_url(m, p) {
|
||||
return portal_link(m, p, portal_hosts(m)[0]);
|
||||
};
|
||||
|
||||
/** Every link to the same portal, the main one first. */
|
||||
export function portal_urls(m, p) {
|
||||
return filter(map(portal_hosts(m), (h) => portal_link(m, p, h)), (x) => x != null);
|
||||
};
|
||||
@@ -0,0 +1,135 @@
|
||||
// Dawnline — city-level locations for the admin map.
|
||||
//
|
||||
// Client addresses are looked up once with a third-party service (ipwho.is,
|
||||
// ipapi.co as fallback) and cached in DATA_DIR/geo.json. Only the agent
|
||||
// performs lookups, a few per minute at most; the UI reads the cache.
|
||||
|
||||
import { read_json, write_json, sh_out, q, ensure_dir, ip2int, DATA_DIR } from 'dawnline.util';
|
||||
|
||||
const CACHE = `${DATA_DIR}/geo.json`;
|
||||
const TTL = 30 * 86400;
|
||||
const RETRY = 86400;
|
||||
|
||||
// [base, prefix] of ranges with no meaningful location (private, CGNAT, multicast, …).
|
||||
const PRIVATE4 = map([ [ '0.0.0.0', 8 ], [ '10.0.0.0', 8 ], [ '100.64.0.0', 10 ], [ '127.0.0.0', 8 ], [ '169.254.0.0', 16 ],
|
||||
[ '172.16.0.0', 12 ], [ '192.168.0.0', 16 ], [ '198.18.0.0', 15 ], [ '224.0.0.0', 3 ] ], (r) => [ ip2int(r[0]), 1 << (32 - r[1]) ]);
|
||||
|
||||
/** True for addresses a geolocation service can say something about. */
|
||||
export function is_public(ip) {
|
||||
if (type(ip) != 'string' || ip == '')
|
||||
return false;
|
||||
let n = ip2int(ip);
|
||||
if (n != null) {
|
||||
for (let r in PRIVATE4)
|
||||
if (n >= r[0] && n < r[0] + r[1])
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
let l = lc(ip);
|
||||
return match(l, /^[0-9a-f:]+$/) != null && !match(l, /^(fe[89ab]|f[cd]|::1$|::$)/);
|
||||
};
|
||||
|
||||
export function load() {
|
||||
return read_json(CACHE, null) ?? { ips: {}, home: null };
|
||||
};
|
||||
|
||||
export function save(cache) {
|
||||
ensure_dir(DATA_DIR, 0o700);
|
||||
write_json(CACHE, cache, 0o600);
|
||||
};
|
||||
|
||||
function fetch_json(url) {
|
||||
let out = sh_out(`uclient-fetch -q -T 8 -O - ${q(url)}`);
|
||||
if (!out)
|
||||
return null;
|
||||
try {
|
||||
return json(out);
|
||||
}
|
||||
catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function lookup_ipwho(ip) {
|
||||
let j = fetch_json(`https://ipwho.is/${ip}?fields=success,ip,latitude,longitude,city,country,country_code,connection`);
|
||||
if (!j || j.success !== true || j.latitude == null)
|
||||
return null;
|
||||
let cn = j.connection ?? {};
|
||||
return { lat: +j.latitude, lon: +j.longitude, city: j.city ?? '', country: j.country ?? '', cc: j.country_code ?? '', ip: j.ip,
|
||||
asn: cn.asn ? +cn.asn : 0, org: cn.isp || cn.org || '' };
|
||||
}
|
||||
|
||||
function lookup_ipapi(ip) {
|
||||
let j = fetch_json(ip ? `https://ipapi.co/${ip}/json/` : 'https://ipapi.co/json/');
|
||||
if (!j || j.error || j.latitude == null)
|
||||
return null;
|
||||
return { lat: +j.latitude, lon: +j.longitude, city: j.city ?? '', country: j.country_name ?? '', cc: j.country_code ?? '', ip: j.ip,
|
||||
asn: +replace(`${j.asn ?? ''}`, /^AS/i, '') || 0, org: j.org ?? '' };
|
||||
}
|
||||
|
||||
/** One lookup with the configured provider and the other as fallback. */
|
||||
export function lookup(provider, ip) {
|
||||
let order = provider == 'ipapi.co' ? [ lookup_ipapi, lookup_ipwho ] : [ lookup_ipwho, lookup_ipapi ];
|
||||
for (let fn in order) {
|
||||
let r = fn(ip ?? '');
|
||||
if (r)
|
||||
return r;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Resolve up to `max` addresses that are missing or stale. Returns true when
|
||||
* the cache changed (the caller saves it).
|
||||
*/
|
||||
export function resolve(settings, cache, ips, max) {
|
||||
let now = time(), changed = false, done = 0;
|
||||
for (let ip in ips) {
|
||||
if (done >= max)
|
||||
break;
|
||||
if (!is_public(ip))
|
||||
continue;
|
||||
let c = cache.ips[ip];
|
||||
if (c && ((c.fail && now - c.fail < RETRY) || (!c.fail && c.asn != null && now - c.ts < TTL)))
|
||||
continue;
|
||||
let r = lookup(settings.geo_provider, ip);
|
||||
done++;
|
||||
changed = true;
|
||||
if (r) {
|
||||
delete r.ip;
|
||||
r.ts = now;
|
||||
cache.ips[ip] = r;
|
||||
}
|
||||
else
|
||||
cache.ips[ip] = { fail: now };
|
||||
}
|
||||
// Keep the cache bounded: drop the oldest entries beyond 500.
|
||||
let all = keys(cache.ips);
|
||||
if (length(all) > 500) {
|
||||
all = sort(all, (a, b) => (cache.ips[a].ts ?? cache.ips[a].fail ?? 0) - (cache.ips[b].ts ?? cache.ips[b].fail ?? 0));
|
||||
for (let i = 0; i < length(all) - 500; i++)
|
||||
delete cache.ips[all[i]];
|
||||
}
|
||||
return changed;
|
||||
};
|
||||
|
||||
/** Locate the router itself (the arcs' origin), at most every 6 hours. */
|
||||
export function resolve_home(settings, cache, wan_ip) {
|
||||
let h = cache.home;
|
||||
let now = time();
|
||||
if (h && h.asn != null && now - (h.ts ?? 0) < 6 * 3600 && (!wan_ip || !is_public(wan_ip) || h.wan == wan_ip))
|
||||
return false;
|
||||
// Behind NAT, ask the service for our public address instead.
|
||||
let r = lookup(settings.geo_provider, is_public(wan_ip) ? wan_ip : '');
|
||||
cache.home = r ? { ...r, wan: wan_ip, ts: now } : { ...(h ?? {}), ts: now };
|
||||
return true;
|
||||
};
|
||||
|
||||
export function place(cache, ip) {
|
||||
let c = cache.ips[ip];
|
||||
return (c && !c.fail) ? c : null;
|
||||
};
|
||||
|
||||
export function clear() {
|
||||
save({ ips: {}, home: null });
|
||||
};
|
||||
@@ -0,0 +1,408 @@
|
||||
// Dawnline — live data: peer status from `awg show all dump`, traffic
|
||||
// accounting and the connection/event log.
|
||||
//
|
||||
// Counters live in RUN_DIR (tmpfs) and are flushed to DATA_DIR at most once
|
||||
// an hour, so flash is not worn by the 60-second agent loop.
|
||||
|
||||
import { readfile, stat, unlink } from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import {
|
||||
q, sh, sh_out, sh_bg, ensure_dir, read_json, write_json, lock, unlock, month_key, day_key, uniq,
|
||||
RUN_DIR, DATA_DIR
|
||||
} from 'dawnline.util';
|
||||
|
||||
export const ONLINE_WINDOW = 300;
|
||||
const KEEP_DAYS = 62;
|
||||
const KEEP_MONTHS = 24;
|
||||
const KEEP_EVENTS = 2000;
|
||||
|
||||
/* ---------- retention policy ---------- */
|
||||
|
||||
/** Event type → log category (what Settings lets you switch off or clear). */
|
||||
export const CATEGORY = {
|
||||
connect: 'connections', disconnect: 'connections', roam: 'connections',
|
||||
device_added: 'devices', device_removed: 'devices', devices_removed: 'devices',
|
||||
person_added: 'people', person_removed: 'people', person_changed: 'people',
|
||||
paused: 'people', resumed: 'people', paused_all: 'people', resumed_all: 'people',
|
||||
server_down: 'problems', server_up: 'problems', portal_blocked: 'problems',
|
||||
};
|
||||
export const CATEGORIES = [ 'connections', 'devices', 'people', 'problems' ];
|
||||
|
||||
export function category_of(type) {
|
||||
return CATEGORY[type] ?? 'problems';
|
||||
};
|
||||
|
||||
function int_or(v, d) {
|
||||
return (v == null || v == '' || match(`${v}`, /[^0-9]/)) ? d : +v;
|
||||
}
|
||||
|
||||
/**
|
||||
* Log and history retention from /etc/config/dawnline (read fresh, the
|
||||
* portal and rpcd call add_event without a loaded model).
|
||||
* log_keep_days days of activity to keep, 0 = until log_max
|
||||
* log_max newest N events kept
|
||||
* log_category categories that are recorded
|
||||
* log_persist how often the log is saved to flash: 10min | hourly | off
|
||||
* usage_keep_days / usage_keep_months daily / monthly traffic buckets
|
||||
*/
|
||||
export function policy(s) {
|
||||
if (s == null) {
|
||||
let c = cursor();
|
||||
s = c.get_all('dawnline', 'settings') ?? {};
|
||||
}
|
||||
let cats = s.log_category;
|
||||
if (cats == null)
|
||||
cats = (s.log_connections == '0') ? filter(CATEGORIES, (x) => x != 'connections') : CATEGORIES;
|
||||
else if (type(cats) != 'array')
|
||||
cats = split(cats, /[ ,]+/);
|
||||
cats = filter(cats, (x) => index(CATEGORIES, x) >= 0);
|
||||
return {
|
||||
keep_days: int_or(s.log_keep_days, 30),
|
||||
max: min(max(int_or(s.log_max, KEEP_EVENTS), 100), 20000),
|
||||
categories: cats,
|
||||
persist: index([ '10min', 'hourly', 'off' ], s.log_persist) >= 0 ? s.log_persist : 'hourly',
|
||||
usage_days: min(max(int_or(s.usage_keep_days, KEEP_DAYS), 7), 1830),
|
||||
usage_months: min(max(int_or(s.usage_keep_months, KEEP_MONTHS), 1), 120),
|
||||
};
|
||||
};
|
||||
|
||||
/** Drop events older than keep_days and beyond max. */
|
||||
function trim_events(ev, pol) {
|
||||
if (pol.keep_days > 0) {
|
||||
let cut = time() - pol.keep_days * 86400;
|
||||
ev = filter(ev, (e) => (e.ts ?? 0) >= cut);
|
||||
}
|
||||
if (length(ev) > pol.max)
|
||||
ev = slice(ev, length(ev) - pol.max);
|
||||
return ev;
|
||||
}
|
||||
|
||||
/* ---------- awg dump ---------- */
|
||||
|
||||
/**
|
||||
* Parse `awg show all dump`. Returns { ifaces: { ifname: {...} }, peers: { pubkey: {...} } }.
|
||||
* Interface lines have many fields (AmneziaWG adds obfuscation values); peer
|
||||
* lines always have 9.
|
||||
*/
|
||||
export function dump() {
|
||||
let r = sh('awg show all dump');
|
||||
let out = { ifaces: {}, peers: {} };
|
||||
if (r.code != 0)
|
||||
return out;
|
||||
for (let line in split(r.out, '\n')) {
|
||||
let f = split(line, '\t');
|
||||
if (length(f) == 9) {
|
||||
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],
|
||||
};
|
||||
}
|
||||
else if (length(f) >= 5) {
|
||||
out.ifaces[f[0]] = { public_key: f[2], port: +f[3] };
|
||||
}
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
export function endpoint_ip(ep) {
|
||||
let m = match(ep ?? '', /^\[?([^\]]+?)\]?:[0-9]+$/);
|
||||
return m ? m[1] : ep;
|
||||
};
|
||||
|
||||
/* ---------- usage ---------- */
|
||||
|
||||
function empty_usage() {
|
||||
return { devices: {}, people: {}, updated: 0, flushed: 0 };
|
||||
}
|
||||
|
||||
export function load_usage() {
|
||||
return read_json(`${RUN_DIR}/usage.json`, null) ?? read_json(`${DATA_DIR}/usage.json`, null) ?? empty_usage();
|
||||
};
|
||||
|
||||
function add(bucket, key, rx, tx) {
|
||||
let v = bucket[key] ?? [ 0, 0 ];
|
||||
bucket[key] = [ v[0] + rx, v[1] + tx ];
|
||||
}
|
||||
|
||||
function prune(obj, keep) {
|
||||
let ks = sort(keys(obj));
|
||||
for (let i = 0; i < length(ks) - keep; i++)
|
||||
delete obj[ks[i]];
|
||||
}
|
||||
|
||||
function account(rec, rx, tx, ts) {
|
||||
rec.total = [ (rec.total?.[0] ?? 0) + rx, (rec.total?.[1] ?? 0) + tx ];
|
||||
rec.months ??= {};
|
||||
rec.days ??= {};
|
||||
add(rec.months, month_key(ts), rx, tx);
|
||||
add(rec.days, day_key(ts), rx, tx);
|
||||
}
|
||||
|
||||
/** Apply the traffic history retention to every record. */
|
||||
export function prune_usage(usage, pol) {
|
||||
pol ??= policy();
|
||||
for (let grp in [ usage.devices, usage.people ])
|
||||
for (let id, rec in grp) {
|
||||
if (rec.months)
|
||||
prune(rec.months, pol.usage_months);
|
||||
if (rec.days)
|
||||
prune(rec.days, pol.usage_days);
|
||||
}
|
||||
};
|
||||
|
||||
/** Forget a record's traffic history; kernel counters (raw) and the last handshake stay. */
|
||||
function wipe(rec) {
|
||||
if (!rec)
|
||||
return;
|
||||
delete rec.total;
|
||||
delete rec.months;
|
||||
delete rec.days;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset traffic history. scope: all | person | device. A person reset also
|
||||
* clears their devices and restarts their data limit; a device reset leaves
|
||||
* the person's totals (and so their limit) alone.
|
||||
*/
|
||||
export function reset_usage(usage, m, scope, id) {
|
||||
if (scope == 'all') {
|
||||
for (let k, rec in usage.devices)
|
||||
wipe(rec);
|
||||
for (let k, rec in usage.people)
|
||||
wipe(rec);
|
||||
}
|
||||
else if (scope == 'person') {
|
||||
wipe(usage.people[id]);
|
||||
for (let did in m.people[id]?.devices ?? [])
|
||||
wipe(usage.devices[did]);
|
||||
}
|
||||
else if (scope == 'device') {
|
||||
wipe(usage.devices[id]);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export function collect(m, usage, d) {
|
||||
d ??= dump();
|
||||
let ts = time();
|
||||
let live = {};
|
||||
let by_key = {};
|
||||
for (let id, dev in m.devices)
|
||||
by_key[dev.public_key] = id;
|
||||
|
||||
for (let id, dev in m.devices) {
|
||||
let rec = usage.devices[id] ??= { raw: [ 0, 0 ] };
|
||||
let peer = d.peers[dev.public_key];
|
||||
if (!peer) {
|
||||
rec.raw = [ 0, 0 ];
|
||||
live[id] = { online: false, handshake: rec.handshake ?? 0, endpoint: rec.endpoint ?? '', present: false };
|
||||
continue;
|
||||
}
|
||||
let raw = rec.raw ?? [ 0, 0 ];
|
||||
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 ];
|
||||
if (drx > 0 || dtx > 0) {
|
||||
account(rec, drx, dtx, ts);
|
||||
let p = usage.people[dev.person] ??= {};
|
||||
account(p, drx, dtx, ts);
|
||||
}
|
||||
if (peer.handshake > 0) {
|
||||
rec.handshake = peer.handshake;
|
||||
rec.endpoint = endpoint_ip(peer.endpoint);
|
||||
// Recent client addresses (for the map): ip → last seen, newest 8.
|
||||
rec.ips ??= {};
|
||||
if (rec.endpoint)
|
||||
rec.ips[rec.endpoint] = peer.handshake;
|
||||
let ips = sort(keys(rec.ips), (x, y) => rec.ips[y] - rec.ips[x]);
|
||||
for (let i = 8; i < length(ips); i++)
|
||||
delete rec.ips[ips[i]];
|
||||
}
|
||||
live[id] = {
|
||||
online: peer.handshake > 0 && ts - peer.handshake < ONLINE_WINDOW,
|
||||
handshake: peer.handshake || rec.handshake || 0,
|
||||
endpoint: endpoint_ip(peer.endpoint) || rec.endpoint || '',
|
||||
present: true,
|
||||
};
|
||||
}
|
||||
|
||||
// Forget counters of devices that no longer exist (their bytes stay in
|
||||
// the person's totals).
|
||||
for (let id in keys(usage.devices))
|
||||
if (!m.devices[id])
|
||||
delete usage.devices[id];
|
||||
|
||||
prune_usage(usage, policy(m.settings.retention));
|
||||
usage.updated = ts;
|
||||
return live;
|
||||
};
|
||||
|
||||
export function save_usage(usage, persist) {
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(`${RUN_DIR}/usage.json`, usage, 0o600);
|
||||
if (persist) {
|
||||
usage.flushed = time();
|
||||
ensure_dir(DATA_DIR, 0o700);
|
||||
write_json(`${DATA_DIR}/usage.json`, usage, 0o600);
|
||||
}
|
||||
};
|
||||
|
||||
/** Sum of [rx, tx] over the last `days` days for a usage record. */
|
||||
export function recent(rec, days) {
|
||||
let out = [ 0, 0 ];
|
||||
let ts = time();
|
||||
for (let i = 0; i < days; i++) {
|
||||
let v = rec?.days?.[day_key(ts - i * 86400)];
|
||||
if (v) {
|
||||
out[0] += v[0];
|
||||
out[1] += v[1];
|
||||
}
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
export function month(rec) {
|
||||
return rec?.months?.[month_key()] ?? [ 0, 0 ];
|
||||
};
|
||||
|
||||
/** Daily series for the last `days` days: [{ day, rx, tx }]. */
|
||||
export function series(recs, days) {
|
||||
let out = [];
|
||||
let ts = time();
|
||||
for (let i = days - 1; i >= 0; i--) {
|
||||
let k = day_key(ts - i * 86400);
|
||||
let rx = 0, tx = 0;
|
||||
for (let r in recs) {
|
||||
let v = r?.days?.[k];
|
||||
if (v) {
|
||||
rx += v[0];
|
||||
tx += v[1];
|
||||
}
|
||||
}
|
||||
push(out, { day: k, rx, tx });
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
/* ---------- events ---------- */
|
||||
|
||||
export function load_events() {
|
||||
return read_json(`${RUN_DIR}/events.json`, null) ?? read_json(`${DATA_DIR}/events.json`, []);
|
||||
};
|
||||
|
||||
export function add_events(list, pol) {
|
||||
pol ??= policy();
|
||||
list = filter(list ?? [], (e) => index(pol.categories, category_of(e.type)) >= 0);
|
||||
if (!length(list))
|
||||
return;
|
||||
let l = lock('events');
|
||||
let ev = load_events();
|
||||
let ts = time();
|
||||
for (let e in list) {
|
||||
e.ts ??= ts;
|
||||
push(ev, e);
|
||||
}
|
||||
ev = trim_events(ev, pol);
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(`${RUN_DIR}/events.json`, ev, 0o600);
|
||||
unlock(l);
|
||||
};
|
||||
|
||||
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. */
|
||||
export function add_event_merged(e, window) {
|
||||
let pol = policy();
|
||||
if (index(pol.categories, category_of(e.type)) < 0)
|
||||
return;
|
||||
let l = lock('events');
|
||||
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)) {
|
||||
let parts = uniq([ ...split(last.detail ?? '', ', '), ...split(e.detail ?? '', ', ') ]);
|
||||
last.detail = join(', ', filter(parts, (x) => x != ''));
|
||||
last.ts = ts;
|
||||
}
|
||||
else {
|
||||
e.ts = ts;
|
||||
push(ev, e);
|
||||
}
|
||||
ev = trim_events(ev, pol);
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(`${RUN_DIR}/events.json`, ev, 0o600);
|
||||
unlock(l);
|
||||
};
|
||||
|
||||
/** Save the log to flash, or drop the flash copy when it is kept in RAM only. */
|
||||
export function persist_events(pol) {
|
||||
pol ??= policy();
|
||||
if (pol.persist == 'off') {
|
||||
if (stat(`${DATA_DIR}/events.json`))
|
||||
unlink(`${DATA_DIR}/events.json`);
|
||||
return;
|
||||
}
|
||||
let ev = read_json(`${RUN_DIR}/events.json`, null);
|
||||
if (ev != null) {
|
||||
ensure_dir(DATA_DIR, 0o700);
|
||||
write_json(`${DATA_DIR}/events.json`, trim_events(ev, pol), 0o600);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Remove events matching every given filter (person, device, category,
|
||||
* older than `before` ts); no filters clears the whole log. Edits both the
|
||||
* live copy and the one on flash. Returns how many were removed.
|
||||
*/
|
||||
export function clear_events(f) {
|
||||
f ??= {};
|
||||
let hit = (e) =>
|
||||
(!f.person || e.person == f.person) &&
|
||||
(!f.device || e.device == f.device) &&
|
||||
(!f.category || category_of(e.type) == f.category) &&
|
||||
(!f.before || (e.ts ?? 0) < f.before);
|
||||
let l = lock('events');
|
||||
let removed = 0;
|
||||
for (let path in [ `${RUN_DIR}/events.json`, `${DATA_DIR}/events.json` ]) {
|
||||
let ev = read_json(path, null);
|
||||
if (ev == null)
|
||||
continue;
|
||||
let keep = filter(ev, (e) => !hit(e));
|
||||
if (path == `${RUN_DIR}/events.json` || removed == 0)
|
||||
removed = max(removed, length(ev) - length(keep));
|
||||
write_json(path, keep, 0o600);
|
||||
}
|
||||
unlock(l);
|
||||
return removed;
|
||||
};
|
||||
|
||||
/* ---------- health ---------- */
|
||||
|
||||
export function iface_status(ifname) {
|
||||
if (!match(ifname ?? '', /^[A-Za-z0-9_.@-]{1,32}$/))
|
||||
return null;
|
||||
let s = sh_out(`ubus call network.interface.${ifname} status 2>/dev/null`);
|
||||
if (!s)
|
||||
return null;
|
||||
try {
|
||||
return json(s);
|
||||
}
|
||||
catch (e) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
export function uptime() {
|
||||
let s = readfile('/proc/uptime');
|
||||
return s ? int(+split(s, ' ')[0]) : 0;
|
||||
};
|
||||
@@ -0,0 +1,555 @@
|
||||
// Dawnline — "like a home device": tunnel clients' internet traffic enters
|
||||
// the router from the LAN, so whatever handles LAN traffic there (proxies,
|
||||
// DPI bypass, DNS filters, fw4's lan zone, ...) handles it too, without
|
||||
// Dawnline knowing about any of them.
|
||||
//
|
||||
// dawn0 ──policy route──▶ dlx0 ═veth═ dlx1 ┐ netns "dawnline" ┌ dll1 ═veth═ dll0 ── br-lan
|
||||
// └── NAT to a LAN address ┘
|
||||
//
|
||||
// The netns is one more device on the LAN bridge with its own address (picked
|
||||
// from the LAN subnet above the DHCP pool). Replies come back the same way.
|
||||
// Home-network destinations keep their direct route; per-person access is
|
||||
// still enforced on dawn0 before any of this (table inet dawnline).
|
||||
//
|
||||
// Clients also use the netns address as DNS: it forwards to the DNS the LAN
|
||||
// gets from DHCP, from the LAN side, so DNS interception applies as well.
|
||||
//
|
||||
// Separately, people with Home-only access get a plain resolver (real
|
||||
// addresses from the WAN's DNS, home names from the LAN DNS): their internet
|
||||
// does not use the tunnel, so fake-IP answers would break it. While the netns
|
||||
// exists the resolver runs inside it and sends its upstream queries back out
|
||||
// through the transit link as forwarded traffic — not as the router's own
|
||||
// traffic and not from the LAN — so tools that capture either leave it alone.
|
||||
//
|
||||
// Everything is derived from the router at run time; nothing assumes a
|
||||
// particular subnet or tool. If the LAN is not a bridge or setup fails, the
|
||||
// direct path stays and status() says why.
|
||||
|
||||
import { readfile, writefile, readlink, stat, unlink } from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import { sh, sh_out, q, ip2int, int2ip, ensure_dir, read_json, write_json, uniq, RUN_DIR } from 'dawnline.util';
|
||||
import * as net from 'dawnline.net';
|
||||
|
||||
export const NS = 'dawnline';
|
||||
const TX_ROOT = net.INTERNAL.transit, TX_NS = 'dlx1', LAN_ROOT = net.INTERNAL.lan, LAN_NS = 'dll1';
|
||||
const PREF_LOOP_DNS = 5205, PREF_MAIN = 5210, PREF_LOOP = 5290;
|
||||
const RESOLVER_PORT = 5354;
|
||||
export const RESOLVER_CONF = '/var/etc/dawnline-dns.conf';
|
||||
const RESOLVER_RESOLV = '/var/etc/dawnline-dns.resolv';
|
||||
const RESOLVER_PID = '/var/run/dawnline-dns.pid';
|
||||
const STATE = `${RUN_DIR}/loop.json`;
|
||||
const FALLBACK_DNS = [ '1.1.1.1', '8.8.8.8' ];
|
||||
|
||||
function log(msg) {
|
||||
system(`logger -t dawnline ${q(msg)}`);
|
||||
}
|
||||
|
||||
function run(cmds) {
|
||||
let errs = [];
|
||||
for (let c in cmds) {
|
||||
let r = sh(c);
|
||||
if (r.code != 0)
|
||||
push(errs, `${c}: ${trim(r.out)}`);
|
||||
}
|
||||
return errs;
|
||||
}
|
||||
|
||||
function exists(dev) {
|
||||
return stat(`/sys/class/net/${dev}`) != null;
|
||||
}
|
||||
|
||||
function cidr_of(a) {
|
||||
let m = match(a ?? '', /^([0-9.]+)\/([0-9]+)$/);
|
||||
if (!m)
|
||||
return null;
|
||||
let ip = ip2int(m[1]), prefix = +m[2];
|
||||
if (ip == null || prefix < 8 || prefix > 30)
|
||||
return null;
|
||||
let size = 1 << (32 - prefix);
|
||||
return { ip, prefix, size, net: ip - ip % size };
|
||||
}
|
||||
|
||||
/* ---------- facts about the LAN ---------- */
|
||||
|
||||
/** DHCP pool, static leases and the DNS handed to LAN clients, for one netifd interface. */
|
||||
function dhcp_facts(logical, lan) {
|
||||
let c = cursor();
|
||||
c.load('dhcp');
|
||||
let pool = null, dns = null, statics = [];
|
||||
c.foreach('dhcp', 'dhcp', (s) => {
|
||||
if (s.interface != logical || s.ignore == '1')
|
||||
return;
|
||||
let start = +(s.start ?? 100), limit = +(s.limit ?? 150);
|
||||
pool = [ lan.net + start, lan.net + start + limit - 1 ];
|
||||
let opts = type(s.dhcp_option) == 'array' ? s.dhcp_option : (s.dhcp_option ? [ s.dhcp_option ] : []);
|
||||
for (let o in opts) {
|
||||
let m = match(o, /^(option:dns-server|6),([0-9.]+)/);
|
||||
if (m && !dns)
|
||||
dns = m[2];
|
||||
}
|
||||
});
|
||||
c.foreach('dhcp', 'host', (s) => {
|
||||
let ip = ip2int(s.ip ?? '');
|
||||
if (ip != null)
|
||||
push(statics, ip);
|
||||
});
|
||||
return { pool, dns, statics };
|
||||
}
|
||||
|
||||
/** Addresses other devices are using right now (neighbour table + leases). */
|
||||
function used_addresses(dev) {
|
||||
let used = {};
|
||||
try {
|
||||
for (let n in json(sh_out(`ip -j -4 neigh show dev ${q(dev)}`) || '[]') ?? [])
|
||||
if (n.dst && !(index(n.state ?? [], 'FAILED') >= 0 || index(n.state ?? [], 'INCOMPLETE') >= 0))
|
||||
used[n.dst] = n.lladdr ?? true;
|
||||
}
|
||||
catch (e) {}
|
||||
for (let l in split(readfile('/tmp/dhcp.leases') ?? '', '\n')) {
|
||||
let f = split(l, ' ');
|
||||
if (length(f) >= 3)
|
||||
used[f[2]] = f[1];
|
||||
}
|
||||
return used;
|
||||
}
|
||||
|
||||
function our_mac() {
|
||||
return sh_out(`ip -n ${NS} -j link show ${LAN_NS} 2>/dev/null | jsonfilter -e '@[0].address'`);
|
||||
}
|
||||
|
||||
/**
|
||||
* A LAN address for the netns: keep the saved one while it is valid and not
|
||||
* taken by someone else, otherwise the highest free host above the DHCP pool
|
||||
* (then below it), skipping static leases and anything that answers.
|
||||
*/
|
||||
function pick_address(lan, facts, saved, dev) {
|
||||
let used = used_addresses(dev);
|
||||
let mine = our_mac();
|
||||
let taken = (ip) => {
|
||||
let s = int2ip(ip);
|
||||
if (ip == lan.ip || index(facts.statics, ip) >= 0)
|
||||
return true;
|
||||
if (facts.pool && ip >= facts.pool[0] && ip <= facts.pool[1])
|
||||
return true;
|
||||
let u = used[s];
|
||||
return u != null && !(mine && u == mine);
|
||||
};
|
||||
let sv = ip2int(saved ?? '');
|
||||
if (sv != null && sv > lan.net && sv < lan.net + lan.size - 1 && !taken(sv))
|
||||
return int2ip(sv);
|
||||
for (let ip = lan.net + lan.size - 2; ip > lan.net; ip--) {
|
||||
if (taken(ip))
|
||||
continue;
|
||||
// Last check: nobody answers on it.
|
||||
sh(`ping -c 1 -W 1 -I ${q(dev)} ${int2ip(ip)}`);
|
||||
let again = used_addresses(dev)[int2ip(ip)];
|
||||
if (again != null && !(mine && again == mine))
|
||||
continue;
|
||||
return int2ip(ip);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** A /30 in 169.254.0.0/16 that no route or address on the router overlaps. */
|
||||
function pick_transit(saved) {
|
||||
let busy = [];
|
||||
for (let dev, d in net.snapshot().devices)
|
||||
for (let n in [ ...d.nets, ...d.addrs ])
|
||||
push(busy, n);
|
||||
let free = (base) => {
|
||||
for (let b in busy) {
|
||||
let c = match(b, /^([0-9.]+)(\/([0-9]+))?$/);
|
||||
if (!c)
|
||||
continue;
|
||||
let ip = ip2int(c[1]), size = 1 << (32 - (c[3] != null ? +c[3] : 32));
|
||||
let bn = ip - ip % size;
|
||||
if (base < bn + size && bn < base + 4)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
let sv = ip2int(saved ?? '');
|
||||
if (sv != null && free(sv))
|
||||
return sv;
|
||||
for (let k = 77; k < 77 + 256; k++) {
|
||||
let base = ip2int(`169.254.${k % 256}.0`);
|
||||
if (free(base))
|
||||
return base;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** A routing table nobody else uses (ours holds a single route via the transit link). */
|
||||
function pick_table(saved) {
|
||||
let free = (t) => {
|
||||
let r = sh_out(`ip -4 route show table ${t}`) ?? '';
|
||||
return r == '' || (length(split(r, '\n')) == 1 && index(r, ` dev ${TX_ROOT}`) >= 0);
|
||||
};
|
||||
if (saved && free(saved))
|
||||
return saved;
|
||||
for (let t = 2077; t < 2177; t++)
|
||||
if (free(t))
|
||||
return t;
|
||||
return null;
|
||||
}
|
||||
|
||||
/* ---------- plan ---------- */
|
||||
|
||||
function settings() {
|
||||
let c = cursor();
|
||||
c.load('dawnline');
|
||||
return c.get_all('dawnline', 'settings') ?? {};
|
||||
}
|
||||
|
||||
/** Servers that want "like a home device" (default on). */
|
||||
function wanted(m) {
|
||||
return filter(values(m.servers), (s) => s.private_key && s.enabled && s.lan_like);
|
||||
}
|
||||
|
||||
/**
|
||||
* What should exist, or { error } when it cannot. Pure apart from reading
|
||||
* router state (and one ping per candidate address).
|
||||
*/
|
||||
export function plan(m) {
|
||||
let srvs = wanted(m);
|
||||
if (!length(srvs))
|
||||
return { off: true };
|
||||
let snap = net.snapshot();
|
||||
let dev = snap.lan;
|
||||
let d = snap.devices[dev];
|
||||
if (!dev || !d)
|
||||
return { error: 'No LAN detected.' };
|
||||
if (d.kind != 'bridge')
|
||||
return { error: `${dev} is not a bridge, so Dawnline cannot join the LAN as a device.` };
|
||||
let lan = cidr_of(d.addrs[0]);
|
||||
if (!lan)
|
||||
return { error: `${dev} has no IPv4 address.` };
|
||||
let facts = dhcp_facts(d.logical, lan);
|
||||
let st = settings();
|
||||
let addr = pick_address(lan, facts, st.lan_address, dev);
|
||||
if (!addr)
|
||||
return { error: `No free address on ${int2ip(lan.net)}/${lan.prefix}.` };
|
||||
let last = read_json(STATE, {});
|
||||
let tx = pick_transit(last?.transit);
|
||||
if (tx == null)
|
||||
return { error: 'No free link-local range for the internal link.' };
|
||||
let table = pick_table(last?.plan?.table);
|
||||
if (table == null)
|
||||
return { error: 'No free routing table.' };
|
||||
let servers = [];
|
||||
for (let srv in srvs) {
|
||||
let sn = net.server_net(srv, snap);
|
||||
push(servers, { ifname: srv.ifname, subnet: srv.subnet, direct: net.collapse([ srv.subnet, ...sn.nets ]) });
|
||||
}
|
||||
return {
|
||||
dev,
|
||||
gateway: int2ip(lan.ip),
|
||||
address: addr,
|
||||
prefix: lan.prefix,
|
||||
dns: facts.dns ?? int2ip(lan.ip),
|
||||
transit: tx,
|
||||
tx_root: int2ip(tx + 1),
|
||||
tx_ns: int2ip(tx + 2),
|
||||
table,
|
||||
servers,
|
||||
};
|
||||
};
|
||||
|
||||
/* ---------- apply ---------- */
|
||||
|
||||
function ns_rules(p) {
|
||||
return `table inet dawnline
|
||||
delete table inet dawnline
|
||||
table inet dawnline {
|
||||
chain nat_pre {
|
||||
type nat hook prerouting priority dstnat; policy accept;
|
||||
iifname "${TX_NS}" ip daddr ${p.address} meta l4proto { tcp, udp } th dport 53 dnat ip to ${p.dns}:53
|
||||
}
|
||||
chain nat_post {
|
||||
type nat hook postrouting priority srcnat; policy accept;
|
||||
oifname "${LAN_NS}" masquerade
|
||||
}
|
||||
chain filter_forward {
|
||||
type filter hook forward priority filter; policy drop;
|
||||
ct state established,related accept
|
||||
iifname "${TX_NS}" oifname "${LAN_NS}" accept
|
||||
}
|
||||
chain filter_input {
|
||||
type filter hook input priority filter; policy drop;
|
||||
ct state established,related accept
|
||||
iifname "lo" accept
|
||||
icmp type echo-request accept
|
||||
iifname "${TX_NS}" meta l4proto { tcp, udp } th dport 53 accept
|
||||
}
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
/** Our policy rules: in our priority band and bound to a Dawnline tunnel interface. */
|
||||
function current_rules(ifnames) {
|
||||
let out = [];
|
||||
try {
|
||||
for (let r in json(sh_out('ip -j -4 rule show') || '[]') ?? [])
|
||||
if (r.priority >= 5200 && r.priority < 5300 && r.iif && index(ifnames, r.iif) >= 0)
|
||||
push(out, r);
|
||||
}
|
||||
catch (e) {}
|
||||
return out;
|
||||
}
|
||||
|
||||
|
||||
function rule_key(pref, iif, to, table) {
|
||||
return `${pref} ${iif} ${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}` ]);
|
||||
}
|
||||
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]}`);
|
||||
return cmds;
|
||||
}
|
||||
|
||||
function tunnel_ifnames() {
|
||||
let c = cursor();
|
||||
c.load('dawnline');
|
||||
let out = [];
|
||||
c.foreach('dawnline', 'server', (s) => push(out, s.ifname ?? s['.name']));
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Remove the netns, links and rules. */
|
||||
export function remove(ifnames) {
|
||||
ifnames ??= tunnel_ifnames();
|
||||
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 t = read_json(STATE, {})?.plan?.table;
|
||||
if (t)
|
||||
push(cmds, `ip -4 route flush table ${t}`);
|
||||
if (exists(TX_ROOT))
|
||||
push(cmds, `ip link del ${TX_ROOT}`);
|
||||
if (exists(LAN_ROOT))
|
||||
push(cmds, `ip link del ${LAN_ROOT}`);
|
||||
if (stat(`/var/run/netns/${NS}`))
|
||||
push(cmds, `ip netns del ${NS}`);
|
||||
run(cmds);
|
||||
unlink(STATE);
|
||||
};
|
||||
|
||||
/**
|
||||
* Bring the loop to the plan. Cheap when nothing changed: compares with the
|
||||
* last applied plan and only checks that links, bridge port and rules exist.
|
||||
*/
|
||||
export function ensure(m, force) {
|
||||
let ifnames = map(values(m.servers), (s) => s.ifname);
|
||||
let p = plan(m);
|
||||
if (p.off || p.error) {
|
||||
if (stat(STATE) || exists(TX_ROOT) || exists(LAN_ROOT) || length(current_rules(ifnames)))
|
||||
remove(ifnames);
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(STATE, { error: p.error, off: !!p.off }, 0o644);
|
||||
if (p.error)
|
||||
log(`like-home routing off: ${p.error}`);
|
||||
return p;
|
||||
}
|
||||
let last = read_json(STATE, {});
|
||||
let same = !force && last.applied && sprintf('%J', last.plan) == sprintf('%J', p);
|
||||
let healthy = exists(TX_ROOT) && exists(LAN_ROOT) && stat(`/var/run/netns/${NS}`) &&
|
||||
replace(readlink(`/sys/class/net/${LAN_ROOT}/master`) ?? '', /^.*\//, '') == p.dev;
|
||||
let rules = sync_rules(p, ifnames);
|
||||
if (same && healthy && !length(rules))
|
||||
return p;
|
||||
|
||||
let cmds = [];
|
||||
if (!stat(`/var/run/netns/${NS}`))
|
||||
push(cmds, `ip netns add ${NS}`);
|
||||
if (!exists(TX_ROOT))
|
||||
push(cmds, `ip link add ${TX_ROOT} type veth peer name ${TX_NS} netns ${NS}`);
|
||||
if (!exists(LAN_ROOT))
|
||||
push(cmds, `ip link add ${LAN_ROOT} type veth peer name ${LAN_NS} netns ${NS}`);
|
||||
let errs = run(cmds);
|
||||
cmds = [
|
||||
`ip addr flush dev ${TX_ROOT}`,
|
||||
`ip addr add ${p.tx_root}/30 dev ${TX_ROOT}`,
|
||||
`ip link set ${TX_ROOT} up`,
|
||||
`ip link set ${LAN_ROOT} master ${q(p.dev)}`,
|
||||
`ip link set ${LAN_ROOT} up`,
|
||||
`ip -n ${NS} link set lo up`,
|
||||
`ip -n ${NS} addr flush dev ${TX_NS}`,
|
||||
`ip -n ${NS} addr add ${p.tx_ns}/30 dev ${TX_NS}`,
|
||||
`ip -n ${NS} link set ${TX_NS} up`,
|
||||
`ip -n ${NS} addr flush dev ${LAN_NS}`,
|
||||
`ip -n ${NS} addr add ${p.address}/${p.prefix} dev ${LAN_NS}`,
|
||||
`ip -n ${NS} link set ${LAN_NS} up`,
|
||||
`ip -n ${NS} route replace default via ${p.gateway} dev ${LAN_NS}`,
|
||||
// The resolver's own queries (from the transit address) go back out the transit link.
|
||||
`ip -n ${NS} route replace default via ${p.tx_root} dev ${TX_NS} table 100`,
|
||||
`ip -n ${NS} rule del from ${p.tx_ns} lookup 100 2>/dev/null; ip -n ${NS} rule add from ${p.tx_ns} lookup 100`,
|
||||
`ip netns exec ${NS} sh -c 'echo 1 > /proc/sys/net/ipv4/ip_forward; echo 0 > /proc/sys/net/ipv4/conf/all/rp_filter; echo 0 > /proc/sys/net/ipv4/conf/default/rp_filter'`,
|
||||
`ip -4 route replace default via ${p.tx_ns} dev ${TX_ROOT} table ${p.table}`,
|
||||
];
|
||||
for (let s in p.servers)
|
||||
push(cmds, `ip -n ${NS} route replace ${q(s.subnet)} via ${q(p.tx_root)} dev ${TX_NS}`);
|
||||
ensure_dir('/var/etc');
|
||||
writefile('/var/etc/dawnline-ns.nft', ns_rules(p));
|
||||
push(cmds, `ip netns exec ${NS} nft -f /var/etc/dawnline-ns.nft`);
|
||||
push(errs, ...run(cmds));
|
||||
push(errs, ...run(sync_rules(p, ifnames)));
|
||||
|
||||
if (length(errs)) {
|
||||
log(`like-home routing failed, using the direct path: ${errs[0]}`);
|
||||
remove(ifnames);
|
||||
write_json(STATE, { error: `Setup failed: ${errs[0]}` }, 0o644);
|
||||
return { error: errs[0] };
|
||||
}
|
||||
// Keep the chosen LAN address stable across restarts.
|
||||
let c = cursor();
|
||||
c.load('dawnline');
|
||||
if (c.get('dawnline', 'settings', 'lan_address') != p.address) {
|
||||
c.set('dawnline', 'settings', 'settings');
|
||||
c.set('dawnline', 'settings', 'lan_address', p.address);
|
||||
c.commit('dawnline');
|
||||
system('chmod 600 /etc/config/dawnline');
|
||||
}
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(STATE, { applied: time(), plan: p, transit: p.transit }, 0o644);
|
||||
log(`like-home routing: ${p.dev} as ${p.address}`);
|
||||
return p;
|
||||
};
|
||||
|
||||
/** Last applied state for views and health checks. */
|
||||
export function status() {
|
||||
let s = read_json(STATE, {});
|
||||
if (s.plan)
|
||||
return {
|
||||
active: exists(TX_ROOT) && exists(LAN_ROOT),
|
||||
dev: s.plan.dev, address: s.plan.address, dns: s.plan.dns, gateway: s.plan.gateway, transit: s.plan.tx_ns,
|
||||
bridged: replace(readlink(`/sys/class/net/${LAN_ROOT}/master`) ?? '', /^.*\//, '') == s.plan.dev,
|
||||
};
|
||||
return { active: false, off: !!s.off, error: s.error };
|
||||
};
|
||||
|
||||
/** The DNS address tunnel clients should use while the loop is up. */
|
||||
export function client_dns() {
|
||||
let s = status();
|
||||
return s.active ? s.address : null;
|
||||
};
|
||||
|
||||
/* ---------- plain resolver for Home-only clients ---------- */
|
||||
|
||||
function wan_dns() {
|
||||
let out = [];
|
||||
let snap = net.snapshot();
|
||||
let wan = snap.devices[snap.wan]?.logical;
|
||||
for (let name in uniq([ wan, 'wan', 'wan6' ])) {
|
||||
if (!name)
|
||||
continue;
|
||||
try {
|
||||
let st = json(sh_out(`ubus call network.interface.${name} status 2>/dev/null`) || 'null');
|
||||
for (let a in st?.['dns-server'] ?? [])
|
||||
if (match(a, /^[0-9.]+$/))
|
||||
push(out, a);
|
||||
}
|
||||
catch (e) {}
|
||||
}
|
||||
return length(out) ? uniq(out) : FALLBACK_DNS;
|
||||
}
|
||||
|
||||
/** Local domain of the LAN DNS (dnsmasq `domain`, else the Dawnline hostname domain). */
|
||||
function lan_domain(m) {
|
||||
let c = cursor();
|
||||
c.load('dhcp');
|
||||
let d = null;
|
||||
c.foreach('dhcp', 'dnsmasq', (s) => { d ??= s.domain; });
|
||||
return uniq(filter([ d, m.settings.domain ], (x) => x));
|
||||
}
|
||||
|
||||
/** The DNS your LAN gets from DHCP (option 6), else the router on the LAN. */
|
||||
export function lan_dns() {
|
||||
let st = status();
|
||||
if (st.dns)
|
||||
return st.dns;
|
||||
let snap = net.snapshot();
|
||||
let d = snap.devices[snap.lan];
|
||||
let a = d?.addrs?.[0];
|
||||
return a ? (dhcp_facts(d.logical, cidr_of(a))?.dns ?? split(a, '/')[0]) : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Where Home-only clients' DNS goes: inside the netns while it is up
|
||||
* (`ns`: transit address, port 53), otherwise on the tunnel address (`root`).
|
||||
*/
|
||||
export function resolver_target() {
|
||||
let st = status();
|
||||
return st.active && st.transit ? { mode: 'ns', address: st.transit, port: 53 } : { mode: 'root', port: RESOLVER_PORT };
|
||||
};
|
||||
|
||||
/**
|
||||
* Write the resolver config; returns true when it changed (the running
|
||||
* instance is then restarted by procd's respawn after a kill). The first line
|
||||
* tells /usr/libexec/dawnline/resolver where to run it.
|
||||
*/
|
||||
export function sync_resolver(m) {
|
||||
ensure_dir('/var/etc');
|
||||
let ifs = map(filter(values(m.servers), (s) => s.private_key), (s) => s.ifname);
|
||||
let target = resolver_target();
|
||||
let lan = lan_dns();
|
||||
let lines = [
|
||||
`# mode=${target.mode}`,
|
||||
'# Generated by Dawnline: plain DNS for Home-only tunnel clients.',
|
||||
`port=${target.port}`,
|
||||
'no-hosts',
|
||||
'bogus-priv',
|
||||
'cache-size=1000',
|
||||
`pid-file=${RESOLVER_PID}`,
|
||||
'user=dnsmasq',
|
||||
'group=dnsmasq',
|
||||
];
|
||||
if (target.mode == 'ns') {
|
||||
push(lines, `listen-address=${target.address}`, 'bind-interfaces', 'no-resolv');
|
||||
// Upstream from the transit address: forwarded through the router to the WAN.
|
||||
for (let a in wan_dns())
|
||||
push(lines, `server=${a}@${target.address}`);
|
||||
}
|
||||
else {
|
||||
push(lines, 'bind-dynamic', ...map(ifs, (i) => `interface=${i}`), `resolv-file=${RESOLVER_RESOLV}`);
|
||||
let resolv = join('', map(wan_dns(), (a) => `nameserver ${a}\n`));
|
||||
if ((readfile(RESOLVER_RESOLV) ?? '') != resolv) {
|
||||
writefile(RESOLVER_RESOLV, resolv);
|
||||
system(`chmod 644 ${RESOLVER_RESOLV}`);
|
||||
}
|
||||
}
|
||||
if (lan)
|
||||
for (let d in lan_domain(m))
|
||||
push(lines, `server=/${d}/${lan}`);
|
||||
let conf = join('\n', lines) + '\n';
|
||||
if ((readfile(RESOLVER_CONF) ?? '') == conf)
|
||||
return false;
|
||||
writefile(RESOLVER_CONF, conf);
|
||||
system(`chmod 644 ${RESOLVER_CONF}`);
|
||||
let pid = trim(readfile(RESOLVER_PID) ?? '');
|
||||
if (match(pid, /^[0-9]+$/))
|
||||
system(`kill ${pid} 2>/dev/null`);
|
||||
return true;
|
||||
};
|
||||
|
||||
/** True when the resolver process is alive. */
|
||||
export function resolver_running() {
|
||||
let pid = trim(readfile(RESOLVER_PID) ?? '');
|
||||
return match(pid, /^[0-9]+$/) != null && stat(`/proc/${pid}`) != null;
|
||||
};
|
||||
|
||||
export const RESOLVER = { port: RESOLVER_PORT, conf: RESOLVER_CONF };
|
||||
@@ -0,0 +1,268 @@
|
||||
// Dawnline — the router's network interfaces: what exists, which one is the
|
||||
// WAN, and which ones make up a server's "home network".
|
||||
//
|
||||
// Per server (uci `server` section):
|
||||
// auto_wan 1 = use the interface of the default route (detected_wan
|
||||
// is kept as a fallback while the WAN is down)
|
||||
// wan_device the WAN interface when auto_wan is off
|
||||
// auto_lan 1 = include the detected LAN (detected_lan as fallback)
|
||||
// lan_device extra interfaces that count as the home network (list)
|
||||
//
|
||||
// Home access is enforced by destination: the networks routed out of the
|
||||
// chosen interfaces form the nft `lan_nets` set, and the tunnel's firewall
|
||||
// zone gets a forwarding to each of their zones.
|
||||
|
||||
import { readfile, readlink, lsdir, stat } from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import { sh_out, ip2int, int2ip, uniq } from 'dawnline.util';
|
||||
|
||||
const SYS = '/sys/class/net';
|
||||
/** Links Dawnline creates itself (dawnline.loop); never offered as interfaces. */
|
||||
export const INTERNAL = { transit: 'dlx0', lan: 'dll0' };
|
||||
const VPN_PROTOS = [ 'amneziawg', 'wireguard', 'openvpn', 'openconnect', 'vpnc', 'pptp', 'l2tp', 'gre', 'gretap', 'vti', 'xfrm' ];
|
||||
// Kernel placeholder devices that never carry a network on their own.
|
||||
const NOISE = /^(ifb|teql|sit|ip6tnl|gre|gretap|erspan|ip6gre|ip6gretap|ip_vti|ip6_vti|tunl|bond)[0-9]*$/;
|
||||
const PRIVATE = [ [ '10.0.0.0', 8 ], [ '172.16.0.0', 12 ], [ '192.168.0.0', 16 ], [ '100.64.0.0', 10 ] ];
|
||||
|
||||
function sysread(dev, f) {
|
||||
return trim(readfile(`${SYS}/${dev}/${f}`) ?? '');
|
||||
}
|
||||
|
||||
function ip_json(args) {
|
||||
try {
|
||||
return json(sh_out(`ip -j ${args} 2>/dev/null`) || '[]') ?? [];
|
||||
}
|
||||
catch (e) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function ubus_json(path, method) {
|
||||
try {
|
||||
return json(sh_out(`ubus call ${path} ${method} 2>/dev/null`) || 'null');
|
||||
}
|
||||
catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** "a.b.c.d[/len]" → { net, prefix, size } for any prefix 1-32; null for default or junk. */
|
||||
function net_of(s) {
|
||||
let m = match(s ?? '', /^([0-9.]+)(\/([0-9]+))?$/);
|
||||
if (!m)
|
||||
return null;
|
||||
let ip = ip2int(m[1]), prefix = m[3] != null ? +m[3] : 32;
|
||||
if (ip == null || prefix < 1 || prefix > 32)
|
||||
return null;
|
||||
let size = 1 << (32 - prefix);
|
||||
if (prefix == 1)
|
||||
size = 2147483648;
|
||||
return { net: ip - ip % size, prefix, size };
|
||||
}
|
||||
|
||||
function net_str(n) {
|
||||
return `${int2ip(n.net)}/${n.prefix}`;
|
||||
}
|
||||
|
||||
/** Drop networks already covered by a wider one. */
|
||||
export function collapse(list) {
|
||||
let nets = filter(map(uniq(list), net_of), (x) => x != null);
|
||||
nets = sort(nets, (a, b) => a.prefix - b.prefix || a.net - b.net);
|
||||
let keep = [];
|
||||
for (let n in nets) {
|
||||
let inside = false;
|
||||
for (let k in keep)
|
||||
if (n.net >= k.net && n.net < k.net + k.size) {
|
||||
inside = true;
|
||||
break;
|
||||
}
|
||||
if (!inside)
|
||||
push(keep, n);
|
||||
}
|
||||
return map(sort(keep, (a, b) => a.net - b.net), net_str);
|
||||
};
|
||||
|
||||
function is_private(cidr) {
|
||||
let n = net_of(cidr);
|
||||
if (!n)
|
||||
return false;
|
||||
for (let p in PRIVATE) {
|
||||
let base = ip2int(p[0]), size = 1 << (32 - p[1]);
|
||||
if (n.net >= base && n.net < base + size)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/* ---------- snapshot ---------- */
|
||||
|
||||
let cache = null;
|
||||
|
||||
/**
|
||||
* One consistent view of the router's interfaces, cached for a few seconds
|
||||
* (rpcd keeps this module loaded, so the cache must expire).
|
||||
*/
|
||||
export function snapshot(fresh) {
|
||||
if (!fresh && cache && time() - cache.ts < 5)
|
||||
return cache;
|
||||
|
||||
// Networks reachable through each device (main table, IPv4).
|
||||
let routes = {}, wan_dev = null;
|
||||
for (let r in ip_json('-4 route show table main')) {
|
||||
if (!r.dev)
|
||||
continue;
|
||||
if (r.dst == 'default') {
|
||||
wan_dev ??= r.dev;
|
||||
continue;
|
||||
}
|
||||
push(routes[r.dev] ??= [], r.dst);
|
||||
}
|
||||
let addrs = {};
|
||||
for (let l in ip_json('-4 addr show'))
|
||||
for (let a in l.addr_info ?? [])
|
||||
if (a.family == 'inet')
|
||||
push(addrs[l.ifname] ??= [], `${a.local}/${a.prefixlen}`);
|
||||
|
||||
// Logical (netifd) interfaces by device, and firewall zones by network.
|
||||
let logical = {};
|
||||
for (let i in ubus_json('network.interface', 'dump')?.interface ?? []) {
|
||||
let dev = i.l3_device ?? i.device;
|
||||
if (dev && !logical[dev])
|
||||
logical[dev] = { name: i.interface, proto: i.proto, up: i.up };
|
||||
}
|
||||
let zone_by_net = {}, zone_by_dev = {}, zones = [];
|
||||
let fc = cursor();
|
||||
fc.load('firewall');
|
||||
fc.foreach('firewall', 'zone', (z) => {
|
||||
if (!z.name)
|
||||
return;
|
||||
push(zones, z.name);
|
||||
for (let n in (type(z.network) == 'array' ? z.network : split(z.network ?? '', /\s+/)))
|
||||
if (n != '')
|
||||
zone_by_net[n] ??= z.name;
|
||||
for (let d in (type(z.device) == 'array' ? z.device : split(z.device ?? '', /\s+/)))
|
||||
if (d != '')
|
||||
zone_by_dev[d] ??= z.name;
|
||||
});
|
||||
|
||||
let devices = {};
|
||||
for (let dev in sort(lsdir(SYS) ?? [])) {
|
||||
if (dev == 'lo' || dev == INTERNAL.transit || dev == INTERNAL.lan)
|
||||
continue;
|
||||
let lg = logical[dev];
|
||||
let flags = hex(sysread(dev, 'flags') || '0');
|
||||
let kind = +(sysread(dev, 'type') || '0');
|
||||
let master = readlink(`${SYS}/${dev}/master`);
|
||||
master = master ? replace(master, /^.*\//, '') : null;
|
||||
let bridge = stat(`${SYS}/${dev}/bridge`) != null;
|
||||
let wifi = stat(`${SYS}/${dev}/phy80211`) != null || stat(`${SYS}/${dev}/wireless`) != null;
|
||||
let nets = routes[dev] ? collapse(routes[dev]) : [];
|
||||
let up = (flags & 1) != 0;
|
||||
if (match(dev, NOISE) && !length(nets))
|
||||
continue;
|
||||
let cat;
|
||||
if (wifi)
|
||||
cat = 'wifi';
|
||||
else if ((lg && index(VPN_PROTOS, lg.proto) >= 0) || kind == 65534 || ((flags & 0x10) && kind != 1) || match(dev, /^(wg|awg|tun|tap|ovpn|ipsec|vti|xfrm)/))
|
||||
cat = 'vpn';
|
||||
else if (kind == 1 || bridge)
|
||||
cat = 'ethernet';
|
||||
else
|
||||
cat = 'other';
|
||||
devices[dev] = {
|
||||
name: dev,
|
||||
category: dev == wan_dev ? 'wan' : cat,
|
||||
kind: bridge ? 'bridge' : cat,
|
||||
up,
|
||||
master,
|
||||
members: [],
|
||||
nets,
|
||||
addrs: addrs[dev] ?? [],
|
||||
logical: lg?.name,
|
||||
proto: lg?.proto,
|
||||
zone: zone_by_dev[dev] ?? (lg ? zone_by_net[lg.name] : null),
|
||||
};
|
||||
}
|
||||
for (let dev, d in devices)
|
||||
if (d.master && devices[d.master])
|
||||
push(devices[d.master].members, dev);
|
||||
|
||||
// The LAN: netifd's "lan" if present, otherwise the first bridge (then
|
||||
// ethernet device) carrying a private network.
|
||||
let lan_dev = null;
|
||||
for (let dev, lg in logical)
|
||||
if (lg.name == 'lan' && devices[dev])
|
||||
lan_dev = dev;
|
||||
if (!lan_dev)
|
||||
for (let pass in [ 'bridge', 'ethernet' ])
|
||||
for (let dev, d in devices)
|
||||
if (!lan_dev && dev != wan_dev && d.kind == pass && !d.master && length(filter(d.nets, is_private)))
|
||||
lan_dev = dev;
|
||||
|
||||
cache = { ts: time(), devices, wan: wan_dev, lan: lan_dev, zones };
|
||||
return cache;
|
||||
};
|
||||
|
||||
/* ---------- per server ---------- */
|
||||
|
||||
/**
|
||||
* What a server actually uses right now:
|
||||
* wan: { dev, zone, auto, missing }
|
||||
* home: [{ dev, auto, nets, zone, missing }]
|
||||
* nets: home networks (collapsed), zones: their firewall zones
|
||||
*/
|
||||
export function server_net(srv, snap) {
|
||||
snap ??= snapshot();
|
||||
let devs = snap.devices;
|
||||
|
||||
let wan_dev = srv.auto_wan ? (snap.wan ?? srv.detected_wan) : srv.wan_device;
|
||||
let wan = {
|
||||
dev: wan_dev || null,
|
||||
auto: !!srv.auto_wan,
|
||||
zone: devs[wan_dev]?.zone ?? srv.wan_zone ?? 'wan',
|
||||
missing: !!wan_dev && !devs[wan_dev],
|
||||
};
|
||||
|
||||
let picked = [];
|
||||
let auto_lan = srv.auto_lan ? (snap.lan ?? srv.detected_lan) : null;
|
||||
if (auto_lan)
|
||||
push(picked, [ auto_lan, true ]);
|
||||
for (let d in srv.lan_devices ?? [])
|
||||
if (d != auto_lan)
|
||||
push(picked, [ d, false ]);
|
||||
|
||||
let home = [], nets = [], zones = [];
|
||||
for (let p in picked) {
|
||||
let dev = p[0];
|
||||
// Never the WAN, the tunnel itself, or a bridge port (routing only sees the bridge).
|
||||
if (dev == wan.dev || dev == srv.ifname || devs[dev]?.master)
|
||||
continue;
|
||||
let d = devs[dev];
|
||||
let h = { dev, auto: p[1], nets: d?.nets ?? [], zone: d?.zone ?? null, missing: !d };
|
||||
push(home, h);
|
||||
push(nets, ...h.nets);
|
||||
if (h.zone)
|
||||
push(zones, h.zone);
|
||||
}
|
||||
// Older configs and routers where nothing could be resolved: the zone set at setup.
|
||||
if (!length(home) && srv.auto_lan && srv.lan_zone)
|
||||
push(zones, srv.lan_zone);
|
||||
return { wan, home, nets: collapse(nets), zones: uniq(zones) };
|
||||
};
|
||||
|
||||
/** Router address on the home network (DNS for tunnel clients). */
|
||||
export function home_address(srv, snap) {
|
||||
snap ??= snapshot();
|
||||
let sn = server_net(srv, snap);
|
||||
for (let h in sn.home)
|
||||
for (let a in snap.devices[h.dev]?.addrs ?? [])
|
||||
return split(a, '/')[0];
|
||||
return null;
|
||||
};
|
||||
|
||||
/** WAN IPv4 address of a server's WAN interface. */
|
||||
export function wan_address(srv, snap) {
|
||||
snap ??= snapshot();
|
||||
let a = snap.devices[server_net(srv, snap).wan.dev]?.addrs?.[0];
|
||||
return a ? split(a, '/')[0] : null;
|
||||
};
|
||||
@@ -0,0 +1,658 @@
|
||||
// Dawnline — operations: health checks (with fixes), backups, export/import.
|
||||
|
||||
import { readfile, writefile, stat, unlink, lsdir } from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import {
|
||||
q, sh, sh_out, ensure_dir, read_json, write_json, write_file, parse_cidr, cidr_overlaps, cidr_str,
|
||||
ip2int, in_cidr, file_exists, valid_host, cloudflare_ip, DATA_DIR, RUN_DIR, VERSION
|
||||
} from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as live from 'dawnline.live';
|
||||
import * as apply from 'dawnline.apply';
|
||||
import * as loop from 'dawnline.loop';
|
||||
import * as net from 'dawnline.net';
|
||||
|
||||
const BACKUP_DIR = `${DATA_DIR}/backups`;
|
||||
const KEEP_BACKUPS = 10;
|
||||
|
||||
/**
|
||||
* Packages a feature needs that are missing, by feature: https (the portal: openssl-util and any
|
||||
* TLS module for uhttpd), acme (Let's Encrypt certificates), home (the home-like link). Checked by
|
||||
* files, so it is cheap enough for every page load.
|
||||
*/
|
||||
export function needs() {
|
||||
let tls = false;
|
||||
for (let d in [ '/lib', '/usr/lib' ])
|
||||
for (let f in lsdir(d) ?? [])
|
||||
if (substr(f, 0, 16) == 'libustream-ssl.s')
|
||||
tls = true;
|
||||
let kver = trim(readfile('/proc/sys/kernel/osrelease') ?? '');
|
||||
let veth = stat('/sys/module/veth') != null || file_exists(`/lib/modules/${kver}/veth.ko`);
|
||||
let miss = (list) => map(filter(list, (x) => !x[0]), (x) => x[1]);
|
||||
return {
|
||||
https: miss([ [ file_exists('/usr/bin/openssl'), 'openssl-util' ], [ tls, 'libustream-openssl' ] ]),
|
||||
acme: miss([ [ file_exists('/usr/lib/acme/client/acme.sh'), 'acme' ], [ file_exists('/usr/lib/acme/client/dnsapi/dns_cf.sh'), 'acme-acmesh-dnsapi' ],
|
||||
[ file_exists('/www/luci-static/resources/view/acme.js'), 'luci-app-acme' ] ]),
|
||||
home: miss([ [ file_exists('/usr/libexec/ip-full'), 'ip-full' ], [ veth, 'kmod-veth' ] ]),
|
||||
};
|
||||
};
|
||||
|
||||
/** ACME certificates on the router and the names each covers. */
|
||||
function acme_certs() {
|
||||
let out = [];
|
||||
for (let f in sort(lsdir('/etc/ssl/acme') ?? [])) {
|
||||
let m = match(f, /^(.+)\.fullchain\.crt$/);
|
||||
if (!m)
|
||||
continue;
|
||||
let c = `/etc/ssl/acme/${f}`, k = `/etc/ssl/acme/${m[1]}.key`;
|
||||
if (!file_exists(k))
|
||||
continue;
|
||||
let sans = sh_out(`openssl x509 -in ${q(c)} -noout -text 2>/dev/null | grep -o 'DNS:[^,]*'`) ?? '';
|
||||
push(out, { cert: c, key: k, names: filter(split(replace(sans, /DNS:/g, ''), /[ \t\r\n]+/), (x) => x != '') });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The ACME certificate that covers host (exact name or a wildcard), if any. */
|
||||
function acme_cert_for(host) {
|
||||
for (let a in acme_certs())
|
||||
for (let n in a.names)
|
||||
if (n == host || (substr(n, 0, 2) == '*.' && index(host, '.') > 0 && substr(host, index(host, '.')) == substr(n, 1)))
|
||||
return a;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Certificate the portal should use: configured, ACME for the host, or self-signed. */
|
||||
export function portal_cert(s) {
|
||||
if (s.portal_cert && s.portal_key && file_exists(s.portal_cert) && file_exists(s.portal_key))
|
||||
return { cert: s.portal_cert, key: s.portal_key, self_signed: false };
|
||||
if (s.portal_host) {
|
||||
for (let base in [ `/etc/ssl/acme/${s.portal_host}`, `/etc/acme/${s.portal_host}_ecc/${s.portal_host}` ]) {
|
||||
let c = `${base}.fullchain.crt`, k = `${base}.key`;
|
||||
if (file_exists(c) && file_exists(k))
|
||||
return { cert: c, key: k, self_signed: false };
|
||||
}
|
||||
// An ACME certificate issued for several names, the portal's among them.
|
||||
let a = acme_cert_for(s.portal_host);
|
||||
if (a)
|
||||
return { cert: a.cert, key: a.key, self_signed: false };
|
||||
}
|
||||
let c = `${DATA_DIR}/portal.crt`, k = `${DATA_DIR}/portal.key`;
|
||||
if (!file_exists(c) || !file_exists(k)) {
|
||||
ensure_dir(DATA_DIR, 0o700);
|
||||
let cn = s.portal_host || 'dawnline';
|
||||
sh(`openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 3650 -subj ${q('/CN=' + cn)} -keyout ${k} -out ${c}`);
|
||||
system(`chmod 600 ${k}`);
|
||||
}
|
||||
return { cert: c, key: k, self_signed: true };
|
||||
};
|
||||
|
||||
/* ---------- health ---------- */
|
||||
|
||||
function check(id, title, status, detail, fix) {
|
||||
return { id, title, status, detail: detail ?? '', fix: fix ?? null };
|
||||
}
|
||||
|
||||
function udp_listening(port) {
|
||||
let hex = sprintf(':%04X ', port);
|
||||
for (let f in [ '/proc/net/udp', '/proc/net/udp6' ])
|
||||
if (index(readfile(f) ?? '', hex) >= 0)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
function tcp_listening(port) {
|
||||
let hex = sprintf(':%04X ', port);
|
||||
for (let f in [ '/proc/net/tcp', '/proc/net/tcp6' ])
|
||||
for (let line in split(readfile(f) ?? '', '\n'))
|
||||
// state 0A = LISTEN
|
||||
if (index(line, hex) > 0 && match(line, / 0A /))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Processes other than our portal listening on a TCP port: [ "name" ]. */
|
||||
export function tcp_port_owners(port) {
|
||||
let out = sh_out(`netstat -lntp 2>/dev/null | awk '$4 ~ /:${+port}$/ {print $7}'`) ?? '';
|
||||
let owners = [];
|
||||
for (let o in split(out, '\n')) {
|
||||
let name = split(o, '/')[1];
|
||||
if (!name || index(owners, name) >= 0)
|
||||
continue;
|
||||
// Our own portal runs as a dedicated uhttpd instance.
|
||||
let pid = +split(o, '/')[0];
|
||||
let cmd = readfile(`/proc/${pid}/cmdline`) ?? '';
|
||||
if (index(cmd, '/usr/share/dawnline/portal') >= 0)
|
||||
continue;
|
||||
push(owners, name);
|
||||
}
|
||||
return owners;
|
||||
};
|
||||
|
||||
function resolve(host) {
|
||||
if (ip2int(host) != null)
|
||||
return [ host ];
|
||||
// Public resolvers first: local DNS often rewrites the router's own name
|
||||
// to its LAN address (split horizon).
|
||||
for (let srv in [ '1.1.1.1', '8.8.8.8', '127.0.0.1' ]) {
|
||||
let out = sh_out(`timeout 5 nslookup ${q(host)} ${srv} 2>/dev/null | awk '/^Address/ && NR>2 {print $NF}'`);
|
||||
let ips = out ? filter(split(out, '\n'), (x) => ip2int(x) != null) : [];
|
||||
if (length(ips))
|
||||
return ips;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function wan_ipv4(zone) {
|
||||
let st = live.iface_status(zone == 'wan' ? 'wan' : zone);
|
||||
return st?.['ipv4-address']?.[0]?.address;
|
||||
}
|
||||
|
||||
/** The router's public IPv4 (the first server's WAN, else the wan interface). */
|
||||
function router_wan(m) {
|
||||
for (let id, srv in m.servers)
|
||||
if (srv.private_key) {
|
||||
let a = net.wan_address(srv) ?? wan_ipv4(srv.wan_zone);
|
||||
if (a)
|
||||
return a;
|
||||
}
|
||||
return wan_ipv4('wan');
|
||||
}
|
||||
|
||||
/*
|
||||
* Addresses the portal could use in links, found on the router: names in ACME
|
||||
* certificates, server endpoints, DDNS names, the current one, and the WAN IP.
|
||||
* Each says where it points and whether a certificate covers it.
|
||||
*/
|
||||
export function portal_candidates(m) {
|
||||
let wan = router_wan(m);
|
||||
let names = [];
|
||||
let add = (h) => {
|
||||
if (h && valid_host(h) && ip2int(h) == null && substr(h, 0, 2) != '*.' && index(names, h) < 0)
|
||||
push(names, h);
|
||||
};
|
||||
for (let a in acme_certs())
|
||||
for (let n in a.names)
|
||||
add(n);
|
||||
for (let id, srv in m.servers)
|
||||
add(srv.endpoint);
|
||||
let dc = cursor();
|
||||
if (dc.load('ddns'))
|
||||
dc.foreach('ddns', 'service', (sv) => {
|
||||
if (sv.enabled != '0') {
|
||||
add(sv.lookup_host);
|
||||
add(sv.domain);
|
||||
}
|
||||
});
|
||||
for (let h in core.portal_hosts(m))
|
||||
add(h);
|
||||
let out = [];
|
||||
for (let h in names) {
|
||||
let ips = resolve(h);
|
||||
push(out, { host: h, kind: 'name', ips, here: wan != null && index(ips, wan) >= 0,
|
||||
cloudflare: length(filter(ips, (x) => cloudflare_ip(x))) > 0, cert: acme_cert_for(h) != null });
|
||||
}
|
||||
if (wan)
|
||||
push(out, { host: wan, kind: 'ip', ips: [ wan ], here: true, cloudflare: false, cert: false });
|
||||
for (let ph in core.portal_hosts(m))
|
||||
if (ip2int(ph) != null && ph != wan)
|
||||
push(out, { host: ph, kind: 'ip', ips: [ ph ], here: false, cloudflare: false, cert: false });
|
||||
// Best first: here with a certificate, then here, then the rest.
|
||||
let score = (c) => (c.here ? 4 : 0) + (c.cert ? 2 : 0) + (c.kind == 'name' ? 1 : 0) - (c.cloudflare ? 8 : 0);
|
||||
return sort(out, (a, b) => score(b) - score(a));
|
||||
};
|
||||
|
||||
function service_running(name, instance) {
|
||||
let s = sh_out(`ubus call service list '{"name":"${name}"}' 2>/dev/null`);
|
||||
if (!s)
|
||||
return false;
|
||||
try {
|
||||
let j = json(s);
|
||||
let inst = j?.[name]?.instances?.[instance];
|
||||
return !!inst?.running;
|
||||
}
|
||||
catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function other_subnets(srv_id) {
|
||||
let out = [];
|
||||
let st = sh_out('ubus call network.interface dump 2>/dev/null');
|
||||
let d = st ? json(st) : null;
|
||||
let ours = {};
|
||||
let m = core.load();
|
||||
for (let id, s in m.servers)
|
||||
ours[s.ifname] = id;
|
||||
for (let i in d?.interface ?? []) {
|
||||
if (srv_id != null && ours[i.interface] == srv_id)
|
||||
continue;
|
||||
for (let a in i['ipv4-address'] ?? [])
|
||||
push(out, { iface: i.interface, cidr: `${a.address}/${a.mask}` });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function used_subnets(except_srv) {
|
||||
return map(other_subnets(except_srv), (x) => x.cidr);
|
||||
};
|
||||
|
||||
/**
|
||||
* Run all checks. Each result: { id, title, status: ok|warn|error|skip, detail, fix }.
|
||||
* `fix` names an action accepted by fix().
|
||||
*/
|
||||
/*
|
||||
* Policy rules that send the router's own (marked) traffic into a local table,
|
||||
* the way transparent proxies capture it: "pref 1000 fwmark 0x1 → table 100".
|
||||
*/
|
||||
function proxy_diverts() {
|
||||
let out = [];
|
||||
for (let line in split(sh_out('ip -4 rule show 2>/dev/null') ?? '', '\n')) {
|
||||
let mm = match(line, /^(\d+):.*fwmark (\S+).* lookup (\S+)/);
|
||||
if (!mm || +mm[1] >= 32766)
|
||||
continue;
|
||||
if (match(sh_out(`ip -4 route show table ${mm[3]} 2>/dev/null`) ?? '', /(^|\n)local default/))
|
||||
push(out, `pref ${mm[1]} fwmark ${mm[2]} → table ${mm[3]}`);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Our "answers leave by main" rule for this port (see apply.sync_reply_routes). */
|
||||
function reply_rule(proto, port) {
|
||||
return index(sh_out('ip -4 rule show priority 90 2>/dev/null') ?? '', `ipproto ${proto} sport ${+port} lookup main`) >= 0;
|
||||
}
|
||||
|
||||
function reply_check(id, title, proto, port, diverts) {
|
||||
let ok = reply_rule(proto, port);
|
||||
let via = length(diverts) ? ` A proxy on the router diverts its own traffic (${join(', ', diverts)}); these answers skip it.` : '';
|
||||
return check(id, title, ok ? 'ok' : (length(diverts) ? 'error' : 'warn'),
|
||||
ok ? `Answers from ${uc(proto)} ${port} go straight out.${via}`
|
||||
: length(diverts) ? `Answers from ${uc(proto)} ${port} can be swallowed by a proxy on the router (${join(', ', diverts)}): clients get no reply.`
|
||||
: `The rule that keeps answers from ${uc(proto)} ${port} out of proxies is missing.`,
|
||||
ok ? null : 'apply');
|
||||
}
|
||||
|
||||
export function health(m) {
|
||||
let diverts = proxy_diverts();
|
||||
m ??= core.load();
|
||||
let out = [];
|
||||
let dmp = live.dump();
|
||||
|
||||
let kmod = file_exists('/sys/module/amneziawg');
|
||||
let tools = file_exists('/usr/bin/awg');
|
||||
push(out, check('awg', 'AmneziaWG installed', kmod && tools ? 'ok' : 'error',
|
||||
kmod && tools ? 'Kernel module and awg tool present.' :
|
||||
(!tools ? 'amneziawg-tools is missing.' : 'The kmod-amneziawg module is not loaded.'), kmod && tools ? null : 'updates'));
|
||||
|
||||
let y = localtime().year;
|
||||
push(out, check('clock', 'Clock is set', y >= 2025 ? 'ok' : 'error',
|
||||
y >= 2025 ? 'End dates and quotas use the router clock.' : 'The router clock looks wrong; end dates will misbehave. Check NTP.'));
|
||||
|
||||
push(out, check('agent', 'Background agent running', service_running('dawnline', 'agent') ? 'ok' : 'error',
|
||||
'Counts traffic and enforces end dates and quotas.', service_running('dawnline', 'agent') ? null : 'restart'));
|
||||
|
||||
if (!length(m.servers)) {
|
||||
push(out, check('server', 'Server configured', 'warn', 'Run the setup wizard on the Server tab.'));
|
||||
return out;
|
||||
}
|
||||
|
||||
let nft_ok = system('nft list table inet dawnline >/dev/null 2>&1') == 0;
|
||||
push(out, check('nft', 'Access rules loaded', nft_ok ? 'ok' : 'error',
|
||||
nft_ok ? 'Table inet dawnline enforces who may reach LAN and the internet.' : 'Table inet dawnline is missing: access is not enforced.',
|
||||
nft_ok ? null : 'apply'));
|
||||
|
||||
let fwc = cursor();
|
||||
fwc.load('firewall');
|
||||
|
||||
for (let id, srv in m.servers) {
|
||||
let label = length(m.servers) > 1 ? ` (${srv.name})` : '';
|
||||
if (!srv.enabled) {
|
||||
push(out, check(`srv_${id}`, `Server${label}`, 'skip', 'Server is disabled.'));
|
||||
continue;
|
||||
}
|
||||
let st = live.iface_status(srv.ifname);
|
||||
let up = !!st?.up;
|
||||
push(out, check(`up_${id}`, `Tunnel interface up${label}`, up ? 'ok' : 'error',
|
||||
up ? `${srv.ifname} is up, listening on UDP ${srv.port}.` :
|
||||
(st ? `${srv.ifname} is down${st.errors ? ': ' + join(', ', map(st.errors, (e) => e.code)) : ''}.` : `${srv.ifname} does not exist.`),
|
||||
up ? null : (st ? 'ifup:' + srv.ifname : 'apply')));
|
||||
|
||||
if (up) {
|
||||
let expected = 0;
|
||||
let states = apply.states_for(m, core.load_usage());
|
||||
for (let did, d in m.devices)
|
||||
if (m.people[d.person]?.server == id && !d.disabled && states[d.person] == 'active')
|
||||
expected++;
|
||||
let actual = 0;
|
||||
for (let k, p in dmp.peers)
|
||||
if (p.ifname == srv.ifname)
|
||||
actual++;
|
||||
push(out, check(`peers_${id}`, `Devices loaded${label}`, expected == actual ? 'ok' : 'warn',
|
||||
`${actual} of ${expected} active devices are loaded in the tunnel.`, expected == actual ? null : 'sync'));
|
||||
}
|
||||
|
||||
let rule = fwc.get('firewall', `dawnline_${id}_port`) == 'rule';
|
||||
let zone = fwc.get('firewall', `dawnline_${id}_zone`) == 'zone';
|
||||
push(out, check(`fw_${id}`, `Firewall${label}`, rule && zone ? 'ok' : 'error',
|
||||
rule && zone ? `Zone ${srv.ifname} and the WAN rule for UDP ${srv.port} exist.` : 'Firewall zone or WAN rule is missing.',
|
||||
rule && zone ? null : 'apply'));
|
||||
push(out, reply_check(`reply_${id}`, `Answers reach clients${label}`, 'udp', srv.port, diverts));
|
||||
|
||||
// Port collisions with other tunnels.
|
||||
let clash = [];
|
||||
let nc = cursor();
|
||||
nc.load('network');
|
||||
nc.foreach('network', 'interface', (s) => {
|
||||
if (s['.name'] != srv.ifname && (s.proto == 'amneziawg' || s.proto == 'wireguard') && +s.listen_port == srv.port)
|
||||
push(clash, s['.name']);
|
||||
});
|
||||
if (length(clash))
|
||||
push(out, check(`port_${id}`, `Port is free${label}`, 'error', `UDP ${srv.port} is also used by ${join(', ', clash)}.`));
|
||||
|
||||
let overlaps = [];
|
||||
let sc = parse_cidr(srv.subnet);
|
||||
for (let o in other_subnets(id)) {
|
||||
let oc = parse_cidr(o.cidr);
|
||||
if (sc && oc && cidr_overlaps(sc, oc))
|
||||
push(overlaps, `${o.iface} (${o.cidr})`);
|
||||
}
|
||||
push(out, check(`subnet_${id}`, `Subnet is unique${label}`, length(overlaps) ? 'error' : 'ok',
|
||||
length(overlaps) ? `${srv.subnet} overlaps ${join(', ', overlaps)}.` : `${srv.subnet} does not overlap other networks.`));
|
||||
|
||||
let host = core.endpoint_host(m, srv);
|
||||
if (!host)
|
||||
push(out, check(`ep_${id}`, `Public address${label}`, 'error', 'No endpoint hostname: clients will not know where to connect.'));
|
||||
else {
|
||||
let ips = resolve(host);
|
||||
let wan = net.wan_address(srv) ?? wan_ipv4(srv.wan_zone);
|
||||
let wc = wan ? ip2int(wan) : null;
|
||||
let cgnat = wc != null && (in_cidr(wc, parse_cidr('100.64.0.0/10')) || in_cidr(wc, parse_cidr('10.0.0.0/8')) ||
|
||||
in_cidr(wc, parse_cidr('172.16.0.0/12')) || in_cidr(wc, parse_cidr('192.168.0.0/16')));
|
||||
let stv = 'ok', det;
|
||||
if (!length(ips)) {
|
||||
stv = 'error';
|
||||
det = `${host} does not resolve.`;
|
||||
}
|
||||
else if (cgnat) {
|
||||
stv = 'warn';
|
||||
det = `WAN address ${wan} is private: forward UDP ${srv.port} on the upstream router, or clients cannot connect.`;
|
||||
}
|
||||
else if (wan && index(ips, wan) < 0) {
|
||||
stv = 'warn';
|
||||
det = `${host} resolves to ${join(', ', ips)}, but the WAN address is ${wan}. Check your DNS / DDNS.`;
|
||||
}
|
||||
else
|
||||
det = `${host} → ${join(', ', ips)}`;
|
||||
push(out, check(`ep_${id}`, `Public address${label}`, stv, det));
|
||||
}
|
||||
|
||||
if (srv.lan_like) {
|
||||
let ls = loop.status();
|
||||
let nh = needs().home;
|
||||
push(out, check(`home_${id}`, `Internet like a home device${label}`, ls.active && ls.bridged ? 'ok' : 'warn',
|
||||
ls.active && ls.bridged ? `Traffic enters ${ls.dev} as ${ls.address}, so it is handled like any device on your LAN.` :
|
||||
length(nh) ? `Needs ${join(' and ', nh)}. Internet traffic leaves through WAN directly until then.` :
|
||||
ls.active ? `The link is up but not attached to ${ls.dev}.` :
|
||||
`${ls.error ?? 'Not set up.'} Internet traffic leaves through WAN directly.`,
|
||||
ls.active && ls.bridged ? null : length(nh) ? 'install:home' : 'apply'));
|
||||
}
|
||||
}
|
||||
|
||||
if (length(filter(values(m.servers), (x) => x.private_key))) {
|
||||
let rt = loop.resolver_target();
|
||||
let ok = stat(loop.RESOLVER.conf) != null && loop.resolver_running();
|
||||
push(out, check('resolver', 'DNS for Home-only devices', ok ? 'ok' : 'warn',
|
||||
ok ? (rt.mode == 'ns' ? `Plain resolver running next to the LAN (${rt.address}).` : `Plain resolver on port ${rt.port}.`)
|
||||
: 'The resolver is not running; Home-only devices cannot resolve names.', ok ? null : 'apply'));
|
||||
}
|
||||
|
||||
let s = m.settings;
|
||||
let need = needs();
|
||||
if (s.portal_enabled && length(need.https))
|
||||
push(out, check('portal', 'Personal portal', 'error',
|
||||
`HTTPS isn't available on this router: install ${join(' and ', need.https)}.`, 'install:https'));
|
||||
else if (s.portal_enabled) {
|
||||
let owners = tcp_port_owners(s.portal_port);
|
||||
let listening = tcp_listening(s.portal_port);
|
||||
if (length(owners))
|
||||
push(out, check('portal', 'Personal portal', 'error',
|
||||
`TCP ${s.portal_port} is already used by ${join(', ', owners)}. Choose another port in Settings.`));
|
||||
else
|
||||
push(out, check('portal', 'Personal portal', listening ? 'ok' : 'error',
|
||||
listening ? `Listening on TCP ${s.portal_port}.` : `Nothing listens on TCP ${s.portal_port}.`, listening ? null : 'restart'));
|
||||
if (!s.portal_host)
|
||||
push(out, check('portal_host', 'Portal address', 'error', 'Set the public hostname in Settings so links can be generated.'));
|
||||
else {
|
||||
let ips = resolve(s.portal_host), wan = router_wan(m);
|
||||
let cf = filter(ips, (x) => cloudflare_ip(x));
|
||||
push(out, check('portal_dns', 'Portal address points here', !length(ips) ? 'error' : length(cf) ? 'warn' : wan && index(ips, wan) < 0 ? 'warn' : 'ok',
|
||||
!length(ips) ? `${s.portal_host} does not resolve.` :
|
||||
length(cf) ? `${s.portal_host} goes through Cloudflare; in Russia such connections often stall after ~16 KB.` :
|
||||
wan && index(ips, wan) < 0 ? `${s.portal_host} points at ${join(', ', ips)}, not this router (${wan}).` :
|
||||
`${s.portal_host} → ${join(', ', ips)}${wan ? ' (this router)' : ''}.`));
|
||||
}
|
||||
push(out, reply_check('portal_reply', 'Portal answers reach visitors', 'tcp', s.portal_port, diverts));
|
||||
if (core.portal_http(m)) {
|
||||
let ipl = filter(core.portal_hosts(m), (h) => ip2int(h) != null);
|
||||
push(out, check('portal_http', 'Plain HTTP links', 'warn',
|
||||
`Links on ${join(', ', ipl)} use plain HTTP: the link and the VPN keys in configurations travel unencrypted.`));
|
||||
}
|
||||
|
||||
// Links on 443: forwarded from outside, and the same link at home through LuCI's web server.
|
||||
let pub = core.portal_public_port(m);
|
||||
if (s.portal_port != 443) {
|
||||
if (!s.portal_443)
|
||||
push(out, check('portal_443', 'Links without a port', 'skip',
|
||||
`Off: links use port ${s.portal_port}. Mobile networks often drop HTTPS on ports other than 443.`));
|
||||
else if (pub != 443)
|
||||
push(out, check('portal_443', 'Links without a port', 'warn',
|
||||
`TCP 443 is already forwarded to another device, so links use port ${s.portal_port}.`));
|
||||
else {
|
||||
let fw = system(`nft list ruleset 2>/dev/null | grep -q 'Dawnline-Portal-443'`) == 0;
|
||||
push(out, check('portal_443', 'Links without a port', fw ? 'ok' : 'error',
|
||||
fw ? `From the internet TCP 443 reaches the portal only (LuCI stays closed there).` : 'The 443 forward to the portal is missing.',
|
||||
fw ? null : 'apply'));
|
||||
let uc_ = cursor();
|
||||
uc_.load('uhttpd');
|
||||
let ep = uc_.get('uhttpd', 'main', 'error_page');
|
||||
let mine = ep == '/cgi-bin/dawnline-portal' && stat('/www/cgi-bin/dawnline-portal') != null;
|
||||
push(out, check('portal_lan', 'Same link at home', mine ? 'ok' : ep ? 'warn' : 'error',
|
||||
mine ? 'At home the link opens through LuCI\'s web server, which hands unknown paths to the portal.'
|
||||
: ep ? `LuCI's web server already uses ${ep} for unknown paths, so at home links need :${s.portal_port}.`
|
||||
: 'LuCI\'s web server does not hand portal links to the portal: at home they show Not found.',
|
||||
mine || ep ? null : 'apply'));
|
||||
}
|
||||
}
|
||||
|
||||
let cert = portal_cert(s);
|
||||
if (ip2int(s.portal_host) != null)
|
||||
push(out, check('cert', 'Portal certificate', 'skip', 'The main address is an IP: its links use plain HTTP.'));
|
||||
else {
|
||||
let ok = system(`openssl x509 -checkend 1209600 -noout -in ${q(cert.cert)} >/dev/null 2>&1`) == 0;
|
||||
let sans = cert.self_signed ? [] : split(replace(sh_out(`openssl x509 -in ${q(cert.cert)} -noout -text 2>/dev/null | grep -o 'DNS:[^,]*'`) ?? '', /DNS:/g, ''), /[ \t\r\n]+/);
|
||||
let covers = !s.portal_host || cert.self_signed || index(sans, s.portal_host) >= 0 ||
|
||||
length(filter(sans, (n) => substr(n, 0, 2) == '*.' && substr(s.portal_host, index(s.portal_host, '.')) == substr(n, 1)));
|
||||
push(out, check('cert', 'Portal certificate', cert.self_signed || !ok || !covers ? 'warn' : 'ok',
|
||||
cert.self_signed ? `Using a self-signed certificate: browsers will show a warning.${length(need.acme) ? ' ACME can get a free Let’s Encrypt one.' : ''}` :
|
||||
!covers ? `${cert.cert} does not cover ${s.portal_host} (it has ${join(', ', sans)}): browsers will warn.` :
|
||||
ok ? `${cert.cert} covers ${s.portal_host} and is valid for more than 14 days.` : `${cert.cert} expires within 14 days.`));
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
};
|
||||
|
||||
export function fix(id) {
|
||||
if (id == 'apply')
|
||||
return apply.apply();
|
||||
if (id == 'sync')
|
||||
return apply.sync();
|
||||
if (id == 'restart')
|
||||
return { code: system('/etc/init.d/dawnline restart >/dev/null 2>&1') };
|
||||
let m = match(id ?? '', /^ifup:([a-z][a-z0-9_]{0,11})$/);
|
||||
if (m) {
|
||||
system(`ifup ${q(m[1])}`);
|
||||
return { ok: true };
|
||||
}
|
||||
die('Unknown fix.');
|
||||
};
|
||||
|
||||
/* ---------- backups ---------- */
|
||||
|
||||
function backup_files() {
|
||||
let out = [ '/etc/config/dawnline' ];
|
||||
for (let f in [ 'usage.json', 'events.json' ])
|
||||
if (file_exists(`${DATA_DIR}/${f}`))
|
||||
push(out, `${DATA_DIR}/${f}`);
|
||||
return out;
|
||||
}
|
||||
|
||||
export function backup_list() {
|
||||
let out = [];
|
||||
for (let f in lsdir(BACKUP_DIR) ?? []) {
|
||||
let mm = match(f, /^dawnline-([0-9]{8}-[0-9]{6})(-([a-z0-9-]+))?\.tar\.gz$/);
|
||||
if (!mm)
|
||||
continue;
|
||||
let st = stat(`${BACKUP_DIR}/${f}`);
|
||||
push(out, { name: f, created: st?.mtime ?? 0, size: st?.size ?? 0, reason: mm[3] ?? 'manual' });
|
||||
}
|
||||
return sort(out, (a, b) => b.created - a.created);
|
||||
};
|
||||
|
||||
export function backup_create(reason) {
|
||||
// Flush live counters first so the backup has current usage.
|
||||
let u = read_json(`${RUN_DIR}/usage.json`, null);
|
||||
if (u)
|
||||
write_json(`${DATA_DIR}/usage.json`, u, 0o600);
|
||||
live.persist_events();
|
||||
ensure_dir(BACKUP_DIR, 0o700);
|
||||
let t = localtime();
|
||||
let tag = reason && match(reason, /^[a-z0-9-]{1,24}$/) ? `-${reason}` : '';
|
||||
let name = sprintf('dawnline-%04d%02d%02d-%02d%02d%02d%s.tar.gz', t.year, t.mon, t.mday, t.hour, t.min, t.sec, tag);
|
||||
let files = join(' ', map(backup_files(), (f) => q(substr(f, 1))));
|
||||
let r = sh(`tar -czf ${q(BACKUP_DIR + '/' + name)} -C / ${files}`);
|
||||
if (r.code != 0)
|
||||
die(`Backup failed: ${trim(r.out)}`);
|
||||
system(`chmod 600 ${q(BACKUP_DIR + '/' + name)}`);
|
||||
let all = backup_list();
|
||||
for (let i = KEEP_BACKUPS; i < length(all); i++)
|
||||
unlink(`${BACKUP_DIR}/${all[i].name}`);
|
||||
return name;
|
||||
};
|
||||
|
||||
function backup_path(name) {
|
||||
if (!match(name ?? '', /^dawnline-[0-9]{8}-[0-9]{6}(-[a-z0-9-]+)?\.tar\.gz$/))
|
||||
die('Invalid backup name.');
|
||||
let p = `${BACKUP_DIR}/${name}`;
|
||||
if (!file_exists(p))
|
||||
die('Backup not found.');
|
||||
return p;
|
||||
}
|
||||
|
||||
/** Validate an archive: only Dawnline's own files may be inside. */
|
||||
function check_archive(path) {
|
||||
let r = sh(`tar -tzf ${q(path)}`);
|
||||
if (r.code != 0)
|
||||
die('Not a valid backup archive.');
|
||||
let allowed = { 'etc/config/dawnline': true };
|
||||
let has_config = false;
|
||||
for (let f in split(trim(r.out), '\n')) {
|
||||
f = replace(f, /^\.?\//, '');
|
||||
// The config plus Dawnline's own data files (older versions had more of them).
|
||||
if (!allowed[f] && !match(f, /^etc\/dawnline\/[a-z0-9_-]+\.json$/))
|
||||
die(`Unexpected file in backup: ${f}`);
|
||||
if (f == 'etc/config/dawnline')
|
||||
has_config = true;
|
||||
}
|
||||
if (!has_config)
|
||||
die('Backup does not contain /etc/config/dawnline.');
|
||||
}
|
||||
|
||||
export function backup_restore(name, path) {
|
||||
path ??= backup_path(name);
|
||||
check_archive(path);
|
||||
backup_create('pre-restore');
|
||||
let r = sh(`tar -xzf ${q(path)} -C /`);
|
||||
if (r.code != 0)
|
||||
die(`Restore failed: ${trim(r.out)}`);
|
||||
system('chmod 600 /etc/config/dawnline');
|
||||
// Live counters must follow the restored file.
|
||||
unlink(`${RUN_DIR}/usage.json`);
|
||||
unlink(`${RUN_DIR}/events.json`);
|
||||
return apply.apply();
|
||||
};
|
||||
|
||||
export function backup_delete(name) {
|
||||
unlink(backup_path(name));
|
||||
return true;
|
||||
};
|
||||
|
||||
export function backup_read(name) {
|
||||
return b64enc(readfile(backup_path(name)));
|
||||
};
|
||||
|
||||
export function backup_upload(data_b64) {
|
||||
let data = b64dec(data_b64 ?? '');
|
||||
if (!data || length(data) > 4 * 1024 * 1024)
|
||||
die('Upload is empty or too large.');
|
||||
ensure_dir(RUN_DIR);
|
||||
let tmp = `${RUN_DIR}/upload.tar.gz`;
|
||||
write_file(tmp, data);
|
||||
let res;
|
||||
try {
|
||||
res = backup_restore(null, tmp);
|
||||
}
|
||||
catch (e) {
|
||||
unlink(tmp);
|
||||
die(e.message);
|
||||
}
|
||||
unlink(tmp);
|
||||
return res;
|
||||
};
|
||||
|
||||
/* ---------- export / import (JSON) ---------- */
|
||||
|
||||
export function export_json() {
|
||||
let c = cursor();
|
||||
c.load('dawnline');
|
||||
let sections = [];
|
||||
c.foreach('dawnline', null, (s) => {
|
||||
let o = { '.type': s['.type'], '.name': s['.name'] };
|
||||
for (let k, v in s)
|
||||
if (substr(k, 0, 1) != '.')
|
||||
o[k] = v;
|
||||
push(sections, o);
|
||||
});
|
||||
return { format: 'dawnline', version: VERSION, exported: time(), sections };
|
||||
};
|
||||
|
||||
export function import_json(data) {
|
||||
if (type(data) != 'object' || data.format != 'dawnline' || type(data.sections) != 'array')
|
||||
die('Not a Dawnline export.');
|
||||
let types = { settings: true, server: true, person: true, device: true, service: true };
|
||||
for (let s in data.sections) {
|
||||
if (!types[s['.type']] || !match(s['.name'] ?? '', /^[A-Za-z0-9_]{1,64}$/))
|
||||
die(`Invalid section ${s['.name']}.`);
|
||||
for (let k, v in s)
|
||||
if (substr(k, 0, 1) != '.' && (!match(k, /^[a-z0-9_]{1,32}$/) || (type(v) != 'string' && type(v) != 'array')))
|
||||
die(`Invalid option ${k}.`);
|
||||
}
|
||||
backup_create('pre-import');
|
||||
let lines = [];
|
||||
for (let s in data.sections) {
|
||||
push(lines, `config ${s['.type']} '${s['.name']}'`);
|
||||
for (let k, v in s) {
|
||||
if (substr(k, 0, 1) == '.')
|
||||
continue;
|
||||
let esc = (x) => replace(`${x}`, "'", "'\\''");
|
||||
if (type(v) == 'array')
|
||||
for (let x in v)
|
||||
push(lines, `\tlist ${k} '${esc(x)}'`);
|
||||
else
|
||||
push(lines, `\toption ${k} '${esc(v)}'`);
|
||||
}
|
||||
push(lines, '');
|
||||
}
|
||||
write_file('/etc/config/dawnline', join('\n', lines), 0o600);
|
||||
return apply.apply();
|
||||
};
|
||||
@@ -0,0 +1,276 @@
|
||||
// Dawnline — small helpers shared by the rpcd plugin, the CLI, the agent and
|
||||
// the portal CGI. Nothing in here touches configuration.
|
||||
|
||||
import { open, readfile, writefile, rename, mkdir, stat, unlink, popen, lsdir } from 'fs';
|
||||
|
||||
export const VERSION = '0.1.0';
|
||||
/** GitHub repository with Dawnline releases (updates and the installer). */
|
||||
export const REPO = 'tickcount/luci-app-dawnline';
|
||||
export const RUN_DIR = '/var/run/dawnline';
|
||||
export const DATA_DIR = '/etc/dawnline';
|
||||
|
||||
/* ---------- shell ---------- */
|
||||
|
||||
export function q(s) {
|
||||
return "'" + replace(`${s}`, "'", "'\\''") + "'";
|
||||
};
|
||||
|
||||
/** Run a shell command; returns { code, out }. Stdout and stderr are merged. */
|
||||
export function sh(cmd) {
|
||||
let p = popen(`${cmd} 2>&1`, 'r');
|
||||
if (!p)
|
||||
return { code: -1, out: '' };
|
||||
let out = p.read('all') ?? '';
|
||||
let code = p.close();
|
||||
return { code: code ?? 0, out: out };
|
||||
};
|
||||
|
||||
/** Trimmed stdout of a command, or null when it failed. */
|
||||
export function sh_out(cmd) {
|
||||
let r = sh(cmd);
|
||||
return r.code == 0 ? trim(r.out) : null;
|
||||
};
|
||||
|
||||
/** Fire-and-forget: run a shell snippet detached from the caller. */
|
||||
export function sh_bg(cmd) {
|
||||
system(`( ${cmd} ) >/dev/null 2>&1 </dev/null &`);
|
||||
};
|
||||
|
||||
/* ---------- randomness ---------- */
|
||||
|
||||
export function rand_bytes(n) {
|
||||
let f = open('/dev/urandom', 'r');
|
||||
let b = f.read(n);
|
||||
f.close();
|
||||
return b;
|
||||
};
|
||||
|
||||
export function rand_hex(n) {
|
||||
return hexenc(rand_bytes(n));
|
||||
};
|
||||
|
||||
const ALNUM = 'abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
|
||||
|
||||
/** URL-safe random token without look-alike characters. */
|
||||
export function rand_token(len) {
|
||||
let b = rand_bytes(len), s = '';
|
||||
for (let i = 0; i < len; i++)
|
||||
s += substr(ALNUM, ord(b, i) % length(ALNUM), 1);
|
||||
return s;
|
||||
};
|
||||
|
||||
export function rand_int(lo, hi) {
|
||||
let b = rand_bytes(4);
|
||||
let n = (ord(b, 0) << 24 | ord(b, 1) << 16 | ord(b, 2) << 8 | ord(b, 3)) & 0x7fffffff;
|
||||
return lo + n % (hi - lo + 1);
|
||||
};
|
||||
|
||||
/* ---------- files ---------- */
|
||||
|
||||
export function ensure_dir(path, mode) {
|
||||
let parts = split(path, '/'), cur = '';
|
||||
for (let p in parts) {
|
||||
if (p == '')
|
||||
continue;
|
||||
cur += '/' + p;
|
||||
if (!stat(cur))
|
||||
mkdir(cur, mode ?? 0o755);
|
||||
}
|
||||
};
|
||||
|
||||
export function read_json(path, fallback) {
|
||||
let s = readfile(path);
|
||||
if (s == null || s == '')
|
||||
return fallback;
|
||||
try {
|
||||
let v = json(s);
|
||||
return v ?? fallback;
|
||||
}
|
||||
catch (e) {
|
||||
return fallback;
|
||||
}
|
||||
};
|
||||
|
||||
/** Atomic write (temp file + rename). `mode` defaults to 0600. */
|
||||
export function write_file(path, data, mode) {
|
||||
let tmp = `${path}.tmp${rand_hex(3)}`;
|
||||
let f = open(tmp, 'w', mode ?? 0o600);
|
||||
if (!f)
|
||||
return false;
|
||||
f.write(data);
|
||||
f.close();
|
||||
return rename(tmp, path);
|
||||
};
|
||||
|
||||
export function write_json(path, data, mode) {
|
||||
return write_file(path, sprintf('%J', data), mode);
|
||||
};
|
||||
|
||||
export function file_exists(path) {
|
||||
return stat(path) != null;
|
||||
};
|
||||
|
||||
/** Exclusive lock on a file under RUN_DIR; returns a handle to pass to unlock(). */
|
||||
export function lock(name) {
|
||||
ensure_dir(RUN_DIR);
|
||||
let f = open(`${RUN_DIR}/${name}.lock`, 'w');
|
||||
if (f)
|
||||
f.lock('x');
|
||||
return f;
|
||||
};
|
||||
|
||||
export function unlock(f) {
|
||||
if (f) {
|
||||
f.lock('u');
|
||||
f.close();
|
||||
}
|
||||
};
|
||||
|
||||
/* ---------- IPv4 ---------- */
|
||||
|
||||
export function ip2int(ip) {
|
||||
let m = match(ip, /^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$/);
|
||||
if (!m)
|
||||
return null;
|
||||
let n = 0;
|
||||
for (let i = 1; i <= 4; i++) {
|
||||
let o = +m[i];
|
||||
if (o > 255)
|
||||
return null;
|
||||
n = n * 256 + o;
|
||||
}
|
||||
return n;
|
||||
};
|
||||
|
||||
export function int2ip(n) {
|
||||
return sprintf('%d.%d.%d.%d', (n >> 24) & 255, (n >> 16) & 255, (n >> 8) & 255, n & 255);
|
||||
};
|
||||
|
||||
// Cloudflare's published ranges (https://www.cloudflare.com/ips/).
|
||||
const CF_V4 = [ '173.245.48.0/20', '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22', '141.101.64.0/18',
|
||||
'108.162.192.0/18', '190.93.240.0/20', '188.114.96.0/20', '197.234.240.0/22', '198.41.128.0/17',
|
||||
'162.158.0.0/15', '104.16.0.0/13', '104.24.0.0/14', '172.64.0.0/13', '131.0.72.0/22' ];
|
||||
const CF_V6 = [ /^2400:cb00:/i, /^2606:4700:/i, /^2803:f800:/i, /^2405:b500:/i, /^2405:8100:/i, /^2a06:98c[0-7]:/i, /^2c0f:f248:/i ];
|
||||
|
||||
/** True for an address in Cloudflare's network (its proxies and edge). */
|
||||
export function cloudflare_ip(a) {
|
||||
let n = ip2int(a);
|
||||
if (n == null) {
|
||||
for (let r in CF_V6)
|
||||
if (match(a ?? '', r))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
for (let c in CF_V4) {
|
||||
let m = match(c, /^([0-9.]+)\/([0-9]+)$/);
|
||||
let size = 1 << (32 - +m[2]), net = ip2int(m[1]);
|
||||
if (n >= net && n < net + size)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
/** Parse "a.b.c.d/len" → { net, prefix, first, last, size } (net is the masked base). */
|
||||
export function parse_cidr(cidr) {
|
||||
let m = match(cidr ?? '', /^([0-9.]+)\/([0-9]+)$/);
|
||||
if (!m)
|
||||
return null;
|
||||
let ip = ip2int(m[1]), prefix = +m[2];
|
||||
if (ip == null || prefix < 8 || prefix > 30)
|
||||
return null;
|
||||
let size = 1 << (32 - prefix);
|
||||
let net = ip - ip % size;
|
||||
return { net, prefix, size, first: net + 1, last: net + size - 2, ip };
|
||||
};
|
||||
|
||||
export function cidr_str(c) {
|
||||
return `${int2ip(c.net)}/${c.prefix}`;
|
||||
};
|
||||
|
||||
export function cidr_overlaps(a, b) {
|
||||
return a.net < b.net + b.size && b.net < a.net + a.size;
|
||||
};
|
||||
|
||||
export function in_cidr(ip, c) {
|
||||
let n = type(ip) == 'int' ? ip : ip2int(ip);
|
||||
return n != null && n >= c.net && n < c.net + c.size;
|
||||
};
|
||||
|
||||
/* ---------- validation ---------- */
|
||||
|
||||
export function valid_slug(s) {
|
||||
return type(s) == 'string' && match(s, /^[a-z0-9][a-z0-9-]{0,30}[a-z0-9]$|^[a-z0-9]$/) != null;
|
||||
};
|
||||
|
||||
export function valid_name(s) {
|
||||
return type(s) == 'string' && length(trim(s)) > 0 && length(s) <= 48 && match(s, /[<>"\\[:cntrl:]]/) == null;
|
||||
};
|
||||
|
||||
export function valid_key(s) {
|
||||
return type(s) == 'string' && match(s, /^[A-Za-z0-9+\/]{42}[AEIMQUYcgkosw048]=$/) != null;
|
||||
};
|
||||
|
||||
export function valid_host(s) {
|
||||
return type(s) == 'string' && length(s) <= 253 &&
|
||||
(match(s, /^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/) != null ||
|
||||
ip2int(s) != null || match(s, /^[0-9a-fA-F:]+$/) != null);
|
||||
};
|
||||
|
||||
export function valid_date(s) {
|
||||
return type(s) == 'string' && match(s, /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/) != null;
|
||||
};
|
||||
|
||||
/** Turn a display name into a portal slug candidate. */
|
||||
export function slugify(s) {
|
||||
let out = lc(trim(`${s ?? ''}`));
|
||||
out = replace(out, /[^a-z0-9]+/g, '-');
|
||||
out = replace(out, /^-+|-+$/g, '');
|
||||
return substr(out, 0, 32) || 'user';
|
||||
};
|
||||
|
||||
/* ---------- time ---------- */
|
||||
|
||||
/** "YYYY-MM-DD" → epoch of the end of that local day (23:59:59). */
|
||||
export function date_end(s) {
|
||||
let m = match(s ?? '', /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/);
|
||||
if (!m)
|
||||
return null;
|
||||
return timelocal({ sec: 59, min: 59, hour: 23, mday: +m[3], mon: +m[2], year: +m[1] });
|
||||
};
|
||||
|
||||
export function today() {
|
||||
let t = localtime();
|
||||
return sprintf('%04d-%02d-%02d', t.year, t.mon, t.mday);
|
||||
};
|
||||
|
||||
export function month_key(ts) {
|
||||
let t = localtime(ts ?? time());
|
||||
return sprintf('%04d-%02d', t.year, t.mon);
|
||||
};
|
||||
|
||||
export function day_key(ts) {
|
||||
let t = localtime(ts ?? time());
|
||||
return sprintf('%04d-%02d-%02d', t.year, t.mon, t.mday);
|
||||
};
|
||||
|
||||
export function uniq(arr) {
|
||||
let seen = {}, out = [];
|
||||
for (let v in arr)
|
||||
if (!seen[v]) {
|
||||
seen[v] = true;
|
||||
push(out, v);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
export function list_dir(path) {
|
||||
return lsdir(path) ?? [];
|
||||
};
|
||||
|
||||
export function remove(path) {
|
||||
return unlink(path);
|
||||
};
|
||||
|
||||
export function now() {
|
||||
return time();
|
||||
};
|
||||
@@ -0,0 +1,103 @@
|
||||
// Dawnline — read models shared by the admin RPC and the portal: people and
|
||||
// devices merged with live peer state and usage.
|
||||
|
||||
import * as core from 'dawnline.core';
|
||||
import * as live from 'dawnline.live';
|
||||
import { day_key, month_key } from 'dawnline.util';
|
||||
|
||||
/** Daily totals (rx+tx) for the last `n` days, oldest first. */
|
||||
export function spark(rec, n) {
|
||||
let out = [], ts = time();
|
||||
for (let i = n - 1; i >= 0; i--) {
|
||||
let v = rec?.days?.[day_key(ts - i * 86400)];
|
||||
push(out, v ? v[0] + v[1] : 0);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
function config_stale(m, d) {
|
||||
m._issued ??= core.issued();
|
||||
let was = m._issued[d.id];
|
||||
return was != null && was != core.config_fingerprint(m, d);
|
||||
}
|
||||
|
||||
export function device_view(m, d, usage, dmp) {
|
||||
let u = usage.devices?.[d.id];
|
||||
let peer = dmp.peers[d.public_key];
|
||||
let ts = time();
|
||||
let hs = peer?.handshake || u?.handshake || 0;
|
||||
let p = m.people[d.person];
|
||||
return {
|
||||
id: d.id,
|
||||
name: d.name,
|
||||
kind: d.kind,
|
||||
address: d.address,
|
||||
disabled: d.disabled,
|
||||
created: d.created,
|
||||
created_by: d.created_by,
|
||||
online: !!(peer && peer.handshake > 0 && ts - peer.handshake < live.ONLINE_WINDOW),
|
||||
handshake: hs,
|
||||
endpoint: live.endpoint_ip(peer?.endpoint) || u?.endpoint || '',
|
||||
active: !!peer,
|
||||
month: live.month(u),
|
||||
total: u?.total ?? [ 0, 0 ],
|
||||
spark: spark(u, 7),
|
||||
hostname: m.settings.hostnames && p ? `${replace(replace(lc(d.name), /[^a-z0-9]+/g, '-'), /^-+|-+$/g, '') || 'device'}.${p.id}.${m.settings.domain}` : '',
|
||||
browser_key: d.private_key == '',
|
||||
// Its configuration changed since it was last shown or downloaded.
|
||||
config_stale: config_stale(m, d),
|
||||
};
|
||||
};
|
||||
|
||||
export function person_view(m, p, usage, dmp, states, opts) {
|
||||
opts ??= {};
|
||||
let u = usage.people?.[p.id];
|
||||
let devs = [];
|
||||
for (let id in p.devices)
|
||||
push(devs, device_view(m, m.devices[id], usage, dmp));
|
||||
devs = sort(devs, (a, b) => a.created - b.created);
|
||||
let used = core.person_usage(p, usage);
|
||||
let v = {
|
||||
id: p.id,
|
||||
name: p.name,
|
||||
server: p.server,
|
||||
access: p.access,
|
||||
device_limit: p.device_limit,
|
||||
expires: p.expires,
|
||||
quota_gb: p.quota_gb,
|
||||
quota_period: p.quota_period,
|
||||
quota_used: used,
|
||||
quota_limit: core.person_quota(p),
|
||||
bonus_gb: (p.bonus_gb > 0 && p.bonus_month == month_key()) ? p.bonus_gb : 0,
|
||||
expire_action: p.expire_action,
|
||||
dns_mode: p.dns_mode,
|
||||
expire_warn: p.expire_warn,
|
||||
paused: p.paused,
|
||||
hours: p.hours,
|
||||
state: states[p.id] ?? core.person_state(m, p, usage),
|
||||
month: live.month(u),
|
||||
total: u?.total ?? [ 0, 0 ],
|
||||
online: length(filter(devs, (d) => d.online)),
|
||||
last_seen: 0,
|
||||
devices: devs,
|
||||
};
|
||||
for (let d in devs)
|
||||
if (d.handshake > v.last_seen)
|
||||
v.last_seen = d.handshake;
|
||||
if (opts.admin) {
|
||||
v.code = p.code;
|
||||
v.link = core.portal_url(m, p);
|
||||
v.links = core.portal_urls(m, p);
|
||||
v.note = p.note;
|
||||
v.services = p.services;
|
||||
v.created = p.created;
|
||||
}
|
||||
return v;
|
||||
};
|
||||
|
||||
export function states(m, usage) {
|
||||
let out = {};
|
||||
for (let id, p in m.people)
|
||||
out[id] = core.person_state(m, p, usage);
|
||||
return out;
|
||||
};
|
||||
Reference in new issue
Block a user