From: Lennart Poettering Date: Wed, 21 Sep 2022 10:40:32 +0000 (+0200) Subject: mkosi: invoke qemu with swtpm, it's 2022! X-Git-Tag: v14~29 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=8becdd8956cf164ee9f11f1bba3f73586c12c55a;p=thirdparty%2Fmkosi.git mkosi: invoke qemu with swtpm, it's 2022! If we find swtpm around we'll use it, otherwise not. Fixes: #1191 --- diff --git a/mkosi/__init__.py b/mkosi/__init__.py index 681df533d..472934252 100644 --- a/mkosi/__init__.py +++ b/mkosi/__init__.py @@ -7693,7 +7693,7 @@ def qemu_check_kvm_support() -> bool: @contextlib.contextmanager -def run_qemu_cmdline(config: MkosiConfig) -> Iterator[List[str]]: +def run_qemu_cmdline(config: MkosiConfig, swtpm_socket: Optional[Path] = None) -> Iterator[List[str]]: accel = "kvm" if config.qemu_kvm else "tcg" firmware, fw_supports_sb = find_qemu_firmware(config) @@ -7753,6 +7753,13 @@ def run_qemu_cmdline(config: MkosiConfig) -> Iterator[List[str]]: "-append", build_auxiliary_output_path(config, ".cmdline").read_text().strip(), ] + if swtpm_socket is not None: + cmdline += [ + "-chardev", f"socket,id=chrtpm,path={swtpm_socket}", + "-tpmdev", "emulator,id=tpm0,chardev=chrtpm", + "-device", "tpm-tis,tpmdev=tpm0", + ] + with contextlib.ExitStack() as stack: if config.qemu_boot == "uefi" and fw_supports_sb: ovmf_vars = stack.enter_context(copy_file_temporary(src=find_ovmf_vars(config), dir=tmp_dir())) @@ -7794,9 +7801,36 @@ def run_qemu_cmdline(config: MkosiConfig) -> Iterator[List[str]]: yield cmdline +@contextlib.contextmanager +def start_swtpm() -> Iterator[Optional[Path]]: + + if not shutil.which("swtpm"): + MkosiPrinter.info("Couldn't find swtpm binary, not invoking qemu with TPM2 device.") + yield None + return + + with tempfile.TemporaryDirectory() as swtpm_state: + swtpm_sock = Path(swtpm_state) / Path("sock") + + cmd = ["swtpm", + "socket", + "--tpm2", + "--tpmstate", f"dir={swtpm_state}", + "--ctrl", f"type=unixio,path={swtpm_sock}", + ] + + swtpm_proc = spawn(cmd) + + yield swtpm_sock + + swtpm_proc.wait() + + def run_qemu(config: MkosiConfig) -> None: - with run_qemu_cmdline(config) as cmdline: - run(cmdline, stdout=sys.stdout, stderr=sys.stderr) + + with start_swtpm() as swtpm_socket: + with run_qemu_cmdline(config, swtpm_socket) as cmdline: + run(cmdline, stdout=sys.stdout, stderr=sys.stderr) def interface_exists(dev: str) -> bool: