Setting Up a Test Environment with QEMU/KVM

About This Task

TPM requires supported hardware to ensure the integrity of a TPM-enabled device. However, a physical TPM is not required for testing. QEMU/KVM with OVMF and swtpm provides a software TPM 2.0 device that you can attach to a virtual machine.

Use this procedure to install the required host dependencies, start the software TPM, launch a VM with UEFI and a virtual TPM (vTPM), and confirm that the TPM device is available inside the guest.

For existing hardware devices with TPM 2.0 support, you must enable TPM in the device firmware settings. Refer to your device user documentation or board support package README file for additional information.

Before You Begin

  • You must have a Linux host with KVM virtualization support enabled.

  • You must have a bianca qcow2 disk image available on the host.

Procedure

  1. Install the required dependencies on the host.

    $ sudo apt install qemu-system-x86 ovmf swtpm tpm2-tools
    
  2. Start the software TPM.

    $ mkdir -p ~/vm/tpm
    $ rm -f ~/vm/tpm/swtpm-sock
    $ swtpm socket --tpm2 \
    --tpmstate dir="$HOME/vm/tpm" \
    --ctrl type=unixio,path="$HOME/vm/tpm/swtpm-sock" \
    --log level=20 \
    --daemon
    
  3. Download the eLxr cloud qcow2 disk image.

    $ mkdir -p ~/vm
    $ wget -P ~/vm https://downloads.elxr.org/elxr-cloud-26.04.02-amd64.qcow2
    

    For additional information, see Deploying eLxr Cloud Virtual Machine Images.

  4. Launch the VM with UEFI and the vTPM.

    $ qemu-system-x86_64 \
    -enable-kvm -m 4096 -smp 4 -cpu host \
    -drive if=pflash,format=raw,readonly=on,file=/usr/share/OVMF/OVMF_CODE_4M.fd \
    -drive if=pflash,format=raw,file=~/vm/OVMF_VARS_4M.fd.current \
    -drive file=~/vm/elxr-cloud-26.04.02-amd64.qcow2,if=virtio,format=qcow2 \
    -chardev socket,id=chrtpm,path="$HOME/vm/tpm/swtpm-sock" \
    -tpmdev emulator,id=tpm0,chardev=chrtpm \
    -device tpm-tis,tpmdev=tpm0 \
    -netdev user,id=net0,hostfwd=tcp::2222-:22 \
    -device virtio-net-pci,netdev=net0 \
    -display none -serial stdio
    
  5. Verify the TPM inside the guest.

    $ ls -l /dev/tpm0 /dev/tpmrm0
    $ cat /sys/class/tpm/tpm0/tpm_version_major
    
    2
    

Results

The command cat /sys/class/tpm/tpm0/tpm_version_major returns 2, confirming that a TPM 2.0 device is available inside the guest. You can now perform Basic TPM Usage and IMA Measured Boot tasks.