Browse Source

Removed the nasty wait from SwtpmHarness::new.

Matthew Carr 2 years ago
parent
commit
046fc3287d
3 changed files with 58 additions and 36 deletions
  1. 32 2
      crates/btnode/Cargo.lock
  2. 2 1
      crates/btnode/Cargo.toml
  3. 24 33
      crates/btnode/src/crypto/tpm.rs

+ 32 - 2
crates/btnode/Cargo.lock

@@ -65,6 +65,7 @@ dependencies = [
  "foreign-types",
  "harness",
  "log",
+ "nix",
  "openssl",
  "serde",
  "serde-big-array",
@@ -190,9 +191,9 @@ checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4"
 
 [[package]]
 name = "libc"
-version = "0.2.126"
+version = "0.2.132"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "349d5a591cd28b49e1d1037471617a32ddcda5731b99419008085f72d5a53836"
+checksum = "8371e4e5341c3a96db127eb2465ac681ced4c433e01dd0e938adbef26ba93ba5"
 
 [[package]]
 name = "log"
@@ -220,6 +221,29 @@ version = "2.5.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d"
 
+[[package]]
+name = "memoffset"
+version = "0.6.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "nix"
+version = "0.25.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e322c04a9e3440c327fca7b6c8a63e6890a32fa2ad689db972425f07e0d22abb"
+dependencies = [
+ "autocfg",
+ "bitflags",
+ "cfg-if",
+ "libc",
+ "memoffset",
+ "pin-utils",
+]
+
 [[package]]
 name = "num-derive"
 version = "0.3.3"
@@ -348,6 +372,12 @@ dependencies = [
  "serde",
 ]
 
+[[package]]
+name = "pin-utils"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
+
 [[package]]
 name = "pkg-config"
 version = "0.3.25"

+ 2 - 1
crates/btnode/Cargo.toml

@@ -23,4 +23,5 @@ foreign-types = "0.3.1"
 
 [dev-dependencies]
 tempdir = "0.3.7"
-ctor = "0.1.22"
+ctor = "0.1.22"
+nix = "0.25.0"

+ 24 - 33
crates/btnode/src/crypto/tpm.rs

@@ -1042,11 +1042,14 @@ impl HasResponseCode for TSS2_RC {
 mod test {
     use super::*;
 
+    use nix::{
+        unistd::Pid,
+        sys::signal::{self, Signal}
+    };
     use tempdir::TempDir;
     use std::{
         fs::File,
         process::{
-            Child,
             Command,
             ExitStatus,
             Stdio
@@ -1062,7 +1065,7 @@ mod test {
             EccScheme,
             KeyDerivationFunctionScheme,
             PublicEccParameters,
-        }
+        }, tcti_ldr::NetworkTPMConfig
     };
     use ctor::ctor;
 
@@ -1081,13 +1084,14 @@ mod test {
 
     struct SwtpmHarness {
         dir: TempDir,
-        swtpm: Child,
-        abrmd: Child,
-        bus_name: String,
+        port: u16,
         state_path: PathBuf,
+        pid_path: PathBuf,
     }
 
     impl SwtpmHarness {
+        const HOST: &'static str = "127.0.0.1";
+
         fn new() -> Result<SwtpmHarness> {
             static PORT: AtomicU16 = AtomicU16::new(21901);
             let port = PORT.fetch_add(2, Ordering::SeqCst);
@@ -1095,10 +1099,10 @@ mod test {
             let dir = TempDir::new(format!("btnode.{port}").as_str())?;
             let dir_path = dir.path();
             let dir_path_display = dir_path.display();
-            let bus_name = format!("btnode.port{port}");
             let conf_path = dir_path.join("swtpm_setup.conf");
             let state_path = dir_path.join("state.bt");
-            let addr = "127.0.0.1";
+            let pid_path = dir_path.join("swtpm.pid");
+            let addr = Self::HOST;
             std::fs::write(&conf_path,
 r#"# Program invoked for creating certificates
 create_certs_tool= /usr/bin/swtpm_localca
@@ -1114,35 +1118,27 @@ active_pcr_banks = sha256
                 .stdout(Stdio::null())
                 .status()?
                 .success_or_err()?;
-            let swtpm = Command::new("swtpm")
+            Command::new("swtpm")
                 .args([
                     "socket",
+                    "--daemon",
                     "--tpm2",
                     "--server", format!("type=tcp,port={port},bindaddr={addr}").as_str(),
                     "--ctrl", format!("type=tcp,port={ctrl_port},bindaddr={addr}").as_str(),
                     "--log", format!("file={dir_path_display}/log.txt,level=5").as_str(),
                     "--flags", "not-need-init,startup-clear",
                     "--tpmstate", format!("dir={dir_path_display}").as_str(),
+                    "--pid", format!("file={}", pid_path.display()).as_str(),
                 ])
-                .spawn()?;
-            let abrmd = Command::new("tpm2-abrmd")
-                .args([
-                    "--session",
-                    format!("--dbus-name={bus_name}").as_str(),
-                    format!("--tcti=swtpm:host={addr},port={port}").as_str(),
-                ])
-                .spawn()?;
-            // TODO: This wait is flakey and system-specific. I need to find a DBus library I can
-            // use to check when tpm2-abrmd has finished starting up and is accepting bus
-            // connections.
-            std::thread::sleep(std::time::Duration::from_millis(50));
-            Ok(SwtpmHarness { dir, swtpm, abrmd, bus_name, state_path })
+                .status()?
+                .success_or_err()?;
+            Ok(SwtpmHarness { dir, port, state_path, pid_path, })
         }
 
         fn context(&self) -> Result<Context> {
-            let config_string = format!("bus_type=session,bus_name={}", self.bus_name);
-            let config = TabrmdConfig::from_str(config_string.as_str())?;
-            Ok(Context::new(TctiNameConf::Tabrmd(config))?)
+            let config_string = format!("host={},port={}", Self::HOST, self.port);
+            let config = NetworkTPMConfig::from_str(config_string.as_str())?;
+            Ok(Context::new(TctiNameConf::Swtpm(config))?)
         }
 
         fn state_path(&self) -> &Path {
@@ -1152,15 +1148,10 @@ active_pcr_banks = sha256
 
     impl Drop for SwtpmHarness {
         fn drop(&mut self) {
-            if let Err(error) = self.abrmd.kill() {
-                error!("failed to kill tpm2-abrmd process with PID {}: {}", self.abrmd.id(), error);
-            }
-            if let Err(error) = self.abrmd.wait() {
-                error!("failed to wait for abrmd with PID {} to halt: {}", self.abrmd.id(), error);
-            }
-            if let Err(error) = self.swtpm.kill() {
-                error!("failed to kill swtpm process with PID {}: {}", self.swtpm.id(), error);
-            }
+            let pid_str = std::fs::read_to_string(&self.pid_path).unwrap();
+            let pid_int = pid_str.parse::<i32>().unwrap();
+            let pid = Pid::from_raw(pid_int);
+            signal::kill(pid, Signal::SIGKILL).unwrap();
         }
     }