summary refs log tree commit diff
path: root/dvm
diff options
context:
space:
mode:
Diffstat (limited to 'dvm')
-rwxr-xr-xdvm424
1 files changed, 424 insertions, 0 deletions
diff --git a/dvm b/dvm
new file mode 100755
index 0000000..b0cfe3c
--- /dev/null
+++ b/dvm
@@ -0,0 +1,424 @@
+#!/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.
+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/{/^#/s/^# \{0,1\}//p}' "$0" ;;
+ *) cmd_run "$@" ;;
+esac