{ 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; }); ''; }; }