clavarium 0.2.301-next.1 → 0.2.303-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -82,11 +82,13 @@ SHELF_MEMORY="1536M"
82
82
  SHELF_STORE="/var/snap/multipass/common"
83
83
  SHELF_INSTANCES="$SHELF_STORE/data/multipassd/vault/instances"
84
84
  SHELF_CACHE="$SHELF_STORE/cache"
85
+ # The leases its DHCP server gave its machines: "<expiry> <mac> <ip> <name> <client id>" per line.
86
+ LEASES="$SHELF_STORE/data/multipassd/network/dnsmasq.leases"
85
87
  # Moved to another disk (deploy/move-machines.sh, Multipass's own way: its
86
88
  # MULTIPASS_STORAGE in a drop-in of its service): <path>/data, <path>/cache.
87
89
  # (No drop-in is the usual case: under pipefail a missing file must not stop this program.)
88
90
  MOVED_TO="$( { sed -n 's/^Environment=MULTIPASS_STORAGE=\(\/[A-Za-z0-9/._-]*\)$/\1/p' /etc/systemd/system/snap.multipass.multipassd.service.d/override.conf 2>/dev/null || true; } | head -1)"
89
- if [ -n "$MOVED_TO" ] && [ -d "$MOVED_TO/data" ]; then SHELF_STORE="$MOVED_TO"; SHELF_INSTANCES="$MOVED_TO/data/vault/instances"; SHELF_CACHE="$MOVED_TO/cache"; fi
91
+ if [ -n "$MOVED_TO" ] && [ -d "$MOVED_TO/data" ]; then SHELF_STORE="$MOVED_TO"; SHELF_INSTANCES="$MOVED_TO/data/vault/instances"; SHELF_CACHE="$MOVED_TO/cache"; LEASES="$MOVED_TO/data/network/dnsmasq.leases"; fi
90
92
  # Also the floor under a grown disk (grow_room): the server keeps the same
91
93
  # (MIN_FREE_MB in server/shelf.mjs, used by server/capacity.mjs).
92
94
  SHELF_MIN_FREE_MB="6144"
@@ -735,7 +737,7 @@ AREA="$1"; VERB="$2"; shift 2
735
737
  # the server's account (its probes every few seconds made some 800 lines in ten minutes, 31-10). Reading
736
738
  # verbs, and commands run inside a machine (the server's own probes, mostly), are not written.
737
739
  case "$AREA $VERB" in
738
- "vm exec"|"vm ping"|"vm states"|"vm info"|"server logs"|"server room"|"server usage"|"shelf info"|"shelf room"|"shelf list"|"shelf size"|"shelf exec"|"git read"|"work room"|"disks list"|"disks room"|"machines places"|"machines moving"|"machines old"|"net taps"|"wifi status"|"wifi scan"|"path held"|"disk room"|"update check"|"meshcentral status"|"operator "*) : ;;
740
+ "vm exec"|"vm ping"|"vm states"|"vm info"|"server logs"|"server room"|"server usage"|"shelf info"|"shelf room"|"shelf list"|"shelf size"|"shelf exec"|"git read"|"work room"|"disks list"|"disks room"|"machines places"|"machines moving"|"machines old"|"net taps"|"net leases"|"wifi status"|"wifi scan"|"path held"|"disk room"|"update check"|"meshcentral status"|"operator "*) : ;;
739
741
  *) [ "$SAY" = yes ] || logger -t clavarium-host -- "$AREA $VERB$(printf ' %.80s' "$@" | head -c 400)" 2>/dev/null || true ;;
740
742
  esac
741
743
 
@@ -1389,14 +1391,38 @@ OOMScoreAdjust=-900'
1389
1391
  "net taps")
1390
1392
  [ $# -eq 0 ] || usage
1391
1393
  run pgrep -a qemu-system ;;
1394
+ "net leases")
1395
+ # Which address the VM manager's DHCP server gave which MAC: one "<mac> <ip>" per
1396
+ # line, each checked; nothing else of that file is printed (the name in it is the
1397
+ # VM's own word, never trusted). Read-only. No file yet: nothing.
1398
+ [ $# -eq 0 ] || usage
1399
+ if [ "$SAY" = "yes" ]; then echo "<mac> <ip> of each lease in $LEASES"; exit 0; fi
1400
+ [ -f "$LEASES" ] || exit 0
1401
+ while read -r _ mac ip _; do
1402
+ if [[ "$mac" =~ ^[0-9a-f]{2}(:[0-9a-f]{2}){5}$ && "$ip" =~ ^[0-9]{1,3}(\.[0-9]{1,3}){3}$ ]]; then printf '%s %s\n' "$mac" "$ip"; fi
1403
+ done < "$LEASES"
1404
+ exit 0 ;;
1392
1405
  "net bridge")
1406
+ # The bridge the machines' taps are on: multipass 1.17 names it per zone
1407
+ # (mpqemubrzone1, ...), older ones mpqemubr0 (04-11: the offline rules
1408
+ # were never written, their bridge not found). The first tap's says.
1393
1409
  [ $# -eq 0 ] || usage
1394
- run ip -4 -o addr show "$BRIDGE" ;;
1410
+ if [ "$SAY" = "yes" ]; then echo "ip -4 -o addr show <the bridge of the taps, else $BRIDGE>"; exit 0; fi
1411
+ bridge="$BRIDGE"
1412
+ for t in /sys/class/net/tap-*; do
1413
+ [ -e "$t/master" ] || continue
1414
+ m=$(basename "$(readlink "$t/master")"); [[ "$m" =~ ^mpqemubr[a-z0-9]{1,12}$ ]] && { bridge="$m"; break; }
1415
+ done
1416
+ if [ "$bridge" = "$BRIDGE" ] && ! [ -e "/sys/class/net/$BRIDGE" ]; then
1417
+ for b in /sys/class/net/mpqemubr*; do [ -e "$b" ] && { bridge=$(basename "$b"); break; }; done
1418
+ fi
1419
+ run ip -4 -o addr show "$bridge" ;;
1395
1420
  "net apply")
1396
1421
  # <ruleset>: the whole table, as text. Each line must be one of the
1397
1422
  # shapes the server writes; one unknown line refuses the whole.
1398
1423
  [ $# -eq 1 ] || usage
1399
1424
  tap='"tap-[0-9a-f]{1,12}"'; addr='[0-9]{1,3}(\.[0-9]{1,3}){3}'
1425
+ mac='[0-9a-f]{2}(:[0-9a-f]{2}){5}'; addrs="\\{ $addr(, $addr)* \\}"
1400
1426
  while IFS= read -r line; do
1401
1427
  [[ -z "$line"
1402
1428
  || "$line" =~ ^(delete\ )?table\ bridge\ $TABLE(\ \{)?$
@@ -1404,6 +1430,13 @@ OOMScoreAdjust=-900'
1404
1430
  || "$line" =~ ^\ \ \ \ type\ filter\ hook\ (forward|input)\ priority\ 0\;$
1405
1431
  || "$line" =~ ^\ \ \ \ iifname\ $tap\ (drop|udp\ dport\ 67\ accept|ether\ type\ arp\ accept)$
1406
1432
  || "$line" =~ ^\ \ \ \ iifname\ $tap\ ip\ daddr\ $addr\ (accept|meta\ l4proto\ \{\ tcp,\ udp\ \}\ th\ dport\ 53\ drop)$
1433
+ || "$line" =~ ^\ \ \ \ iifname\ $tap\ (ether\ saddr|arp\ saddr\ ether)\ !=\ $mac\ drop$
1434
+ || "$line" =~ ^\ \ \ \ iifname\ $tap\ ether\ type\ !=\ \{\ ip,\ arp\ \}\ drop$
1435
+ || "$line" =~ ^\ \ \ \ iifname\ $tap\ udp\ dport\ 67\ @th,288,48\ !=\ 0x[0-9a-f]{12}\ drop$
1436
+ || "$line" =~ ^\ \ \ \ iifname\ $tap\ ip\ saddr\ 0\.0\.0\.0\ ip\ daddr\ 255\.255\.255\.255\ udp\ dport\ 67\ accept$
1437
+ || "$line" =~ ^\ \ \ \ iifname\ $tap\ ip\ saddr\ !=\ $addr\ drop$
1438
+ || "$line" =~ ^\ \ \ \ iifname\ $tap\ arp\ saddr\ ip\ !=\ \{\ 0\.0\.0\.0,\ $addr\ \}\ drop$
1439
+ || "$line" =~ ^\ \ \ \ iifname\ $tap\ (ip\ saddr|arp\ saddr\ ip)\ $addrs\ drop$
1407
1440
  || "$line" =~ ^(\ \ )?\}$ ]] || refuse "a network rule of an unknown shape: $line"
1408
1441
  done <<< "$1"
1409
1442
  run nft "$1" ;;
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.301-next.1",
3
+ "version": "0.2.303-next.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.301-next.1",
9
+ "version": "0.2.303-next.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.301-next.1",
3
+ "version": "0.2.303-next.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "A conversation is a VM with a terminal in it. Everything else is a folder.",
package/server/main.mjs CHANGED
@@ -361,6 +361,8 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
361
361
  /* Each opening: the runner and the attached secrets are put in the VM,
362
362
  and the tool is started through the runner. */
363
363
  const network = new Network({ host: asHost, offline: () => all.offline() });
364
+ /* A machine the VM manager started by itself (after a reboot) is put in its silo too (04-11). */
365
+ const stopNetworkWatch = network.watch();
364
366
  /* The rules follow what runs: applied now, and again each time a
365
367
  conversation is opened, since a VM that just started has a new tap. */
366
368
  const hostReady = (async () => { await hostSteps; await network.apply().catch((error) => console.error(`network rules: ${error.message}`)); })();
@@ -656,7 +658,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
656
658
  rooms.boxesBound(boxes.all());
657
659
  rooms.refresh();
658
660
  const { server, listening } = serve(port, all, folders, { gate, originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, wifi, binders, meshcentral, tethers, accounts, groups, boxes, catalogue, rooms, bundles: new Bundles({ dir: `${dataDir}/imports`, folder: (name) => folders.folder(name) }), repair: (name) => repairTerminal(name) });
659
- server.on('close', () => { closing = true; stopBinders(); stopTethers(); clearInterval(historyTimer); clearInterval(secretsTimer); history.save(); stopVmWatch(); stopShelf(); stopHealth(); stopUpdates(); stopWatch(); clearInterval(mailTimer); clearInterval(restartTimer); clearInterval(expiryTimer); clearInterval(answerTimer); clearInterval(wakeTimer); clearInterval(docketTimer); dockets.stop(); clearInterval(gitTimer); talk.stop(); });
661
+ server.on('close', () => { closing = true; stopBinders(); stopTethers(); clearInterval(historyTimer); clearInterval(secretsTimer); history.save(); stopVmWatch(); stopShelf(); stopHealth(); stopNetworkWatch(); stopUpdates(); stopWatch(); clearInterval(mailTimer); clearInterval(restartTimer); clearInterval(expiryTimer); clearInterval(answerTimer); clearInterval(wakeTimer); clearInterval(docketTimer); dockets.stop(); clearInterval(gitTimer); talk.stop(); });
660
662
  let closing = false;
661
663
  boxes.attach(server, WebSocketServer);
662
664
  for (const c of all.list()) talk.speakers(c.name, boxes.speakersOf(c.name));
@@ -14,41 +14,112 @@
14
14
  * (that is how its terminal and its folders work), and not the host's
15
15
  * name resolver, which would be a way to carry data out.
16
16
  *
17
+ * AND NO VM PASSES FOR ANOTHER: root in a VM can give itself another VM's
18
+ * address, or answer the host's ARP for it, and the server reaches each VM at
19
+ * its address (its terminal, its folders, its secrets). So every frame from a
20
+ * tap must carry that VM's own MAC (read from its qemu line, which the VM
21
+ * cannot change), be IPv4 or ARP only (no IPv6: nothing of ours uses it, the
22
+ * VM manager's network gives none), and come from that VM's own IPv4 address
23
+ * (the lease the VM manager's DHCP server gave that MAC, pinned for the life
24
+ * of its qemu process). Its DHCP must name its own MAC. While its address is
25
+ * not known yet (it boots), it may lease one, but never use an address known
26
+ * to be another VM's or the host's.
27
+ *
17
28
  * WHAT THIS DOES NOT CLOSE, and it is said rather than hidden: a tap is only
18
29
  * known once its VM runs, so a VM is filtered a moment AFTER it starts, not
19
- * before. The rules are applied before the tool is attached.
30
+ * before. The rules are applied before the tool is attached. A VM whose qemu
31
+ * line has no MAC we can read keeps its silo but no address check.
20
32
  */
21
33
  import { isConversationName } from './names.mjs';
22
34
 
23
35
  export const TABLE = 'clavarium';
24
36
  const TAP = /^tap-[0-9a-f]{1,12}$/;
37
+ const MAC = /^[0-9a-f]{2}(?::[0-9a-f]{2}){5}$/;
38
+ const ADDRESS = /^\d{1,3}(?:\.\d{1,3}){3}$/;
39
+
40
+ export const isMac = (v) => typeof v === 'string' && MAC.test(v) && (parseInt(v.slice(0, 2), 16) & 1) === 0; /* unicast */
41
+ export const isAddress = (v) => typeof v === 'string' && ADDRESS.test(v) && v.split('.').every((n) => Number(n) <= 255 && String(Number(n)) === n);
42
+ /* An address a VM may hold: not 0.0.0.0, not broadcast, not multicast. */
43
+ const isHostAddress = (v) => isAddress(v) && v.split('.')[0] !== '0' && Number(v.split('.')[0]) < 224;
25
44
 
26
- /* The taps of the running conversation VMs, read from the process list:
27
- { conversation: tap }. Anything that does not look exactly as expected is
28
- left out: a rule is never built from a string that was not checked. */
45
+ /* How often what runs is looked at, for the rules (see watch). */
46
+ export const WATCH_MS = 20_000;
47
+ export const RELOAD_MS = 10 * 60_000;
48
+
49
+ /* The running conversation VMs, read from the process list:
50
+ { conversation: { tap, mac, pid } }. Anything that does not look exactly as
51
+ expected is left out (a bad tap: the VM; a bad or missing MAC: the MAC):
52
+ a rule is never built from a string that was not checked. */
29
53
  export function readTaps(processList) {
30
54
  const taps = {};
31
55
  for (const line of String(processList ?? '').split('\n')) {
32
56
  const name = /\/instances\/clv-([a-z0-9-]+)\//.exec(line)?.[1];
33
57
  const tap = /[ ,]ifname=([^, ]+)/.exec(line)?.[1];
34
- if (name && tap && isConversationName(name) && TAP.test(tap)) taps[name] = tap;
58
+ if (!(name && tap && isConversationName(name) && TAP.test(tap))) continue;
59
+ const mac = /[ ,]mac=([^, ]+)/.exec(line)?.[1];
60
+ const pid = /^\s*(\d{1,10}) /.exec(line)?.[1];
61
+ taps[name] = { tap, mac: isMac(mac) ? mac : undefined, pid };
35
62
  }
36
63
  return taps;
37
64
  }
38
65
 
66
+ /* The leases of the VM manager's DHCP server, as the host program prints them
67
+ ("<mac> <ip>" per line): { mac: ip }. A MAC or an address seen twice is
68
+ ambiguous: left out, unknown. */
69
+ export function readLeases(text) {
70
+ const byMac = new Map(); const seen = new Map();
71
+ for (const line of String(text ?? '').split('\n')) {
72
+ const [mac, ip, extra] = line.trim().split(/\s+/);
73
+ if (extra !== undefined || !isMac(mac) || !isHostAddress(ip)) continue;
74
+ byMac.set(mac, byMac.has(mac) && byMac.get(mac) !== ip ? null : ip);
75
+ seen.set(ip, (seen.get(ip) ?? new Set()).add(mac));
76
+ }
77
+ const leases = {};
78
+ for (const [mac, ip] of byMac) if (ip && seen.get(ip).size === 1) leases[mac] = ip;
79
+ return leases;
80
+ }
81
+
39
82
  export function readBridgeAddress(text) {
40
83
  const address = /\binet (\d{1,3}(?:\.\d{1,3}){3})\//.exec(String(text ?? ''))?.[1];
41
84
  return address && address.split('.').every((n) => Number(n) <= 255) ? address : undefined;
42
85
  }
43
86
 
44
- /* The whole table, as text for the firewall. Replaced atomically. */
45
- export function ruleset(taps, offline, bridgeAddress) {
46
- const all = Object.values(taps);
87
+ /* What a frame from one VM must be. `known` is every address held by another
88
+ VM, and the host's, for a VM whose own is not known yet. */
89
+ function guard(tap, mac, ip, known) {
90
+ const at = ` iifname "${tap}"`;
91
+ const lines = [
92
+ `${at} ether saddr != ${mac} drop`,
93
+ `${at} ether type != { ip, arp } drop`, /* IPv6, VLAN tags, the rest */
94
+ `${at} arp saddr ether != ${mac} drop`,
95
+ `${at} udp dport 67 @th,288,48 != 0x${mac.replaceAll(':', '')} drop`, /* DHCP: its own MAC (chaddr) */
96
+ `${at} ip saddr 0.0.0.0 ip daddr 255.255.255.255 udp dport 67 accept`, /* its lease, before it has one */
97
+ ];
98
+ if (ip) {
99
+ lines.push(`${at} ip saddr != ${ip} drop`);
100
+ lines.push(`${at} arp saddr ip != { 0.0.0.0, ${ip} } drop`);
101
+ } else if (known.length) {
102
+ lines.push(`${at} ip saddr { ${known.join(', ')} } drop`);
103
+ lines.push(`${at} arp saddr ip { ${known.join(', ')} } drop`);
104
+ }
105
+ return lines;
106
+ }
107
+
108
+ /* The whole table, as text for the firewall. Replaced atomically.
109
+ `vms`: { conversation: { tap, mac?, ip? } } (mac and ip already checked). */
110
+ export function ruleset(vms, offline, bridgeAddress) {
111
+ const all = Object.values(vms);
47
112
  const lines = [`table bridge ${TABLE}`, `delete table bridge ${TABLE}`, `table bridge ${TABLE} {`];
48
113
  lines.push(' chain between_vms {', ' type filter hook forward priority 0;');
49
- for (const tap of all) lines.push(` iifname "${tap}" drop`);
114
+ for (const { tap } of all) lines.push(` iifname "${tap}" drop`);
50
115
  lines.push(' }', ' chain from_vm {', ' type filter hook input priority 0;');
51
- for (const [name, tap] of Object.entries(taps)) {
116
+ const held = [...new Set([...all.map((v) => v.ip).filter(isHostAddress), ...(isHostAddress(bridgeAddress) ? [bridgeAddress] : [])])].sort();
117
+ for (const { tap, mac, ip } of all) {
118
+ if (!isMac(mac)) continue;
119
+ const own = isHostAddress(ip) ? ip : undefined;
120
+ lines.push(...guard(tap, mac, own, held));
121
+ }
122
+ for (const [name, { tap }] of Object.entries(vms)) {
52
123
  if (!offline.includes(name)) continue;
53
124
  lines.push(` iifname "${tap}" udp dport 67 accept`); /* its address lease */
54
125
  lines.push(` iifname "${tap}" ether type arp accept`);
@@ -62,6 +133,12 @@ export function ruleset(taps, offline, bridgeAddress) {
62
133
 
63
134
  export class Network {
64
135
  #host; #offline;
136
+ /* The table last loaded, and whether it was: the same table is not loaded again. */
137
+ #last = null;
138
+ /* PINNED: the address first leased to a VM, kept for the life of its qemu
139
+ process (its pid, tap and MAC). A lease that changes while it runs is
140
+ the VM asking for another address by itself: not followed. */
141
+ #pins = new Map();
65
142
 
66
143
  /* `host(argv)` reaches the host program;
67
144
  `offline()` returns the names of the conversations switched offline. */
@@ -72,14 +149,45 @@ export class Network {
72
149
  async apply() {
73
150
  const taps = readTaps((await this.#host(['net', 'taps'])).stdout);
74
151
  const bridge = readBridgeAddress((await this.#host(['net', 'bridge'])).stdout);
152
+ const leased = await this.#host(['net', 'leases']);
153
+ const vms = this.#addresses(taps, leased.code === 0 ? readLeases(leased.stdout) : {});
75
154
  const wanted = this.#offline().filter((name) => taps[name]);
76
155
  /* Without the host's address the "offline" rules cannot be written
77
156
  safely; the silo rule still can, and is. */
78
157
  /* As ONE argument, not on standard input: this firewall tool refuses
79
158
  a pipe as its input file (measured), and nothing in the rules is
80
- secret. Every name in them was checked by readTaps, and the host
159
+ secret. Every name, MAC and address in them was checked here, and the host
81
160
  program checks every line again before loading it. */
82
- const r = await this.#host(['net', 'apply', ruleset(taps, bridge ? wanted : [], bridge ?? '0.0.0.0')]);
83
- return r.code === 0 && (bridge !== undefined || wanted.length === 0);
161
+ const text = ruleset(vms, bridge ? wanted : [], bridge ?? '0.0.0.0');
162
+ const ok = bridge !== undefined || wanted.length === 0;
163
+ /* Loaded again anyway now and then: a table taken off by someone else comes back. */
164
+ if (this.#last?.text === text && this.#last.loaded && Date.now() - this.#last.at < RELOAD_MS) return ok;
165
+ const r = await this.#host(['net', 'apply', text]);
166
+ this.#last = { text, loaded: r.code === 0, at: Date.now() };
167
+ return r.code === 0 && ok;
168
+ }
169
+
170
+ /* Each VM's address: its pin, else its lease if no other VM holds it. */
171
+ #addresses(taps, leases) {
172
+ const keyOf = ({ pid, tap, mac }) => `${pid} ${tap} ${mac}`;
173
+ const running = new Set(Object.values(taps).filter((v) => v.mac && v.pid).map(keyOf));
174
+ for (const key of this.#pins.keys()) if (!running.has(key)) this.#pins.delete(key);
175
+ const vms = {};
176
+ for (const [name, v] of Object.entries(taps)) {
177
+ let ip = v.mac && v.pid ? this.#pins.get(keyOf(v)) : undefined;
178
+ const lease = v.mac ? leases[v.mac] : undefined;
179
+ if (!ip && lease && v.pid && ![...this.#pins.values()].includes(lease)) { ip = lease; this.#pins.set(keyOf(v), ip); }
180
+ vms[name] = { tap: v.tap, mac: v.mac, ip };
181
+ }
182
+ return vms;
183
+ }
184
+
185
+ /* KEPT UP TO DATE (04-11): a machine started by the VM manager itself -- after the server
186
+ restarted -- has a new tap that no opening told: looked at every `everyMs`, the table loaded
187
+ again only when what runs changed. Returns the stop. */
188
+ watch(everyMs = WATCH_MS) {
189
+ const timer = setInterval(() => { void this.apply().catch(() => {}); }, everyMs);
190
+ timer.unref?.();
191
+ return () => clearInterval(timer);
84
192
  }
85
193
  }