Files
rust-discovery/crates/agent-windows/src/update_cache.rs
T

222 lines
7.1 KiB
Rust

//! Public signed artifact bytes only, before any startgrant is requested.
//! This cache grants no execution authority. SYSTEM reopens and hashes each
//! source independently; the writable LocalService source is never a trust pin.
use crate::helper_ipc::{self as ipc, PinnedFile};
use anyhow::{Context, Result, ensure};
use rmm_domain::agent_update::{ArtifactDescriptor, ReleaseManifest};
use sha2::{Digest, Sha256};
use std::{
fs::{File, OpenOptions},
io::{Read, Seek, SeekFrom, Write},
mem::zeroed,
os::windows::{
fs::OpenOptionsExt,
io::{AsRawHandle, FromRawHandle},
},
path::{Path, PathBuf},
ptr,
};
use windows_sys::Win32::{Foundation::*, Storage::FileSystem::*};
pub const ROOT: &str = r"C:\ProgramData\RustDiscovery\state\update-stage";
fn path(a: &ArtifactDescriptor, partial: bool) -> Result<PathBuf> {
ensure!(
!a.artifact_id.is_nil()
&& ipc::digest(&a.sha256)
&& a.bytes > 0
&& a.bytes <= rmm_domain::agent_update::MAX_ARTIFACT_BYTES,
"UPDATE_CACHE_DESCRIPTOR"
);
Ok(Path::new(ROOT).join(format!(
"{}.{}",
a.sha256,
if partial { "part" } else { "bin" }
)))
}
fn regular(f: &File, dir: bool) -> Result<()> {
let mut i: BY_HANDLE_FILE_INFORMATION = unsafe { zeroed() };
ensure!(
unsafe { GetFileInformationByHandle(f.as_raw_handle(), &mut i) } != 0
&& i.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT == 0
&& (i.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY != 0) == dir
&& (dir || i.nNumberOfLinks == 1),
"UPDATE_CACHE_FILE_TYPE"
);
Ok(())
}
fn parents(p: &Path) -> Result<Vec<File>> {
let mut guards = Vec::new();
for parent in p.ancestors().skip(1) {
let h = unsafe {
CreateFileW(
ipc::wide(parent).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!(h != INVALID_HANDLE_VALUE, "UPDATE_CACHE_NOT_PROVISIONED");
let file = unsafe { File::from_raw_handle(h) };
regular(&file, true)?;
guards.push(file);
}
Ok(guards)
}
fn verify(file: &mut File, a: &ArtifactDescriptor) -> Result<()> {
regular(file, false)?;
ensure!(file.metadata()?.len() == a.bytes, "UPDATE_CACHE_LENGTH");
file.seek(SeekFrom::Start(0))?;
let mut digest = Sha256::new();
let mut bytes = [0; 65536];
let mut length = 0u64;
loop {
let n = file.read(&mut bytes)?;
if n == 0 {
break;
}
length += n as u64;
ensure!(length <= a.bytes, "UPDATE_CACHE_LENGTH");
digest.update(&bytes[..n]);
}
ensure!(
length == a.bytes && format!("{:x}", digest.finalize()) == a.sha256,
"UPDATE_CACHE_DIGEST"
);
file.seek(SeekFrom::Start(0))?;
Ok(())
}
/// An already open independently hashed source. Parent and source handles deny
/// replacement and the source denies data writes until protected staging ends.
pub struct Source {
pub file: File,
_parents: Vec<File>,
identity: ipc::FileIdentity,
descriptor: ArtifactDescriptor,
}
impl Source {
pub fn open(a: &ArtifactDescriptor) -> Result<Self> {
let p = path(a, false)?;
let parents = parents(&p)?;
let mut file = OpenOptions::new()
.read(true)
.share_mode(FILE_SHARE_READ)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
.open(&p)
.context("UPDATE_CACHE_MISSING")?;
verify(&mut file, a)?;
Ok(Self {
identity: ipc::file_identity(&file)?,
file,
_parents: parents,
descriptor: a.clone(),
})
}
pub fn check(&mut self) -> Result<()> {
ensure!(
ipc::file_identity(&self.file)? == self.identity,
"UPDATE_CACHE_IDENTITY"
);
verify(&mut self.file, &self.descriptor)
}
}
pub fn configured() -> bool {
crate::native::private_path(Path::new(ROOT), true).is_ok()
}
pub fn ready(m: &ReleaseManifest) -> Result<bool> {
ensure!(m.validate(), "UPDATE_CACHE_MANIFEST");
for a in &m.artifacts {
if !path(a, false)?.try_exists()? {
return Ok(false);
}
let _ = Source::open(a)?;
}
Ok(true)
}
/// The only resumable operation is a bounded public byte download. No journal,
/// request, consumption, handoff or effect is resumed by this cache.
pub struct Download {
file: File,
descriptor: ArtifactDescriptor,
received: u64,
_parents: Vec<File>,
_root: PinnedFile,
}
impl Download {
pub fn begin(a: &ArtifactDescriptor) -> Result<Self> {
crate::native::require_local_service()?;
let p = path(a, true)?;
let parents = parents(&p)?;
crate::native::private_path(Path::new(ROOT), true)?;
let root = PinnedFile::open(
Path::new(ROOT),
true,
&[crate::native::service_sid()?],
&[crate::native::service_sid()?],
false,
)?;
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.share_mode(FILE_SHARE_READ)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
.open(&p)?;
regular(&file, false)?;
crate::native::private_path(&p, false)?;
let received = file.metadata()?.len();
ensure!(received <= a.bytes, "UPDATE_CACHE_PARTIAL_OVERSIZE");
file.seek(SeekFrom::Start(received))?;
Ok(Self {
file,
descriptor: a.clone(),
received,
_parents: parents,
_root: root,
})
}
pub fn offset(&self) -> u64 {
self.received
}
pub fn append(&mut self, offset: u64, bytes: &[u8]) -> Result<()> {
ensure!(
offset == self.received
&& !bytes.is_empty()
&& bytes.len() <= 512 * 1024
&& self.received + bytes.len() as u64 <= self.descriptor.bytes,
"UPDATE_CACHE_CHUNK"
);
self._root.check()?;
self.file.write_all(bytes)?;
self.received += bytes.len() as u64;
Ok(())
}
pub fn finish(mut self) -> Result<()> {
ensure!(
self.received == self.descriptor.bytes,
"UPDATE_CACHE_INCOMPLETE"
);
self.file.sync_all()?;
verify(&mut self.file, &self.descriptor)?;
self._root.check()?;
let src = path(&self.descriptor, true)?;
let dst = path(&self.descriptor, false)?;
drop(self.file);
// No replace, no delete of an existing source, and no shell invocation.
ensure!(
unsafe {
MoveFileExW(
ipc::wide(src).as_ptr(),
ipc::wide(dst).as_ptr(),
MOVEFILE_WRITE_THROUGH,
)
} != 0,
"UPDATE_CACHE_PUBLISH"
);
let _ = Source::open(&self.descriptor)?;
Ok(())
}
}