repositories

NixDaemon

NixOS pentest workstation as one flake — IceBreaker's successor

clonegit clone https://git.daemon-sec.xyz/NixDaemon.git
virtualisation.nixNix246 lines11.0 KiBraw download
# modules/hosts/laptop/virtualisation.nix
#
# KVM/QEMU as a hypervisor host, with libvirtd + virt-manager. Everything the
# laptop needs to run guests:
#   - virtualisation.libvirtd (qemu, UEFI via OVMF, swtpm TPM, host passthrough)
#   - virt-manager GUI + the user in the libvirtd group
#   - VM storage lives on the spare SSD (/mnt/ssd/vms), NOT the root disk
#   - a one-shot activation service (libvirt-provision) that, idempotently:
#       * starts the default NAT network (192.168.122.0/24)
#       * defines a dir storage pool "vms" → /mnt/ssd/vms/images
#       * defines the "kali" domain from the qcow2 extracted into that pool
#
# So after one `nixos-rebuild switch` the Kali VM is defined and ready in
# virt-manager / `virsh`, with its disk on the SSD. The user must re-login once
# for the new libvirtd group to take effect in their session (or use sudo
# virsh / virt-manager prompts for the system connection until then).
#
# The qcow2 is extracted out-of-band from ~/Downloads (it is 16 GB, not a nix
# artifact); the provision service skips the domain if the disk is not present
# yet, so a missing/not-yet-extracted image never breaks activation.
{ ... }:
{
  flake.nixosModules.laptop-virt =
    { config, pkgs, lib, user, ... }:
    let
      vmRoot = "/mnt/ssd/vms";
      images = "${vmRoot}/images";
      kaliDisk = "${images}/kali.qcow2";

      # libvirt domain for the Kali guest. The kali-*-qemu-amd64 image is a
      # BIOS/MBR disk, so this boots with SeaBIOS (NOT UEFI) — forcing
      # firmware="efi" would leave it unbootable. q35, virtio disk/net, SPICE +
      # QXL display, on the default NAT network. 4 vCPU / 6 GiB — tune in
      # virt-manager.
      kaliXml = pkgs.writeText "kali.xml" ''
        <domain type="kvm">
          <name>kali</name>
          <memory unit="GiB">6</memory>
          <currentMemory unit="GiB">6</currentMemory>
          <vcpu>4</vcpu>
          <os>
            <type arch="x86_64" machine="q35">hvm</type>
            <boot dev="hd"/>
          </os>
          <features><acpi/><apic/></features>
          <cpu mode="host-passthrough" check="none" migratable="on"/>
          <clock offset="utc">
            <timer name="rtc" tickpolicy="catchup"/>
            <timer name="pit" tickpolicy="delay"/>
            <timer name="hpet" present="no"/>
          </clock>
          <on_poweroff>destroy</on_poweroff>
          <on_reboot>restart</on_reboot>
          <on_crash>destroy</on_crash>
          <devices>
            <emulator>${pkgs.qemu}/bin/qemu-system-x86_64</emulator>
            <disk type="file" device="disk">
              <driver name="qemu" type="qcow2" discard="unmap"/>
              <source file="${kaliDisk}"/>
              <target dev="vda" bus="virtio"/>
            </disk>
            <interface type="network">
              <source network="default"/>
              <model type="virtio"/>
            </interface>
            <!-- host↔guest file share (loot). In Kali:
                 sudo mkdir -p /mnt/host &&
                 sudo mount -t 9p -o trans=virtio,version=9p2000.L,msize=512000 hostshare /mnt/host
                 (add to /etc/fstab to persist). Backed by ${vmRoot}/share. -->
            <filesystem type="mount" accessmode="mapped">
              <driver type="path"/>
              <source dir="${vmRoot}/share"/>
              <target dir="hostshare"/>
            </filesystem>
            <!-- The NixOS host's tools, exposed read-only to Kali. NixOS
                 binaries are dynamically linked against /nix/store paths (their
                 ELF interpreter lives there), so BOTH the store and the system
                 profile must be shared for them to run. In Kali:
                   sudo /mnt/host/mount-host-tools.sh   (hostshare mounted first)
                 then every host tool (netexec, impacket, certipy, the HTB
                 suite: htbbox/htbscan/dmnfuzz/revshell…) is on PATH via
                 /opt/host-sw/bin. Read-only: the guest cannot alter the store. -->
            <filesystem type="mount" accessmode="passthrough">
              <driver type="path"/>
              <source dir="/nix/store"/>
              <target dir="nixstore"/>
              <readonly/>
            </filesystem>
            <filesystem type="mount" accessmode="passthrough">
              <driver type="path"/>
              <source dir="/run/current-system/sw"/>
              <target dir="hostsw"/>
              <readonly/>
            </filesystem>
            <!-- SPICE agent: clipboard + auto screen-resize -->
            <channel type="spicevmc">
              <target type="virtio" name="com.redhat.spice.0"/>
            </channel>
            <!-- QEMU guest agent: host can query/shutdown the guest cleanly -->
            <channel type="unix">
              <target type="virtio" name="org.qemu.guest_agent.0"/>
            </channel>
            <input type="tablet" bus="usb"/>
            <graphics type="spice" autoport="yes">
              <listen type="address" address="127.0.0.1"/>
              <gl enable="no"/>
            </graphics>
            <sound model="ich9"/>
            <video><model type="qxl" heads="1"/></video>
            <!-- three hot-redirect USB slots: in virt-manager use
                 Virtual Machine ▸ Redirect USB device to attach a WiFi
                 adapter / Proxmark / Rubber Ducky to Kali on the fly. -->
            <redirdev bus="usb" type="spicevmc"/>
            <redirdev bus="usb" type="spicevmc"/>
            <redirdev bus="usb" type="spicevmc"/>
            <!-- Permanent USB passthrough of a specific device: find it with
                 `lsusb`, then add (vendor/product in hex) and redefine:
                 <hostdev mode="subsystem" type="usb" managed="yes">
                   <source><vendor id="0x0bda"/><product id="0x8812"/></source>
                 </hostdev> -->
            <memballoon model="virtio"/>
            <rng model="virtio"><backend model="random">/dev/urandom</backend></rng>
          </devices>
        </domain>
      '';
    in
    {
      # ---- the hypervisor ----
      virtualisation.libvirtd = {
        enable = true;
        qemu = {
          package = pkgs.qemu;
          runAsRoot = true;
          swtpm.enable = true; # emulated TPM 2.0 for guests that want it
          # OVMF (UEFI) firmware ships by default on this nixpkgs, so the
          # domain's os firmware="efi" resolves with no extra config.
        };
        onBoot = "ignore"; # only autostart guests that are marked autostart
        onShutdown = "shutdown";
      };

      # ---- passthrough groundwork (IOMMU / VFIO / nested) ----
      # AMD-Vi on, pass-through DMA remapping. Enables *any* device passthrough
      # (PCI/USB) without binding anything yet — safe on this laptop.
      boot.kernelParams = [ "amd_iommu=on" "iommu=pt" ];
      # VFIO stubs loaded and ready; nothing is bound to vfio-pci until you add
      # a device id below (see "PCI passthrough" note), so the host keeps every
      # device including the NVIDIA dGPU.
      boot.kernelModules = [ "vfio" "vfio_iommu_type1" "vfio_pci" ];
      # Nested virtualisation, so you can run VMs/containers-in-KVM inside Kali.
      boot.extraModprobeConfig = "options kvm_amd nested=1";

      # PCI passthrough (opt-in, left OFF). Full GPU passthrough on this muxless
      # NVIDIA laptop will fight nvidia.nix and can kill the host display, so it
      # is deliberately not wired. To pass a *discrete* PCI device:
      #   1. nixos-rebuild switch (for the IOMMU params above), reboot
      #   2. find its group + id:
      #        for d in /sys/kernel/iommu_groups/*/devices/*; do
      #          echo "group $(basename "$(dirname "$(dirname "$d")")"): \
      #          $(basename "$d") $(lspci -nns "$(basename "$d")" 2>/dev/null)"; done | sort -V
      #   3. bind it at boot by appending to boot.kernelParams here, e.g.:
      #        "vfio-pci.ids=10de:1c8d,10de:0fb9"
      #      (every function in the device's IOMMU group must go to the guest)
      #   4. add a <hostdev> for it to the domain XML below.

      # SPICE USB redirection + the GUI + the virtiofs helper.
      virtualisation.spiceUSBRedirection.enable = true;
      programs.virt-manager.enable = true;
      programs.dconf.enable = true; # virt-manager stores its settings in dconf

      environment.systemPackages = with pkgs; [
        virt-viewer # remote-viewer for SPICE consoles
        spice-gtk
        swtpm
        qemu
        virtio-win # virtio driver ISO, handy for future Windows guests
      ];

      # The user drives the SYSTEM libvirt connection (qemu:///system) without
      # sudo. Takes effect after the next login.
      users.users.${user}.extraGroups = [ "libvirtd" "kvm" ];

      # VM tree on the spare SSD, owned by the user + libvirtd group so both the
      # user and the daemon can write. The root disk is left alone.
      systemd.tmpfiles.rules = [
        "d ${vmRoot} 0775 ${user} libvirtd - -"
        "d ${images} 0775 ${user} libvirtd - -"
        "d ${vmRoot}/share 0775 ${user} libvirtd - -" # host↔guest 9p share
      ];

      # ---- declarative provisioning at activation ----
      # Idempotent: defines the default network, the SSD pool, and the kali
      # domain only when they are missing. Safe to run on every boot.
      systemd.services.libvirt-provision = {
        description = "Provision libvirt default network, SSD pool and Kali domain";
        after = [ "libvirtd.service" ];
        requires = [ "libvirtd.service" ];
        wantedBy = [ "multi-user.target" ];
        serviceConfig = {
          Type = "oneshot";
          RemainAfterExit = true;
        };
        path = [ pkgs.libvirt ];
        script = ''
          set -eu
          VIRSH="virsh -c qemu:///system"

          # 1. default NAT network (192.168.122.0/24)
          if ! $VIRSH net-info default >/dev/null 2>&1; then
            # mktemp, not a fixed name: this runs as root and /tmp is shared.
            xml=$(mktemp)
            cat > "$xml" <<'EOF'
          <network>
            <name>default</name>
            <forward mode="nat"/>
            <bridge name="virbr0" stp="on" delay="0"/>
            <ip address="192.168.122.1" netmask="255.255.255.0">
              <dhcp><range start="192.168.122.2" end="192.168.122.254"/></dhcp>
            </ip>
          </network>
          EOF
            $VIRSH net-define "$xml" || true
            rm -f "$xml"
          fi
          $VIRSH net-autostart default >/dev/null 2>&1 || true
          $VIRSH net-start default >/dev/null 2>&1 || true

          # 2. storage pool on the SSD
          if ! $VIRSH pool-info vms >/dev/null 2>&1; then
            $VIRSH pool-define-as vms dir --target ${images} || true
          fi
          $VIRSH pool-autostart vms >/dev/null 2>&1 || true
          $VIRSH pool-start vms >/dev/null 2>&1 || true

          # 3. the Kali domain — only once the disk has been extracted
          if [ -f ${kaliDisk} ]; then
            if ! $VIRSH dominfo kali >/dev/null 2>&1; then
              $VIRSH define ${kaliXml} || true
            fi
          else
            echo "libvirt-provision: ${kaliDisk} not present yet; skipping kali domain" >&2
          fi
        '';
      };
    };
}