]> git.ipfire.org Git - thirdparty/mkosi.git/commitdiff
mkosi: invoke qemu with swtpm, it's 2022!
authorLennart Poettering <lennart@poettering.net>
Wed, 21 Sep 2022 10:40:32 +0000 (12:40 +0200)
committerDaan De Meyer <daan.j.demeyer@gmail.com>
Wed, 21 Sep 2022 16:36:09 +0000 (18:36 +0200)
If we find swtpm around we'll use it, otherwise not.

Fixes: #1191
mkosi/__init__.py

index 681df533de079b1b5d64e8ca54f9f9f59f449615..472934252e976c8fa5f9e2dea418b1c3c0eba5bc 100644 (file)
@@ -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: