1155 lines
46 KiB
Rust
1155 lines
46 KiB
Rust
//! Passive TLS renewal. SQLite commits only public CSR/certificate/version data;
|
|
//! private keys stay in immutable, protected files outside the telemetry WAL.
|
|
//! Mutation/current callers retain the exclusive agent-state journal lock.
|
|
//! `read_only_current` is the bounded, snapshot-only stable-updater exception.
|
|
use anyhow::{Context, Result, ensure};
|
|
use rcgen::{CertificateParams, DnType, KeyPair};
|
|
use rusqlite::{Connection, OptionalExtension, params};
|
|
use rustls::{RootCertStore, pki_types::UnixTime, sign::CertifiedKey};
|
|
use serde::Deserialize;
|
|
use std::{io::Cursor, sync::Arc, time::Duration};
|
|
use uuid::Uuid;
|
|
use x509_parser::prelude::*;
|
|
|
|
pub struct DeviceIdentity {
|
|
pub certificate_pem: Vec<u8>,
|
|
pub private_key_pem: Vec<u8>,
|
|
}
|
|
/// Never supplies private bytes to the SQLite writer.
|
|
pub trait KeyFiles {
|
|
fn read(&self, version: Uuid) -> Result<Vec<u8>>;
|
|
/// CreateNew, protected before writing, and durable before returning.
|
|
fn create(&self, version: Uuid, key: &[u8]) -> Result<()>;
|
|
}
|
|
pub struct RotationStore {
|
|
agent: Uuid,
|
|
enrollment: u64,
|
|
ca: Vec<u8>,
|
|
}
|
|
pub struct PendingRequest {
|
|
pub identity: DeviceIdentity,
|
|
pub csr_pem: String,
|
|
base: Uuid,
|
|
version: Uuid,
|
|
}
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct RenewalResponse {
|
|
agent_id: Uuid,
|
|
certificate_pem: String,
|
|
overlap_seconds: u32,
|
|
}
|
|
impl RotationStore {
|
|
pub fn new(agent: Uuid, enrollment: u64, ca: Vec<u8>) -> Result<Self> {
|
|
ensure!(
|
|
!agent.is_nil() && enrollment > 0,
|
|
"ROTATION_IDENTITY_INVALID"
|
|
);
|
|
Ok(Self {
|
|
agent,
|
|
enrollment,
|
|
ca,
|
|
})
|
|
}
|
|
/// Called under the journal lock. Legacy files are eligible exactly once,
|
|
/// before any selector exists. There is no recovery fallback or reenrollment.
|
|
pub fn initialize(
|
|
&self,
|
|
db: &mut Connection,
|
|
keys: &impl KeyFiles,
|
|
cert: &[u8],
|
|
now: i64,
|
|
) -> Result<()> {
|
|
let tx = db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
|
|
tx.execute_batch("CREATE TABLE IF NOT EXISTS tls_versions(version TEXT PRIMARY KEY,certificate BLOB,csr TEXT);
|
|
CREATE TABLE IF NOT EXISTS tls_rotation(id INTEGER PRIMARY KEY CHECK(id=1),schema_version INTEGER NOT NULL,agent TEXT NOT NULL,enrollment INTEGER NOT NULL,current_version TEXT NOT NULL REFERENCES tls_versions(version),pending_version TEXT REFERENCES tls_versions(version));
|
|
CREATE TABLE IF NOT EXISTS tls_idle_admission(version TEXT PRIMARY KEY REFERENCES tls_versions(version),witness BLOB NOT NULL CHECK(length(witness) BETWEEN 1 AND 32768));
|
|
CREATE TRIGGER IF NOT EXISTS tls_idle_no_update BEFORE UPDATE ON tls_idle_admission BEGIN SELECT RAISE(ABORT,'ROTATION_IDLE_IMMUTABLE');END;
|
|
CREATE TRIGGER IF NOT EXISTS tls_idle_no_delete BEFORE DELETE ON tls_idle_admission BEGIN SELECT RAISE(ABORT,'ROTATION_IDLE_IMMUTABLE');END;")?;
|
|
let present: bool = tx.query_row("SELECT EXISTS(SELECT 1 FROM tls_rotation)", [], |r| {
|
|
r.get(0)
|
|
})?;
|
|
if !present {
|
|
let count: u64 = tx.query_row("SELECT count(*) FROM tls_versions", [], |r| r.get(0))?;
|
|
ensure!(count == 0, "ROTATION_SELECTOR_MISSING");
|
|
self.verify(cert, &keys.read(Uuid::nil())?, now)?;
|
|
tx.execute(
|
|
"INSERT INTO tls_versions VALUES(?1,?2,NULL)",
|
|
params![Uuid::nil().to_string(), cert],
|
|
)?;
|
|
tx.execute(
|
|
"INSERT INTO tls_rotation VALUES(1,1,?1,?2,?3,NULL)",
|
|
params![
|
|
self.agent.to_string(),
|
|
self.enrollment,
|
|
Uuid::nil().to_string()
|
|
],
|
|
)?;
|
|
}
|
|
self.current(&tx, keys, now)?;
|
|
tx.commit()?;
|
|
Ok(())
|
|
}
|
|
fn selector(&self, db: &Connection) -> Result<(Uuid, Option<Uuid>)> {
|
|
let (schema, agent, enrollment, current, pending): (u32,String,u64,String,Option<String>) = db.query_row("SELECT schema_version,agent,enrollment,current_version,pending_version FROM tls_rotation WHERE id=1",[],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?)))?;
|
|
ensure!(
|
|
schema == 1 && agent == self.agent.to_string() && enrollment == self.enrollment,
|
|
"ROTATION_IDENTITY_CHANGED"
|
|
);
|
|
Ok((
|
|
Uuid::parse_str(¤t)?,
|
|
pending.map(|s| Uuid::parse_str(&s)).transpose()?,
|
|
))
|
|
}
|
|
pub fn current(
|
|
&self,
|
|
db: &Connection,
|
|
keys: &impl KeyFiles,
|
|
now: i64,
|
|
) -> Result<DeviceIdentity> {
|
|
let (version, _) = self.selector(db)?;
|
|
let cert: Vec<u8> = db.query_row(
|
|
"SELECT certificate FROM tls_versions WHERE version=?1",
|
|
[version.to_string()],
|
|
|r| r.get(0),
|
|
)?;
|
|
let key = keys.read(version)?;
|
|
self.verify(&cert, &key, now)?;
|
|
Ok(DeviceIdentity {
|
|
certificate_pem: cert,
|
|
private_key_pem: key,
|
|
})
|
|
}
|
|
/// Independent stable-updater mTLS read ONLY. This cannot initialize,
|
|
/// rotate, acknowledge, alter selectors, enroll or allocate a generation.
|
|
/// Concurrent rotation may make transport fail; it never selects a key
|
|
/// from another device or treats old TLS as an execution/sync lease.
|
|
pub fn read_only_current(
|
|
&self,
|
|
db: &Connection,
|
|
keys: &impl KeyFiles,
|
|
now: i64,
|
|
) -> Result<DeviceIdentity> {
|
|
ensure!(
|
|
unsafe { rusqlite::ffi::sqlite3_db_readonly(db.handle(), c"main".as_ptr()) } == 1
|
|
&& db.query_row("PRAGMA query_only", [], |r| r.get::<_, bool>(0))?
|
|
&& !db.query_row("PRAGMA trusted_schema", [], |r| r.get::<_, bool>(0))?,
|
|
"ROTATION_READ_ONLY_CONNECTION_REQUIRED"
|
|
);
|
|
let tx = db.unchecked_transaction()?;
|
|
for table in ["tls_rotation", "tls_versions"] {
|
|
ensure!(
|
|
tx.query_row(
|
|
"SELECT type FROM sqlite_master WHERE name=?1",
|
|
[table],
|
|
|r| r.get::<_, String>(0)
|
|
)? == "table",
|
|
"ROTATION_SELECTOR_MUST_BE_TABLE"
|
|
);
|
|
}
|
|
let (version, _) = self.selector(&tx)?;
|
|
let length: u64 = tx.query_row(
|
|
"SELECT length(certificate) FROM tls_versions WHERE version=?1",
|
|
[version.to_string()],
|
|
|r| r.get(0),
|
|
)?;
|
|
ensure!(length > 0 && length <= 32768, "ROTATION_CERTIFICATE_LIMIT");
|
|
let identity = self.current(&tx, keys, now)?;
|
|
ensure!(
|
|
self.selector(&tx)?.0 == version,
|
|
"ROTATION_READ_ONLY_SNAPSHOT_CHANGED"
|
|
);
|
|
tx.commit()?;
|
|
Ok(identity)
|
|
}
|
|
fn verify(&self, pem: &[u8], key: &[u8], now: i64) -> Result<(i64, i64)> {
|
|
ensure!(
|
|
pem.len() <= 32768 && key.len() <= 16384,
|
|
"ROTATION_IDENTITY_LIMIT"
|
|
);
|
|
let chain =
|
|
rustls_pemfile::certs(&mut Cursor::new(pem)).collect::<std::io::Result<Vec<_>>>()?;
|
|
let leaf = chain.first().context("ROTATION_CERTIFICATE_MISSING")?;
|
|
let (rest, cert) = X509Certificate::from_der(leaf.as_ref())
|
|
.map_err(|_| anyhow::anyhow!("ROTATION_CERTIFICATE_PARSE"))?;
|
|
let names = cert.subject().iter_common_name().collect::<Vec<_>>();
|
|
ensure!(
|
|
rest.is_empty()
|
|
&& names.len() == 1
|
|
&& names[0].as_str()? == self.agent.to_string()
|
|
&& !cert.is_ca(),
|
|
"ROTATION_AGENT_MISMATCH"
|
|
);
|
|
let mut roots = RootCertStore::empty();
|
|
for ca in rustls_pemfile::certs(&mut Cursor::new(&self.ca)) {
|
|
roots.add(ca?)?;
|
|
}
|
|
ensure!(!roots.is_empty(), "ROTATION_CA_MISSING");
|
|
let provider = Arc::new(rustls::crypto::ring::default_provider());
|
|
let verifier = rustls::server::WebPkiClientVerifier::builder_with_provider(
|
|
Arc::new(roots),
|
|
provider.clone(),
|
|
)
|
|
.build()?;
|
|
verifier.verify_client_cert(
|
|
leaf,
|
|
&chain[1..],
|
|
UnixTime::since_unix_epoch(Duration::from_secs(u64::try_from(now)?)),
|
|
)?;
|
|
let key =
|
|
rustls_pemfile::private_key(&mut Cursor::new(key))?.context("ROTATION_KEY_MISSING")?;
|
|
// from_der allows unknown key consistency; require an actual match.
|
|
CertifiedKey::from_der(chain.clone(), key, &provider)?.keys_match()?;
|
|
let begin = cert.validity().not_before.timestamp();
|
|
let end = cert.validity().not_after.timestamp();
|
|
ensure!(
|
|
begin <= now && now < end,
|
|
"ROTATION_EXPIRED_RECOVERY_REQUIRED"
|
|
);
|
|
Ok((begin, end))
|
|
}
|
|
pub fn due(&self, db: &Connection, keys: &impl KeyFiles, now: i64) -> Result<bool> {
|
|
let identity = self.current(db, keys, now)?;
|
|
let (begin, end) =
|
|
self.verify(&identity.certificate_pem, &identity.private_key_pem, now)?;
|
|
Ok(self.selector(db)?.1.is_some()
|
|
|| now.saturating_sub(begin) >= 20 * 86400
|
|
|| end.saturating_sub(now) <= 10 * 86400)
|
|
}
|
|
pub fn has_pending(&self, db: &Connection) -> Result<bool> {
|
|
Ok(self.selector(db)?.1.is_some())
|
|
}
|
|
/// Retained local maintenance context, never readiness or job authority.
|
|
/// Legacy passive requests deliberately have no active-idle admission.
|
|
pub fn pending_idle_admission(&self, db: &Connection) -> Result<Option<Vec<u8>>> {
|
|
let Some(version) = self.selector(db)?.1 else {
|
|
return Ok(None);
|
|
};
|
|
Ok(db
|
|
.query_row(
|
|
"SELECT witness FROM tls_idle_admission WHERE version=?1",
|
|
[version.to_string()],
|
|
|r| r.get(0),
|
|
)
|
|
.optional()?)
|
|
}
|
|
/// A crash before the transaction leaves only an unselected key file. A
|
|
/// response loss reuses the committed CSR/key and still-valid old mTLS leaf.
|
|
pub fn prepare(
|
|
&self,
|
|
db: &mut Connection,
|
|
keys: &impl KeyFiles,
|
|
now: i64,
|
|
) -> Result<PendingRequest> {
|
|
self.prepare_with_idle_admission(db, keys, now, None)
|
|
}
|
|
/// Commit a caller-verified idle witness in the SAME transaction as the
|
|
/// pending CSR/selector. A resumed active request must retain exact bytes.
|
|
pub fn prepare_with_idle_admission(
|
|
&self,
|
|
db: &mut Connection,
|
|
keys: &impl KeyFiles,
|
|
now: i64,
|
|
admission: Option<&[u8]>,
|
|
) -> Result<PendingRequest> {
|
|
ensure!(
|
|
admission.is_none_or(|bytes| !bytes.is_empty() && bytes.len() <= 32768),
|
|
"ROTATION_IDLE_ADMISSION_LIMIT"
|
|
);
|
|
let identity = self.current(db, keys, now)?;
|
|
let tx = db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
|
|
let (base, pending) = self.selector(&tx)?;
|
|
if let (Some(version), Some(expected)) = (pending, admission) {
|
|
let saved: Option<Vec<u8>> = tx
|
|
.query_row(
|
|
"SELECT witness FROM tls_idle_admission WHERE version=?1",
|
|
[version.to_string()],
|
|
|r| r.get(0),
|
|
)
|
|
.optional()?;
|
|
ensure!(
|
|
saved.as_deref() == Some(expected),
|
|
"ROTATION_IDLE_ADMISSION_CHANGED"
|
|
);
|
|
}
|
|
let (version, csr_pem) = if let Some(version) = pending {
|
|
ensure!(
|
|
!version.is_nil() && version != base,
|
|
"ROTATION_PENDING_CONFLICT"
|
|
);
|
|
let csr: String = tx.query_row(
|
|
"SELECT csr FROM tls_versions WHERE version=?1 AND certificate IS NULL",
|
|
[version.to_string()],
|
|
|r| r.get(0),
|
|
)?;
|
|
let key = KeyPair::from_pem(std::str::from_utf8(&keys.read(version)?)?)?;
|
|
let (rest, pem) = x509_parser::pem::parse_x509_pem(csr.as_bytes())
|
|
.map_err(|_| anyhow::anyhow!("ROTATION_PENDING_CSR"))?;
|
|
ensure!(
|
|
rest.is_empty() && pem.label == "CERTIFICATE REQUEST",
|
|
"ROTATION_PENDING_CSR"
|
|
);
|
|
let (rest, request) = X509CertificationRequest::from_der(&pem.contents)
|
|
.map_err(|_| anyhow::anyhow!("ROTATION_PENDING_CSR"))?;
|
|
ensure!(
|
|
rest.is_empty()
|
|
&& request
|
|
.certification_request_info
|
|
.subject_pki
|
|
.subject_public_key
|
|
.data
|
|
.as_ref()
|
|
== key.public_key_raw(),
|
|
"ROTATION_PENDING_KEY_MISMATCH"
|
|
);
|
|
request
|
|
.verify_signature()
|
|
.map_err(|_| anyhow::anyhow!("ROTATION_PENDING_SIGNATURE"))?;
|
|
(version, csr)
|
|
} else {
|
|
let key = KeyPair::generate()?;
|
|
let csr = self.csr(&key)?;
|
|
let version = Uuid::new_v4();
|
|
keys.create(version, key.serialize_pem().as_bytes())?;
|
|
tx.execute(
|
|
"INSERT INTO tls_versions VALUES(?1,NULL,?2)",
|
|
params![version.to_string(), csr],
|
|
)?;
|
|
tx.execute(
|
|
"UPDATE tls_rotation SET pending_version=?1 WHERE id=1",
|
|
[version.to_string()],
|
|
)?;
|
|
if let Some(witness) = admission {
|
|
tx.execute(
|
|
"INSERT INTO tls_idle_admission VALUES(?1,?2)",
|
|
params![version.to_string(), witness],
|
|
)?;
|
|
}
|
|
(version, csr)
|
|
};
|
|
tx.commit()?;
|
|
Ok(PendingRequest {
|
|
identity,
|
|
csr_pem,
|
|
base,
|
|
version,
|
|
})
|
|
}
|
|
fn csr(&self, key: &KeyPair) -> Result<String> {
|
|
let mut parameters = CertificateParams::default();
|
|
parameters
|
|
.distinguished_name
|
|
.push(DnType::CommonName, self.agent.to_string());
|
|
Ok(parameters.serialize_request(key)?.pem()?)
|
|
}
|
|
/// Commit only the exact pending version, with fresh certificate validation.
|
|
/// Prior certs and key files are retained; failed installs change no selector.
|
|
pub fn install(
|
|
&self,
|
|
db: &mut Connection,
|
|
keys: &impl KeyFiles,
|
|
request: &PendingRequest,
|
|
bytes: &[u8],
|
|
now: i64,
|
|
) -> Result<()> {
|
|
ensure!(bytes.len() <= 65536, "ROTATION_RESPONSE_LIMIT");
|
|
let response: RenewalResponse = serde_json::from_slice(bytes)?;
|
|
ensure!(
|
|
response.agent_id == self.agent && response.overlap_seconds == 300,
|
|
"ROTATION_RESPONSE_BINDING_INVALID"
|
|
);
|
|
self.verify(
|
|
response.certificate_pem.as_bytes(),
|
|
&keys.read(request.version)?,
|
|
now,
|
|
)?;
|
|
let tx = db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
|
|
ensure!(
|
|
self.selector(&tx)? == (request.base, Some(request.version)),
|
|
"ROTATION_SELECTOR_CHANGED"
|
|
);
|
|
let csr: String = tx.query_row(
|
|
"SELECT csr FROM tls_versions WHERE version=?1 AND certificate IS NULL",
|
|
[request.version.to_string()],
|
|
|r| r.get(0),
|
|
)?;
|
|
ensure!(csr == request.csr_pem, "ROTATION_PENDING_CHANGED");
|
|
ensure!(
|
|
tx.execute(
|
|
"UPDATE tls_versions SET certificate=?1 WHERE version=?2 AND certificate IS NULL",
|
|
params![
|
|
response.certificate_pem.as_bytes(),
|
|
request.version.to_string()
|
|
]
|
|
)? == 1,
|
|
"ROTATION_PENDING_MISSING"
|
|
);
|
|
tx.execute(
|
|
"UPDATE tls_rotation SET current_version=?1,pending_version=NULL WHERE id=1",
|
|
[request.version.to_string()],
|
|
)?;
|
|
tx.commit()?;
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
/// A local idle witness for certificate maintenance, not an execution grant.
|
|
/// All accepted/unknown work and missing effect evidence block rotation. The
|
|
/// caller retains both existing database guards while computing this digest.
|
|
pub fn idle_history_sha256(journal: &Connection, ledger: &Connection) -> Result<String> {
|
|
use rusqlite::types::ValueRef;
|
|
use sha2::{Digest, Sha256};
|
|
let safe: bool = journal.query_row("SELECT count(*)=1 AND min(last_decision IS NOT NULL AND pending_request IS NULL AND fault IS NULL AND generation>0) FROM reconcile_meta WHERE id=1", [], |r| r.get(0))?;
|
|
let idle: bool = journal.query_row("SELECT NOT EXISTS(SELECT 1 FROM job_attempts WHERE state NOT IN ('succeeded','failed','cancelled','expired')) AND NOT EXISTS(SELECT 1 FROM job_events) AND NOT EXISTS(SELECT 1 FROM events)", [], |r| r.get(0))?;
|
|
let resolved: bool = ledger.query_row("SELECT NOT EXISTS(SELECT 1 FROM consumed c LEFT JOIN execution_evidence e USING(grant_id) WHERE c.result IS NULL OR e.start IS NULL OR e.outcome IS NULL) AND NOT EXISTS(SELECT 1 FROM execution_evidence e LEFT JOIN consumed c USING(grant_id) WHERE c.grant_id IS NULL)", [], |r| r.get(0))?;
|
|
ensure!(
|
|
safe && idle && resolved,
|
|
"ROTATION_EFFECT_OR_CONTROL_UNRESOLVED"
|
|
);
|
|
let mut hash = Sha256::new();
|
|
hash.update(b"rmm.windows.tls-idle.v1\0");
|
|
for (db, sql) in [
|
|
(journal, "SELECT seq FROM counter WHERE id=1"),
|
|
(
|
|
journal,
|
|
"SELECT journal_id,checkpoint,high_sequence,generation,last_decision,pending_request,helper_id,helper_checkpoint,fault FROM reconcile_meta WHERE id=1",
|
|
),
|
|
(
|
|
journal,
|
|
"SELECT job,attempt,offer,state,revision,grant_id,cancel_requested FROM job_attempts ORDER BY job,attempt",
|
|
),
|
|
(
|
|
ledger,
|
|
"SELECT c.grant_id,c.agent,c.generation,c.job,c.attempt,c.result,e.start,e.outcome FROM consumed c JOIN execution_evidence e USING(grant_id) ORDER BY c.grant_id",
|
|
),
|
|
] {
|
|
hash.update(sql.as_bytes());
|
|
let mut query = db.prepare(sql)?;
|
|
let columns = query.column_count();
|
|
let mut rows = query.query([])?;
|
|
let mut count = 0u64;
|
|
while let Some(row) = rows.next()? {
|
|
count += 1;
|
|
ensure!(count <= 256, "ROTATION_HISTORY_LIMIT");
|
|
hash.update([0xff]);
|
|
for column in 0..columns {
|
|
match row.get_ref(column)? {
|
|
ValueRef::Null => hash.update([0]),
|
|
ValueRef::Integer(value) => {
|
|
hash.update([1]);
|
|
hash.update(value.to_be_bytes());
|
|
}
|
|
ValueRef::Text(bytes) | ValueRef::Blob(bytes) => {
|
|
ensure!(bytes.len() <= 1048576, "ROTATION_HISTORY_BLOB_LIMIT");
|
|
hash.update([if matches!(row.get_ref(column)?, ValueRef::Text(_)) {
|
|
2
|
|
} else {
|
|
3
|
|
}]);
|
|
hash.update((bytes.len() as u64).to_be_bytes());
|
|
hash.update(bytes);
|
|
}
|
|
ValueRef::Real(_) => anyhow::bail!("ROTATION_HISTORY_TYPE"),
|
|
}
|
|
}
|
|
}
|
|
hash.update(count.to_be_bytes());
|
|
}
|
|
Ok(format!("{:x}", hash.finalize()))
|
|
}
|
|
|
|
#[cfg(windows)]
|
|
pub struct ProtectedKeyFiles {
|
|
root: std::path::PathBuf,
|
|
// Denying FILE_SHARE_DELETE holds the actual parent against rename/removal.
|
|
_directory: std::fs::File,
|
|
}
|
|
#[cfg(windows)]
|
|
impl ProtectedKeyFiles {
|
|
pub fn open(root: &std::path::Path) -> Result<Self> {
|
|
use std::{fs::OpenOptions, os::windows::fs::OpenOptionsExt};
|
|
use windows_sys::Win32::Storage::FileSystem::*;
|
|
ensure!(root.is_absolute(), "ROTATION_ABSOLUTE_STATE_REQUIRED");
|
|
let directory = OpenOptions::new()
|
|
.read(true)
|
|
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
|
|
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
|
|
.open(root)?;
|
|
crate::native::private_path(root, true)?;
|
|
Self::information(&directory, true)?;
|
|
Ok(Self {
|
|
root: root.into(),
|
|
_directory: directory,
|
|
})
|
|
}
|
|
fn path(&self, version: Uuid) -> std::path::PathBuf {
|
|
self.root.join(if version.is_nil() {
|
|
"device.key".into()
|
|
} else {
|
|
format!("device-{version}.key")
|
|
})
|
|
}
|
|
fn information(file: &std::fs::File, directory: bool) -> Result<()> {
|
|
use std::os::windows::io::AsRawHandle;
|
|
use windows_sys::Win32::Storage::FileSystem::*;
|
|
let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
|
|
ensure!(
|
|
unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut info) } != 0,
|
|
"ROTATION_FILE_INFORMATION"
|
|
);
|
|
ensure!(
|
|
info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT == 0
|
|
&& (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY != 0) == directory
|
|
&& (directory || info.nNumberOfLinks == 1),
|
|
"ROTATION_FILE_TYPE_OR_LINKS"
|
|
);
|
|
Ok(())
|
|
}
|
|
}
|
|
#[cfg(windows)]
|
|
impl KeyFiles for ProtectedKeyFiles {
|
|
fn read(&self, version: Uuid) -> Result<Vec<u8>> {
|
|
use std::{fs::OpenOptions, io::Read, os::windows::fs::OpenOptionsExt};
|
|
use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT;
|
|
let path = self.path(version);
|
|
let mut file = OpenOptions::new()
|
|
.read(true)
|
|
.share_mode(0)
|
|
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
|
|
.open(&path)?;
|
|
Self::information(&file, false)?;
|
|
crate::native::private_path(&path, false)?;
|
|
let mut bytes = Vec::new();
|
|
Read::by_ref(&mut file)
|
|
.take(16385)
|
|
.read_to_end(&mut bytes)?;
|
|
ensure!(bytes.len() <= 16384, "ROTATION_KEY_LIMIT");
|
|
Ok(bytes)
|
|
}
|
|
fn create(&self, version: Uuid, key: &[u8]) -> Result<()> {
|
|
use std::{fs::OpenOptions, io::Write, os::windows::fs::OpenOptionsExt};
|
|
use windows_sys::Win32::Storage::FileSystem::{
|
|
FILE_FLAG_OPEN_REPARSE_POINT, FILE_FLAG_WRITE_THROUGH,
|
|
};
|
|
ensure!(
|
|
!version.is_nil() && key.len() <= 16384,
|
|
"ROTATION_NEW_KEY_REQUIRED"
|
|
);
|
|
let path = self.path(version);
|
|
let mut file = OpenOptions::new()
|
|
.write(true)
|
|
.create_new(true)
|
|
.share_mode(0)
|
|
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_WRITE_THROUGH)
|
|
.open(&path)?;
|
|
Self::information(&file, false)?;
|
|
// Inherited ACL must already be private: no secret byte precedes this.
|
|
crate::native::private_path(&path, false)?;
|
|
file.write_all(key)?;
|
|
file.sync_all()?;
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use rcgen::{BasicConstraints, ExtendedKeyUsagePurpose, IsCa, Issuer, KeyUsagePurpose};
|
|
use std::{cell::RefCell, collections::BTreeMap};
|
|
#[derive(Default)]
|
|
struct Keys(RefCell<BTreeMap<Uuid, Vec<u8>>>);
|
|
impl KeyFiles for Keys {
|
|
fn read(&self, id: Uuid) -> Result<Vec<u8>> {
|
|
self.0
|
|
.borrow()
|
|
.get(&id)
|
|
.cloned()
|
|
.context("MISSING_TEST_KEY")
|
|
}
|
|
fn create(&self, id: Uuid, key: &[u8]) -> Result<()> {
|
|
ensure!(!self.0.borrow().contains_key(&id), "TEST_CREATE_NEW");
|
|
self.0.borrow_mut().insert(id, key.to_vec());
|
|
Ok(())
|
|
}
|
|
}
|
|
fn now() -> i64 {
|
|
chrono::DateTime::parse_from_rfc3339("2026-11-21T00:00:00Z")
|
|
.unwrap()
|
|
.timestamp()
|
|
}
|
|
fn ca() -> (String, Issuer<'static, KeyPair>) {
|
|
let mut p = CertificateParams::default();
|
|
p.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
|
|
p.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign];
|
|
let key = KeyPair::generate().unwrap();
|
|
let cert = p.self_signed(&key).unwrap().pem();
|
|
(cert, Issuer::new(p, key))
|
|
}
|
|
fn certificate(agent: Uuid, key: &[u8], issuer: &Issuer<'_, KeyPair>, client: bool) -> String {
|
|
let mut p = CertificateParams::default();
|
|
p.distinguished_name
|
|
.push(DnType::CommonName, agent.to_string());
|
|
p.not_before = rcgen::date_time_ymd(2026, 11, 1);
|
|
p.not_after = rcgen::date_time_ymd(2026, 12, 1);
|
|
p.key_usages = vec![KeyUsagePurpose::DigitalSignature];
|
|
p.extended_key_usages = vec![if client {
|
|
ExtendedKeyUsagePurpose::ClientAuth
|
|
} else {
|
|
ExtendedKeyUsagePurpose::ServerAuth
|
|
}];
|
|
p.signed_by(
|
|
&KeyPair::from_pem(std::str::from_utf8(key).unwrap()).unwrap(),
|
|
issuer,
|
|
)
|
|
.unwrap()
|
|
.pem()
|
|
}
|
|
fn setup() -> (
|
|
Connection,
|
|
Keys,
|
|
RotationStore,
|
|
Issuer<'static, KeyPair>,
|
|
String,
|
|
) {
|
|
let (ca, issuer) = ca();
|
|
let store = RotationStore::new(Uuid::new_v4(), 1, ca.into_bytes()).unwrap();
|
|
let keys = Keys::default();
|
|
keys.create(
|
|
Uuid::nil(),
|
|
KeyPair::generate().unwrap().serialize_pem().as_bytes(),
|
|
)
|
|
.unwrap();
|
|
let cert = certificate(store.agent, &keys.read(Uuid::nil()).unwrap(), &issuer, true);
|
|
let mut db = Connection::open_in_memory().unwrap();
|
|
store
|
|
.initialize(&mut db, &keys, cert.as_bytes(), now())
|
|
.unwrap();
|
|
(db, keys, store, issuer, cert)
|
|
}
|
|
fn reply(agent: Uuid, cert: &str) -> Vec<u8> {
|
|
serde_json::to_vec(
|
|
&serde_json::json!({"agent_id":agent,"certificate_pem":cert,"overlap_seconds":300}),
|
|
)
|
|
.unwrap()
|
|
}
|
|
#[test]
|
|
fn updater_tls_snapshot_requires_read_only_handle_and_preserves_selector() {
|
|
let (db, keys, store, _, cert) = setup();
|
|
db.execute_batch("PRAGMA trusted_schema=OFF;PRAGMA query_only=ON")
|
|
.unwrap();
|
|
assert!(store.read_only_current(&db, &keys, now()).is_err());
|
|
db.execute_batch("PRAGMA query_only=OFF").unwrap();
|
|
let path = std::env::temp_dir().join(format!("rmm-tls-read-{}.sqlite", Uuid::new_v4()));
|
|
db.execute("VACUUM INTO ?1", [path.to_str().unwrap()])
|
|
.unwrap();
|
|
let read =
|
|
Connection::open_with_flags(&path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY).unwrap();
|
|
assert!(store.read_only_current(&read, &keys, now()).is_err());
|
|
read.execute_batch("PRAGMA query_only=ON;PRAGMA trusted_schema=OFF")
|
|
.unwrap();
|
|
let before = store.selector(&read).unwrap();
|
|
let identity = store.read_only_current(&read, &keys, now()).unwrap();
|
|
assert_eq!(identity.certificate_pem, cert.as_bytes());
|
|
assert_eq!(identity.private_key_pem, keys.read(Uuid::nil()).unwrap());
|
|
assert_eq!(store.selector(&read).unwrap(), before);
|
|
drop(read);
|
|
std::fs::remove_file(path).unwrap();
|
|
}
|
|
#[test]
|
|
fn active_idle_admission_is_atomic_retained_and_cannot_adopt_legacy_pending() {
|
|
let (mut db, keys, store, _, _) = setup();
|
|
let witness = b"exact independently checked idle context";
|
|
db.execute_batch("CREATE TEMP TRIGGER deny_idle BEFORE INSERT ON tls_idle_admission BEGIN SELECT RAISE(ABORT,'TEST_IDLE_COMMIT_DENIED');END;").unwrap();
|
|
assert!(
|
|
store
|
|
.prepare_with_idle_admission(&mut db, &keys, now(), Some(witness))
|
|
.is_err()
|
|
);
|
|
assert_eq!(store.selector(&db).unwrap(), (Uuid::nil(), None));
|
|
assert_eq!(
|
|
db.query_row("SELECT count(*) FROM tls_versions", [], |r| r
|
|
.get::<_, u64>(0))
|
|
.unwrap(),
|
|
1
|
|
);
|
|
db.execute_batch("DROP TRIGGER deny_idle").unwrap();
|
|
let original = store
|
|
.prepare_with_idle_admission(&mut db, &keys, now(), Some(witness))
|
|
.unwrap();
|
|
assert_eq!(
|
|
store.pending_idle_admission(&db).unwrap().as_deref(),
|
|
Some(witness.as_slice())
|
|
);
|
|
assert!(
|
|
store
|
|
.prepare_with_idle_admission(&mut db, &keys, now(), Some(b"changed context"))
|
|
.is_err()
|
|
);
|
|
let retained = store
|
|
.prepare_with_idle_admission(&mut db, &keys, now(), Some(witness))
|
|
.unwrap();
|
|
assert_eq!(original.version, retained.version);
|
|
assert_eq!(original.csr_pem, retained.csr_pem);
|
|
assert!(
|
|
db.execute(
|
|
"UPDATE tls_idle_admission SET witness=?1",
|
|
[b"replacement".as_slice()]
|
|
)
|
|
.is_err()
|
|
);
|
|
assert!(db.execute("DELETE FROM tls_idle_admission", []).is_err());
|
|
let (mut legacy, legacy_keys, legacy_store, _, _) = setup();
|
|
legacy_store
|
|
.prepare(&mut legacy, &legacy_keys, now())
|
|
.unwrap();
|
|
assert!(
|
|
legacy_store
|
|
.pending_idle_admission(&legacy)
|
|
.unwrap()
|
|
.is_none()
|
|
);
|
|
assert!(
|
|
legacy_store
|
|
.prepare_with_idle_admission(&mut legacy, &legacy_keys, now(), Some(witness))
|
|
.is_err()
|
|
);
|
|
}
|
|
#[test]
|
|
fn idle_history_rejects_unfinished_jobs_missing_effect_evidence_and_changed_heads() {
|
|
let root = std::env::temp_dir().join(format!("rmm-rotation-idle-{}", Uuid::new_v4()));
|
|
std::fs::create_dir(&root).unwrap();
|
|
let journal = crate::journal::Journal::open(&root).unwrap();
|
|
let ledger = Connection::open_in_memory().unwrap();
|
|
rmm_agent_core::ledger::initialize_ledger(&ledger).unwrap();
|
|
assert!(idle_history_sha256(journal.connection(), &ledger).is_err());
|
|
journal
|
|
.connection()
|
|
.execute(
|
|
"UPDATE reconcile_meta SET generation=1,last_decision=?1 WHERE id=1",
|
|
[Uuid::new_v4().to_string()],
|
|
)
|
|
.unwrap();
|
|
let clean = idle_history_sha256(journal.connection(), &ledger).unwrap();
|
|
journal.connection().execute("INSERT INTO job_attempts(job,attempt,offer,state) VALUES('fixture','attempt',x'01','accepted')",[]).unwrap();
|
|
for state in [
|
|
"queued",
|
|
"accepted",
|
|
"requesting",
|
|
"running",
|
|
"verifying",
|
|
"unknown",
|
|
"awaiting_reboot",
|
|
] {
|
|
journal
|
|
.connection()
|
|
.execute("UPDATE job_attempts SET state=?1", [state])
|
|
.unwrap();
|
|
assert!(
|
|
idle_history_sha256(journal.connection(), &ledger).is_err(),
|
|
"{state}"
|
|
);
|
|
}
|
|
journal
|
|
.connection()
|
|
.execute("UPDATE job_attempts SET state='succeeded'", [])
|
|
.unwrap();
|
|
let finished = idle_history_sha256(journal.connection(), &ledger).unwrap();
|
|
assert_ne!(clean, finished);
|
|
ledger
|
|
.execute(
|
|
"INSERT INTO consumed VALUES('grant','agent',1,'fixture','attempt',NULL)",
|
|
[],
|
|
)
|
|
.unwrap();
|
|
assert!(idle_history_sha256(journal.connection(), &ledger).is_err());
|
|
ledger
|
|
.execute("UPDATE consumed SET result=x'02'", [])
|
|
.unwrap();
|
|
assert!(idle_history_sha256(journal.connection(), &ledger).is_err());
|
|
ledger
|
|
.execute(
|
|
"INSERT INTO execution_evidence VALUES('grant',x'01',x'02')",
|
|
[],
|
|
)
|
|
.unwrap();
|
|
let resolved = idle_history_sha256(journal.connection(), &ledger).unwrap();
|
|
journal
|
|
.connection()
|
|
.execute(
|
|
"UPDATE reconcile_meta SET checkpoint=checkpoint+1 WHERE id=1",
|
|
[],
|
|
)
|
|
.unwrap();
|
|
assert_ne!(
|
|
resolved,
|
|
idle_history_sha256(journal.connection(), &ledger).unwrap()
|
|
);
|
|
journal
|
|
.connection()
|
|
.execute(
|
|
"UPDATE reconcile_meta SET pending_request='pending' WHERE id=1",
|
|
[],
|
|
)
|
|
.unwrap();
|
|
assert!(idle_history_sha256(journal.connection(), &ledger).is_err());
|
|
drop(journal);
|
|
std::fs::remove_dir_all(root).unwrap();
|
|
}
|
|
#[test]
|
|
fn response_loss_reuses_exact_pending_csr_and_private_key_stays_outside_sqlite() {
|
|
let (mut db, keys, store, issuer, old) = setup();
|
|
assert!(store.due(&db, &keys, now()).unwrap());
|
|
let first = store.prepare(&mut db, &keys, now()).unwrap();
|
|
let second = store.prepare(&mut db, &keys, now()).unwrap();
|
|
assert_eq!(first.version, second.version);
|
|
assert_eq!(first.csr_pem, second.csr_pem);
|
|
assert_eq!(keys.0.borrow().len(), 2);
|
|
assert_eq!(
|
|
store.current(&db, &keys, now()).unwrap().certificate_pem,
|
|
old.as_bytes()
|
|
);
|
|
let new = certificate(
|
|
store.agent,
|
|
&keys.read(first.version).unwrap(),
|
|
&issuer,
|
|
true,
|
|
);
|
|
store
|
|
.install(&mut db, &keys, &first, &reply(store.agent, &new), now())
|
|
.unwrap();
|
|
assert_eq!(
|
|
store.current(&db, &keys, now()).unwrap().certificate_pem,
|
|
new.as_bytes()
|
|
);
|
|
assert_eq!(store.selector(&db).unwrap(), (first.version, None));
|
|
assert!(
|
|
store
|
|
.install(&mut db, &keys, &second, &reply(store.agent, &new), now())
|
|
.is_err()
|
|
);
|
|
assert_eq!(keys.0.borrow().len(), 2);
|
|
let values:Vec<String>=db.prepare("SELECT coalesce(CAST(certificate AS TEXT),'') || coalesce(csr,'') FROM tls_versions").unwrap().query_map([],|r|r.get(0)).unwrap().collect::<rusqlite::Result<_>>().unwrap();
|
|
assert!(values.iter().all(|v| !v.contains("PRIVATE KEY")));
|
|
}
|
|
#[test]
|
|
fn bad_reply_preserves_current_pending_and_original_identity() {
|
|
let (mut db, keys, store, issuer, old) = setup();
|
|
let pending = store.prepare(&mut db, &keys, now()).unwrap();
|
|
let key = keys.read(pending.version).unwrap();
|
|
let (_wrong_ca, wrong_issuer) = ca();
|
|
let wrong_key = KeyPair::generate().unwrap().serialize_pem();
|
|
for cert in [
|
|
certificate(Uuid::new_v4(), &key, &issuer, true),
|
|
certificate(store.agent, wrong_key.as_bytes(), &issuer, true),
|
|
certificate(store.agent, &key, &issuer, false),
|
|
certificate(store.agent, &key, &wrong_issuer, true),
|
|
] {
|
|
assert!(
|
|
store
|
|
.install(&mut db, &keys, &pending, &reply(store.agent, &cert), now())
|
|
.is_err()
|
|
);
|
|
assert_eq!(
|
|
store.current(&db, &keys, now()).unwrap().certificate_pem,
|
|
old.as_bytes()
|
|
);
|
|
assert_eq!(
|
|
store.selector(&db).unwrap(),
|
|
(Uuid::nil(), Some(pending.version))
|
|
);
|
|
}
|
|
let valid = certificate(store.agent, &key, &issuer, true);
|
|
assert!(
|
|
store
|
|
.install(
|
|
&mut db,
|
|
&keys,
|
|
&pending,
|
|
&reply(store.agent, &valid),
|
|
now() + 11 * 86400
|
|
)
|
|
.is_err()
|
|
);
|
|
assert!(
|
|
store
|
|
.install(
|
|
&mut db,
|
|
&keys,
|
|
&pending,
|
|
&reply(Uuid::new_v4(), &valid),
|
|
now()
|
|
)
|
|
.is_err()
|
|
);
|
|
}
|
|
#[test]
|
|
fn committed_version_never_falls_back_to_legacy_on_restart_or_missing_key() {
|
|
let (mut db, keys, store, issuer, old) = setup();
|
|
let pending = store.prepare(&mut db, &keys, now()).unwrap();
|
|
let valid = certificate(
|
|
store.agent,
|
|
&keys.read(pending.version).unwrap(),
|
|
&issuer,
|
|
true,
|
|
);
|
|
store
|
|
.install(&mut db, &keys, &pending, &reply(store.agent, &valid), now())
|
|
.unwrap();
|
|
store
|
|
.initialize(&mut db, &keys, old.as_bytes(), now())
|
|
.unwrap();
|
|
assert_eq!(store.selector(&db).unwrap().0, pending.version);
|
|
keys.0.borrow_mut().remove(&pending.version);
|
|
assert!(
|
|
store
|
|
.initialize(&mut db, &keys, old.as_bytes(), now())
|
|
.is_err()
|
|
);
|
|
assert!(store.current(&db, &keys, now()).is_err());
|
|
assert_eq!(store.selector(&db).unwrap().0, pending.version);
|
|
assert!(keys.read(Uuid::nil()).is_ok());
|
|
}
|
|
#[test]
|
|
fn changed_pending_key_or_identity_cannot_create_a_second_request() {
|
|
let (mut db, keys, store, _issuer, _old) = setup();
|
|
let pending = store.prepare(&mut db, &keys, now()).unwrap();
|
|
keys.0.borrow_mut().insert(
|
|
pending.version,
|
|
KeyPair::generate().unwrap().serialize_pem().into_bytes(),
|
|
);
|
|
assert!(store.prepare(&mut db, &keys, now()).is_err());
|
|
assert_eq!(keys.0.borrow().len(), 2);
|
|
let other = RotationStore::new(store.agent, 2, store.ca.clone()).unwrap();
|
|
assert!(other.current(&db, &keys, now()).is_err());
|
|
db.execute("DELETE FROM tls_rotation", []).unwrap();
|
|
assert!(
|
|
store
|
|
.initialize(&mut db, &keys, b"not a bootstrap", now())
|
|
.is_err()
|
|
);
|
|
}
|
|
#[test]
|
|
fn journal_reopen_recovers_pending_before_hello_and_install_is_one_transaction() {
|
|
let (_db, keys, store, issuer, old) = setup();
|
|
let directory = std::env::temp_dir().join(format!("rmm-tls-renewal-{}", Uuid::new_v4()));
|
|
std::fs::create_dir(&directory).unwrap();
|
|
let mut journal = crate::journal::Journal::open(&directory).unwrap();
|
|
journal.pin_identity(&store.agent.to_string()).unwrap();
|
|
assert_eq!(journal.next_sequence().unwrap(), 1);
|
|
store
|
|
.initialize(journal.connection_mut(), &keys, old.as_bytes(), now())
|
|
.unwrap();
|
|
let pending = store
|
|
.prepare(journal.connection_mut(), &keys, now())
|
|
.unwrap();
|
|
drop(journal);
|
|
let mut journal = crate::journal::Journal::open(&directory).unwrap();
|
|
journal.pin_identity(&store.agent.to_string()).unwrap();
|
|
assert_eq!(journal.next_sequence().unwrap(), 2);
|
|
assert!(store.has_pending(journal.connection()).unwrap());
|
|
let recovered = store
|
|
.prepare(journal.connection_mut(), &keys, now())
|
|
.unwrap();
|
|
assert_eq!(pending.version, recovered.version);
|
|
assert_eq!(pending.csr_pem, recovered.csr_pem);
|
|
let new = certificate(
|
|
store.agent,
|
|
&keys.read(pending.version).unwrap(),
|
|
&issuer,
|
|
true,
|
|
);
|
|
let response = reply(store.agent, &new);
|
|
// Force the second SQL write to fail, after writing the certificate:
|
|
// neither the cert nor selector may survive this aborted transaction.
|
|
journal.connection().execute_batch("CREATE TEMP TRIGGER refuse_tls_commit BEFORE UPDATE OF current_version ON tls_rotation BEGIN SELECT RAISE(ABORT,'TEST_COMMIT_DENIED'); END;").unwrap();
|
|
assert!(
|
|
store
|
|
.install(
|
|
journal.connection_mut(),
|
|
&keys,
|
|
&recovered,
|
|
&response,
|
|
now()
|
|
)
|
|
.is_err()
|
|
);
|
|
assert_eq!(
|
|
store
|
|
.current(journal.connection(), &keys, now())
|
|
.unwrap()
|
|
.certificate_pem,
|
|
old.as_bytes()
|
|
);
|
|
let staged: Option<Vec<u8>> = journal
|
|
.connection()
|
|
.query_row(
|
|
"SELECT certificate FROM tls_versions WHERE version=?1",
|
|
[pending.version.to_string()],
|
|
|r| r.get(0),
|
|
)
|
|
.unwrap();
|
|
assert!(staged.is_none());
|
|
journal
|
|
.connection()
|
|
.execute_batch("DROP TRIGGER refuse_tls_commit;")
|
|
.unwrap();
|
|
store
|
|
.install(
|
|
journal.connection_mut(),
|
|
&keys,
|
|
&recovered,
|
|
&response,
|
|
now(),
|
|
)
|
|
.unwrap();
|
|
drop(journal);
|
|
let journal = crate::journal::Journal::open(&directory).unwrap();
|
|
assert!(!store.has_pending(journal.connection()).unwrap());
|
|
assert_eq!(
|
|
store
|
|
.current(journal.connection(), &keys, now())
|
|
.unwrap()
|
|
.certificate_pem,
|
|
new.as_bytes()
|
|
);
|
|
// Windows SQLite holds byte-range locks in the live WAL/SHM files.
|
|
// Release the database before inspecting its remaining raw files.
|
|
drop(journal);
|
|
for entry in std::fs::read_dir(&directory).unwrap() {
|
|
let bytes = std::fs::read(entry.unwrap().path()).unwrap();
|
|
assert!(
|
|
!bytes
|
|
.windows(b"PRIVATE KEY".len())
|
|
.any(|s| s == b"PRIVATE KEY")
|
|
);
|
|
}
|
|
std::fs::remove_dir_all(directory).unwrap();
|
|
}
|
|
|
|
/// Deliberately selected fixture-only native I/O, never a default elevated
|
|
/// operation. Uses the production KeyFiles implementation; no service,
|
|
/// account, impersonation, installed state or network operation is involved.
|
|
#[cfg(windows)]
|
|
#[test]
|
|
#[ignore = "explicit Windows administrator fixture; does not prove LocalService execution"]
|
|
fn protected_key_files_create_new_reopen_acl_and_hardlink_guards() {
|
|
use std::{fs, os::windows::ffi::OsStrExt, ptr};
|
|
use windows_sys::Win32::{
|
|
Foundation::LocalFree,
|
|
Security::{
|
|
Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW,
|
|
CheckTokenMembership, CreateWellKnownSid, SECURITY_ATTRIBUTES,
|
|
WinBuiltinAdministratorsSid,
|
|
},
|
|
Storage::FileSystem::CreateDirectoryW,
|
|
};
|
|
// The current token must already be an administrator. This fixture
|
|
// never obtains or substitutes a different principal's token.
|
|
let mut admin = [0usize; 16];
|
|
let mut length = std::mem::size_of_val(&admin) as u32;
|
|
let mut member = 0;
|
|
assert!(
|
|
unsafe {
|
|
CreateWellKnownSid(
|
|
WinBuiltinAdministratorsSid,
|
|
ptr::null_mut(),
|
|
admin.as_mut_ptr().cast(),
|
|
&mut length,
|
|
)
|
|
} != 0
|
|
);
|
|
assert!(
|
|
unsafe {
|
|
CheckTokenMembership(ptr::null_mut(), admin.as_mut_ptr().cast(), &mut member)
|
|
} != 0
|
|
&& member == 1
|
|
);
|
|
let service_sid = crate::native::service_sid().unwrap();
|
|
let create_directory = |path: &std::path::Path, broad: bool| {
|
|
let sddl = format!(
|
|
"O:BAG:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FA;;;{service_sid}){}",
|
|
if broad { "(A;OICI;FR;;;BU)" } else { "" }
|
|
);
|
|
let sddl: Vec<u16> = sddl.encode_utf16().chain(Some(0)).collect();
|
|
let mut descriptor = ptr::null_mut();
|
|
assert!(
|
|
unsafe {
|
|
ConvertStringSecurityDescriptorToSecurityDescriptorW(
|
|
sddl.as_ptr(),
|
|
1,
|
|
&mut descriptor,
|
|
ptr::null_mut(),
|
|
)
|
|
} != 0
|
|
);
|
|
let wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
|
|
let attributes = SECURITY_ATTRIBUTES {
|
|
nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
|
|
lpSecurityDescriptor: descriptor,
|
|
bInheritHandle: 0,
|
|
};
|
|
let created = unsafe { CreateDirectoryW(wide.as_ptr(), &attributes) };
|
|
unsafe {
|
|
LocalFree(descriptor.cast());
|
|
}
|
|
assert!(created != 0, "fresh protected fixture directory required");
|
|
};
|
|
let root =
|
|
std::env::temp_dir().join(format!("rmm-protected-key-fixture-{}", Uuid::new_v4()));
|
|
create_directory(&root, false);
|
|
// On failure retain this isolated case for the operator to inspect;
|
|
// successful cleanup addresses only this newly created fixed namespace.
|
|
let files = ProtectedKeyFiles::open(&root).unwrap();
|
|
// A broad ACL is tested only on an empty, separate fixture directory;
|
|
// no private key is ever written there.
|
|
let broad = root.join("broad-empty");
|
|
create_directory(&broad, true);
|
|
let denied = match ProtectedKeyFiles::open(&broad) {
|
|
Err(error) => error,
|
|
Ok(_) => panic!("broad fixture DACL must be refused"),
|
|
};
|
|
assert_eq!(denied.to_string(), "PRIVATE_PATH_BROAD_ACL");
|
|
fs::remove_dir(broad).unwrap();
|
|
let version = Uuid::new_v4();
|
|
let key = KeyPair::generate().unwrap();
|
|
let pem = key.serialize_pem();
|
|
files.create(version, pem.as_bytes()).unwrap();
|
|
let path = root.join(format!("device-{version}.key"));
|
|
crate::native::private_path(&path, false).unwrap();
|
|
let read = files.read(version).unwrap();
|
|
// Never put private key bytes into assert_eq's panic formatter.
|
|
assert!(read == pem.as_bytes(), "private key bytes changed");
|
|
let parsed = KeyPair::from_pem(std::str::from_utf8(&read).unwrap()).unwrap();
|
|
use sha2::{Digest, Sha256};
|
|
assert_eq!(
|
|
Sha256::digest(parsed.public_key_raw()),
|
|
Sha256::digest(key.public_key_raw())
|
|
);
|
|
let duplicate = files
|
|
.create(version, b"must not replace the key")
|
|
.unwrap_err();
|
|
assert_eq!(
|
|
duplicate.downcast_ref::<std::io::Error>().unwrap().kind(),
|
|
std::io::ErrorKind::AlreadyExists
|
|
);
|
|
assert!(files.read(version).unwrap() == pem.as_bytes());
|
|
// The actual held directory handle must prevent rename while in use.
|
|
assert!(fs::rename(&root, root.with_extension("renamed")).is_err());
|
|
drop(files);
|
|
let files = ProtectedKeyFiles::open(&root).unwrap();
|
|
assert!(files.read(version).unwrap() == pem.as_bytes());
|
|
let link = root.join("own-fixture-hardlink");
|
|
fs::hard_link(&path, &link).unwrap();
|
|
let denied = match files.read(version) {
|
|
Err(error) => error,
|
|
Ok(_) => panic!("hardlinked private key must be refused"),
|
|
};
|
|
assert_eq!(denied.to_string(), "ROTATION_FILE_TYPE_OR_LINKS");
|
|
fs::remove_file(link).unwrap();
|
|
assert!(files.read(version).unwrap() == pem.as_bytes());
|
|
drop(files);
|
|
fs::remove_file(path).unwrap();
|
|
fs::remove_dir(root).unwrap();
|
|
}
|
|
}
|