216 lines
8.6 KiB
Rust
216 lines
8.6 KiB
Rust
//! Persist the exact test offer through service and binary restarts.
|
|
//! A subsequent, separate operator decision is needed to change this constraint.
|
|
use anyhow::{Context, Result, ensure};
|
|
use prost::Message;
|
|
use rmm_domain::{
|
|
jobs::{JobPayload, hash},
|
|
windows_echo_probe::ProbeScope,
|
|
};
|
|
use rmm_protocol::JobOffer;
|
|
use rusqlite::{Connection, Transaction, params};
|
|
use uuid::Uuid;
|
|
|
|
pub const TABLE: &str = "windows_echo_probe_scope";
|
|
pub const OBJECTS: [&str; 6] = [
|
|
TABLE,
|
|
"windows_echo_probe_no_replace",
|
|
"windows_echo_probe_no_change",
|
|
"windows_echo_probe_no_delete",
|
|
"windows_echo_probe_offer_insert",
|
|
"windows_echo_probe_offer_update",
|
|
];
|
|
const POLICY: &str = "CREATE TABLE windows_echo_probe_scope(id INTEGER PRIMARY KEY CHECK(id=1),scope BLOB NOT NULL,review BLOB NOT NULL,job TEXT NOT NULL,attempt TEXT NOT NULL,prefix BLOB NOT NULL,suffix BLOB NOT NULL)";
|
|
const IMMUTABLE: &str = "CREATE TRIGGER windows_echo_probe_no_change BEFORE UPDATE ON windows_echo_probe_scope BEGIN SELECT RAISE(ABORT,'WINDOWS_ECHO_SCOPE_IMMUTABLE'); END";
|
|
const RETAIN: &str = "CREATE TRIGGER windows_echo_probe_no_delete BEFORE DELETE ON windows_echo_probe_scope BEGIN SELECT RAISE(ABORT,'WINDOWS_ECHO_SCOPE_IMMUTABLE'); END";
|
|
const BOUND: &str = "WHEN NOT EXISTS(SELECT 1 FROM windows_echo_probe_scope s WHERE s.id=1 AND s.job=NEW.job AND s.attempt=NEW.attempt AND typeof(NEW.offer)='blob' AND length(NEW.offer)=length(s.prefix)+36+length(s.suffix) AND substr(NEW.offer,1,length(s.prefix))=s.prefix AND substr(NEW.offer,-length(s.suffix))=s.suffix) BEGIN SELECT RAISE(ABORT,'WINDOWS_ECHO_OFFER_OUT_OF_SCOPE'); END";
|
|
|
|
fn schema(completed: bool) -> [String; 6] {
|
|
let bound = if completed {
|
|
BOUND.replacen(
|
|
"WHEN ",
|
|
"WHEN NOT EXISTS(SELECT 1 FROM windows_echo_scope_completion WHERE id=1) AND ",
|
|
1,
|
|
)
|
|
} else {
|
|
BOUND.to_owned()
|
|
};
|
|
[
|
|
POLICY.to_owned(),
|
|
"CREATE TRIGGER windows_echo_probe_no_replace BEFORE INSERT ON windows_echo_probe_scope WHEN EXISTS(SELECT 1 FROM windows_echo_probe_scope) BEGIN SELECT RAISE(ABORT,'WINDOWS_ECHO_SCOPE_IMMUTABLE'); END".to_owned(),
|
|
IMMUTABLE.to_owned(),
|
|
RETAIN.to_owned(),
|
|
format!(
|
|
"CREATE TRIGGER windows_echo_probe_offer_insert BEFORE INSERT ON job_attempts {bound}"
|
|
),
|
|
format!(
|
|
"CREATE TRIGGER windows_echo_probe_offer_update BEFORE UPDATE OF job,attempt,offer ON job_attempts {bound}"
|
|
),
|
|
]
|
|
}
|
|
fn blobs(scope: &ProbeScope, payload: &[u8]) -> Result<(Vec<u8>, Vec<u8>)> {
|
|
let job: JobPayload = serde_json::from_slice(payload)?;
|
|
ensure!(
|
|
scope.matches_job(&job)
|
|
&& serde_json::to_vec(&job)? == payload
|
|
&& hash(payload) == scope.job_payload_hash,
|
|
"echo job bytes"
|
|
);
|
|
let offer = JobOffer {
|
|
job_id: job.job_id.to_string(),
|
|
attempt_id: job.attempt_id.to_string(),
|
|
authorization_id: Uuid::nil().to_string(),
|
|
plan_hash: scope.plan_hash.clone(),
|
|
job_payload_hash: scope.job_payload_hash.clone(),
|
|
payload_bytes: payload.to_vec(),
|
|
};
|
|
// Derive the span of the sole variable protobuf field, whose canonical UUID
|
|
// is separately checked by normal offer and signed grant verification.
|
|
let base = offer.encode_to_vec();
|
|
let changed = JobOffer {
|
|
authorization_id: "x".repeat(36),
|
|
..offer
|
|
}
|
|
.encode_to_vec();
|
|
let at = base
|
|
.iter()
|
|
.zip(&changed)
|
|
.position(|(a, b)| a != b)
|
|
.context("authorization span")?;
|
|
ensure!(
|
|
base.len() == changed.len()
|
|
&& base[at..at + 36] == *Uuid::nil().to_string().as_bytes()
|
|
&& base[at + 36..] == changed[at + 36..],
|
|
"authorization wire shape"
|
|
);
|
|
Ok((base[..at].to_vec(), base[at + 36..].to_vec()))
|
|
}
|
|
pub fn install(
|
|
tx: &Transaction<'_>,
|
|
scope: &ProbeScope,
|
|
payload: &[u8],
|
|
review: &[u8],
|
|
) -> Result<()> {
|
|
let (prefix, suffix) = blobs(scope, payload)?;
|
|
for sql in schema(false) {
|
|
tx.execute_batch(&sql)?;
|
|
}
|
|
tx.execute(
|
|
"INSERT INTO windows_echo_probe_scope VALUES(1,?,?,?,?,?,?)",
|
|
params![
|
|
serde_json::to_vec(scope)?,
|
|
review,
|
|
scope.job_id.to_string(),
|
|
scope.attempt_id.to_string(),
|
|
prefix,
|
|
suffix
|
|
],
|
|
)?;
|
|
check(tx, scope, payload, review)
|
|
}
|
|
pub fn check(db: &Connection, scope: &ProbeScope, payload: &[u8], review: &[u8]) -> Result<()> {
|
|
let (prefix, suffix) = blobs(scope, payload)?;
|
|
let completed: bool = db.query_row(
|
|
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE name='windows_echo_scope_completion')",
|
|
[],
|
|
|r| r.get(0),
|
|
)?;
|
|
for (name, expected) in OBJECTS.iter().zip(schema(completed)) {
|
|
let actual: String =
|
|
db.query_row("SELECT sql FROM sqlite_schema WHERE name=?", [name], |r| {
|
|
r.get(0)
|
|
})?;
|
|
ensure!(actual == expected, "echo scope schema");
|
|
}
|
|
let matches: bool=db.query_row("SELECT EXISTS(SELECT 1 FROM windows_echo_probe_scope WHERE id=1 AND scope=? AND review=? AND job=? AND attempt=? AND prefix=? AND suffix=?)", params![serde_json::to_vec(scope)?,review,scope.job_id.to_string(),scope.attempt_id.to_string(),prefix,suffix],|r|r.get(0))?;
|
|
ensure!(matches, "stored echo scope");
|
|
Ok(())
|
|
}
|
|
pub fn installed(
|
|
db: &Connection,
|
|
binding: &rmm_agent_core::auth::Binding,
|
|
) -> Result<Option<ProbeScope>> {
|
|
let Some((scope, raw)) = archive(db, binding)? else {
|
|
return Ok(None);
|
|
};
|
|
if crate::echo_completion::installed(db, binding, &scope, &raw)? {
|
|
return Ok(None);
|
|
}
|
|
Ok(Some(scope))
|
|
}
|
|
|
|
/// Verify the retained original, including after the separately reviewed completion.
|
|
pub fn archive(
|
|
db: &Connection,
|
|
binding: &rmm_agent_core::auth::Binding,
|
|
) -> Result<Option<(ProbeScope, Vec<u8>)>> {
|
|
use rmm_agent_core::crypto::{DalekVerifier, Ed25519Verifier};
|
|
use rmm_domain::{
|
|
checkpoint_repair::SignedReceipt, windows_echo_probe::ProbeReceipt,
|
|
windows_sync_history::case_witness,
|
|
};
|
|
let objects:u32=db.query_row("SELECT count(*) FROM sqlite_schema WHERE name IN ('windows_echo_probe_scope','windows_echo_checkpoint_recovery')",[],|r|r.get(0))?;
|
|
if objects == 0 {
|
|
return Ok(None);
|
|
}
|
|
ensure!(objects == 2, "incomplete Echo scope archive");
|
|
let raw:Vec<u8>=db.query_row("SELECT original_receipt FROM windows_echo_checkpoint_recovery WHERE id=1 AND length(original_receipt) BETWEEN 1 AND 65536",[],|r|r.get(0))?;
|
|
let envelope: SignedReceipt = serde_json::from_slice(&raw)?;
|
|
let r: ProbeReceipt = serde_json::from_slice(&envelope.payload)?;
|
|
let b = &binding.public_key_hex;
|
|
ensure!(b.len() == 64 && b.is_ascii(), "echo job pin size");
|
|
let key = (0..64)
|
|
.step_by(2)
|
|
.map(|i| u8::from_str_radix(&b[i..i + 2], 16))
|
|
.collect::<std::result::Result<Vec<_>, _>>()?;
|
|
ensure!(
|
|
hash(&key) == r.key_id
|
|
&& DalekVerifier.verify(&key, &envelope.payload, &envelope.signature)?
|
|
&& r.matches_reviewed_witness(&case_witness(), r.issued_at),
|
|
"Echo archive signature"
|
|
);
|
|
check(db, &r.scope, &r.job_payload_bytes, &raw)?;
|
|
Ok(Some((r.scope, raw)))
|
|
}
|
|
|
|
pub(crate) fn retire_triggers(tx: &Transaction<'_>) -> Result<()> {
|
|
for name in &OBJECTS[4..] {
|
|
tx.execute_batch(&format!("DROP TRIGGER {name}"))?;
|
|
}
|
|
for ddl in &schema(true)[4..] {
|
|
tx.execute_batch(ddl)?;
|
|
}
|
|
Ok(())
|
|
}
|
|
pub fn permits_offer(scope: &ProbeScope, offer: &JobOffer, job: &JobPayload) -> bool {
|
|
scope.matches_job(job)
|
|
&& scope.job_id.to_string() == offer.job_id
|
|
&& scope.attempt_id.to_string() == offer.attempt_id
|
|
&& scope.plan_hash == offer.plan_hash
|
|
&& scope.job_payload_hash == offer.job_payload_hash
|
|
&& hash(&offer.payload_bytes) == scope.job_payload_hash
|
|
}
|
|
|
|
#[cfg(all(windows, feature = "system-helper"))]
|
|
pub fn protected_scope() -> Result<ProbeScope> {
|
|
use crate::{
|
|
SERVICE_NAME,
|
|
helper_ipc::{self, PinnedFile},
|
|
};
|
|
use std::{io::Read, path::Path};
|
|
let path = Path::new(r"C:\ProgramData\RustDiscovery\windows-echo-scope.json");
|
|
let readers = [helper_ipc::service_sid(SERVICE_NAME)?];
|
|
let _root = PinnedFile::open(
|
|
path.parent().context("echo scope parent")?,
|
|
true,
|
|
&readers,
|
|
&[],
|
|
false,
|
|
)?;
|
|
let mut file = PinnedFile::open(path, false, &readers, &[], false)?;
|
|
let mut bytes = Vec::new();
|
|
(&mut file.file).take(8193).read_to_end(&mut bytes)?;
|
|
ensure!(bytes.len() <= 8192, "echo scope size");
|
|
file.check()?;
|
|
Ok(serde_json::from_slice(&bytes)?)
|
|
}
|