summary refs log tree commit diff
path: root/dvm
blob: ae041462089331b2af2f76fdf2eea17d7c9b1a2d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
#!/usr/bin/env bash
# dvm — run apps in throwaway KVM virtual machines, shown as ordinary
# Wayland windows on the host (waypipe over vsock), in the spirit of
# QubesOS disposables.
#
#   dvm build                  make the template VM (Arch cloud image)
#   dvm [run] [CMD [ARGS...]]  run CMD (default: mullvad-browser) in a fresh
#                              disposable
#   dvm template [CMD...]      run CMD (default: foot) in the template itself;
#                              changes persist into every later disposable
#   dvm update                 upgrade the template's packages, Mullvad Browser
#                              and extensions
#
# A disposable boots from a copy-on-write overlay of the template kept in
# $XDG_RUNTIME_DIR (RAM); the overlay is deleted when the app exits and the
# VM powers off. Environment: DVM_MEM (4G), DVM_CPUS (4), DVM_DISK (20G),
# DVM_MIC=1 to give the VM the host microphone, DVM_NOTIFY=0 to skip
# desktop notifications when VMs start and stop.
#
# SPDX-License-Identifier: MIT
set -euo pipefail

DATA=${DVM_DATA:-${XDG_DATA_HOME:-$HOME/.local/share}/dvm}
TEMPLATE=$DATA/template.qcow2
IMAGE_URL=https://geo.mirror.pkgbuild.com/images/latest/Arch-Linux-x86_64-cloudimg.qcow2
MEM=${DVM_MEM:-4G}
CPUS=${DVM_CPUS:-4}
DISK=${DVM_DISK:-20G}
GUEST_PKGS=(firefox firefox-ublock-origin waypipe foot sudo jq
            xwayland-satellite xorg-xwayland
            pipewire pipewire-pulse pipewire-alsa wireplumber
            dconf adw-gtk-theme adwaita-fonts noto-fonts noto-fonts-emoji
            ttf-dejavu ttf-liberation)

WP= RUN= NOTE_ID=
cleanup() {
	[[ -z $WP ]] || { kill "$WP" 2>/dev/null; wait "$WP" 2>/dev/null || true; }
	[[ -z $RUN ]] || rm -rf "$RUN"
}
trap cleanup EXIT

die() {
	echo "dvm: $*" >&2
	[[ -t 2 || ${DVM_NOTIFY:-1} == 0 ]] || notify-send -a dvm -i dialog-error "dvm failed" "$*" 2>/dev/null || true
	exit 1
}

# --- host side -------------------------------------------------------------

# Desktop notification; the stop notice replaces the start one so each VM
# leaves a single entry.
notify() { # summary body [icon]
	[[ ${DVM_NOTIFY:-1} == 1 ]] || return 0
	local id
	id=$(notify-send -a dvm -p ${NOTE_ID:+-r "$NOTE_ID"} -i "${3:-computer}" "$1" "$2" 2>/dev/null) \
		&& NOTE_ID=$id || true
}

elapsed() { # seconds -> "3 min" / "1 h 5 min" / "40 s"
	local t=$1
	if (( t < 60 )); then echo "$t s"
	elif (( t < 3600 )); then echo "$(( t / 60 )) min"
	else echo "$(( t / 3600 )) h $(( t % 3600 / 60 )) min"; fi
}

# Common QEMU arguments: KVM, no emulated display, user-mode network via
# passt (guest cannot reach the host's loopback services), virtio sound to
# the host's PipeWire (playback only unless DVM_MIC=1), and a vsock device
# for waypipe.
qemu_args() { # $1 = disk image, $2 = cache mode, $3 = console log
	local cid=$(( (RANDOM << 15 | RANDOM) + 3 ))
	QEMU=(qemu-system-x86_64
		-machine q35,accel=kvm -cpu host -smp "$CPUS" -m "$MEM"
		-nodefaults -display none -vga none -monitor none
		-serial "file:$3"
		-drive "if=virtio,file=$1,format=qcow2,cache=$2,discard=unmap"
		-netdev passt,id=net0,map-host-loopback=none
		-device virtio-net-pci,netdev=net0
		-device "vhost-vsock-pci,guest-cid=$cid"
		-audiodev pipewire,id=snd0
		-device "virtio-sound-pci,audiodev=snd0,streams=$(( ${DVM_MIC:-0} == 1 ? 2 : 1 ))"
		-device virtio-rng-pci)
}

credential() { # name value — handed to the guest's systemd via SMBIOS
	QEMU+=(-smbios "type=11,value=io.systemd.credential.binary:$1=$(printf %s "$2" | base64 -w0)")
}

host_gtk_theme() {
	sed -n 's/^gtk-theme-name *= *//p' "${XDG_CONFIG_HOME:-$HOME/.config}/gtk-3.0/settings.ini" 2>/dev/null | head -1
}

# Boot DISK with CMD as the app, showing its windows titled "[LABEL] ...".
launch() { # label disk cache extra-credential... -- cmd
	local label=$1 disk=$2 cache=$3; shift 3
	local creds=(); while [[ $1 != -- ]]; do creds+=("$1"); shift; done; shift
	command -v waypipe >/dev/null || die "waypipe is not installed on the host"
	[[ -n ${WAYLAND_DISPLAY:-} ]] || die "no Wayland session (WAYLAND_DISPLAY unset)"

	local port=$(( (RANDOM << 15 | RANDOM) + 1024 ))
	waypipe --vsock --no-gpu -c none --title-prefix "[$label] " -s "$port" client &
	WP=$!

	qemu_args "$disk" "$cache" "$RUN/console.log"
	QEMU+=(-name "dvm:$label,process=dvm-$label")
	credential dvm.cmd "$(printf '%q ' "$@")"
	credential dvm.port "$port"
	credential dvm.gtk-theme "$(host_gtk_theme)"
	local c; for c in "${creds[@]}"; do credential "${c%%=*}" "${c#*=}"; done

	local what=$1 kind=disposable started=$SECONDS
	[[ $label == template ]] && kind="template — changes persist"
	notify "$label starting" "$what ($kind)"
	if ! "${QEMU[@]}"; then
		tail -n 30 "$RUN/console.log" >&2
		notify "$label failed" "$what: QEMU exited with an error" dialog-error
		DVM_NOTIFY=0 die "VM $label failed"
	fi
	local ran; ran=$(elapsed $(( SECONDS - started )))
	if [[ $label == template ]]; then
		notify "$label stopped" "$what closed after $ran; changes saved to the template"
	else
		notify "$label stopped" "$what closed after $ran; VM and its disk discarded"
	fi
}

new_rundir() {
	RUN=$(mktemp -d "${XDG_RUNTIME_DIR:-/tmp}/dvm.XXXXXX")
}

lock_template() { # shared|exclusive
	[[ -f $TEMPLATE ]] || die "no template yet — run: dvm build"
	exec 9>"$DATA/template.lock"
	if [[ $1 == shared ]]; then
		flock -s -n 9 || die "the template is open for changes (dvm template/update); close it first"
	else
		flock -x -n 9 || die "disposables are running from the template; close them first"
	fi
}

cmd_run() {
	(( $# )) || set -- mullvad-browser
	lock_template shared
	new_rundir
	local label="disp$(( RANDOM % 9000 + 1000 ))"
	qemu-img create -q -f qcow2 -b "$TEMPLATE" -F qcow2 "$RUN/disk.qcow2"
	launch "$label" "$RUN/disk.qcow2" unsafe -- "$@"
}

cmd_template() {
	(( $# )) || set -- foot
	lock_template exclusive
	new_rundir
	launch template "$TEMPLATE" writeback dvm.template=1 -- "$@"
}

cmd_update() {
	cmd_template foot -T "dvm template update" bash -c \
		'sudo pacman -Syu && sudo dvm-refresh-browsers && sudo pacman -Scc --noconfirm >/dev/null \
		 && { timeout -s TERM 30 mullvad-browser --headless >/dev/null 2>&1; true; }; echo; read -rp "Press Enter to close. "'
}

# --- template build ----------------------------------------------------------

cmd_build() {
	[[ ! -e $TEMPLATE ]] || die "$TEMPLATE exists; delete it to rebuild"
	mkdir -p "$DATA/cache"
	local base=$DATA/cache/base.qcow2
	if [[ ! -f $base ]]; then
		echo "Downloading Arch Linux cloud image..."
		curl -fL --progress-bar -o "$base.part" "$IMAGE_URL"
		curl -fsSL -o "$base.SHA256" "$IMAGE_URL.SHA256"
		[[ $(cut -d' ' -f1 "$base.SHA256") == $(sha256sum "$base.part" | cut -d' ' -f1) ]] \
			|| die "checksum mismatch for downloaded image"
		mv "$base.part" "$base"
	fi

	new_rundir
	local new=$DATA/template.qcow2.new
	qemu-img convert -O qcow2 "$base" "$new"
	qemu-img resize -q "$new" "$DISK"

	mkdir "$RUN/seed"
	printf 'instance-id: dvm-build\nlocal-hostname: dvm\n' >"$RUN/seed/meta-data"
	{
		echo '#cloud-config'
		echo 'users: []'
		echo 'write_files:'
		echo '  - path: /root/dvm-provision.sh'
		echo "    permissions: '0755'"
		echo '    encoding: b64'
		echo "    content: $(guest_provision_script | base64 -w0)"
		echo 'runcmd:'
		echo '  - [/root/dvm-provision.sh]'
	} >"$RUN/seed/user-data"
	xorriso -as mkisofs -quiet -o "$RUN/seed.iso" -V cidata -J -r "$RUN/seed"

	qemu_args "$new" writeback "$RUN/console.log"
	QEMU+=(-drive "if=virtio,file=$RUN/seed.iso,format=raw,readonly=on")
	[[ -d /var/cache/pacman/pkg ]] && QEMU+=(-virtfs \
		"local,path=/var/cache/pacman/pkg,mount_tag=hostpkg,security_model=none,readonly=on")
	echo "Provisioning the template (installs ${#GUEST_PKGS[@]} packages; several minutes)..."
	"${QEMU[@]}" & local q=$!
	tail -n +1 -F --pid=$q "$RUN/console.log" 2>/dev/null | grep --line-buffered '^dvm>' || true
	wait $q || die "QEMU failed during provisioning"
	grep -q '^dvm> PROVISION-OK' "$RUN/console.log" || {
		cp "$RUN/console.log" "$DATA/build.log"
		die "provisioning failed; console log saved to $DATA/build.log"
	}
	mv "$new" "$TEMPLATE"
	echo "Template ready: $TEMPLATE"
}

# The script cloud-init runs inside the fresh Arch image. Host values are
# baked in with printf %q.
guest_provision_script() {
	local themes; themes=$(tar -C "${XDG_DATA_HOME:-$HOME/.local/share}" -cz themes 2>/dev/null | base64 -w0 || true)
	cat <<-EOF
	#!/bin/bash
	set -euo pipefail
	exec > >(sed -u 's/^/dvm> /' >/dev/ttyS0) 2>&1
	trap 'systemctl poweroff --no-block' EXIT
	PKGS=(${GUEST_PKGS[*]})
	THEMES=$(printf %q "$themes")
	EOF
	cat <<-'EOF'
	echo "keyring and packages"
	systemctl start pacman-init.service 2>/dev/null || { pacman-key --init; pacman-key --populate archlinux; }
	# The host's package cache is shared read-only (9p) to save downloading;
	# pacman still verifies every package's signature.
	cache=(--cachedir /var/cache/pacman/pkg)
	if mkdir -p /mnt/hostpkg && mount -t 9p -o trans=virtio,version=9p2000.L,ro hostpkg /mnt/hostpkg; then
		cache+=(--cachedir /mnt/hostpkg)
	fi
	for try in 1 2 3; do
		pacman -Syu --noconfirm --needed --noprogressbar --disable-download-timeout "${cache[@]}" "${PKGS[@]}" \
			| grep -E '^(:: |error|warning)' || true
		pacman -Q "${PKGS[@]}" >/dev/null 2>&1 && break
		echo "retrying package install ($try)"
	done
	pacman -Q "${PKGS[@]}" >/dev/null
	umount /mnt/hostpkg 2>/dev/null || true

	echo "user account"
	useradd -m -u 1000 -G audio -s /bin/bash user
	echo 'user ALL=(ALL) NOPASSWD: ALL' >/etc/sudoers.d/dvm; chmod 440 /etc/sudoers.d/dvm
	mkdir -p /var/lib/systemd/linger; touch /var/lib/systemd/linger/user

	echo "app service"
	cat >/usr/local/bin/dvm-guest-app <<'APP'
	#!/bin/bash
	# Started by dvm-app.service: run the host's requested command under
	# waypipe, connected to the host (vsock CID 2).
	c=$CREDENTIALS_DIRECTORY
	theme=$(<"$c/dvm.gtk-theme")
	if [[ -n $theme && -d /usr/share/themes/$theme ]]; then
		export GTK_THEME=$theme
		[[ $theme == *-dark || $theme == *-dark-* ]] && scheme=prefer-dark || scheme=prefer-light
		gsettings set org.gnome.desktop.interface gtk-theme "$theme"
		gsettings set org.gnome.desktop.interface color-scheme "$scheme"
	fi
	cd ~
	# --xwls: X11 apps (Mullvad Browser defaults to X11) via xwayland-satellite
	exec waypipe --vsock --no-gpu -c none --xwls -s "2:$(<"$c/dvm.port")" server -- bash -lc "$(<"$c/dvm.cmd")"
	APP
	chmod 755 /usr/local/bin/dvm-guest-app
	cat >/etc/systemd/system/dvm-app.service <<'UNIT'
	[Unit]
	Description=dvm app shown on the host through waypipe
	ConditionCredential=dvm.cmd
	Wants=user@1000.service
	After=user@1000.service systemd-user-sessions.service
	SuccessAction=poweroff
	FailureAction=poweroff

	[Service]
	User=user
	ImportCredential=dvm.*
	Environment=XDG_RUNTIME_DIR=/run/user/1000 DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus
	ExecStart=/usr/local/bin/dvm-guest-app

	[Install]
	WantedBy=multi-user.target
	UNIT
	# When the template itself is booted, forget the machine ID it gets so
	# every disposable invents its own.
	cat >/etc/systemd/system/dvm-template.service <<'UNIT'
	[Unit]
	Description=Clear machine ID when the dvm template shuts down
	ConditionCredential=dvm.template
	[Service]
	Type=oneshot
	RemainAfterExit=yes
	ExecStart=/bin/true
	ExecStop=/usr/bin/truncate -s 0 /etc/machine-id
	[Install]
	WantedBy=multi-user.target
	UNIT
	systemctl enable dvm-app.service dvm-template.service

	# Guest volume at 100%: the host's mixer is the one volume control.
	mkdir -p /etc/wireplumber/wireplumber.conf.d
	printf 'wireplumber.settings = {\n  device.routes.default-sink-volume = 1.0\n}\n' \
		>/etc/wireplumber/wireplumber.conf.d/dvm.conf

	echo "look and feel"
	[[ -z $THEMES ]] || base64 -d <<<"$THEMES" | tar -C /usr/share -xz --no-same-owner
	mkdir -p /etc/dconf/profile /etc/dconf/db/local.d
	printf 'user-db:user\nsystem-db:local\n' >/etc/dconf/profile/user
	cat >/etc/dconf/db/local.d/00-dvm <<'DCONF'
	[org/gnome/desktop/interface]
	gtk-theme='adw-gtk3-dark'
	color-scheme='prefer-dark'
	font-name='DejaVu Serif 10.5'
	document-font-name='Adwaita Sans 12'
	monospace-font-name='Noto Sans Mono 10.5'
	cursor-theme='Adwaita'
	cursor-size=24
	DCONF
	dconf update

	echo "firefox defaults"
	mkdir -p /usr/lib/firefox/distribution
	cat >/usr/lib/firefox/distribution/policies.json <<'JSON'
	{"policies": {
	  "DisableTelemetry": true, "DisableFirefoxStudies": true,
	  "DontCheckDefaultBrowser": true, "DisableProfileImport": true,
	  "OverrideFirstRunPage": "", "OverridePostUpdatePage": "",
	  "NoDefaultBookmarks": true,
	  "UserMessaging": {"WhatsNew": false, "ExtensionRecommendations": false,
	    "FeatureRecommendations": false, "UrlbarInterventions": false,
	    "SkipOnboarding": true, "MoreFromMozilla": false},
	  "FirefoxHome": {"SponsoredTopSites": false, "SponsoredPocket": false, "Pocket": false}
	}}
	JSON

	echo "mullvad browser and extensions"
	cat >/usr/local/bin/dvm-refresh-browsers <<'REFRESH'
	#!/bin/bash
	# Install or update Mullvad Browser (official tarball; signature must come
	# from the Tor Browser Developers key) and the extensions that both
	# browsers get by policy from local XPIs. Run as root.
	set -euo pipefail
	KEY=EF6E286DDA85EA2A4BA7DE684E2C6E8793298290
	MB=/opt/mullvad-browser
	EXT=/usr/local/share/dvm/extensions
	EXTENSIONS=(vimium-c darkreader)   # addons.mozilla.org slugs
	tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT
	fetch() { curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 "$@"; }

	url=$(fetch -I -o /dev/null -w '%{url_effective}' https://mullvad.net/download/browser/linux-x86_64/latest)
	ver=$(basename "$(dirname "$url")")
	if [[ $(cat "$MB/.dvm-version" 2>/dev/null) != "$ver" ]]; then
		echo "Mullvad Browser $ver"
		fetch -o "$tmp/mb.tar.xz" "$url"
		fetch -o "$tmp/mb.tar.xz.asc" "$url.asc"
		export GNUPGHOME=$tmp/gnupg; mkdir -m 700 "$GNUPGHOME"
		gpg -q --batch --auto-key-locate nodefault,wkd --locate-keys torbrowser@torproject.org >/dev/null
		gpg --batch --status-fd 1 --verify "$tmp/mb.tar.xz.asc" "$tmp/mb.tar.xz" 2>/dev/null \
			| grep -q "^\[GNUPG:\] VALIDSIG .* $KEY\$" \
			|| { echo "Mullvad Browser signature check FAILED" >&2; exit 1; }
		echo "signature OK (Tor Browser Developers)"
		mkdir "$tmp/x"; tar -C "$tmp/x" -xJf "$tmp/mb.tar.xz"
		# Packaged-app mode keeps the profile in ~/.mullvad-browser, so updates
		# replacing $MB don't wipe settings.
		touch "$tmp/x/mullvad-browser/Browser/is-packaged-app"
		chmod -R u+rwX,go+rX,go-w "$tmp/x/mullvad-browser"   # mktemp's 0700 leaks in
		echo "$ver" >"$tmp/x/mullvad-browser/.dvm-version"
		rm -rf "$MB.old"; [[ ! -e $MB ]] || mv "$MB" "$MB.old"
		mv "$tmp/x/mullvad-browser" "$MB"; rm -rf "$MB.old"
	fi

	mkdir -p "$EXT"; ext='{}'
	for e in "${EXTENSIONS[@]}"; do
		fetch -o "$tmp/$e.xpi" "https://addons.mozilla.org/firefox/downloads/latest/$e/latest.xpi"
		id=$(bsdtar -xOf "$tmp/$e.xpi" manifest.json \
			| jq -er '(.browser_specific_settings // .applications).gecko.id')
		install -m644 "$tmp/$e.xpi" "$EXT/$e.xpi"
		ext=$(jq --arg id "$id" --arg url "file://$EXT/$e.xpi" \
			'.[$id] = {installation_mode: "normal_installed", install_url: $url, private_browsing: true}' <<<"$ext")
		echo "extension $e ($id)"
	done
	for f in /usr/lib/firefox/distribution/policies.json "$MB/Browser/distribution/policies.json"; do
		mkdir -p "${f%/*}"; [[ -s $f ]] || echo '{"policies":{}}' >"$f"
		jq --argjson ext "$ext" '.policies.ExtensionSettings = ((.policies.ExtensionSettings // {}) + $ext)' "$f" >"$f.new"
		mv "$f.new" "$f"
	done
	# Updates come from dvm update; a disposable's own update would be lost.
	f=$MB/Browser/distribution/policies.json
	jq '.policies.DisableAppUpdate = true' "$f" >"$f.new" && mv "$f.new" "$f"
	REFRESH
	chmod 755 /usr/local/bin/dvm-refresh-browsers
	printf '#!/bin/sh\nexec /opt/mullvad-browser/Browser/start-mullvad-browser "$@"\n' >/usr/local/bin/mullvad-browser
	chmod 755 /usr/local/bin/mullvad-browser
	/usr/local/bin/dvm-refresh-browsers
	# Start Mullvad Browser once headless so first-run steps (extension
	# welcome tabs, language banner) happen here, not in every disposable.
	runuser -u user -- env HOME=/home/user timeout -s TERM 30 /usr/local/bin/mullvad-browser --headless >/dev/null 2>&1 || true

	echo "boot and cleanup"
	sed -i 's/^GRUB_TIMEOUT=.*/GRUB_TIMEOUT=0/' /etc/default/grub
	grub-mkconfig -o /boot/grub/grub.cfg 2>/dev/null
	mkdir -p /etc/systemd/journald.conf.d
	printf '[Journal]\nStorage=volatile\n' >/etc/systemd/journald.conf.d/dvm.conf
	systemctl disable systemd-networkd-wait-online.service 2>/dev/null || true
	echo dvm >/etc/hostname
	touch /etc/cloud/cloud-init.disabled
	pacman -Scc --noconfirm >/dev/null
	rm -f /var/lib/dbus/machine-id; truncate -s 0 /etc/machine-id
	rm -f /root/dvm-provision.sh
	fstrim -a || true
	echo "PROVISION-OK"
	EOF
}

# --- main ----------------------------------------------------------------------

mkdir -p "$DATA"
case ${1:-} in
	build)    shift; cmd_build "$@" ;;
	template) shift; cmd_template "$@" ;;
	update)   shift; cmd_update ;;
	run)      shift; cmd_run "$@" ;;
	-h|--help) sed -n '2,/^set -e/{/SPDX/d;/^#/s/^# \{0,1\}//p}' "$0" ;;
	*)        cmd_run "$@" ;;
esac