|
| 1 | +use crate::opt::TpmVersion; |
| 2 | +use crate::util::command_to_string; |
| 3 | +use anyhow::Result; |
| 4 | +use std::process::{Child, Command}; |
| 5 | +use tempfile::TempDir; |
| 6 | + |
| 7 | +// Adapted from https://qemu.readthedocs.io/en/latest/specs/tpm.html |
| 8 | + |
| 9 | +/// Wrapper for running `swtpm`, a software TPM emulator. |
| 10 | +/// |
| 11 | +/// <https://github.com/stefanberger/swtpm> |
| 12 | +/// |
| 13 | +/// The process is killed on drop. |
| 14 | +pub struct Swtpm { |
| 15 | + tmp_dir: TempDir, |
| 16 | + child: Child, |
| 17 | +} |
| 18 | + |
| 19 | +impl Swtpm { |
| 20 | + /// Run `swtpm` in a new process. |
| 21 | + pub fn spawn(version: TpmVersion) -> Result<Self> { |
| 22 | + let tmp_dir = TempDir::new()?; |
| 23 | + let tmp_path = tmp_dir.path().to_str().unwrap(); |
| 24 | + |
| 25 | + let mut cmd = Command::new("swtpm"); |
| 26 | + cmd.args(&[ |
| 27 | + "socket", |
| 28 | + "--tpmstate", |
| 29 | + &format!("dir={tmp_path}"), |
| 30 | + "--ctrl", |
| 31 | + &format!("type=unixio,path={tmp_path}/swtpm-sock"), |
| 32 | + // Terminate when the connection drops. If for any reason |
| 33 | + // this fails, the process will be killed on drop. |
| 34 | + "--terminate", |
| 35 | + // Hide some log spam. |
| 36 | + "--log", |
| 37 | + "file=-", |
| 38 | + ]); |
| 39 | + |
| 40 | + if version == TpmVersion::V2 { |
| 41 | + cmd.arg("--tpm2"); |
| 42 | + } |
| 43 | + |
| 44 | + println!("{}", command_to_string(&cmd)); |
| 45 | + let child = cmd.spawn()?; |
| 46 | + |
| 47 | + Ok(Self { tmp_dir, child }) |
| 48 | + } |
| 49 | + |
| 50 | + /// Get the QEMU args needed to connect to the TPM emulator. |
| 51 | + pub fn qemu_args(&self) -> Vec<String> { |
| 52 | + let socket_path = self.tmp_dir.path().join("swtpm-sock"); |
| 53 | + vec![ |
| 54 | + "-chardev".into(), |
| 55 | + format!("socket,id=chrtpm0,path={}", socket_path.to_str().unwrap()), |
| 56 | + "-tpmdev".into(), |
| 57 | + "emulator,id=tpm0,chardev=chrtpm0".into(), |
| 58 | + "-device".into(), |
| 59 | + "tpm-tis,tpmdev=tpm0".into(), |
| 60 | + ] |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +impl Drop for Swtpm { |
| 65 | + fn drop(&mut self) { |
| 66 | + let _ = self.child.kill(); |
| 67 | + let _ = self.child.wait(); |
| 68 | + } |
| 69 | +} |
0 commit comments