#!/bin/bash # Fix swtpm permissions for libvirt TPM emulation # # PROBLEM: libvirtd (running as root) creates per-VM swtpm state directories # as root:root with restrictive mode (0111), but swtpm runs as libvirt-qemu # and can't write to them. This causes "CMD_INIT: 0x9 operation failed". # # SOLUTION: Configure libvirt's swtpm_user/swtpm_group in qemu.conf so # libvirt creates swtpm state dirs owned by libvirt-qemu directly. # # Run this script ONCE with sudo: # sudo bash scripts/fix-swtpm-permissions.sh set -euo pipefail SWTPM_DIR="/var/lib/libvirt/swtpm" QEMU_CONF="/etc/libvirt/qemu.conf" if [[ "$(id -u)" -ne 0 ]]; then echo "ERROR: This script must be run as root (use sudo)" exit 1 fi echo "Fixing swtpm permissions for libvirt TPM emulation..." # 1. Ensure swtpm state directory exists with correct ownership mkdir -p "$SWTPM_DIR" chown libvirt-qemu:libvirt-qemu "$SWTPM_DIR" # 2. Fix any existing stale state directories find "$SWTPM_DIR" -mindepth 1 -type d -exec chown -R libvirt-qemu:libvirt-qemu {} \; 2>/dev/null || true # 3. Configure libvirt to create swtpm dirs as libvirt-qemu # This is the permanent fix - tells libvirt to run swtpm as the correct user if ! grep -q "^swtpm_user" "$QEMU_CONF" 2>/dev/null; then { echo "" echo "# KNEL-Football: Fix swtpm permissions for TPM emulation" echo "swtpm_user = \"libvirt-qemu\"" echo "swtpm_group = \"libvirt-qemu\"" } >> "$QEMU_CONF" echo "Added swtpm_user/swtpm_group to $QEMU_CONF" else echo "swtpm_user already configured in $QEMU_CONF" fi # 4. Restart libvirtd to pick up the config change echo "Restarting libvirtd..." systemctl restart libvirtd 2>/dev/null || systemctl restart libvirt-bin 2>/dev/null || { echo "WARN: Could not restart libvirtd automatically" echo "Please run: sudo systemctl restart libvirtd" } echo "" echo "Done. swtpm permissions fixed permanently." echo "New VMs with TPM will now work correctly."