Qualify Windows system delegation and crash-safe mirror adapter on native VM
Rust development slice / linux (push) Failing after 6s
Rust development slice / linux (push) Failing after 6s
This commit is contained in:
@@ -0,0 +1,414 @@
|
||||
//! Fixed, preprovisioned confidential delegation journal. Never log request bytes.
|
||||
use crate::helper_ipc::{self as ipc, FileIdentity, PinnedFile};
|
||||
use anyhow::{Result, ensure};
|
||||
use chrono::{DateTime, Utc};
|
||||
use rmm_agent_core::{
|
||||
auth::Request,
|
||||
helper_reconcile::{NoDispatchObservation, NoStartAnchor},
|
||||
};
|
||||
use rmm_domain::jobs::{ExecutionPermitPayload, hash};
|
||||
use rusqlite::{Connection, OpenFlags, OptionalExtension, TransactionBehavior, params};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{path::Path, time::Duration};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub const ROOT: &str = r"C:\ProgramData\RustDiscoverySystem\agent-intents";
|
||||
pub const DB: &str = r"C:\ProgramData\RustDiscoverySystem\agent-intents\system-intents.sqlite";
|
||||
const ACTOR_RW: u32 = 0x0012_019f;
|
||||
const SCHEMA:&str="CREATE TABLE IF NOT EXISTS system_intent_meta(id INTEGER PRIMARY KEY CHECK(id=1),file_identity BLOB NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS system_intents(id TEXT PRIMARY KEY,job TEXT NOT NULL,attempt TEXT NOT NULL,grant_id TEXT NOT NULL UNIQUE,body BLOB NOT NULL CHECK(length(body)<=196608),digest TEXT NOT NULL,phase TEXT NOT NULL CHECK(phase IN ('prepared','known_no_dispatch','may_have_dispatched')),UNIQUE(job,attempt));
|
||||
CREATE TABLE IF NOT EXISTS system_intent_mirrors(id TEXT PRIMARY KEY,outcome_sha256 TEXT NOT NULL,mirror_observed_at TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS system_intent_denial_resumes(id TEXT NOT NULL,agent_instance TEXT NOT NULL,observed_at TEXT NOT NULL,PRIMARY KEY(id,agent_instance));
|
||||
CREATE TRIGGER IF NOT EXISTS system_intents_no_delete BEFORE DELETE ON system_intents BEGIN SELECT RAISE(ABORT,'SYSTEM_INTENT_IMMUTABLE');END;
|
||||
CREATE TRIGGER IF NOT EXISTS system_intents_monotonic BEFORE UPDATE ON system_intents WHEN NEW.id!=OLD.id OR NEW.job!=OLD.job OR NEW.attempt!=OLD.attempt OR NEW.grant_id!=OLD.grant_id OR NEW.body!=OLD.body OR NEW.digest!=OLD.digest OR OLD.phase!='prepared' OR NEW.phase NOT IN ('known_no_dispatch','may_have_dispatched') BEGIN SELECT RAISE(ABORT,'SYSTEM_INTENT_IMMUTABLE');END;
|
||||
CREATE TRIGGER IF NOT EXISTS system_mirrors_no_delete BEFORE DELETE ON system_intent_mirrors BEGIN SELECT RAISE(ABORT,'SYSTEM_MIRROR_IMMUTABLE');END;
|
||||
CREATE TRIGGER IF NOT EXISTS system_mirrors_no_update BEFORE UPDATE ON system_intent_mirrors BEGIN SELECT RAISE(ABORT,'SYSTEM_MIRROR_IMMUTABLE');END;
|
||||
CREATE TRIGGER IF NOT EXISTS system_denial_resumes_no_delete BEFORE DELETE ON system_intent_denial_resumes BEGIN SELECT RAISE(ABORT,'SYSTEM_DENIAL_RESUME_IMMUTABLE');END;
|
||||
CREATE TRIGGER IF NOT EXISTS system_denial_resumes_no_update BEFORE UPDATE ON system_intent_denial_resumes BEGIN SELECT RAISE(ABORT,'SYSTEM_DENIAL_RESUME_IMMUTABLE');END;";
|
||||
const CLAIM_RESUME: &str = "INSERT OR IGNORE INTO system_intent_denial_resumes(id,agent_instance,observed_at) VALUES(?1,?2,?3)";
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Intent {
|
||||
pub schema_version: u32,
|
||||
pub id: Uuid,
|
||||
pub request: Request,
|
||||
pub anchor: NoStartAnchor,
|
||||
pub original_boot_id: Uuid,
|
||||
pub agent_instance: Uuid,
|
||||
pub connection_generation: u64,
|
||||
pub recorded_at: DateTime<Utc>,
|
||||
pub policy_sha256: String,
|
||||
pub helper_binary_sha256: String,
|
||||
}
|
||||
impl Intent {
|
||||
pub fn digest(&self) -> Result<String> {
|
||||
Ok(hash(&serde_json::to_vec(self)?))
|
||||
}
|
||||
pub fn permit(&self) -> Result<ExecutionPermitPayload> {
|
||||
Ok(serde_json::from_slice(&self.request.permit_bytes)?)
|
||||
}
|
||||
fn validate(&self) -> Result<()> {
|
||||
ensure!(
|
||||
self.schema_version == 1
|
||||
&& !self.id.is_nil()
|
||||
&& !self.agent_instance.is_nil()
|
||||
&& !self.original_boot_id.is_nil()
|
||||
&& self.original_boot_id == self.anchor.boot_id()
|
||||
&& self.connection_generation == self.anchor.connection_generation()
|
||||
&& ipc::digest(&self.policy_sha256)
|
||||
&& ipc::digest(&self.helper_binary_sha256)
|
||||
&& serde_json::to_vec(self)?.len() <= 196608,
|
||||
"SYSTEM_INTENT_BINDING"
|
||||
);
|
||||
let p = self.permit()?;
|
||||
ensure!(
|
||||
p.execution_identity == "system"
|
||||
&& p.authorization_id == self.request.authorization_id
|
||||
&& p.plan_hash == self.request.plan_hash
|
||||
&& p.job_payload_hash == hash(&self.request.job_bytes),
|
||||
"SYSTEM_INTENT_REQUEST_BINDING"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub enum Phase {
|
||||
Prepared,
|
||||
KnownNoDispatch,
|
||||
MayHaveDispatched,
|
||||
}
|
||||
impl Phase {
|
||||
fn parse(s: &str) -> Result<Self> {
|
||||
match s {
|
||||
"prepared" => Ok(Self::Prepared),
|
||||
"known_no_dispatch" => Ok(Self::KnownNoDispatch),
|
||||
"may_have_dispatched" => Ok(Self::MayHaveDispatched),
|
||||
_ => anyhow::bail!("SYSTEM_INTENT_PHASE"),
|
||||
}
|
||||
}
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Prepared => "prepared",
|
||||
Self::KnownNoDispatch => "known_no_dispatch",
|
||||
Self::MayHaveDispatched => "may_have_dispatched",
|
||||
}
|
||||
}
|
||||
}
|
||||
fn advance(db: &mut Connection, id: Uuid, desired: Phase) -> Result<(usize, Phase)> {
|
||||
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let changed = tx.execute(
|
||||
"UPDATE system_intents SET phase=?2 WHERE id=?1 AND phase='prepared'",
|
||||
params![id.to_string(), desired.name()],
|
||||
)?;
|
||||
let phase: String = tx.query_row(
|
||||
"SELECT phase FROM system_intents WHERE id=?1",
|
||||
[id.to_string()],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
tx.commit()?;
|
||||
Ok((changed, Phase::parse(&phase)?))
|
||||
}
|
||||
pub struct Store {
|
||||
db: Connection,
|
||||
files: Vec<PinnedFile>,
|
||||
identity: FileIdentity,
|
||||
}
|
||||
impl Store {
|
||||
/// Bootstrap, never LocalService, creates both fixed leaves and their ACLs.
|
||||
/// PERSIST retains the precreated rollback journal, requiring no Actor delete
|
||||
/// or directory-create rights. A hot journal on the read-only side refuses.
|
||||
pub fn open(write: bool) -> Result<Self> {
|
||||
let actor = ipc::service_sid(crate::SERVICE_NAME)?;
|
||||
let root =
|
||||
PinnedFile::open_read_shared(Path::new(ROOT), true, std::slice::from_ref(&actor), &[])?;
|
||||
let mut files = vec![root];
|
||||
for path in [DB, &format!("{DB}-journal")] {
|
||||
let mut file = if write {
|
||||
PinnedFile::open(
|
||||
Path::new(path),
|
||||
false,
|
||||
&[],
|
||||
std::slice::from_ref(&actor),
|
||||
true,
|
||||
)?
|
||||
} else {
|
||||
PinnedFile::open_read_shared(
|
||||
Path::new(path),
|
||||
false,
|
||||
&[],
|
||||
std::slice::from_ref(&actor),
|
||||
)?
|
||||
};
|
||||
file.limit_writer_rights(ACTOR_RW)?;
|
||||
files.push(file);
|
||||
}
|
||||
let identity = files[1].identity;
|
||||
let flags = if write {
|
||||
OpenFlags::SQLITE_OPEN_READ_WRITE
|
||||
} else {
|
||||
OpenFlags::SQLITE_OPEN_READ_ONLY
|
||||
};
|
||||
let db = Connection::open_with_flags(DB, flags)?;
|
||||
db.busy_timeout(Duration::from_millis(250))?;
|
||||
if write {
|
||||
rmm_agent_core::ledger::bounded_journal_capacity(&db)?;
|
||||
let mode: String = db.query_row("PRAGMA journal_mode=PERSIST", [], |r| r.get(0))?;
|
||||
ensure!(mode == "persist", "SYSTEM_INTENT_JOURNAL_MODE");
|
||||
db.execute_batch("PRAGMA synchronous=FULL;PRAGMA temp_store=MEMORY;PRAGMA journal_size_limit=1048576;")?;
|
||||
db.execute_batch(SCHEMA)?;
|
||||
db.execute(
|
||||
"INSERT OR IGNORE INTO system_intent_meta VALUES(1,?1)",
|
||||
[serde_json::to_vec(&identity)?],
|
||||
)?;
|
||||
}
|
||||
let stored: Vec<u8> = db.query_row(
|
||||
"SELECT file_identity FROM system_intent_meta WHERE id=1",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(
|
||||
stored == serde_json::to_vec(&identity)?,
|
||||
"SYSTEM_INTENT_FILE_REPLACED"
|
||||
);
|
||||
ensure!(
|
||||
db.query_row("PRAGMA integrity_check", [], |r| r.get::<_, String>(0))? == "ok",
|
||||
"SYSTEM_INTENT_INTEGRITY"
|
||||
);
|
||||
let mut value = Self {
|
||||
db,
|
||||
files,
|
||||
identity,
|
||||
};
|
||||
value.check()?;
|
||||
Ok(value)
|
||||
}
|
||||
pub fn check(&mut self) -> Result<()> {
|
||||
for file in &mut self.files {
|
||||
file.check()?;
|
||||
}
|
||||
ensure!(
|
||||
ipc::file_identity(&self.files[1].file)? == self.identity,
|
||||
"SYSTEM_INTENT_FILE_REPLACED"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
pub fn prepare(&mut self, intent: &Intent) -> Result<()> {
|
||||
self.check()?;
|
||||
intent.validate()?;
|
||||
let tx = self
|
||||
.db
|
||||
.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let count: u64 = tx.query_row("SELECT count(*) FROM system_intents", [], |r| r.get(0))?;
|
||||
ensure!(count < 10000, "SYSTEM_INTENT_CAPACITY_BLOCKED");
|
||||
let busy:bool=tx.query_row("SELECT EXISTS(SELECT 1 FROM system_intents i WHERE NOT EXISTS(SELECT 1 FROM system_intent_mirrors m WHERE m.id=i.id))",[],|r|r.get(0))?;
|
||||
ensure!(!busy, "SYSTEM_DELEGATION_UNRESOLVED");
|
||||
let p = intent.permit()?;
|
||||
tx.execute("INSERT INTO system_intents(id,job,attempt,grant_id,body,digest,phase) VALUES(?1,?2,?3,?4,?5,?6,'prepared')",params![intent.id.to_string(),p.job_id.to_string(),p.attempt_id.to_string(),p.grant_id.to_string(),serde_json::to_vec(intent)?,intent.digest()?])?;
|
||||
tx.commit()?;
|
||||
self.check()
|
||||
}
|
||||
pub fn load(&self, id: Uuid) -> Result<(Intent, Phase)> {
|
||||
let (body, digest, phase): (Vec<u8>, String, String) = self.db.query_row(
|
||||
"SELECT body,digest,phase FROM system_intents WHERE id=?1",
|
||||
[id.to_string()],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
||||
)?;
|
||||
ensure!(
|
||||
body.len() <= 196608 && hash(&body) == digest,
|
||||
"SYSTEM_INTENT_DIGEST"
|
||||
);
|
||||
let intent: Intent = serde_json::from_slice(&body)?;
|
||||
intent.validate()?;
|
||||
ensure!(intent.id == id, "SYSTEM_INTENT_ID");
|
||||
Ok((intent, Phase::parse(&phase)?))
|
||||
}
|
||||
/// Both cancellation and dispatcher use this same transaction/CAS. A known
|
||||
/// non-dispatch can never follow the conservative may-dispatch marker.
|
||||
pub fn decide(&mut self, id: Uuid, dispatch: bool) -> Result<Phase> {
|
||||
self.check()?;
|
||||
let desired = if dispatch {
|
||||
Phase::MayHaveDispatched
|
||||
} else {
|
||||
Phase::KnownNoDispatch
|
||||
};
|
||||
let (changed, phase) = advance(&mut self.db, id, desired)?;
|
||||
self.check()?;
|
||||
ensure!(
|
||||
changed == 1 || phase != Phase::MayHaveDispatched,
|
||||
"SYSTEM_EXECUTE_REDELIVERY_FORBIDDEN"
|
||||
);
|
||||
Ok(phase)
|
||||
}
|
||||
pub fn cancel_before_dispatch(&mut self, id: Uuid) -> Result<Phase> {
|
||||
self.check()?;
|
||||
let (_, phase) = advance(&mut self.db, id, Phase::KnownNoDispatch)?;
|
||||
self.check()?;
|
||||
Ok(phase)
|
||||
}
|
||||
pub fn pending(&self) -> Result<Vec<Intent>> {
|
||||
let mut rows=self.db.prepare("SELECT i.id FROM system_intents i WHERE NOT EXISTS(SELECT 1 FROM system_intent_mirrors m WHERE m.id=i.id) ORDER BY i.rowid LIMIT 2")?;
|
||||
let ids = rows
|
||||
.query_map([], |r| r.get::<_, String>(0))?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
ensure!(ids.len() <= 1, "SYSTEM_MULTIPLE_PENDING_DELEGATIONS");
|
||||
ids.into_iter()
|
||||
.map(|id| self.load(Uuid::parse_str(&id)?).map(|v| v.0))
|
||||
.collect()
|
||||
}
|
||||
pub fn by_grant(&self, grant: Uuid) -> Result<Intent> {
|
||||
let id: String = self.db.query_row(
|
||||
"SELECT id FROM system_intents WHERE grant_id=?1",
|
||||
[grant.to_string()],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
Ok(self.load(Uuid::parse_str(&id)?)?.0)
|
||||
}
|
||||
/// One deny-only attempt per NEW process instance. Original intent/anchor
|
||||
/// bytes and the historical helper process binding are never rewritten.
|
||||
pub fn claim_denial_resume(
|
||||
&mut self,
|
||||
id: Uuid,
|
||||
instance: Uuid,
|
||||
boot: Uuid,
|
||||
observed_at: DateTime<Utc>,
|
||||
) -> Result<bool> {
|
||||
self.check()?;
|
||||
let (intent, phase) = self.load(id)?;
|
||||
ensure!(
|
||||
phase == Phase::KnownNoDispatch
|
||||
&& intent.original_boot_id == boot
|
||||
&& intent.agent_instance != instance
|
||||
&& !instance.is_nil()
|
||||
&& observed_at >= intent.recorded_at,
|
||||
"SYSTEM_DENIAL_RESUME_BINDING"
|
||||
);
|
||||
let changed = self.db.execute(
|
||||
CLAIM_RESUME,
|
||||
params![
|
||||
id.to_string(),
|
||||
instance.to_string(),
|
||||
observed_at.to_rfc3339()
|
||||
],
|
||||
)?;
|
||||
self.check()?;
|
||||
Ok(changed == 1)
|
||||
}
|
||||
pub fn mirrored(
|
||||
&mut self,
|
||||
id: Uuid,
|
||||
outcome_sha256: &str,
|
||||
observed_at: DateTime<Utc>,
|
||||
) -> Result<()> {
|
||||
self.check()?;
|
||||
ensure!(ipc::digest(outcome_sha256), "SYSTEM_MIRROR_HASH");
|
||||
let old: Option<String> = self
|
||||
.db
|
||||
.query_row(
|
||||
"SELECT outcome_sha256 FROM system_intent_mirrors WHERE id=?1",
|
||||
[id.to_string()],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.optional()?;
|
||||
if let Some(old) = old {
|
||||
ensure!(old == outcome_sha256, "SYSTEM_MIRROR_CONFLICT");
|
||||
return Ok(());
|
||||
}
|
||||
self.db.execute(
|
||||
"INSERT INTO system_intent_mirrors VALUES(?1,?2,?3)",
|
||||
params![id.to_string(), outcome_sha256, observed_at.to_rfc3339()],
|
||||
)?;
|
||||
self.check()
|
||||
}
|
||||
pub fn verify_no_dispatch(
|
||||
&mut self,
|
||||
id: Uuid,
|
||||
digest: &str,
|
||||
original: &Request,
|
||||
anchor: &NoStartAnchor,
|
||||
) -> Result<NoDispatchObservation> {
|
||||
self.check()?;
|
||||
let (intent, phase) = self.load(id)?;
|
||||
ensure!(
|
||||
phase == Phase::KnownNoDispatch
|
||||
&& intent.digest()? == digest
|
||||
&& serde_json::to_vec(&intent.request)? == serde_json::to_vec(original)?
|
||||
&& serde_json::to_vec(&intent.anchor)? == serde_json::to_vec(anchor)?,
|
||||
"SYSTEM_NO_DISPATCH_PROOF_INVALID"
|
||||
);
|
||||
self.check()?;
|
||||
Ok(NoDispatchObservation {
|
||||
intent_id: id,
|
||||
intent_sha256: digest.into(),
|
||||
intent_recorded_at: intent.recorded_at,
|
||||
original_boot_id: intent.original_boot_id,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn cancel_and_dispatch_cas_are_exclusive_and_history_cannot_be_rewritten() {
|
||||
let mut db = Connection::open_in_memory().unwrap();
|
||||
db.execute_batch(SCHEMA).unwrap();
|
||||
let cancelled = Uuid::new_v4();
|
||||
let dispatched = Uuid::new_v4();
|
||||
for id in [cancelled, dispatched] {
|
||||
db.execute(
|
||||
"INSERT INTO system_intents VALUES(?1,?1,?1,?1,x'01','immutable','prepared')",
|
||||
[id.to_string()],
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
assert_eq!(
|
||||
advance(&mut db, cancelled, Phase::KnownNoDispatch).unwrap(),
|
||||
(1, Phase::KnownNoDispatch)
|
||||
);
|
||||
assert_eq!(
|
||||
advance(&mut db, cancelled, Phase::MayHaveDispatched).unwrap(),
|
||||
(0, Phase::KnownNoDispatch)
|
||||
);
|
||||
assert_eq!(
|
||||
advance(&mut db, dispatched, Phase::MayHaveDispatched).unwrap(),
|
||||
(1, Phase::MayHaveDispatched)
|
||||
);
|
||||
assert_eq!(
|
||||
advance(&mut db, dispatched, Phase::KnownNoDispatch).unwrap(),
|
||||
(0, Phase::MayHaveDispatched)
|
||||
);
|
||||
assert!(
|
||||
db.execute(
|
||||
"UPDATE system_intents SET phase='prepared' WHERE id=?1",
|
||||
[dispatched.to_string()]
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
db.execute(
|
||||
"UPDATE system_intents SET body=x'02' WHERE id=?1",
|
||||
[cancelled.to_string()]
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
db.execute(
|
||||
"DELETE FROM system_intents WHERE id=?1",
|
||||
[cancelled.to_string()]
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
let retained: u64 = db
|
||||
.query_row("SELECT count(*) FROM system_intents", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
assert_eq!(retained, 2);
|
||||
let resumed = Uuid::new_v4();
|
||||
let args = params![
|
||||
cancelled.to_string(),
|
||||
resumed.to_string(),
|
||||
Utc::now().to_rfc3339()
|
||||
];
|
||||
assert_eq!(db.execute(CLAIM_RESUME, args).unwrap(), 1);
|
||||
assert_eq!(db.execute(CLAIM_RESUME, args).unwrap(), 0);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user