feat(terra): qBittorrent confined to a ProtonVPN WireGuard netns

The qBittorrent GUI runs as a system unit inside a `proton` network
namespace whose only interface is WireGuard to Proton (NL#490, P2P with
NAT-PMP) and whose only route is the tunnel, so a dropped VPN stalls
torrents instead of leaking them. DNS goes to Proton's 10.2.0.1, with
the host's nscd/resolved sockets hidden since they would answer from the
root namespace. A NAT-PMP loop keeps Proton's forwarded port mapped and
sets it through the netns-local WebUI.

qbittorrent itself is not on PATH: the qbittorrent-vpn launcher and
desktop entry (also the magnet/.torrent handler, via a watch folder)
start the unit, which polkit lets darman start and stop without a
password. The namespace comes up with the GUI and goes away with it.

The client is internet-facing, so it is sandboxed too: it sees only its
own state, the watch folder, the download dir and read-only theming;
the rest of $HOME, /mnt, darman's sops secrets, pass-broker/tailscale
sockets and the session bus are gone. The bus would let it run anything
through systemd --user, so no tray icon or notifications.

Covered by checks.qbittorrent-vpn against a fake Proton peer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-21 11:38:05 +02:00
co-authored by Claude Opus 5.5
parent 71f3dec4b5
commit 2719ed7707
5 changed files with 497 additions and 0 deletions
+199
View File
@@ -0,0 +1,199 @@
# VM test for qbittorrent-vpn.nix. Run:
# nix build .#checks.x86_64-linux.qbittorrent-vpn -L
#
# vpn plays Proton: WireGuard peer at 10.2.0.1 with DNS, a fake NAT-PMP
# gateway and an HTTP echo of the caller's address. client runs the module
# with Qt offscreen. Keys are throwaway, test-only.
{ pkgs }:
let
clientKey = "sD38/QEAIwOEVNFlvNy7k0w/E/PJ9yA6twXF1Ef461Y=";
clientPub = "apnW/TFK+Jx6LDCwSZUgPLYN9+U4b65CHdrGVqfJiEs=";
serverKey = "IHQiVlBcfl2fKus+QiQ5Z6ubIFfg4lb0glszV0vIHnQ=";
serverPub = "4esStqi/GKbgHQpWOwKLLtf3pc/7JvXgeTv+eJ+poE0=";
mappedPort = 41234;
natpmp = pkgs.writers.writePython3 "fake-natpmp" { } ''
import socket
import struct
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("0.0.0.0", 5351))
while True:
req, addr = s.recvfrom(64)
op = req[1]
if op == 0:
resp = struct.pack("!BBHI4s", 0, 128, 0, 1,
socket.inet_aton("1.2.3.4"))
else:
priv = struct.unpack("!H", req[4:6])[0]
resp = struct.pack("!BBHIHHI", 0, 128 + op, 0, 1, priv,
${toString mappedPort}, 60)
s.sendto(resp, addr)
'';
echo = pkgs.writers.writePython3 "echo-addr" { } ''
from http.server import BaseHTTPRequestHandler, HTTPServer
class H(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.end_headers()
self.wfile.write(self.client_address[0].encode())
HTTPServer(("0.0.0.0", 80), H).serve_forever()
'';
in
pkgs.testers.runNixOSTest {
name = "qbittorrent-vpn";
nodes.vpn = {
networking.wireguard.interfaces.wg0 = {
ips = [ "10.2.0.1/24" ];
listenPort = 51820;
privateKeyFile = "${pkgs.writeText "server.key" serverKey}";
peers = [{ publicKey = clientPub; allowedIPs = [ "10.2.0.2/32" ]; }];
};
networking.firewall.allowedUDPPorts = [ 51820 ];
networking.firewall.allowedTCPPorts = [ 80 ];
networking.firewall.trustedInterfaces = [ "wg0" ];
services.dnsmasq = {
enable = true;
resolveLocalQueries = false;
settings = {
interface = "wg0";
bind-dynamic = true;
no-resolv = true;
address = "/tracker.test/10.2.0.1";
};
};
systemd.services.fake-natpmp = {
wantedBy = [ "multi-user.target" ];
serviceConfig.ExecStart = natpmp;
};
systemd.services.echo-addr = {
wantedBy = [ "multi-user.target" ];
serviceConfig.ExecStart = echo;
};
};
nodes.client = { nodes, lib, ... }: {
imports = [ ./qbittorrent-vpn.nix ];
users.users.darman = { isNormalUser = true; uid = 1000; };
environment.systemPackages = [ pkgs.curl pkgs.jq ];
environment.etc."wg/client.key" = { text = clientKey; mode = "0400"; };
homelab.qbittorrentVpn = {
enable = true;
downloadDir = "/mnt/data/Torrents";
privateKeyFile = "/etc/wg/client.key";
peerPublicKey = serverPub;
endpoint = "${nodes.vpn.networking.primaryIPAddress}:51820";
};
systemd.services.qbittorrent-vpn.environment.QT_QPA_PLATFORM = lib.mkForce "offscreen";
# Things the sandbox must hide; the "Wayland socket" is a plain file, only
# its bind is checked.
systemd.tmpfiles.rules = [
"d /mnt/data 0755 darman users -"
"f /mnt/data/other.txt 0644 darman users - other"
"d /home/darman/.ssh 0700 darman users -"
"f /home/darman/.ssh/id_ed25519 0600 darman users - key"
"d /run/user/1000 0700 darman users -"
"f /run/user/1000/wayland-1 0600 darman users -"
"f /run/user/1000/bus 0600 darman users -"
"f /run/pass-broker.sock 0666 root root -"
"d /run/secrets 0755 root root -"
"f /run/secrets/mine 0400 darman users - secret"
];
};
testScript = { nodes, ... }: let vpnIP = nodes.vpn.networking.primaryIPAddress; in ''
import json
start_all()
vpn.wait_for_unit("wireguard-wg0.service")
vpn.wait_for_unit("dnsmasq.service")
vpn.wait_for_unit("fake-natpmp.service")
vpn.wait_for_unit("echo-addr.service")
client.wait_for_unit("multi-user.target")
def ns(cmd):
return client.succeed(f"ip netns exec proton {cmd}")
def api(path):
return ns(f"curl -sf http://127.0.0.1:8080/api/v2/{path}")
with subtest("darman starts it via polkit, launcher queues a magnet"):
client.succeed(
"runuser -u darman -- qbittorrent-vpn "
"'magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567&dn=t'"
)
client.wait_for_unit("qbittorrent-vpn.service")
client.wait_for_unit("proton-netns.service")
client.wait_until_succeeds("ip netns exec proton curl -sf http://127.0.0.1:8080/api/v2/app/version")
with subtest("sandbox: own state and downloads only"):
pid = client.succeed("systemctl show -p MainPID --value qbittorrent-vpn").strip()
def inside(cmd):
return f"nsenter -t {pid} -m -S 1000 -G 100 sh -c '{cmd}'"
client.succeed(inside("[ -e /run/qbittorrent-vpn/wayland ]"))
client.succeed(inside("touch /mnt/data/Torrents/w /home/darman/.config/qBittorrent/w"))
# InaccessiblePaths leaves a mode-000 node behind, so access, not
# existence, is what's checked.
for hidden in ["/home/darman/.ssh/id_ed25519", "/mnt/data/other.txt",
"/run/user/1000/bus", "/run/pass-broker.sock", "/run/secrets/mine"]:
client.fail(inside(f"cat {hidden}"))
for hidden in ["/home/darman/.ssh", "/run/user/1000", "/run/secrets"]:
client.fail(inside(f"ls {hidden}"))
client.fail(inside("touch /home/darman/x.sh /etc/x"))
client.succeed(f"! tr '\\0' '\\n' < /proc/{pid}/environ | grep -q DBUS_SESSION_BUS_ADDRESS")
with subtest("magnet is picked up from the watch folder"):
client.wait_until_succeeds(
"ip netns exec proton curl -sf http://127.0.0.1:8080/api/v2/torrents/info"
" | jq -e 'length == 1'"
)
client.succeed("[ -z \"$(ls -A /home/darman/.local/share/qbittorrent-vpn/watch)\" ]")
with subtest("NAT-PMP port lands in qBittorrent"):
client.wait_until_succeeds(
"ip netns exec proton curl -sf http://127.0.0.1:8080/api/v2/app/preferences"
" | jq -e '.listen_port == ${toString mappedPort}'"
)
prefs = json.loads(api("app/preferences"))
assert prefs["current_network_interface"] == "wg-proton", prefs["current_network_interface"]
assert prefs["save_path"].rstrip("/") == "/mnt/data/Torrents", prefs["save_path"]
with subtest("traffic leaves through the tunnel only"):
assert ns("curl -sf --max-time 5 http://${vpnIP}/") == "10.2.0.2"
# Root namespace still goes direct.
assert client.succeed("curl -sf --max-time 5 http://${vpnIP}/") != "10.2.0.2"
with subtest("qBittorrent resolves via tunnel DNS, not host nscd"):
pid = client.succeed("systemctl show -p MainPID --value qbittorrent-vpn").strip()
out = client.succeed(f"nsenter -t {pid} -m -n getent hosts tracker.test")
assert out.startswith("10.2.0.1"), out
client.succeed(f"nsenter -t {pid} -m sh -c '! [ -S /run/nscd/socket ]'")
client.fail("getent hosts tracker.test")
with subtest("tunnel down = no connectivity, no fallback"):
vpn.succeed("ip link set wg0 down")
client.fail("ip netns exec proton curl -sf --max-time 5 http://${vpnIP}/")
vpn.succeed("ip link set wg0 up && ip addr replace 10.2.0.1/24 dev wg0")
client.wait_until_succeeds("ip netns exec proton curl -sf --max-time 5 http://${vpnIP}/")
with subtest("stopping the GUI tears the namespace down"):
client.succeed("runuser -u darman -- systemctl stop qbittorrent-vpn.service")
client.wait_until_succeeds("! systemctl is-active proton-netns.service")
client.succeed("! systemctl is-active proton-portforward.service")
client.succeed("! [ -e /run/netns/proton ]")
with subtest("polkit grants only this unit"):
client.fail("runuser -u darman -- systemctl start proton-netns.service")
'';
}
+280
View File
@@ -0,0 +1,280 @@
{ config, pkgs, lib, ... }:
# qBittorrent GUI confined to a ProtonVPN WireGuard network namespace: its
# only route is the tunnel, so a dropped VPN stalls torrents instead of
# leaking them. qbittorrent is deliberately NOT on PATH — an unconfined
# launch would bypass all of this; `qbittorrent-vpn` (and the .desktop
# entry, magnet/.torrent handler) start it as a system unit instead.
let
cfg = config.homelab.qbittorrentVpn;
ns = "proton";
iface = "wg-proton";
gateway = "10.2.0.1"; # Proton's in-tunnel DNS + NAT-PMP
webuiPort = 8080; # netns-local only
user = config.users.users.${cfg.user};
# Outside the netns, so the launcher can hand torrents to a running GUI.
stateDir = "${user.home}/.local/share/qbittorrent-vpn";
watchDir = "${stateDir}/watch";
envFile = "${stateDir}/session.env";
qb = pkgs.qbittorrent;
launcher = pkgs.writeShellApplication {
name = "qbittorrent-vpn";
runtimeInputs = [ pkgs.coreutils pkgs.systemd pkgs.gnugrep ];
text = ''
mkdir -p ${watchDir}
for arg in "$@"; do
case "$arg" in
magnet:*) printf '%s\n' "$arg" > "${watchDir}/$(printf '%s' "$arg" | sha1sum | cut -c1-16).magnet" ;;
file://*) p="''${arg#file://}"; cp -- "$(printf '%b' "''${p//%/\\x}")" ${watchDir}/ ;;
*) cp -- "$arg" ${watchDir}/ ;;
esac
done
# The sandbox binds this one socket by name.
if [ "''${WAYLAND_DISPLAY:-${cfg.waylandDisplay}}" != ${cfg.waylandDisplay} ]; then
echo "qbittorrent-vpn: session is $WAYLAND_DISPLAY, sandbox binds ${cfg.waylandDisplay} (homelab.qbittorrentVpn.waylandDisplay)" >&2
exit 1
fi
env | grep -E '^(XDG_CURRENT_DESKTOP|XDG_DATA_DIRS|XCURSOR_[A-Z]+|QT_[A-Z_]+|LANG|LC_[A-Z]+|PATH)=' \
> ${envFile} || true
exec systemctl start qbittorrent-vpn.service
'';
};
desktopItem = pkgs.makeDesktopItem {
name = "qbittorrent-vpn";
desktopName = "qBittorrent (ProtonVPN)";
exec = "qbittorrent-vpn %U";
icon = "${qb}/share/icons/hicolor/scalable/apps/qbittorrent.svg";
categories = [ "Network" "FileTransfer" "P2P" ];
mimeTypes = [ "application/x-bittorrent" "x-scheme-handler/magnet" ];
};
# The only paths qBittorrent can write; the rest of $HOME is invisible.
writable = [
"${user.home}/.config/qBittorrent"
"${user.home}/.local/share/qBittorrent"
"${user.home}/.cache/qBittorrent"
watchDir
cfg.downloadDir
];
# Theme, icons and cursor, read-only; "-" = skip if absent.
themes = map (p: "-${user.home}/${p}") [
".config/qt5ct" ".config/qt6ct" ".config/Kvantum" ".config/fontconfig"
".config/gtk-3.0" ".config/kdeglobals" ".icons" ".local/share/icons"
".local/share/mime" ".nix-profile" ".local/state/nix/profile"
];
# Unsandboxed, as the user: bind sources must exist before the sandbox is
# built. Also re-applies the settings the confinement relies on, since the
# GUI owns qBittorrent.conf and writes it back on exit.
prepare = pkgs.writeShellScript "qbittorrent-vpn-prepare" ''
set -eu
dir="$HOME/.config/qBittorrent"
mkdir -p ${lib.escapeShellArgs writable}
set_() { ${pkgs.crudini}/bin/crudini --ini-options=nospace --set "$dir/qBittorrent.conf" "$1" "$2" "$3"; }
set_ BitTorrent 'Session\Interface' ${iface}
set_ BitTorrent 'Session\InterfaceName' ${iface}
set_ BitTorrent 'Session\DefaultSavePath' ${cfg.downloadDir}
set_ Network PortForwardingEnabled false
set_ Preferences 'WebUI\Enabled' true
set_ Preferences 'WebUI\Address' 127.0.0.1
set_ Preferences 'WebUI\Port' ${toString webuiPort}
set_ Preferences 'WebUI\LocalHostAuth' false
# The WebUI refuses to start without credentials; LocalHostAuth=false means
# they're never checked, so a random hash nobody knows the password to.
${pkgs.crudini}/bin/crudini --get "$dir/qBittorrent.conf" Preferences 'WebUI\Password_PBKDF2' >/dev/null 2>&1 ||
set_ Preferences 'WebUI\Password_PBKDF2' \
"@ByteArray($(head -c16 /dev/urandom | base64 -w0):$(head -c64 /dev/urandom | base64 -w0))"
[ -e "$dir/watched_folders.json" ] ||
echo '{"${watchDir}":{"add_torrent_params":{},"recursive":false}}' > "$dir/watched_folders.json"
'';
# Proton's documented NAT-PMP loop (60s lease, renewed every 45s); the
# mapped port is pushed into qBittorrent whenever it changes.
portForward = pkgs.writeShellScript "proton-portforward" ''
set -u
api=http://127.0.0.1:${toString webuiPort}/api/v2/app
while :; do
port=$(${pkgs.libnatpmp}/bin/natpmpc -g ${gateway} -a 1 0 udp 60 \
| ${pkgs.gnused}/bin/sed -n 's/.*Mapped public port \([0-9]*\).*/\1/p')
${pkgs.libnatpmp}/bin/natpmpc -g ${gateway} -a 1 0 tcp 60 >/dev/null
if [ -n "$port" ]; then
cur=$(${pkgs.curl}/bin/curl -sf $api/preferences | ${pkgs.jq}/bin/jq -r .listen_port) &&
[ "$cur" != "$port" ] &&
${pkgs.curl}/bin/curl -sf --data "json={\"listen_port\":$port}" $api/setPreferences &&
echo "listen port $cur -> $port"
else
echo "NAT-PMP mapping failed (is this a P2P server?)" >&2
fi
sleep 45
done
'';
in
{
options.homelab.qbittorrentVpn = {
enable = lib.mkEnableOption "qBittorrent GUI confined to a ProtonVPN netns";
user = lib.mkOption { type = lib.types.str; default = "darman"; };
# Fixed at build time: the sandbox binds the Wayland socket by path.
uid = lib.mkOption { type = lib.types.int; default = 1000; };
waylandDisplay = lib.mkOption { type = lib.types.str; default = "wayland-1"; };
downloadDir = lib.mkOption { type = lib.types.str; };
privateKeyFile = lib.mkOption {
type = lib.types.path;
description = "WireGuard PrivateKey from the Proton config.";
};
address = lib.mkOption {
type = lib.types.str;
default = "10.2.0.2/32";
description = "IPv4 [Interface] Address. IPv6 is left out: no v6 route, so no v6 leak.";
};
peerPublicKey = lib.mkOption { type = lib.types.str; };
endpoint = lib.mkOption {
type = lib.types.str;
description = "[Peer] Endpoint, ip:port — an IP, so no DNS is needed to bring it up.";
};
};
config = lib.mkIf cfg.enable {
environment.systemPackages = [ launcher desktopItem ];
xdg.mime.defaultApplications = {
"application/x-bittorrent" = "qbittorrent-vpn.desktop";
"x-scheme-handler/magnet" = "qbittorrent-vpn.desktop";
};
# `ip netns exec` would bind this over /etc/resolv.conf; systemd's
# NetworkNamespacePath does not, so the units below do it themselves.
environment.etc."netns/${ns}/resolv.conf".text = "nameserver ${gateway}\n";
# The interface is created in the root namespace and then moved, so its
# UDP socket stays outside (where the internet is) while the interface
# is the netns's only way out.
systemd.services.proton-netns = {
description = "ProtonVPN WireGuard network namespace";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
path = [ pkgs.iproute2 pkgs.wireguard-tools ];
unitConfig.StopWhenUnneeded = true;
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
ExecStop = "${pkgs.iproute2}/bin/ip netns del ${ns}";
};
script = ''
ip netns del ${ns} 2>/dev/null || true
ip netns add ${ns}
ip -n ${ns} link set lo up
ip link add ${iface} type wireguard
ip link set ${iface} netns ${ns}
ip netns exec ${ns} wg set ${iface} \
private-key ${cfg.privateKeyFile} \
peer ${cfg.peerPublicKey} endpoint ${cfg.endpoint} \
allowed-ips 0.0.0.0/0 persistent-keepalive 25
ip -n ${ns} addr add ${cfg.address} dev ${iface}
ip -n ${ns} link set ${iface} up
ip -n ${ns} route add default dev ${iface}
'';
};
systemd.services.qbittorrent-vpn-prepare = {
description = "Prepare qBittorrent (ProtonVPN netns) state";
unitConfig.RequiresMountsFor = [ cfg.downloadDir ];
serviceConfig = {
Type = "oneshot";
User = cfg.user;
ExecStart = prepare;
};
};
# Sandboxed so a compromised client (it's internet-facing) gets its own
# state and downloads, not ~/.ssh, the sops age key or the session.
systemd.services.qbittorrent-vpn = {
description = "qBittorrent (ProtonVPN netns)";
bindsTo = [ "proton-netns.service" ];
requires = [ "qbittorrent-vpn-prepare.service" ];
after = [ "proton-netns.service" "qbittorrent-vpn-prepare.service" ];
wants = [ "proton-portforward.service" ];
unitConfig.RequiresMountsFor = [ cfg.downloadDir ];
environment = {
QT_QPA_PLATFORM = "wayland";
XDG_RUNTIME_DIR = "/run/qbittorrent-vpn";
WAYLAND_DISPLAY = "/run/qbittorrent-vpn/wayland";
};
serviceConfig = {
User = cfg.user;
EnvironmentFile = "-${envFile}";
ExecStart = "${qb}/bin/qbittorrent --confirm-legal-notice";
NetworkNamespacePath = "/run/netns/${ns}";
RuntimeDirectory = "qbittorrent-vpn";
RuntimeDirectoryMode = "0700";
# Hides /home and /run/user; only the paths bound below come back. No
# session bus: through it, systemd --user runs anything unsandboxed.
ProtectHome = "tmpfs";
TemporaryFileSystem = [ "/mnt:ro" "/media:ro" ];
BindPaths = writable
++ [ "-/run/user/${toString cfg.uid}/${cfg.waylandDisplay}:/run/qbittorrent-vpn/wayland" ];
BindReadOnlyPaths = themes
++ [ "/etc/netns/${ns}/resolv.conf:/etc/resolv.conf" ];
InaccessiblePaths = [
# nscd and resolved answer from the ROOT namespace — reachable through
# their sockets, they would resolve outside the tunnel.
"-/run/nscd"
"-/run/systemd/resolve"
# darman-owned sops secrets, and sockets that act on darman's behalf.
"-/run/secrets"
"-/run/secrets.d"
"-/run/pass-broker.sock"
"-/run/tailscale"
"-/run/ssh-unix-local"
];
ProtectSystem = "strict";
PrivateTmp = true;
PrivateDevices = true;
PrivatePIDs = true;
ProtectProc = "invisible";
NoNewPrivileges = true;
CapabilityBoundingSet = "";
RestrictSUIDSGID = true;
ProtectKernelTunables = true;
ProtectKernelModules = true;
ProtectKernelLogs = true;
ProtectControlGroups = true;
ProtectClock = true;
ProtectHostname = true;
RestrictNamespaces = true;
RestrictRealtime = true;
LockPersonality = true;
SystemCallArchitectures = "native";
RestrictAddressFamilies = [ "AF_UNIX" "AF_INET" "AF_INET6" "AF_NETLINK" ];
};
};
systemd.services.proton-portforward = {
description = "ProtonVPN NAT-PMP port forwarding for qBittorrent";
bindsTo = [ "qbittorrent-vpn.service" ];
after = [ "qbittorrent-vpn.service" ];
serviceConfig = {
ExecStart = portForward;
DynamicUser = true;
Restart = "always";
RestartSec = 10;
NetworkNamespacePath = "/run/netns/${ns}";
BindReadOnlyPaths = [ "/etc/netns/${ns}/resolv.conf:/etc/resolv.conf" ];
InaccessiblePaths = [ "-/run/nscd" "-/run/systemd/resolve" ];
};
};
security.polkit.enable = true;
security.polkit.extraConfig = ''
polkit.addRule(function(action, subject) {
if (action.id == "org.freedesktop.systemd1.manage-units" &&
action.lookup("unit") == "qbittorrent-vpn.service" &&
["start", "stop", "restart"].indexOf(action.lookup("verb")) >= 0 &&
subject.user == "${cfg.user}")
return polkit.Result.YES;
});
'';
};
}