Files
rust-discovery/crates/server/src/job_signer.rs
T
BuTzZ 6c3203d725
Rust development slice / linux (push) Failing after 1m10s
feat: snapshot Linux-first RMM MVP and pause handover
2026-11-12 22:06:25 +01:00

90 lines
3.0 KiB
Rust

//! Administrative Ed25519 key is separate from TLS CA and update signing keys.
use anyhow::{Result, ensure};
use openssl::{
pkey::{PKey, Private},
sign::Signer,
};
use std::{
fs::{self, OpenOptions},
io::Write,
os::unix::fs::{OpenOptionsExt, PermissionsExt},
path::Path,
};
pub struct JobSigner {
key: PKey<Private>,
pub key_id: String,
}
impl JobSigner {
pub fn load_or_create(path: &Path) -> Result<Self> {
if !path.exists() {
let parent = path
.parent()
.ok_or_else(|| anyhow::anyhow!("key parent missing"))?;
fs::create_dir_all(parent)?;
fs::set_permissions(parent, fs::Permissions::from_mode(0o700))?;
let key = PKey::generate_ed25519()?;
let mut f = OpenOptions::new()
.create_new(true)
.write(true)
.mode(0o600)
.open(path)?;
f.write_all(&key.private_key_to_pem_pkcs8()?)?;
f.sync_all()?;
}
let m = fs::symlink_metadata(path)?;
ensure!(
m.is_file() && m.permissions().mode() & 0o077 == 0,
"unsafe administrative key permissions"
);
let key = PKey::private_key_from_pem(&fs::read(path)?)?;
ensure!(
key.id() == openssl::pkey::Id::ED25519,
"fixed Ed25519 profile required"
);
let public = key.raw_public_key()?;
Ok(Self {
key,
key_id: rmm_domain::jobs::hash(&public),
})
}
pub fn public_key(&self) -> Result<Vec<u8>> {
Ok(self.key.raw_public_key()?)
}
pub fn sign(&self, bytes: &[u8]) -> Result<Vec<u8>> {
Ok(Signer::new_without_digest(&self.key)?.sign_oneshot_to_vec(bytes)?)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ed25519_restart_and_tamper() {
let folder = std::path::PathBuf::from(format!(
"/tmp/opencode/rmm-signing-test-{}",
uuid::Uuid::new_v4()
));
let path = folder.join("key.pem");
let first = JobSigner::load_or_create(&path).unwrap();
let bytes = b"rmm.execution-permit/v1/exact-bytes";
let signature = first.sign(bytes).unwrap();
assert_eq!(signature.len(), 64);
let second = JobSigner::load_or_create(&path).unwrap();
assert_eq!(first.key_id, second.key_id);
let public = PKey::public_key_from_raw_bytes(
&second.public_key().unwrap(),
openssl::pkey::Id::ED25519,
)
.unwrap();
let mut verify = openssl::sign::Verifier::new_without_digest(&public).unwrap();
assert!(verify.verify_oneshot(&signature, bytes).unwrap());
assert!(
!verify
.verify_oneshot(&signature, b"rmm.execution-permit/v1/changed")
.unwrap()
);
fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
assert!(JobSigner::load_or_create(&path).is_err());
fs::remove_dir_all(folder).unwrap();
}
}