2022-12-28 17:49:45 -05:00
|
|
|
use std::ffi::OsString;
|
2022-12-29 21:39:39 -05:00
|
|
|
use std::io::Write;
|
2022-11-23 05:59:54 -05:00
|
|
|
use std::path::{Path, PathBuf};
|
2022-11-25 07:07:04 -05:00
|
|
|
use std::process::Command;
|
2022-11-23 05:59:54 -05:00
|
|
|
|
2022-12-30 20:57:01 -05:00
|
|
|
use anyhow::{Context, Result};
|
2022-11-25 09:46:33 -05:00
|
|
|
|
2022-11-26 17:19:08 -05:00
|
|
|
pub struct KeyPair {
|
2022-11-25 07:07:04 -05:00
|
|
|
pub private_key: PathBuf,
|
|
|
|
pub public_key: PathBuf,
|
2022-11-23 05:59:54 -05:00
|
|
|
}
|
|
|
|
|
2022-11-26 17:19:08 -05:00
|
|
|
impl KeyPair {
|
2022-11-25 07:07:04 -05:00
|
|
|
pub fn new(public_key: &Path, private_key: &Path) -> Self {
|
2022-11-23 05:59:54 -05:00
|
|
|
Self {
|
2022-11-25 07:07:04 -05:00
|
|
|
public_key: public_key.into(),
|
|
|
|
private_key: private_key.into(),
|
2022-11-23 05:59:54 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-11-26 09:32:43 -05:00
|
|
|
pub fn sign_and_copy(&self, from: &Path, to: &Path) -> Result<()> {
|
2022-12-28 17:49:45 -05: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 05:59:54 -05:00
|
|
|
];
|
|
|
|
|
2022-11-26 09:34:48 -05:00
|
|
|
let output = Command::new("sbsign").args(&args).output()?;
|
2022-11-23 05:59:54 -05:00
|
|
|
|
2022-11-26 09:34:48 -05:00
|
|
|
if !output.status.success() {
|
2022-12-30 20:57:01 -05:00
|
|
|
std::io::stderr()
|
|
|
|
.write_all(&output.stderr)
|
|
|
|
.context("Failed to write output of sbsign to stderr")?;
|
2022-11-25 09:15:58 -05:00
|
|
|
return Err(anyhow::anyhow!(
|
|
|
|
"Failed to sign file using sbsign with args `{:?}`",
|
|
|
|
&args
|
2022-11-26 17:19:08 -05:00
|
|
|
));
|
2022-11-23 05:59:54 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
2023-01-17 19:58:45 -05: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;
|
|
|
|
};
|
|
|
|
println!(
|
|
|
|
"Failed to verify signature using sbverify with args `{:?}`",
|
|
|
|
&args
|
|
|
|
);
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
true
|
|
|
|
}
|
2022-11-23 05:59:54 -05:00
|
|
|
}
|