Add reviewed Windows scope completion and idle certificate renewal; deploy completion API
Rust development slice / linux (push) Failing after 7s
Rust development slice / linux (push) Failing after 7s
This commit is contained in:
@@ -0,0 +1,278 @@
|
||||
//! File-swap fence against the SAME original guarded SYSTEM helper ledger.
|
||||
//! Construction never re-enters a partial replacement or creates a handoff.
|
||||
use super::{
|
||||
Budget, DurableEffectFence, Effect, Role, digest,
|
||||
files::{self, Location, Proof},
|
||||
};
|
||||
use anyhow::{Result, ensure};
|
||||
use rmm_agent_core::{
|
||||
reconcile::SyncClock,
|
||||
update_handoff::{
|
||||
self as core, NativeEffect, NativeEffectClaim, NativeFileRole, Participant,
|
||||
UpdateParticipantGuard,
|
||||
},
|
||||
};
|
||||
use rmm_updater_handoff::{Evidence, Handoff, Phase, PinTransition};
|
||||
use rusqlite::Connection;
|
||||
|
||||
const ROLES: [Role; 5] = [
|
||||
Role::Agent,
|
||||
Role::Helper,
|
||||
Role::Settings,
|
||||
Role::Pin,
|
||||
Role::TimeProfile,
|
||||
];
|
||||
fn native(role: Role) -> NativeFileRole {
|
||||
match role {
|
||||
Role::Agent => NativeFileRole::AgentBinary,
|
||||
Role::Helper => NativeFileRole::HelperBinary,
|
||||
Role::Settings => NativeFileRole::WindowsSettings,
|
||||
Role::Pin => NativeFileRole::WindowsPin,
|
||||
Role::TimeProfile => NativeFileRole::WindowsTimeProfile,
|
||||
}
|
||||
}
|
||||
pub struct LedgerFence<'a, 'b, G, C> {
|
||||
db: &'a mut Connection,
|
||||
guard: &'a G,
|
||||
clock: &'a C,
|
||||
budget: &'a Budget<'b>,
|
||||
original: Handoff,
|
||||
originals: &'a [Proof; 5],
|
||||
staged: &'a [Proof; 5],
|
||||
pending: Option<(Effect, NativeEffectClaim)>,
|
||||
next: usize,
|
||||
saved: bool,
|
||||
poisoned: bool,
|
||||
}
|
||||
/// Bindings are independently re-read before effects; parsed/transferred Proof
|
||||
/// records never substitute for actual protected file identities/bytes.
|
||||
pub struct Inputs<'a, 'b, G, C> {
|
||||
pub db: &'a mut Connection,
|
||||
pub guard: &'a G,
|
||||
pub clock: &'a C,
|
||||
pub budget: &'a Budget<'b>,
|
||||
pub original: &'a Handoff,
|
||||
pub originals: &'a [Proof; 5],
|
||||
pub staged: &'a [Proof; 5],
|
||||
}
|
||||
impl<'a, 'b, G: UpdateParticipantGuard, C: SyncClock> LedgerFence<'a, 'b, G, C> {
|
||||
pub fn new(input: Inputs<'a, 'b, G, C>) -> Result<Self> {
|
||||
input.budget.check()?;
|
||||
input.original.validate()?;
|
||||
ensure!(
|
||||
input.original.pin_transition == PinTransition::WindowsCodePairClockV1
|
||||
&& input.guard.participant() == Participant::StableUpdater,
|
||||
"UPDATE_WINDOWS_FENCE_ROLE"
|
||||
);
|
||||
let grant = input.original.attempt.grant_id;
|
||||
let journal = core::read(input.db, input.guard, grant)?;
|
||||
ensure!(
|
||||
journal.phase() == Phase::UpdaterOwnsLedger,
|
||||
"UPDATE_NO_FENCE_RESUME"
|
||||
);
|
||||
// Retained Handoff is immutable and read through the actual executor
|
||||
// guard. No separately supplied record may stand in for those bytes.
|
||||
let raw: Vec<u8> = input.db.query_row(
|
||||
"SELECT record FROM agent_update_handoffs WHERE grant_id=?1",
|
||||
[grant.to_string()],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(
|
||||
raw == input.original.bytes()?,
|
||||
"UPDATE_WINDOWS_ORIGINAL_HANDOFF"
|
||||
);
|
||||
for (i, role) in ROLES.iter().copied().enumerate() {
|
||||
let original = &input.original.files[i];
|
||||
ensure!(
|
||||
original.role == role.handoff_role()
|
||||
&& original.old_sha256 == input.originals[i].sha256
|
||||
&& original.new_sha256 == input.staged[i].sha256
|
||||
&& input.originals[i].identity.volume_serial
|
||||
== input.staged[i].identity.volume_serial
|
||||
&& input.originals[i].identity != input.staged[i].identity
|
||||
&& input.originals[i].security_sha256 == input.staged[i].security_sha256
|
||||
&& files::observe_bound(
|
||||
role,
|
||||
input.original.owner_nonce,
|
||||
Location::Target,
|
||||
input.budget
|
||||
)? == input.originals[i]
|
||||
&& files::observe_bound(
|
||||
role,
|
||||
input.original.owner_nonce,
|
||||
Location::Stage,
|
||||
input.budget
|
||||
)? == input.staged[i],
|
||||
"UPDATE_WINDOWS_SWAP_FILES"
|
||||
);
|
||||
}
|
||||
Ok(Self {
|
||||
db: input.db,
|
||||
guard: input.guard,
|
||||
clock: input.clock,
|
||||
budget: input.budget,
|
||||
original: input.original.clone(),
|
||||
originals: input.originals,
|
||||
staged: input.staged,
|
||||
pending: None,
|
||||
next: 0,
|
||||
saved: false,
|
||||
poisoned: false,
|
||||
})
|
||||
}
|
||||
fn append(&mut self, evidence: Evidence) -> Result<()> {
|
||||
self.budget.check()?;
|
||||
let grant = self.original.attempt.grant_id;
|
||||
let journal = core::read(self.db, self.guard, grant)?;
|
||||
let now = self.clock.reading()?.upper;
|
||||
ensure!(
|
||||
u64::try_from(now.timestamp())? < self.original.finish_before,
|
||||
"UPDATE_WINDOWS_DEADLINE"
|
||||
);
|
||||
let bytes = journal.prepare(u64::try_from(now.timestamp())?, evidence)?;
|
||||
core::append(self.db, self.guard, grant, journal.head_sha256(), &bytes)
|
||||
}
|
||||
pub fn finish(mut self) -> Result<()> {
|
||||
ensure!(
|
||||
!self.poisoned && self.pending.is_none() && self.next == ROLES.len() && !self.saved,
|
||||
"UPDATE_WINDOWS_FENCE_INCOMPLETE"
|
||||
);
|
||||
for (i, role) in ROLES.iter().copied().enumerate() {
|
||||
ensure!(
|
||||
files::observe_bound(
|
||||
role,
|
||||
self.original.owner_nonce,
|
||||
Location::Target,
|
||||
self.budget
|
||||
)? == self.staged[i]
|
||||
&& files::observe_bound(
|
||||
role,
|
||||
self.original.owner_nonce,
|
||||
Location::Previous,
|
||||
self.budget
|
||||
)? == self.originals[i],
|
||||
"UPDATE_WINDOWS_FINAL_PAIR_CHANGED"
|
||||
);
|
||||
}
|
||||
self.append(Evidence::PairVerified {
|
||||
pair: self.original.target.clone(),
|
||||
retained_state_sha256: self.original.retained_state_sha256.clone(),
|
||||
})
|
||||
}
|
||||
}
|
||||
impl<G: UpdateParticipantGuard, C: SyncClock> DurableEffectFence for LedgerFence<'_, '_, G, C> {
|
||||
fn before_effect(&mut self, effect: &Effect) -> Result<()> {
|
||||
ensure!(
|
||||
!self.poisoned && self.pending.is_none() && self.next < ROLES.len(),
|
||||
"UPDATE_WINDOWS_FENCE_REENTRY"
|
||||
);
|
||||
self.poisoned = true;
|
||||
self.budget.check()?;
|
||||
let role = ROLES[self.next];
|
||||
let native = match *effect {
|
||||
Effect::SavePredecessor { role: r } if r == role && !self.saved => {
|
||||
ensure!(
|
||||
files::observe_bound(
|
||||
role,
|
||||
self.original.owner_nonce,
|
||||
Location::Target,
|
||||
self.budget
|
||||
)? == self.originals[self.next]
|
||||
&& files::observe_bound(
|
||||
role,
|
||||
self.original.owner_nonce,
|
||||
Location::Stage,
|
||||
self.budget
|
||||
)? == self.staged[self.next],
|
||||
"UPDATE_WINDOWS_FILES_CHANGED"
|
||||
);
|
||||
self.append(Evidence::ReplaceIntent {
|
||||
role: role.handoff_role(),
|
||||
})?;
|
||||
NativeEffect::SavePredecessor { role: native(role) }
|
||||
}
|
||||
Effect::PublishReplacement { role: r } if r == role && self.saved => {
|
||||
ensure!(
|
||||
files::observe_bound(
|
||||
role,
|
||||
self.original.owner_nonce,
|
||||
Location::Previous,
|
||||
self.budget
|
||||
)? == self.originals[self.next]
|
||||
&& files::observe_bound(
|
||||
role,
|
||||
self.original.owner_nonce,
|
||||
Location::Stage,
|
||||
self.budget
|
||||
)? == self.staged[self.next],
|
||||
"UPDATE_WINDOWS_FILES_CHANGED"
|
||||
);
|
||||
NativeEffect::PublishReplacement { role: native(role) }
|
||||
}
|
||||
_ => anyhow::bail!("UPDATE_WINDOWS_SWAP_FENCE_SCOPE"),
|
||||
};
|
||||
let journal = core::read(self.db, self.guard, self.original.attempt.grant_id)?;
|
||||
let claim = core::claim_native_effect(
|
||||
self.db,
|
||||
self.guard,
|
||||
self.original.attempt.grant_id,
|
||||
journal.head_sha256(),
|
||||
&native,
|
||||
self.clock.reading()?.upper,
|
||||
)?;
|
||||
self.pending = Some((effect.clone(), claim));
|
||||
Ok(())
|
||||
}
|
||||
fn after_effect(&mut self, effect: &Effect, observation: &str) -> Result<()> {
|
||||
let (expected, claim) = self
|
||||
.pending
|
||||
.take()
|
||||
.ok_or_else(|| anyhow::anyhow!("UPDATE_WINDOWS_EFFECT_NOT_CLAIMED"))?;
|
||||
ensure!(
|
||||
self.poisoned && *effect == expected,
|
||||
"UPDATE_WINDOWS_EFFECT_CALLBACK_CHANGED"
|
||||
);
|
||||
self.budget.check()?;
|
||||
let role = ROLES[self.next];
|
||||
let replaced = matches!(effect, Effect::PublishReplacement { .. });
|
||||
let proof = files::observe_bound(
|
||||
role,
|
||||
self.original.owner_nonce,
|
||||
if replaced {
|
||||
Location::Target
|
||||
} else {
|
||||
Location::Previous
|
||||
},
|
||||
self.budget,
|
||||
)?;
|
||||
ensure!(
|
||||
proof
|
||||
== if replaced {
|
||||
self.staged[self.next].clone()
|
||||
} else {
|
||||
self.originals[self.next].clone()
|
||||
}
|
||||
&& digest(&serde_json::to_vec(&proof)?) == observation,
|
||||
"UPDATE_WINDOWS_EFFECT_READBACK_CHANGED"
|
||||
);
|
||||
core::observe_native_effect(
|
||||
self.db,
|
||||
self.guard,
|
||||
&claim,
|
||||
observation,
|
||||
self.clock.reading()?.upper,
|
||||
)?;
|
||||
if replaced {
|
||||
self.append(Evidence::Replaced {
|
||||
role: role.handoff_role(),
|
||||
observed_sha256: proof.sha256,
|
||||
})?;
|
||||
self.next += 1;
|
||||
self.saved = false;
|
||||
} else {
|
||||
self.saved = true;
|
||||
}
|
||||
self.poisoned = false;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,576 @@
|
||||
//! Fixed-file, same-volume native staging and one-step-at-a-time publication.
|
||||
//! No archive extraction, free target path, overwrite, replacement of journals,
|
||||
//! or implicit retry/rollback. A failed rename/readback is an uncertain effect.
|
||||
use super::{Budget, DurableEffectFence, Effect, Role, digest, valid_digest};
|
||||
use crate::{
|
||||
helper_ipc::{self as ipc, FileIdentity, PinnedFile},
|
||||
job_binding,
|
||||
};
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{Read, Seek, SeekFrom, Write},
|
||||
mem::{offset_of, size_of, zeroed},
|
||||
os::windows::{
|
||||
ffi::OsStrExt,
|
||||
io::{AsRawHandle, FromRawHandle},
|
||||
},
|
||||
path::{Path, PathBuf},
|
||||
ptr,
|
||||
};
|
||||
use uuid::Uuid;
|
||||
use windows_sys::Win32::{
|
||||
Foundation::{INVALID_HANDLE_VALUE, LocalFree},
|
||||
Security::{
|
||||
self,
|
||||
Authorization::{GetSecurityInfo, SE_FILE_OBJECT},
|
||||
SECURITY_ATTRIBUTES,
|
||||
},
|
||||
Storage::FileSystem::*,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Proof {
|
||||
pub identity: FileIdentity,
|
||||
pub bytes: u64,
|
||||
pub sha256: String,
|
||||
pub security_sha256: String,
|
||||
}
|
||||
/// All ancestors remain open without DELETE sharing. The protected immediate
|
||||
/// directory also remains pinned by file identity/owner/DACL throughout effects.
|
||||
struct Directory {
|
||||
root: PinnedFile,
|
||||
ancestors: Vec<File>,
|
||||
}
|
||||
fn regular(file: &File, directory: bool) -> Result<()> {
|
||||
let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { zeroed() };
|
||||
ensure!(
|
||||
unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut info) } != 0
|
||||
&& info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT == 0
|
||||
&& (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY != 0) == directory
|
||||
&& (directory || info.nNumberOfLinks == 1),
|
||||
"UPDATE_NONREGULAR_FILE"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
fn open(
|
||||
path: &Path,
|
||||
desired: u32,
|
||||
creation: u32,
|
||||
security: *const SECURITY_ATTRIBUTES,
|
||||
) -> Result<File> {
|
||||
let handle = unsafe {
|
||||
CreateFileW(
|
||||
ipc::wide(path).as_ptr(),
|
||||
desired,
|
||||
FILE_SHARE_READ,
|
||||
security,
|
||||
creation,
|
||||
FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_WRITE_THROUGH,
|
||||
ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
ensure!(
|
||||
handle != INVALID_HANDLE_VALUE,
|
||||
"UPDATE_NATIVE_FILE_OPEN: {}",
|
||||
std::io::Error::last_os_error()
|
||||
);
|
||||
let file = unsafe { File::from_raw_handle(handle) };
|
||||
regular(&file, false)?;
|
||||
Ok(file)
|
||||
}
|
||||
impl Directory {
|
||||
fn open(role: Role) -> Result<Self> {
|
||||
let path = Path::new(role.target())
|
||||
.parent()
|
||||
.context("UPDATE_TARGET_DIRECTORY")?;
|
||||
let readers = vec![
|
||||
ipc::service_sid(crate::SERVICE_NAME)?,
|
||||
ipc::service_sid(ipc::HELPER_SERVICE)?,
|
||||
];
|
||||
let root = PinnedFile::open_read_shared(path, true, &readers, &[])?;
|
||||
let mut ancestors = Vec::new();
|
||||
for ancestor in path.ancestors().skip(1) {
|
||||
let raw = unsafe {
|
||||
CreateFileW(
|
||||
ipc::wide(ancestor).as_ptr(),
|
||||
FILE_READ_ATTRIBUTES,
|
||||
FILE_SHARE_READ | FILE_SHARE_WRITE,
|
||||
ptr::null(),
|
||||
OPEN_EXISTING,
|
||||
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
|
||||
ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
ensure!(raw != INVALID_HANDLE_VALUE, "UPDATE_ANCESTOR_OPEN");
|
||||
let file = unsafe { File::from_raw_handle(raw) };
|
||||
regular(&file, true)?;
|
||||
ancestors.push(file);
|
||||
}
|
||||
Ok(Self { root, ancestors })
|
||||
}
|
||||
fn check(&mut self) -> Result<()> {
|
||||
self.root.check()?;
|
||||
for ancestor in &self.ancestors {
|
||||
regular(ancestor, true)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn child(&self, name: &str) -> PathBuf {
|
||||
self.root.path.join(name)
|
||||
}
|
||||
}
|
||||
struct SecurityDescriptor(*mut core::ffi::c_void);
|
||||
impl Drop for SecurityDescriptor {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
LocalFree(self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
impl SecurityDescriptor {
|
||||
fn read(file: &File) -> Result<Self> {
|
||||
let mut descriptor = ptr::null_mut();
|
||||
ensure!(
|
||||
unsafe {
|
||||
GetSecurityInfo(
|
||||
file.as_raw_handle(),
|
||||
SE_FILE_OBJECT,
|
||||
Security::OWNER_SECURITY_INFORMATION
|
||||
| Security::GROUP_SECURITY_INFORMATION
|
||||
| Security::DACL_SECURITY_INFORMATION,
|
||||
ptr::null_mut(),
|
||||
ptr::null_mut(),
|
||||
ptr::null_mut(),
|
||||
ptr::null_mut(),
|
||||
&mut descriptor,
|
||||
)
|
||||
} == 0
|
||||
&& !descriptor.is_null(),
|
||||
"UPDATE_FILE_SECURITY"
|
||||
);
|
||||
Ok(Self(descriptor))
|
||||
}
|
||||
fn hash(&self) -> Result<String> {
|
||||
let mut owner = ptr::null_mut();
|
||||
let mut group = ptr::null_mut();
|
||||
let mut defaulted = 0;
|
||||
let mut present = 0;
|
||||
let mut acl = ptr::null_mut();
|
||||
let mut control = 0;
|
||||
let mut revision = 0;
|
||||
ensure!(
|
||||
unsafe {
|
||||
Security::GetSecurityDescriptorOwner(self.0, &mut owner, &mut defaulted) != 0
|
||||
&& Security::GetSecurityDescriptorGroup(self.0, &mut group, &mut defaulted) != 0
|
||||
&& Security::GetSecurityDescriptorDacl(
|
||||
self.0,
|
||||
&mut present,
|
||||
&mut acl,
|
||||
&mut defaulted,
|
||||
) != 0
|
||||
&& Security::GetSecurityDescriptorControl(self.0, &mut control, &mut revision)
|
||||
!= 0
|
||||
} && !owner.is_null()
|
||||
&& !group.is_null()
|
||||
&& present != 0
|
||||
&& !acl.is_null(),
|
||||
"UPDATE_FILE_SECURITY_PARTS"
|
||||
);
|
||||
// Only actual owner, group, ACL bytes and inheritance protection are
|
||||
// hashed. Windows may clear the informational AUTO_INHERITED bit when
|
||||
// creating an explicitly protected object; that bit grants no rights.
|
||||
let mut bytes = Vec::new();
|
||||
for sid in [owner, group] {
|
||||
let len = unsafe { Security::GetLengthSid(sid) };
|
||||
ensure!((8..=256).contains(&len), "UPDATE_SECURITY_SID_SIZE");
|
||||
bytes.extend_from_slice(&len.to_le_bytes());
|
||||
bytes.extend_from_slice(unsafe {
|
||||
std::slice::from_raw_parts(sid.cast::<u8>(), len as usize)
|
||||
});
|
||||
}
|
||||
let len = unsafe { (*acl).AclSize };
|
||||
ensure!(
|
||||
(size_of::<Security::ACL>() as u16..=32768).contains(&len),
|
||||
"UPDATE_SECURITY_ACL_SIZE"
|
||||
);
|
||||
bytes.extend_from_slice(&(control & Security::SE_DACL_PROTECTED).to_le_bytes());
|
||||
bytes.extend_from_slice(unsafe {
|
||||
std::slice::from_raw_parts(acl.cast::<u8>(), len as usize)
|
||||
});
|
||||
Ok(digest(&bytes))
|
||||
}
|
||||
fn attributes(&self) -> SECURITY_ATTRIBUTES {
|
||||
SECURITY_ATTRIBUTES {
|
||||
nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
|
||||
lpSecurityDescriptor: self.0,
|
||||
bInheritHandle: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
fn hash_file(file: &mut File, max: u64) -> Result<String> {
|
||||
ensure!((1..=256 * 1024 * 1024).contains(&max), "UPDATE_FILE_LIMIT");
|
||||
file.seek(SeekFrom::Start(0))?;
|
||||
let mut hash = Sha256::new();
|
||||
let mut count = 0u64;
|
||||
let mut buf = [0u8; 65536];
|
||||
loop {
|
||||
let read = file.read(&mut buf)?;
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
count = count
|
||||
.checked_add(read as u64)
|
||||
.context("UPDATE_FILE_LIMIT")?;
|
||||
ensure!(count <= max, "UPDATE_FILE_LIMIT");
|
||||
hash.update(&buf[..read]);
|
||||
}
|
||||
Ok(format!("{:x}", hash.finalize()))
|
||||
}
|
||||
fn proof(file: &mut File, path: &Path, max: u64) -> Result<Proof> {
|
||||
regular(file, false)?;
|
||||
job_binding::check_admin_readonly(path)?;
|
||||
let identity = ipc::file_identity(file)?;
|
||||
let bytes = file.metadata()?.len();
|
||||
ensure!(bytes > 0 && bytes <= max, "UPDATE_FILE_SIZE");
|
||||
let security_sha256 = SecurityDescriptor::read(file)?.hash()?;
|
||||
let sha256 = hash_file(file, max)?;
|
||||
regular(file, false)?;
|
||||
ensure!(
|
||||
ipc::file_identity(file)? == identity
|
||||
&& file.metadata()?.len() == bytes
|
||||
&& SecurityDescriptor::read(file)?.hash()? == security_sha256,
|
||||
"UPDATE_FILE_CHANGED_DURING_READ"
|
||||
);
|
||||
let named = unsafe {
|
||||
CreateFileW(
|
||||
ipc::wide(path).as_ptr(),
|
||||
FILE_READ_ATTRIBUTES,
|
||||
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
|
||||
ptr::null(),
|
||||
OPEN_EXISTING,
|
||||
FILE_FLAG_OPEN_REPARSE_POINT,
|
||||
ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
ensure!(named != INVALID_HANDLE_VALUE, "UPDATE_FILE_NAME_READBACK");
|
||||
let named = unsafe { File::from_raw_handle(named) };
|
||||
regular(&named, false)?;
|
||||
ensure!(
|
||||
ipc::file_identity(&named)? == identity,
|
||||
"UPDATE_FILE_NAME_REPLACED"
|
||||
);
|
||||
Ok(Proof {
|
||||
identity,
|
||||
bytes,
|
||||
sha256,
|
||||
security_sha256,
|
||||
})
|
||||
}
|
||||
/// Read-only predecessor capture while the original services may still run.
|
||||
/// This is an observation, not an authenticated InstalledRecord or baseline.
|
||||
pub fn observe(role: Role, budget: &Budget<'_>) -> Result<Proof> {
|
||||
budget.check()?;
|
||||
let mut directory = Directory::open(role)?;
|
||||
let mut file = open(
|
||||
Path::new(role.target()),
|
||||
FILE_GENERIC_READ,
|
||||
OPEN_EXISTING,
|
||||
ptr::null(),
|
||||
)?;
|
||||
let value = proof(&mut file, Path::new(role.target()), role.max_bytes())?;
|
||||
directory.check()?;
|
||||
budget.check()?;
|
||||
Ok(value)
|
||||
}
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) enum Location {
|
||||
Target,
|
||||
Stage,
|
||||
Previous,
|
||||
}
|
||||
/// Independent readback while the actual swap retains DELETE/write handles.
|
||||
/// Opening this read-only observer grants no write/delete access or authority.
|
||||
pub(crate) fn observe_bound(
|
||||
role: Role,
|
||||
nonce: Uuid,
|
||||
location: Location,
|
||||
budget: &Budget<'_>,
|
||||
) -> Result<Proof> {
|
||||
ensure!(!nonce.is_nil(), "UPDATE_READBACK_NONCE");
|
||||
budget.check()?;
|
||||
let mut directory = Directory::open(role)?;
|
||||
let path = match location {
|
||||
Location::Target => PathBuf::from(role.target()),
|
||||
Location::Stage => directory.child(&format!(".rmm-update-{nonce}-{}.stage", role.label())),
|
||||
Location::Previous => {
|
||||
directory.child(&format!(".rmm-update-{nonce}-{}.previous", role.label()))
|
||||
}
|
||||
};
|
||||
let raw = unsafe {
|
||||
CreateFileW(
|
||||
ipc::wide(&path).as_ptr(),
|
||||
FILE_GENERIC_READ,
|
||||
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
|
||||
ptr::null(),
|
||||
OPEN_EXISTING,
|
||||
FILE_FLAG_OPEN_REPARSE_POINT,
|
||||
ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
ensure!(raw != INVALID_HANDLE_VALUE, "UPDATE_READBACK_OPEN");
|
||||
let mut file = unsafe { File::from_raw_handle(raw) };
|
||||
let result = proof(&mut file, &path, role.max_bytes())?;
|
||||
directory.check()?;
|
||||
budget.check()?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub struct StageDescriptor<'a> {
|
||||
pub role: Role,
|
||||
pub owner_nonce: Uuid,
|
||||
pub original: &'a Proof,
|
||||
pub replacement_sha256: &'a str,
|
||||
pub replacement_bytes: u64,
|
||||
}
|
||||
pub struct Staged {
|
||||
role: Role,
|
||||
nonce: Uuid,
|
||||
directory: Directory,
|
||||
path: PathBuf,
|
||||
file: File,
|
||||
original: Proof,
|
||||
staged: Proof,
|
||||
}
|
||||
impl Staged {
|
||||
/// Source is a bounded stream of already independently release-verified
|
||||
/// artifact bytes. No URL or caller-chosen destination is accepted. Both
|
||||
/// code files MUST be fully staged before original activation consumption.
|
||||
pub fn create(
|
||||
descriptor: StageDescriptor<'_>,
|
||||
source: &mut impl Read,
|
||||
budget: &Budget<'_>,
|
||||
fence: &mut impl DurableEffectFence,
|
||||
) -> Result<Self> {
|
||||
let StageDescriptor {
|
||||
role,
|
||||
owner_nonce: nonce,
|
||||
original,
|
||||
replacement_sha256,
|
||||
replacement_bytes,
|
||||
} = descriptor;
|
||||
ensure!(
|
||||
!nonce.is_nil()
|
||||
&& valid_digest(&original.sha256)
|
||||
&& valid_digest(replacement_sha256)
|
||||
&& replacement_bytes > 0
|
||||
&& replacement_bytes <= role.max_bytes(),
|
||||
"UPDATE_STAGE_DESCRIPTOR"
|
||||
);
|
||||
budget.check()?;
|
||||
let mut directory = Directory::open(role)?;
|
||||
let mut predecessor = open(
|
||||
Path::new(role.target()),
|
||||
FILE_GENERIC_READ,
|
||||
OPEN_EXISTING,
|
||||
ptr::null(),
|
||||
)?;
|
||||
ensure!(
|
||||
proof(&mut predecessor, Path::new(role.target()), role.max_bytes())? == *original,
|
||||
"UPDATE_PREDECESSOR_CHANGED"
|
||||
);
|
||||
let security = SecurityDescriptor::read(&predecessor)?;
|
||||
let attributes = security.attributes();
|
||||
let path = directory.child(&format!(".rmm-update-{nonce}-{}.stage", role.label()));
|
||||
let effect = Effect::StageFile { role };
|
||||
fence.before_effect(&effect)?;
|
||||
budget.check()?;
|
||||
directory.check()?;
|
||||
let mut file = open(
|
||||
&path,
|
||||
FILE_GENERIC_READ | FILE_GENERIC_WRITE | DELETE,
|
||||
CREATE_NEW,
|
||||
&attributes,
|
||||
)?;
|
||||
let mut total = 0u64;
|
||||
let mut buffer = [0u8; 65536];
|
||||
loop {
|
||||
budget.check()?;
|
||||
let read = source.read(&mut buffer)?;
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
total = total
|
||||
.checked_add(read as u64)
|
||||
.context("UPDATE_STAGE_LENGTH")?;
|
||||
ensure!(total <= replacement_bytes, "UPDATE_STAGE_EXTRA_BYTES");
|
||||
file.write_all(&buffer[..read])?;
|
||||
}
|
||||
ensure!(total == replacement_bytes, "UPDATE_STAGE_TRUNCATED");
|
||||
file.sync_all()?;
|
||||
let staged = proof(&mut file, &path, role.max_bytes())?;
|
||||
ensure!(
|
||||
staged.bytes == replacement_bytes
|
||||
&& staged.sha256 == replacement_sha256
|
||||
&& staged.identity != original.identity
|
||||
&& staged.identity.volume_serial == original.identity.volume_serial
|
||||
&& staged.security_sha256 == original.security_sha256,
|
||||
"UPDATE_STAGE_VERIFICATION"
|
||||
);
|
||||
directory.check()?;
|
||||
budget.check()?;
|
||||
fence.after_effect(&effect, &digest(&serde_json::to_vec(&staged)?))?;
|
||||
Ok(Self {
|
||||
role,
|
||||
nonce,
|
||||
directory,
|
||||
path,
|
||||
file,
|
||||
original: original.clone(),
|
||||
staged,
|
||||
})
|
||||
}
|
||||
pub fn original(&self) -> &Proof {
|
||||
&self.original
|
||||
}
|
||||
pub fn staged(&self) -> &Proof {
|
||||
&self.staged
|
||||
}
|
||||
/// Publication consists of TWO separately fenced native renames. This is
|
||||
/// explicitly not an atomic pair swap. Any missing reply/readback requires
|
||||
/// retained-namespace adjudication, never automatic re-entry/replacement.
|
||||
pub fn publish(
|
||||
mut self,
|
||||
stopped: &super::services::Stopped,
|
||||
budget: &Budget<'_>,
|
||||
fence: &mut impl DurableEffectFence,
|
||||
) -> Result<Published> {
|
||||
stopped.check(budget)?;
|
||||
self.directory.check()?;
|
||||
ensure!(
|
||||
proof(&mut self.file, &self.path, self.role.max_bytes())? == self.staged,
|
||||
"UPDATE_STAGED_FILE_CHANGED"
|
||||
);
|
||||
let target = Path::new(self.role.target());
|
||||
let mut original = open(
|
||||
target,
|
||||
FILE_GENERIC_READ | FILE_GENERIC_WRITE | DELETE,
|
||||
OPEN_EXISTING,
|
||||
ptr::null(),
|
||||
)?;
|
||||
ensure!(
|
||||
proof(&mut original, target, self.role.max_bytes())? == self.original,
|
||||
"UPDATE_PREDECESSOR_CHANGED"
|
||||
);
|
||||
let previous = self.directory.child(&format!(
|
||||
".rmm-update-{}-{}.previous",
|
||||
self.nonce,
|
||||
self.role.label()
|
||||
));
|
||||
let save = Effect::SavePredecessor { role: self.role };
|
||||
fence.before_effect(&save)?;
|
||||
budget.check()?;
|
||||
stopped.check(budget)?;
|
||||
self.directory.check()?;
|
||||
rename_new(&original, &previous)?;
|
||||
let saved = proof(&mut original, &previous, self.role.max_bytes())?;
|
||||
ensure!(saved == self.original, "UPDATE_SAVED_PREDECESSOR_CHANGED");
|
||||
fence.after_effect(&save, &digest(&serde_json::to_vec(&saved)?))?;
|
||||
let publish = Effect::PublishReplacement { role: self.role };
|
||||
fence.before_effect(&publish)?;
|
||||
budget.check()?;
|
||||
stopped.check(budget)?;
|
||||
self.directory.check()?;
|
||||
rename_new(&self.file, target)?;
|
||||
let published = proof(&mut self.file, target, self.role.max_bytes())?;
|
||||
ensure!(published == self.staged, "UPDATE_PUBLISHED_FILE_CHANGED");
|
||||
fence.after_effect(&publish, &digest(&serde_json::to_vec(&published)?))?;
|
||||
Ok(Published {
|
||||
role: self.role,
|
||||
directory: self.directory,
|
||||
original,
|
||||
predecessor: previous,
|
||||
original_proof: saved,
|
||||
replacement: self.file,
|
||||
replacement_proof: published,
|
||||
})
|
||||
}
|
||||
}
|
||||
fn rename_new(file: &File, target: &Path) -> Result<()> {
|
||||
let name: Vec<u16> = target.as_os_str().encode_wide().collect();
|
||||
ensure!(
|
||||
target.is_absolute() && name.len() <= 32767 && !name.contains(&0),
|
||||
"UPDATE_RENAME_TARGET"
|
||||
);
|
||||
let length = offset_of!(FILE_RENAME_INFO, FileName) + name.len() * 2;
|
||||
let mut bytes = vec![0usize; length.div_ceil(size_of::<usize>())];
|
||||
let info = bytes.as_mut_ptr().cast::<FILE_RENAME_INFO>();
|
||||
// SAFETY: aligned, zeroed buffer with exact capacity for the fixed header
|
||||
// and full UTF16 name. The native call is handle-relative to the already
|
||||
// held SOURCE; ReplaceIfExists=false refuses files, links or a raced target.
|
||||
unsafe {
|
||||
(*info).Anonymous.ReplaceIfExists = false;
|
||||
(*info).RootDirectory = ptr::null_mut();
|
||||
(*info).FileNameLength = (name.len() * 2) as u32;
|
||||
ptr::copy_nonoverlapping(
|
||||
name.as_ptr(),
|
||||
ptr::addr_of_mut!((*info).FileName).cast::<u16>(),
|
||||
name.len(),
|
||||
);
|
||||
}
|
||||
ensure!(
|
||||
unsafe {
|
||||
SetFileInformationByHandle(
|
||||
file.as_raw_handle(),
|
||||
FileRenameInfo,
|
||||
info.cast(),
|
||||
length as u32,
|
||||
)
|
||||
} != 0,
|
||||
"UPDATE_RENAME_UNCERTAIN: {}",
|
||||
std::io::Error::last_os_error()
|
||||
);
|
||||
// Flush the held write-through file after the rename; a power loss or
|
||||
// failed metadata observation still remains uncertain in the durable ledger.
|
||||
file.sync_all()?;
|
||||
Ok(())
|
||||
}
|
||||
pub struct Published {
|
||||
role: Role,
|
||||
directory: Directory,
|
||||
original: File,
|
||||
predecessor: PathBuf,
|
||||
original_proof: Proof,
|
||||
replacement: File,
|
||||
replacement_proof: Proof,
|
||||
}
|
||||
impl Published {
|
||||
pub fn proof(&self) -> &Proof {
|
||||
&self.replacement_proof
|
||||
}
|
||||
pub fn verify(&mut self, budget: &Budget<'_>) -> Result<()> {
|
||||
budget.check()?;
|
||||
self.directory.check()?;
|
||||
ensure!(
|
||||
proof(&mut self.original, &self.predecessor, self.role.max_bytes())?
|
||||
== self.original_proof
|
||||
&& proof(
|
||||
&mut self.replacement,
|
||||
Path::new(self.role.target()),
|
||||
self.role.max_bytes()
|
||||
)? == self.replacement_proof,
|
||||
"UPDATE_PUBLISHED_PAIR_CHANGED"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
/// Close replacement/delete handles before SCM startup. The caller retains
|
||||
/// the proofs and must independently reopen/recheck them during Health.
|
||||
/// No predecessor is removed; this module contains no cleanup primitive.
|
||||
pub fn release(mut self, budget: &Budget<'_>) -> Result<(Proof, Proof)> {
|
||||
self.verify(budget)?;
|
||||
Ok((self.original_proof, self.replacement_proof))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
//! Native Windows primitives for the separately provisioned stable updater.
|
||||
//!
|
||||
//! This module neither approves an update nor activates a worker. The caller
|
||||
//! authenticates the approved original admission and (after staging) consumed
|
||||
//! handoff, owns the existing ledger guard, and supplies a durable effect fence.
|
||||
//! No default/permissive fence, resume,
|
||||
//! reset, shell, reboot, or arbitrary service/path operation is provided.
|
||||
use anyhow::{Result, ensure};
|
||||
use rmm_agent_core::helper_reconcile::BootSource;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::time::{Duration, Instant};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[cfg(windows)]
|
||||
pub mod fence;
|
||||
#[cfg(windows)]
|
||||
pub mod files;
|
||||
#[cfg(windows)]
|
||||
pub mod services;
|
||||
pub mod transition;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Service {
|
||||
Agent,
|
||||
Helper,
|
||||
}
|
||||
impl Service {
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Agent => "RmmDiscoveryWindows",
|
||||
Self::Helper => "RmmDiscoverySystemHelper",
|
||||
}
|
||||
}
|
||||
pub fn handoff_service(self) -> rmm_updater_handoff::Service {
|
||||
match self {
|
||||
Self::Agent => rmm_updater_handoff::Service::WindowsAgent,
|
||||
Self::Helper => rmm_updater_handoff::Service::WindowsHelper,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Role {
|
||||
Agent,
|
||||
Helper,
|
||||
Settings,
|
||||
Pin,
|
||||
TimeProfile,
|
||||
}
|
||||
impl Role {
|
||||
pub fn target(self) -> &'static str {
|
||||
match self {
|
||||
Self::Agent => r"C:\Program Files\RustDiscovery\rmm-agent-windows.exe",
|
||||
Self::Helper => r"C:\Program Files\RustDiscovery\rmm-helper-windows.exe",
|
||||
Self::Settings => r"C:\ProgramData\RustDiscoverySystem\helper.json",
|
||||
Self::Pin => r"C:\ProgramData\RustDiscoverySystem\agent-pin.json",
|
||||
Self::TimeProfile => r"C:\ProgramData\RustDiscoverySystem\time-attestation.json",
|
||||
}
|
||||
}
|
||||
pub fn handoff_role(self) -> rmm_updater_handoff::FileRole {
|
||||
match self {
|
||||
Self::Agent => rmm_updater_handoff::FileRole::AgentBinary,
|
||||
Self::Helper => rmm_updater_handoff::FileRole::HelperBinary,
|
||||
Self::Settings => rmm_updater_handoff::FileRole::WindowsSettings,
|
||||
Self::Pin => rmm_updater_handoff::FileRole::WindowsPin,
|
||||
Self::TimeProfile => rmm_updater_handoff::FileRole::WindowsTimeProfile,
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Agent => "agent",
|
||||
Self::Helper => "helper",
|
||||
Self::Settings => "settings",
|
||||
Self::Pin => "pin",
|
||||
Self::TimeProfile => "time-profile",
|
||||
}
|
||||
}
|
||||
pub fn max_bytes(self) -> u64 {
|
||||
match self {
|
||||
Self::Agent | Self::Helper => 256 * 1024 * 1024,
|
||||
Self::Settings | Self::Pin | Self::TimeProfile => 64 * 1024,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The embedding worker must additionally check its original trusted-clock
|
||||
/// interval and signed deadline at each effect. This budget cannot extend it.
|
||||
pub struct Budget<'a> {
|
||||
boot: &'a dyn BootSource,
|
||||
boot_id: Uuid,
|
||||
until: Instant,
|
||||
}
|
||||
impl<'a> Budget<'a> {
|
||||
pub fn new(boot: &'a dyn BootSource, expected: Uuid, remaining: Duration) -> Result<Self> {
|
||||
ensure!(
|
||||
!expected.is_nil() && !remaining.is_zero() && remaining <= Duration::from_secs(600),
|
||||
"UPDATE_BUDGET"
|
||||
);
|
||||
let value = Self {
|
||||
boot,
|
||||
boot_id: expected,
|
||||
until: Instant::now()
|
||||
.checked_add(remaining)
|
||||
.ok_or_else(|| anyhow::anyhow!("UPDATE_BUDGET"))?,
|
||||
};
|
||||
value.check()?;
|
||||
Ok(value)
|
||||
}
|
||||
pub fn check(&self) -> Result<()> {
|
||||
ensure!(Instant::now() < self.until, "UPDATE_DEADLINE");
|
||||
ensure!(
|
||||
self.boot.current_boot()? == self.boot_id,
|
||||
"UPDATE_BOOT_CHANGED"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "effect", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum Effect {
|
||||
StopService { service: Service },
|
||||
StageFile { role: Role },
|
||||
SavePredecessor { role: Role },
|
||||
PublishReplacement { role: Role },
|
||||
RestorePredecessor { role: Role },
|
||||
StartService { service: Service },
|
||||
}
|
||||
|
||||
/// Implementations MUST independently check the original approved admission
|
||||
/// for StageFile; every later effect additionally needs the consumed original
|
||||
/// handoff. Retained owner/process/boot/clock/ledger witnesses and a COMMITTED
|
||||
/// create-once intent are required. Observation failure never allows a retry.
|
||||
pub trait DurableEffectFence {
|
||||
fn before_effect(&mut self, effect: &Effect) -> Result<()>;
|
||||
fn after_effect(&mut self, effect: &Effect, observation_sha256: &str) -> Result<()>;
|
||||
}
|
||||
fn valid_digest(value: &str) -> bool {
|
||||
value.len() == 64
|
||||
&& value
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
|
||||
}
|
||||
#[cfg(windows)]
|
||||
fn digest(bytes: &[u8]) -> String {
|
||||
use sha2::{Digest, Sha256};
|
||||
Sha256::digest(bytes)
|
||||
.iter()
|
||||
.map(|b| format!("{b:02x}"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
struct Boot(AtomicBool, Uuid);
|
||||
impl BootSource for Boot {
|
||||
fn current_boot(&self) -> Result<Uuid> {
|
||||
Ok(if self.0.load(Ordering::SeqCst) {
|
||||
Uuid::nil()
|
||||
} else {
|
||||
self.1
|
||||
})
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn budget_is_original_boot_bound_and_never_has_an_unbounded_window() {
|
||||
let boot = Boot(AtomicBool::new(false), Uuid::new_v4());
|
||||
assert!(Budget::new(&boot, boot.1, Duration::ZERO).is_err());
|
||||
assert!(Budget::new(&boot, boot.1, Duration::from_secs(601)).is_err());
|
||||
assert!(Budget::new(&boot, Uuid::nil(), Duration::from_secs(1)).is_err());
|
||||
let bound = Budget::new(&boot, boot.1, Duration::from_secs(1)).unwrap();
|
||||
bound.check().unwrap();
|
||||
boot.0.store(true, Ordering::SeqCst);
|
||||
assert!(bound.check().is_err());
|
||||
}
|
||||
#[test]
|
||||
fn windows_roles_are_closed_and_effects_reject_unknown_fields() {
|
||||
assert_eq!(Service::Agent.name(), crate::SERVICE_NAME);
|
||||
assert_eq!(
|
||||
Role::Pin.handoff_role(),
|
||||
rmm_updater_handoff::FileRole::WindowsPin
|
||||
);
|
||||
for raw in [
|
||||
r#"{"effect":"stop_service","service":"updater"}"#,
|
||||
r#"{"effect":"publish_replacement","role":"arbitrary"}"#,
|
||||
r#"{"effect":"stop_service","service":"helper","command":"extra"}"#,
|
||||
] {
|
||||
assert!(serde_json::from_str::<Effect>(raw).is_err());
|
||||
}
|
||||
assert!(valid_digest(&"ab".repeat(32)));
|
||||
assert!(!valid_digest(&"AB".repeat(32)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,393 @@
|
||||
//! Closed native SCM stop/start with held original process witnesses.
|
||||
//! Service recovery actions, triggers and dependencies are refused rather than
|
||||
//! modified. Every native request is issued once after a durable caller intent.
|
||||
use super::{Budget, DurableEffectFence, Effect, Service, digest};
|
||||
use crate::helper_ipc::{PeerPin, PeerProof, utf16_pointer, wide};
|
||||
use anyhow::{Result, ensure};
|
||||
use rmm_updater_handoff::{Process, StartedService};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
mem::{size_of, zeroed},
|
||||
ptr, thread,
|
||||
time::Duration,
|
||||
};
|
||||
use windows_sys::Win32::System::Services::*;
|
||||
|
||||
struct Handle(SC_HANDLE);
|
||||
impl Drop for Handle {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
CloseServiceHandle(self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Configuration {
|
||||
pub service: Service,
|
||||
pub command: String,
|
||||
pub account: String,
|
||||
pub start_type: u32,
|
||||
pub error_control: u32,
|
||||
pub sid_type: u32,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Proof {
|
||||
pub configuration: Configuration,
|
||||
pub process: Process,
|
||||
}
|
||||
struct HeldService {
|
||||
service: Service,
|
||||
handle: Handle,
|
||||
peer: PeerProof,
|
||||
proof: Proof,
|
||||
}
|
||||
fn handle(service: Service, rights: u32) -> Result<Handle> {
|
||||
let manager = Handle(unsafe { OpenSCManagerW(ptr::null(), ptr::null(), SC_MANAGER_CONNECT) });
|
||||
ensure!(!manager.0.is_null(), "UPDATE_SCM_MANAGER");
|
||||
let value = Handle(unsafe { OpenServiceW(manager.0, wide(service.name()).as_ptr(), rights) });
|
||||
ensure!(!value.0.is_null(), "UPDATE_SCM_SERVICE");
|
||||
Ok(value)
|
||||
}
|
||||
fn status(handle: &Handle) -> Result<SERVICE_STATUS_PROCESS> {
|
||||
let mut value = unsafe { zeroed() };
|
||||
let mut needed = 0;
|
||||
ensure!(
|
||||
unsafe {
|
||||
QueryServiceStatusEx(
|
||||
handle.0,
|
||||
SC_STATUS_PROCESS_INFO,
|
||||
(&mut value as *mut SERVICE_STATUS_PROCESS).cast(),
|
||||
size_of::<SERVICE_STATUS_PROCESS>() as u32,
|
||||
&mut needed,
|
||||
)
|
||||
} != 0,
|
||||
"UPDATE_SCM_STATUS"
|
||||
);
|
||||
Ok(value)
|
||||
}
|
||||
fn config2(handle: &Handle, kind: u32) -> Result<Vec<usize>> {
|
||||
let mut needed = 0;
|
||||
unsafe {
|
||||
QueryServiceConfig2W(handle.0, kind, ptr::null_mut(), 0, &mut needed);
|
||||
}
|
||||
ensure!((1..=32768).contains(&needed), "UPDATE_SCM_CONFIG_SIZE");
|
||||
let mut bytes = vec![0usize; (needed as usize).div_ceil(size_of::<usize>())];
|
||||
ensure!(
|
||||
unsafe {
|
||||
QueryServiceConfig2W(
|
||||
handle.0,
|
||||
kind,
|
||||
bytes.as_mut_ptr().cast(),
|
||||
needed,
|
||||
&mut needed,
|
||||
)
|
||||
} != 0,
|
||||
"UPDATE_SCM_CONFIG"
|
||||
);
|
||||
Ok(bytes)
|
||||
}
|
||||
fn configuration(handle: &Handle, service: Service, pin: &PeerPin) -> Result<Configuration> {
|
||||
pin.validate(service == Service::Helper)?;
|
||||
let mut needed = 0;
|
||||
unsafe {
|
||||
QueryServiceConfigW(handle.0, ptr::null_mut(), 0, &mut needed);
|
||||
}
|
||||
ensure!((1..=32768).contains(&needed), "UPDATE_SCM_CONFIG_SIZE");
|
||||
let mut bytes = vec![0usize; (needed as usize).div_ceil(size_of::<usize>())];
|
||||
ensure!(
|
||||
unsafe { QueryServiceConfigW(handle.0, bytes.as_mut_ptr().cast(), needed, &mut needed) }
|
||||
!= 0,
|
||||
"UPDATE_SCM_CONFIG"
|
||||
);
|
||||
let cfg = unsafe { &*bytes.as_ptr().cast::<QUERY_SERVICE_CONFIGW>() };
|
||||
let command = unsafe { utf16_pointer(cfg.lpBinaryPathName) }?;
|
||||
let account = unsafe { utf16_pointer(cfg.lpServiceStartName) }?;
|
||||
let expected = if service == Service::Agent {
|
||||
format!(
|
||||
"\"{}\" --service --config \"C:\\ProgramData\\RustDiscovery\\config.json\"",
|
||||
pin.binary.display()
|
||||
)
|
||||
} else {
|
||||
format!("\"{}\" --service", pin.binary.display())
|
||||
};
|
||||
ensure!(
|
||||
cfg.dwServiceType == SERVICE_WIN32_OWN_PROCESS
|
||||
&& command == expected
|
||||
&& cfg.dwStartType
|
||||
== if service == Service::Agent {
|
||||
SERVICE_AUTO_START
|
||||
} else {
|
||||
SERVICE_DEMAND_START
|
||||
}
|
||||
&& (cfg.lpDependencies.is_null() || unsafe { *cfg.lpDependencies } == 0)
|
||||
&& (cfg.lpLoadOrderGroup.is_null() || unsafe { *cfg.lpLoadOrderGroup } == 0),
|
||||
"UPDATE_SCM_UNEXPECTED_CONFIGURATION"
|
||||
);
|
||||
let recovery = config2(handle, SERVICE_CONFIG_FAILURE_ACTIONS)?;
|
||||
let recovery = unsafe { &*recovery.as_ptr().cast::<SERVICE_FAILURE_ACTIONSW>() };
|
||||
ensure!(recovery.cActions == 0, "UPDATE_SCM_RECOVERY_ACTIONS");
|
||||
let triggers = config2(handle, SERVICE_CONFIG_TRIGGER_INFO)?;
|
||||
let triggers = unsafe { &*triggers.as_ptr().cast::<SERVICE_TRIGGER_INFO>() };
|
||||
ensure!(triggers.cTriggers == 0, "UPDATE_SCM_TRIGGERS");
|
||||
let sid = config2(handle, SERVICE_CONFIG_SERVICE_SID_INFO)?;
|
||||
let sid = unsafe { &*sid.as_ptr().cast::<SERVICE_SID_INFO>() };
|
||||
ensure!(
|
||||
sid.dwServiceSidType == SERVICE_SID_TYPE_UNRESTRICTED,
|
||||
"UPDATE_SCM_SERVICE_SID"
|
||||
);
|
||||
// Refuse active dependent services; stopping this pair cannot stop another
|
||||
// product or cause StartService's implicit dependency side effects.
|
||||
let mut dependent_bytes = 0;
|
||||
let mut dependent_count = 0;
|
||||
let no_dependents = unsafe {
|
||||
EnumDependentServicesW(
|
||||
handle.0,
|
||||
SERVICE_ACTIVE,
|
||||
ptr::null_mut(),
|
||||
0,
|
||||
&mut dependent_bytes,
|
||||
&mut dependent_count,
|
||||
)
|
||||
};
|
||||
ensure!(
|
||||
no_dependents != 0 && dependent_count == 0 && dependent_bytes == 0,
|
||||
"UPDATE_SCM_ACTIVE_DEPENDENTS"
|
||||
);
|
||||
Ok(Configuration {
|
||||
service,
|
||||
command,
|
||||
account,
|
||||
start_type: cfg.dwStartType,
|
||||
error_control: cfg.dwErrorControl,
|
||||
sid_type: sid.dwServiceSidType,
|
||||
})
|
||||
}
|
||||
fn observe(service: Service, pin: &PeerPin, budget: &Budget<'_>) -> Result<HeldService> {
|
||||
budget.check()?;
|
||||
let handle = handle(
|
||||
service,
|
||||
SERVICE_QUERY_STATUS
|
||||
| SERVICE_QUERY_CONFIG
|
||||
| SERVICE_ENUMERATE_DEPENDENTS
|
||||
| SERVICE_STOP
|
||||
| SERVICE_START,
|
||||
)?;
|
||||
let before = configuration(&handle, service, pin)?;
|
||||
let state = status(&handle)?;
|
||||
ensure!(
|
||||
state.dwCurrentState == SERVICE_RUNNING && state.dwProcessId > 0,
|
||||
"UPDATE_SERVICE_NOT_RUNNING"
|
||||
);
|
||||
let mut peer = PeerProof::for_service(pin, state.dwProcessId)?;
|
||||
peer.check()?;
|
||||
let id = peer.identity();
|
||||
let proof = Proof {
|
||||
configuration: before.clone(),
|
||||
process: Process {
|
||||
pid: id.pid,
|
||||
birth: id.creation_ticks,
|
||||
image_sha256: id.image_sha256.clone(),
|
||||
},
|
||||
};
|
||||
ensure!(
|
||||
configuration(&handle, service, pin)? == before
|
||||
&& status(&handle)?.dwProcessId == proof.process.pid,
|
||||
"UPDATE_SERVICE_OBSERVATION_CHANGED"
|
||||
);
|
||||
budget.check()?;
|
||||
Ok(HeldService {
|
||||
service,
|
||||
handle,
|
||||
peer,
|
||||
proof,
|
||||
})
|
||||
}
|
||||
|
||||
/// Observation holds both original processes/images, not a freely constructible
|
||||
/// Running flag. Drop these witnesses only after confirmed process termination.
|
||||
pub struct Running {
|
||||
pins: [PeerPin; 2],
|
||||
held: Vec<HeldService>,
|
||||
}
|
||||
impl Running {
|
||||
pub fn observe(pins: [PeerPin; 2], budget: &Budget<'_>) -> Result<Self> {
|
||||
let held = vec![
|
||||
observe(Service::Agent, &pins[0], budget)?,
|
||||
observe(Service::Helper, &pins[1], budget)?,
|
||||
];
|
||||
Ok(Self { pins, held })
|
||||
}
|
||||
pub fn proofs(&self) -> Vec<Proof> {
|
||||
self.held.iter().map(|s| s.proof.clone()).collect()
|
||||
}
|
||||
pub fn check(&mut self, budget: &Budget<'_>) -> Result<()> {
|
||||
budget.check()?;
|
||||
for (i, service) in self.held.iter_mut().enumerate() {
|
||||
service.peer.check()?;
|
||||
ensure!(
|
||||
configuration(&service.handle, service.service, &self.pins[i])?
|
||||
== service.proof.configuration,
|
||||
"UPDATE_SERVICE_CONFIG_CHANGED"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn stop(
|
||||
mut self,
|
||||
budget: &Budget<'_>,
|
||||
fence: &mut impl DurableEffectFence,
|
||||
) -> Result<Stopped> {
|
||||
self.check(budget)?;
|
||||
for (i, service) in self.held.iter_mut().enumerate() {
|
||||
service.peer.check()?;
|
||||
ensure!(
|
||||
configuration(&service.handle, service.service, &self.pins[i])?
|
||||
== service.proof.configuration,
|
||||
"UPDATE_SERVICE_CONFIG_CHANGED"
|
||||
);
|
||||
let effect = Effect::StopService {
|
||||
service: service.service,
|
||||
};
|
||||
fence.before_effect(&effect)?;
|
||||
budget.check()?;
|
||||
service.peer.check()?;
|
||||
let mut stopped = unsafe { zeroed() };
|
||||
ensure!(
|
||||
unsafe { ControlService(service.handle.0, SERVICE_CONTROL_STOP, &mut stopped) }
|
||||
!= 0,
|
||||
"UPDATE_STOP_REQUEST_UNCERTAIN"
|
||||
);
|
||||
loop {
|
||||
budget.check()?;
|
||||
let state = status(&service.handle)?;
|
||||
if state.dwCurrentState == SERVICE_STOPPED
|
||||
&& state.dwProcessId == 0
|
||||
&& service.peer.exited()?
|
||||
{
|
||||
break;
|
||||
}
|
||||
ensure!(
|
||||
matches!(state.dwCurrentState, SERVICE_STOP_PENDING | SERVICE_STOPPED),
|
||||
"UPDATE_STOP_STATE_UNCERTAIN"
|
||||
);
|
||||
thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
fence.after_effect(&effect, &digest(&serde_json::to_vec(&service.proof)?))?;
|
||||
}
|
||||
let proofs = self.proofs();
|
||||
let stopped = Stopped {
|
||||
pins: self.pins,
|
||||
configurations: [
|
||||
proofs[0].configuration.clone(),
|
||||
proofs[1].configuration.clone(),
|
||||
],
|
||||
};
|
||||
// Held image handles intentionally close here, after BOTH exact original
|
||||
// processes have terminated. Neither PID reuse nor SCM state suffices.
|
||||
drop(self.held);
|
||||
stopped.check(budget)?;
|
||||
Ok(stopped)
|
||||
}
|
||||
}
|
||||
|
||||
/// Only the actual completed stop sequence constructs this token. It is not a
|
||||
/// closed-reader census or a helper-ledger lock; those remain separate gates.
|
||||
pub struct Stopped {
|
||||
pins: [PeerPin; 2],
|
||||
configurations: [Configuration; 2],
|
||||
}
|
||||
impl Stopped {
|
||||
pub fn check(&self, budget: &Budget<'_>) -> Result<()> {
|
||||
budget.check()?;
|
||||
for (i, service) in [Service::Agent, Service::Helper].into_iter().enumerate() {
|
||||
let handle = handle(
|
||||
service,
|
||||
SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG | SERVICE_ENUMERATE_DEPENDENTS,
|
||||
)?;
|
||||
let state = status(&handle)?;
|
||||
ensure!(
|
||||
state.dwCurrentState == SERVICE_STOPPED
|
||||
&& state.dwProcessId == 0
|
||||
&& configuration(&handle, service, &self.pins[i])? == self.configurations[i],
|
||||
"UPDATE_STOPPED_STATE_CHANGED"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Caller MUST commit the original ledger-return/start-reservation before
|
||||
/// dropping its guard and calling this. Helper starts before agent. This
|
||||
/// function never retries a failed or uncertain native start request.
|
||||
pub fn start(
|
||||
self,
|
||||
replacement_pins: [PeerPin; 2],
|
||||
budget: &Budget<'_>,
|
||||
fence: &mut impl DurableEffectFence,
|
||||
) -> Result<Running> {
|
||||
self.check(budget)?;
|
||||
let mut started = Vec::with_capacity(2);
|
||||
for (i, service) in [(1, Service::Helper), (0, Service::Agent)] {
|
||||
replacement_pins[i].validate(service == Service::Helper)?;
|
||||
ensure!(
|
||||
replacement_pins[i].binary == self.pins[i].binary
|
||||
&& replacement_pins[i].service_name == self.pins[i].service_name
|
||||
&& replacement_pins[i].service_sid == self.pins[i].service_sid
|
||||
&& replacement_pins[i].user_sid == self.pins[i].user_sid,
|
||||
"UPDATE_REPLACEMENT_SERVICE_IDENTITY"
|
||||
);
|
||||
let handle = handle(
|
||||
service,
|
||||
SERVICE_QUERY_STATUS
|
||||
| SERVICE_QUERY_CONFIG
|
||||
| SERVICE_ENUMERATE_DEPENDENTS
|
||||
| SERVICE_START,
|
||||
)?;
|
||||
ensure!(
|
||||
configuration(&handle, service, &replacement_pins[i])? == self.configurations[i],
|
||||
"UPDATE_SERVICE_CONFIG_CHANGED"
|
||||
);
|
||||
let effect = Effect::StartService { service };
|
||||
fence.before_effect(&effect)?;
|
||||
budget.check()?;
|
||||
ensure!(
|
||||
status(&handle)?.dwCurrentState == SERVICE_STOPPED,
|
||||
"UPDATE_START_ALREADY_RUNNING"
|
||||
);
|
||||
ensure!(
|
||||
unsafe { StartServiceW(handle.0, 0, ptr::null()) } != 0,
|
||||
"UPDATE_START_REQUEST_UNCERTAIN"
|
||||
);
|
||||
loop {
|
||||
budget.check()?;
|
||||
let state = status(&handle)?;
|
||||
if state.dwCurrentState == SERVICE_RUNNING {
|
||||
break;
|
||||
}
|
||||
ensure!(
|
||||
state.dwCurrentState == SERVICE_START_PENDING,
|
||||
"UPDATE_START_STATE_UNCERTAIN"
|
||||
);
|
||||
thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
let held = observe(service, &replacement_pins[i], budget)?;
|
||||
fence.after_effect(&effect, &digest(&serde_json::to_vec(&held.proof)?))?;
|
||||
started.push(held);
|
||||
}
|
||||
started.reverse();
|
||||
let mut running = Running {
|
||||
pins: replacement_pins,
|
||||
held: started,
|
||||
};
|
||||
running.check(budget)?;
|
||||
Ok(running)
|
||||
}
|
||||
}
|
||||
impl Proof {
|
||||
pub fn started(&self) -> StartedService {
|
||||
StartedService {
|
||||
service: self.configuration.service.handoff_service(),
|
||||
process: self.process.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,540 @@
|
||||
//! Closed Windows code/pin/time-profile rendering, without OS effects.
|
||||
//!
|
||||
//! Input bytes must come from protected, independently authenticated original
|
||||
//! files. Candidate time qualifications must be independently verified by the
|
||||
//! embedding admission worker BEFORE offering a release. This pure renderer
|
||||
//! binds their exact bytes/hashes; parsing a receipt hash does not qualify code.
|
||||
use super::valid_digest;
|
||||
use crate::signed_clock::{ActiveGuestOperation, TrustedOsConfiguration, TrustedPlatform};
|
||||
use anyhow::{Result, ensure};
|
||||
use rmm_agent_core::{
|
||||
auth::Binding,
|
||||
crypto::{DalekVerifier, Ed25519Verifier},
|
||||
};
|
||||
use rmm_domain::{
|
||||
agent_update::{PeerPinTransition, WindowsTimeProfileTransition},
|
||||
jobs::{PrivilegedScriptProfile, hash},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::value::RawValue;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Peer {
|
||||
service_name: String,
|
||||
service_sid: String,
|
||||
user_sid: String,
|
||||
binary: PathBuf,
|
||||
binary_sha256: String,
|
||||
}
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Rule {
|
||||
name: String,
|
||||
binary: PathBuf,
|
||||
binary_sha256: String,
|
||||
}
|
||||
/// Versioned snapshot of Settings' SERIALIZATION field order. No new rights,
|
||||
/// service rules, reboot setting or interpreter policy can be introduced here.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Settings {
|
||||
schema_version: u32,
|
||||
binding: Binding,
|
||||
agent: Peer,
|
||||
helper: Peer,
|
||||
allowed_services: Vec<Rule>,
|
||||
max_runtime_seconds: u32,
|
||||
enable_effects: bool,
|
||||
allow_reboot: bool,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
deserialize_with = "strict_hashes"
|
||||
)]
|
||||
allowed_msi_recipe_sha256: Option<Vec<String>>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
deserialize_with = "rmm_domain::jobs::deserialize_script_profiles"
|
||||
)]
|
||||
allowed_script_profiles: Option<Vec<PrivilegedScriptProfile>>,
|
||||
}
|
||||
fn strict_hashes<'de, D: serde::Deserializer<'de>>(
|
||||
d: D,
|
||||
) -> std::result::Result<Option<Vec<String>>, D::Error> {
|
||||
Vec::<String>::deserialize(d).map(Some)
|
||||
}
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Pin {
|
||||
schema_version: u32,
|
||||
binding: Binding,
|
||||
policy_sha256: String,
|
||||
agent: Peer,
|
||||
helper: Peer,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct PeerSpan<'a> {
|
||||
#[serde(borrow)]
|
||||
binary_sha256: &'a RawValue,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct Spans<'a> {
|
||||
#[serde(borrow)]
|
||||
agent: PeerSpan<'a>,
|
||||
#[serde(borrow)]
|
||||
helper: PeerSpan<'a>,
|
||||
#[serde(default, borrow)]
|
||||
policy_sha256: Option<&'a RawValue>,
|
||||
}
|
||||
pub struct CodePairTransition {
|
||||
proof: PeerPinTransition,
|
||||
settings: Vec<u8>,
|
||||
pin: Vec<u8>,
|
||||
time_profile: Vec<u8>,
|
||||
}
|
||||
impl CodePairTransition {
|
||||
pub fn proof(&self) -> &PeerPinTransition {
|
||||
&self.proof
|
||||
}
|
||||
pub fn settings_bytes(&self) -> &[u8] {
|
||||
&self.settings
|
||||
}
|
||||
pub fn pin_bytes(&self) -> &[u8] {
|
||||
&self.pin
|
||||
}
|
||||
pub fn time_profile_bytes(&self) -> &[u8] {
|
||||
&self.time_profile
|
||||
}
|
||||
}
|
||||
pub struct Inputs<'a> {
|
||||
pub settings: &'a [u8],
|
||||
pub pin: &'a [u8],
|
||||
pub time_profile: &'a [u8],
|
||||
pub qualified_candidate_time_profile: &'a [u8],
|
||||
pub target_agent_sha256: &'a str,
|
||||
pub target_helper_sha256: &'a str,
|
||||
}
|
||||
fn bound_peer(peer: &Peer, helper: bool) -> bool {
|
||||
let service = if helper {
|
||||
super::Service::Helper
|
||||
} else {
|
||||
super::Service::Agent
|
||||
};
|
||||
let role = if helper {
|
||||
super::Role::Helper
|
||||
} else {
|
||||
super::Role::Agent
|
||||
};
|
||||
peer.service_name == service.name()
|
||||
&& peer.user_sid == if helper { "S-1-5-18" } else { "S-1-5-19" }
|
||||
&& peer.service_sid.starts_with("S-1-5-80-")
|
||||
&& peer.binary.to_str() == Some(role.target())
|
||||
&& valid_digest(&peer.binary_sha256)
|
||||
}
|
||||
fn time_configuration(
|
||||
bytes: &[u8],
|
||||
binding: &Binding,
|
||||
agent: &str,
|
||||
helper: &str,
|
||||
) -> Result<TrustedOsConfiguration> {
|
||||
let value: TrustedOsConfiguration = serde_json::from_slice(bytes)?;
|
||||
let profile = &value.trusted_os_active_guest;
|
||||
ensure!(
|
||||
value.schema_version == 2
|
||||
&& value.key_generation > 0
|
||||
&& !value.server_instance.is_nil()
|
||||
&& serde_json::to_value(&value.binding)? == serde_json::to_value(binding)?
|
||||
&& !value.public_keys_hex.is_empty()
|
||||
&& value.public_keys_hex.len() <= 8
|
||||
&& matches!(
|
||||
profile.operating_assumption,
|
||||
ActiveGuestOperation::NoPauseSaveRestoreSnapshotMigrationHostSuspend
|
||||
)
|
||||
&& matches!(profile.platform, TrustedPlatform::KvmQemuHypervClock)
|
||||
&& valid_digest(&profile.platform_provenance_sha256)
|
||||
&& profile.qualifications.len() == 2,
|
||||
"UPDATE_TIME_PROFILE_BINDING"
|
||||
);
|
||||
for (id, public) in &value.public_keys_hex {
|
||||
ensure!(
|
||||
!id.is_empty()
|
||||
&& id.len() <= 64
|
||||
&& id
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b"_-".contains(&b))
|
||||
&& valid_digest(public)
|
||||
&& public != &binding.public_key_hex,
|
||||
"UPDATE_TIME_PROFILE_KEY"
|
||||
);
|
||||
let key = (0..32)
|
||||
.map(|i| u8::from_str_radix(&public[i * 2..i * 2 + 2], 16))
|
||||
.collect::<std::result::Result<Vec<_>, _>>()?;
|
||||
ensure!(DalekVerifier.validate_key(&key)?, "UPDATE_TIME_PROFILE_KEY");
|
||||
}
|
||||
for (role, image) in [
|
||||
(rmm_time_attestation::Role::Agent, agent),
|
||||
(rmm_time_attestation::Role::SystemHelper, helper),
|
||||
] {
|
||||
let found: Vec<_> = profile
|
||||
.qualifications
|
||||
.iter()
|
||||
.filter(|q| q.role == role)
|
||||
.collect();
|
||||
ensure!(
|
||||
found.len() == 1
|
||||
&& found[0].binary_sha256 == image
|
||||
&& valid_digest(&found[0].qualification_sha256),
|
||||
"UPDATE_TIME_PROFILE_QUALIFICATION"
|
||||
);
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
pub fn render(input: Inputs<'_>) -> Result<CodePairTransition> {
|
||||
for raw in [
|
||||
input.settings,
|
||||
input.pin,
|
||||
input.time_profile,
|
||||
input.qualified_candidate_time_profile,
|
||||
] {
|
||||
ensure!(
|
||||
!raw.is_empty() && raw.len() <= 32768,
|
||||
"UPDATE_WINDOWS_RENDER_LIMIT"
|
||||
);
|
||||
}
|
||||
ensure!(
|
||||
valid_digest(input.target_agent_sha256) && valid_digest(input.target_helper_sha256),
|
||||
"UPDATE_WINDOWS_IMAGE"
|
||||
);
|
||||
let mut settings: Settings = serde_json::from_slice(input.settings)?;
|
||||
let mut pin: Pin = serde_json::from_slice(input.pin)?;
|
||||
ensure!(
|
||||
matches!(settings.schema_version, 1..=3)
|
||||
&& !settings.allow_reboot
|
||||
&& (1..=120).contains(&settings.max_runtime_seconds)
|
||||
&& settings.allowed_services.len() <= 16
|
||||
&& (settings.schema_version >= 2 || settings.allowed_msi_recipe_sha256.is_none())
|
||||
&& (settings.schema_version == 3 || settings.allowed_script_profiles.is_none())
|
||||
&& bound_peer(&settings.agent, false)
|
||||
&& bound_peer(&settings.helper, true)
|
||||
&& !settings.binding.tenant_id.is_nil()
|
||||
&& !settings.binding.asset_id.is_nil()
|
||||
&& !settings.binding.agent_id.is_nil()
|
||||
&& settings.binding.enrollment_generation > 0
|
||||
&& settings.binding.assignment_version > 0
|
||||
&& pin.schema_version == 1
|
||||
&& pin.policy_sha256 == hash(&serde_json::to_vec(&settings)?)
|
||||
&& serde_json::to_value(&pin.binding)? == serde_json::to_value(&settings.binding)?
|
||||
&& serde_json::to_value(&pin.agent)? == serde_json::to_value(&settings.agent)?
|
||||
&& serde_json::to_value(&pin.helper)? == serde_json::to_value(&settings.helper)?,
|
||||
"UPDATE_WINDOWS_ORIGINAL_PAIR"
|
||||
);
|
||||
let old_agent = settings.agent.binary_sha256.clone();
|
||||
let old_helper = settings.helper.binary_sha256.clone();
|
||||
let old_time = time_configuration(
|
||||
input.time_profile,
|
||||
&settings.binding,
|
||||
&old_agent,
|
||||
&old_helper,
|
||||
)?;
|
||||
let candidate = time_configuration(
|
||||
input.qualified_candidate_time_profile,
|
||||
&settings.binding,
|
||||
input.target_agent_sha256,
|
||||
input.target_helper_sha256,
|
||||
)?;
|
||||
let mut unchanged_candidate = serde_json::to_value(&candidate)?;
|
||||
unchanged_candidate["trusted_os_active_guest"]["qualifications"] =
|
||||
serde_json::to_value(&old_time.trusted_os_active_guest.qualifications)?;
|
||||
ensure!(
|
||||
unchanged_candidate == serde_json::to_value(&old_time)?,
|
||||
"UPDATE_TIME_TRUST_OR_PLATFORM_CHANGE"
|
||||
);
|
||||
for new in &candidate.trusted_os_active_guest.qualifications {
|
||||
let old = old_time
|
||||
.trusted_os_active_guest
|
||||
.qualifications
|
||||
.iter()
|
||||
.find(|q| q.role == new.role)
|
||||
.ok_or_else(|| anyhow::anyhow!("UPDATE_TIME_ROLE"))?;
|
||||
ensure!(
|
||||
new.binary_sha256 == old.binary_sha256
|
||||
|| new.qualification_sha256 != old.qualification_sha256,
|
||||
"UPDATE_TIME_OLD_QUALIFICATION_REUSED"
|
||||
);
|
||||
}
|
||||
settings.agent.binary_sha256 = input.target_agent_sha256.into();
|
||||
settings.helper.binary_sha256 = input.target_helper_sha256.into();
|
||||
pin.agent.binary_sha256 = input.target_agent_sha256.into();
|
||||
pin.helper.binary_sha256 = input.target_helper_sha256.into();
|
||||
pin.policy_sha256 = hash(&serde_json::to_vec(&settings)?);
|
||||
let settings_spans: Spans<'_> = serde_json::from_slice(input.settings)?;
|
||||
let pin_spans: Spans<'_> = serde_json::from_slice(input.pin)?;
|
||||
let settings_bytes = replace(
|
||||
input.settings,
|
||||
vec![
|
||||
(
|
||||
settings_spans.agent.binary_sha256,
|
||||
input.target_agent_sha256,
|
||||
),
|
||||
(
|
||||
settings_spans.helper.binary_sha256,
|
||||
input.target_helper_sha256,
|
||||
),
|
||||
],
|
||||
)?;
|
||||
let pin_bytes = replace(
|
||||
input.pin,
|
||||
vec![
|
||||
(pin_spans.agent.binary_sha256, input.target_agent_sha256),
|
||||
(pin_spans.helper.binary_sha256, input.target_helper_sha256),
|
||||
(
|
||||
pin_spans
|
||||
.policy_sha256
|
||||
.ok_or_else(|| anyhow::anyhow!("UPDATE_PIN_POLICY_HASH"))?,
|
||||
&pin.policy_sha256,
|
||||
),
|
||||
],
|
||||
)?;
|
||||
// Confirm the span edits exactly equal the typed, closed intended objects.
|
||||
ensure!(
|
||||
serde_json::to_value(serde_json::from_slice::<Settings>(&settings_bytes)?)?
|
||||
== serde_json::to_value(&settings)?
|
||||
&& serde_json::to_value(serde_json::from_slice::<Pin>(&pin_bytes)?)?
|
||||
== serde_json::to_value(&pin)?,
|
||||
"UPDATE_WINDOWS_RENDER_CHANGED"
|
||||
);
|
||||
let quals = &candidate.trusted_os_active_guest.qualifications;
|
||||
let agent = quals
|
||||
.iter()
|
||||
.find(|q| q.role == rmm_time_attestation::Role::Agent)
|
||||
.unwrap();
|
||||
let helper = quals
|
||||
.iter()
|
||||
.find(|q| q.role == rmm_time_attestation::Role::SystemHelper)
|
||||
.unwrap();
|
||||
let transition = PeerPinTransition::WindowsCodePairV1 {
|
||||
old_settings_sha256: hash(input.settings),
|
||||
new_settings_sha256: hash(&settings_bytes),
|
||||
old_pin_sha256: hash(input.pin),
|
||||
new_pin_sha256: hash(&pin_bytes),
|
||||
time_profile: Some(WindowsTimeProfileTransition {
|
||||
schema_version: 1,
|
||||
old_time_profile_sha256: hash(input.time_profile),
|
||||
new_time_profile_sha256: hash(input.qualified_candidate_time_profile),
|
||||
agent_qualification_sha256: agent.qualification_sha256.clone(),
|
||||
helper_qualification_sha256: helper.qualification_sha256.clone(),
|
||||
}),
|
||||
};
|
||||
Ok(CodePairTransition {
|
||||
proof: transition,
|
||||
settings: settings_bytes,
|
||||
pin: pin_bytes,
|
||||
time_profile: input.qualified_candidate_time_profile.to_vec(),
|
||||
})
|
||||
}
|
||||
fn replace(bytes: &[u8], values: Vec<(&RawValue, &str)>) -> Result<Vec<u8>> {
|
||||
let mut spans = Vec::new();
|
||||
for (raw, replacement) in values {
|
||||
let raw = raw.get();
|
||||
let start = (raw.as_ptr() as usize)
|
||||
.checked_sub(bytes.as_ptr() as usize)
|
||||
.ok_or_else(|| anyhow::anyhow!("UPDATE_RENDER_SPAN"))?;
|
||||
let end = start
|
||||
.checked_add(raw.len())
|
||||
.ok_or_else(|| anyhow::anyhow!("UPDATE_RENDER_SPAN"))?;
|
||||
ensure!(
|
||||
bytes.get(start..end) == Some(raw.as_bytes())
|
||||
&& raw.len() == 66
|
||||
&& raw.starts_with('"')
|
||||
&& raw.ends_with('"')
|
||||
&& valid_digest(&raw[1..65])
|
||||
&& valid_digest(replacement),
|
||||
"UPDATE_RENDER_HASH_ENCODING"
|
||||
);
|
||||
spans.push((start, end, format!("\"{replacement}\"")));
|
||||
}
|
||||
spans.sort_by_key(|s| s.0);
|
||||
ensure!(
|
||||
spans.windows(2).all(|p| p[0].1 <= p[1].0),
|
||||
"UPDATE_RENDER_OVERLAP"
|
||||
);
|
||||
let mut result = Vec::with_capacity(bytes.len());
|
||||
let mut cursor = 0;
|
||||
for (start, end, value) in spans {
|
||||
result.extend_from_slice(&bytes[cursor..start]);
|
||||
result.extend_from_slice(value.as_bytes());
|
||||
cursor = end;
|
||||
}
|
||||
result.extend_from_slice(&bytes[cursor..]);
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ed25519_dalek::SigningKey;
|
||||
use serde_json::{Value, json};
|
||||
struct Fixture {
|
||||
settings: Vec<u8>,
|
||||
pin: Vec<u8>,
|
||||
time: Vec<u8>,
|
||||
candidate: Vec<u8>,
|
||||
}
|
||||
fn fixture() -> Fixture {
|
||||
let public = |byte| {
|
||||
SigningKey::from_bytes(&[byte; 32])
|
||||
.verifying_key()
|
||||
.to_bytes()
|
||||
.iter()
|
||||
.map(|b| format!("{b:02x}"))
|
||||
.collect::<String>()
|
||||
};
|
||||
let binding = json!({"tenant_id":uuid::Uuid::from_u128(1),"asset_id":uuid::Uuid::from_u128(2),
|
||||
"agent_id":uuid::Uuid::from_u128(3),"enrollment_generation":1,"assignment_version":1,"public_key_hex":public(17)});
|
||||
let peer = |helper: bool| {
|
||||
json!({"service_name":if helper {super::super::Service::Helper.name()}else{super::super::Service::Agent.name()},
|
||||
"service_sid":if helper {"S-1-5-80-1-2-3-4-5"}else{"S-1-5-80-6-7-8-9-10"},
|
||||
"user_sid":if helper{"S-1-5-18"}else{"S-1-5-19"},
|
||||
"binary":if helper {super::super::Role::Helper.target()}else{super::super::Role::Agent.target()},
|
||||
"binary_sha256":if helper{"cd".repeat(32)}else{"ab".repeat(32)}})
|
||||
};
|
||||
let settings = json!({"schema_version":3,"binding":binding,"agent":peer(false),"helper":peer(true),
|
||||
"allowed_services":[{"name":"RmmDiscoveryFixtureUpdater","binary":"C:\\Program Files\\RustDiscoveryFixtures\\fixture.exe","binary_sha256":"ab".repeat(32)}],
|
||||
"max_runtime_seconds":120,"enable_effects":true,"allow_reboot":false,
|
||||
"allowed_msi_recipe_sha256":[],"allowed_script_profiles":["full_maintenance_v1"]});
|
||||
let typed: Settings = serde_json::from_value(settings.clone()).unwrap();
|
||||
let pin = json!({"schema_version":1,"binding":binding,"policy_sha256":hash(&serde_json::to_vec(&typed).unwrap()),"agent":peer(false),"helper":peer(true)});
|
||||
let time = json!({"schema_version":2,"key_generation":1,"server_instance":uuid::Uuid::from_u128(4),"binding":binding,
|
||||
"public_keys_hex":{"development_time_v1":public(19)},"trusted_os_active_guest":{
|
||||
"operating_assumption":"active_guest_no_pause_save_restore_snapshot_migration_host_suspend","platform":"kvm_qemu_hypervclock",
|
||||
"platform_provenance_sha256":"01".repeat(32),"qualifications":[
|
||||
{"role":"agent","binary_sha256":"ab".repeat(32),"qualification_sha256":"02".repeat(32)},
|
||||
{"role":"system_helper","binary_sha256":"cd".repeat(32),"qualification_sha256":"03".repeat(32)}]}});
|
||||
let mut candidate = time.clone();
|
||||
candidate["trusted_os_active_guest"]["qualifications"][0]["binary_sha256"] =
|
||||
json!("ef".repeat(32));
|
||||
candidate["trusted_os_active_guest"]["qualifications"][0]["qualification_sha256"] =
|
||||
json!("04".repeat(32));
|
||||
candidate["trusted_os_active_guest"]["qualifications"][1]["binary_sha256"] =
|
||||
json!("ac".repeat(32));
|
||||
candidate["trusted_os_active_guest"]["qualifications"][1]["qualification_sha256"] =
|
||||
json!("05".repeat(32));
|
||||
Fixture {
|
||||
settings: serde_json::to_vec_pretty(&settings).unwrap(),
|
||||
pin: serde_json::to_vec_pretty(&pin).unwrap(),
|
||||
time: serde_json::to_vec_pretty(&time).unwrap(),
|
||||
candidate: serde_json::to_vec_pretty(&candidate).unwrap(),
|
||||
}
|
||||
}
|
||||
fn render_fixture(f: &Fixture) -> Result<CodePairTransition> {
|
||||
render(Inputs {
|
||||
settings: &f.settings,
|
||||
pin: &f.pin,
|
||||
time_profile: &f.time,
|
||||
qualified_candidate_time_profile: &f.candidate,
|
||||
target_agent_sha256: &"ef".repeat(32),
|
||||
target_helper_sha256: &"ac".repeat(32),
|
||||
})
|
||||
}
|
||||
#[test]
|
||||
fn windows_transition_preserves_raw_policy_bytes_and_binds_prequalified_time_profile() {
|
||||
let f = fixture();
|
||||
let result = render_fixture(&f).unwrap();
|
||||
let old: Settings = serde_json::from_slice(&f.settings).unwrap();
|
||||
let new: Settings = serde_json::from_slice(result.settings_bytes()).unwrap();
|
||||
assert_eq!(
|
||||
new.allowed_services[0].binary_sha256,
|
||||
old.agent.binary_sha256
|
||||
);
|
||||
let reversed = String::from_utf8(result.settings_bytes().to_vec())
|
||||
.unwrap()
|
||||
.replace(&"ef".repeat(32), &"ab".repeat(32))
|
||||
.replace(&"ac".repeat(32), &"cd".repeat(32));
|
||||
assert_eq!(reversed.as_bytes(), f.settings);
|
||||
assert_eq!(result.time_profile_bytes(), f.candidate);
|
||||
let new_pin: Pin = serde_json::from_slice(result.pin_bytes()).unwrap();
|
||||
assert_eq!(
|
||||
new_pin.policy_sha256,
|
||||
hash(&serde_json::to_vec(&new).unwrap())
|
||||
);
|
||||
let PeerPinTransition::WindowsCodePairV1 {
|
||||
time_profile: Some(t),
|
||||
..
|
||||
} = result.proof()
|
||||
else {
|
||||
panic!("fixed clock transition")
|
||||
};
|
||||
assert_eq!(t.old_time_profile_sha256, hash(&f.time));
|
||||
assert_eq!(t.new_time_profile_sha256, hash(&f.candidate));
|
||||
assert_eq!(t.agent_qualification_sha256, "04".repeat(32));
|
||||
#[cfg(windows)]
|
||||
{
|
||||
// Both OS-native production codecs must derive the SAME policy
|
||||
// hash; a mirrored test-only serialization cannot satisfy this.
|
||||
let actual: crate::helper_system::Settings =
|
||||
serde_json::from_slice(result.settings_bytes()).unwrap();
|
||||
assert_eq!(actual.policy_sha256().unwrap(), new_pin.policy_sha256);
|
||||
let _: crate::helper_ipc::Pin = serde_json::from_slice(result.pin_bytes()).unwrap();
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn windows_transition_denies_changed_time_trust_reused_qualification_and_unbound_pin() {
|
||||
for change in [
|
||||
"key",
|
||||
"platform",
|
||||
"qualification",
|
||||
"role",
|
||||
"extra",
|
||||
"pin",
|
||||
"null",
|
||||
] {
|
||||
let mut f = fixture();
|
||||
if change == "pin" {
|
||||
let mut value: Value = serde_json::from_slice(&f.pin).unwrap();
|
||||
value["policy_sha256"] = json!("ff".repeat(32));
|
||||
f.pin = serde_json::to_vec(&value).unwrap();
|
||||
} else if change == "null" {
|
||||
let mut value: Value = serde_json::from_slice(&f.settings).unwrap();
|
||||
value["allowed_msi_recipe_sha256"] = Value::Null;
|
||||
f.settings = serde_json::to_vec(&value).unwrap();
|
||||
} else {
|
||||
let mut value: Value = serde_json::from_slice(&f.candidate).unwrap();
|
||||
match change {
|
||||
"key" => value["key_generation"] = json!(2),
|
||||
"platform" => {
|
||||
value["trusted_os_active_guest"]["platform_provenance_sha256"] =
|
||||
json!("ff".repeat(32))
|
||||
}
|
||||
"qualification" => {
|
||||
value["trusted_os_active_guest"]["qualifications"][0]["qualification_sha256"] =
|
||||
json!("02".repeat(32))
|
||||
}
|
||||
"role" => {
|
||||
value["trusted_os_active_guest"]["qualifications"][1]["role"] =
|
||||
json!("agent")
|
||||
}
|
||||
_ => value["trusted_os_active_guest"]["assume_ready"] = json!(true),
|
||||
}
|
||||
f.candidate = serde_json::to_vec(&value).unwrap();
|
||||
}
|
||||
assert!(render_fixture(&f).is_err(), "changed field {change}");
|
||||
}
|
||||
let f = fixture();
|
||||
let mut value: Value = serde_json::from_slice(&f.pin).unwrap();
|
||||
value["helper"]["binary_sha256"] = json!("ff".repeat(32));
|
||||
assert!(
|
||||
render(Inputs {
|
||||
settings: &f.settings,
|
||||
pin: &serde_json::to_vec(&value).unwrap(),
|
||||
time_profile: &f.time,
|
||||
qualified_candidate_time_profile: &f.candidate,
|
||||
target_agent_sha256: &"ef".repeat(32),
|
||||
target_helper_sha256: &"ac".repeat(32)
|
||||
})
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user