2022-12-28 16:49:45 -06:00
|
|
|
use std::ffi::OsString;
|
2022-12-29 20:39:39 -06:00
|
|
|
use std::io::Write;
|
2022-11-23 04:59:54 -06:00
|
|
|
use std::path::{Path, PathBuf};
|
2022-11-25 06:07:04 -06:00
|
|
|
use std::process::Command;
|
2022-11-23 04:59:54 -06:00
|
|
|
|
2022-12-30 19:57:01 -06:00
|
|
|
use anyhow::{Context, Result};
|
2022-11-25 08:46:33 -06:00
|
|
|
|
2022-11-26 16:19:08 -06:00
|
|
|
pub struct KeyPair {
|
2022-11-25 06:07:04 -06:00
|
|
|
pub private_key: PathBuf,
|
|
|
|
pub public_key: PathBuf,
|
2022-11-23 04:59:54 -06:00
|
|
|
}
|
|
|
|
|
2022-11-26 16:19:08 -06:00
|
|
|
impl KeyPair {
|
2022-11-25 06:07:04 -06:00
|
|
|
pub fn new(public_key: &Path, private_key: &Path) -> Self {
|
2022-11-23 04:59:54 -06:00
|
|
|
Self {
|
2022-11-25 06:07:04 -06:00
|
|
|
public_key: public_key.into(),
|
|
|
|
private_key: private_key.into(),
|
2022-11-23 04:59:54 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-11-26 08:32:43 -06:00
|
|
|
pub fn sign_and_copy(&self, from: &Path, to: &Path) -> Result<()> {
|
2022-12-28 16:49:45 -06:00
|
|
|
let args: Vec<OsString> = vec![
|
|
|
|
OsString::from("--key"),
|
|
|
|
self.private_key.clone().into(),
|
|
|
|
OsString::from("--cert"),
|
|
|
|
self.public_key.clone().into(),
|
|
|
|
from.as_os_str().to_owned(),
|
|
|
|
OsString::from("--output"),
|
|
|
|
to.as_os_str().to_owned(),
|
2022-11-23 04:59:54 -06:00
|
|
|
];
|
|
|
|
|
2022-11-26 08:34:48 -06:00
|
|
|
let output = Command::new("sbsign").args(&args).output()?;
|
2022-11-23 04:59:54 -06:00
|
|
|
|
2022-11-26 08:34:48 -06:00
|
|
|
if !output.status.success() {
|
2022-12-30 19:57:01 -06:00
|
|
|
std::io::stderr()
|
|
|
|
.write_all(&output.stderr)
|
2023-02-27 03:03:37 -06:00
|
|
|
.context("Failed to write output of sbsign to stderr.")?;
|
|
|
|
log::debug!("sbsign failed with args: `{args:?}`.");
|
|
|
|
return Err(anyhow::anyhow!("Failed to sign {to:?}."));
|
2022-11-23 04:59:54 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
2023-01-17 18:58:45 -06:00
|
|
|
|
|
|
|
/// Verify the signature of a PE binary. Return true if the signature was verified.
|
|
|
|
pub fn verify(&self, path: &Path) -> bool {
|
|
|
|
let args: Vec<OsString> = vec![
|
|
|
|
OsString::from("--cert"),
|
|
|
|
self.public_key.clone().into(),
|
|
|
|
path.as_os_str().to_owned(),
|
|
|
|
];
|
|
|
|
|
|
|
|
let output = match Command::new("sbverify").args(&args).output() {
|
|
|
|
Ok(output) => output,
|
|
|
|
Err(_) => return false,
|
|
|
|
};
|
|
|
|
|
|
|
|
if !output.status.success() {
|
|
|
|
if std::io::stderr().write_all(&output.stderr).is_err() {
|
|
|
|
return false;
|
|
|
|
};
|
2023-02-27 03:03:37 -06:00
|
|
|
log::debug!("sbverify failed with args: `{args:?}`.");
|
2023-01-17 18:58:45 -06:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
true
|
|
|
|
}
|
2022-11-23 04:59:54 -06:00
|
|
|
}
|