Add isolated time broker and raw Windows capture with Linux evidence
Rust development slice / linux (push) Failing after 7s
Rust development slice / linux (push) Failing after 7s
This commit is contained in:
@@ -0,0 +1,343 @@
|
||||
//! Fixed, temporary SCM capture probe. It never installs a service or opens an
|
||||
//! RMM store, key/pin, network endpoint, W32Time, job or clock setter.
|
||||
#[cfg(all(windows, feature = "system-helper"))]
|
||||
mod probe {
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use rmm_agent_windows::{helper_ipc as ipc, signed_clock};
|
||||
use rmm_domain::jobs::hash;
|
||||
use serde::Serialize;
|
||||
use std::{
|
||||
fs::OpenOptions,
|
||||
io::Write,
|
||||
mem::{size_of, zeroed},
|
||||
os::windows::{
|
||||
fs::OpenOptionsExt,
|
||||
io::{AsRawHandle, FromRawHandle, OwnedHandle},
|
||||
},
|
||||
path::{Path, PathBuf},
|
||||
ptr,
|
||||
sync::{
|
||||
OnceLock,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
},
|
||||
};
|
||||
use windows_sys::Win32::{
|
||||
Foundation::*,
|
||||
Security::*,
|
||||
Storage::FileSystem::*,
|
||||
System::{Services::*, Threading::*},
|
||||
};
|
||||
const BASE: &str = r"C:\ProgramData\RustDiscoverySignedClockCapture";
|
||||
const LS: &str = "RmmSignedClockCaptureLocalService";
|
||||
const SYSTEM: &str = "RmmSignedClockCaptureSystem";
|
||||
static CASE: OnceLock<uuid::Uuid> = OnceLock::new();
|
||||
static ROLE: OnceLock<Role> = OnceLock::new();
|
||||
static STATUS: AtomicUsize = AtomicUsize::new(0);
|
||||
static STAGE: AtomicUsize = AtomicUsize::new(0);
|
||||
#[derive(Clone, Copy)]
|
||||
enum Role {
|
||||
LocalService,
|
||||
System,
|
||||
}
|
||||
impl Role {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::LocalService => LS,
|
||||
Self::System => SYSTEM,
|
||||
}
|
||||
}
|
||||
fn tag(self) -> &'static str {
|
||||
match self {
|
||||
Self::LocalService => "local-service",
|
||||
Self::System => "system",
|
||||
}
|
||||
}
|
||||
fn user(self) -> &'static str {
|
||||
match self {
|
||||
Self::LocalService => "S-1-5-19",
|
||||
Self::System => "S-1-5-18",
|
||||
}
|
||||
}
|
||||
}
|
||||
fn wide(value: &str) -> Vec<u16> {
|
||||
value.encode_utf16().chain(Some(0)).collect()
|
||||
}
|
||||
fn owned(value: HANDLE) -> Result<OwnedHandle> {
|
||||
ensure!(
|
||||
!value.is_null() && value != INVALID_HANDLE_VALUE,
|
||||
"CAPTURE_NATIVE_HANDLE"
|
||||
);
|
||||
// SAFETY: only uniquely owned handles returned by successful APIs enter.
|
||||
Ok(unsafe { OwnedHandle::from_raw_handle(value) })
|
||||
}
|
||||
#[derive(Serialize)]
|
||||
struct TokenReport {
|
||||
user_sid: &'static str,
|
||||
service_sid_sha256: String,
|
||||
elevation_flag: u32,
|
||||
elevation_type: i32,
|
||||
}
|
||||
fn token(role: Role) -> Result<TokenReport> {
|
||||
let mut thread = ptr::null_mut();
|
||||
// SAFETY: valid output pointer, query only, no impersonation is created.
|
||||
if unsafe { OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, 1, &mut thread) } != 0 {
|
||||
let _thread = owned(thread)?;
|
||||
anyhow::bail!("CAPTURE_IMPERSONATION_FORBIDDEN");
|
||||
}
|
||||
ensure!(
|
||||
unsafe { GetLastError() } == ERROR_NO_TOKEN,
|
||||
"CAPTURE_THREAD_TOKEN"
|
||||
);
|
||||
let mut raw = ptr::null_mut();
|
||||
ensure!(
|
||||
unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut raw) } != 0,
|
||||
"CAPTURE_PROCESS_TOKEN"
|
||||
);
|
||||
let handle = owned(raw)?;
|
||||
let sid = ipc::service_sid(role.name())?;
|
||||
ipc::verify_token(handle.as_raw_handle(), role.user(), &sid)?;
|
||||
let mut elevation: TOKEN_ELEVATION = unsafe { zeroed() };
|
||||
let mut count = 0;
|
||||
ensure!(
|
||||
unsafe {
|
||||
GetTokenInformation(
|
||||
handle.as_raw_handle(),
|
||||
TokenElevation,
|
||||
ptr::addr_of_mut!(elevation).cast(),
|
||||
size_of::<TOKEN_ELEVATION>() as u32,
|
||||
&mut count,
|
||||
)
|
||||
} != 0
|
||||
&& count as usize == size_of::<TOKEN_ELEVATION>(),
|
||||
"CAPTURE_ELEVATION"
|
||||
);
|
||||
let mut kind: TOKEN_ELEVATION_TYPE = 0;
|
||||
ensure!(
|
||||
unsafe {
|
||||
GetTokenInformation(
|
||||
handle.as_raw_handle(),
|
||||
TokenElevationType,
|
||||
ptr::addr_of_mut!(kind).cast(),
|
||||
size_of::<TOKEN_ELEVATION_TYPE>() as u32,
|
||||
&mut count,
|
||||
)
|
||||
} != 0
|
||||
&& count as usize == size_of::<TOKEN_ELEVATION_TYPE>()
|
||||
&& (1..=3).contains(&kind),
|
||||
"CAPTURE_ELEVATION_TYPE"
|
||||
);
|
||||
Ok(TokenReport {
|
||||
user_sid: role.user(),
|
||||
service_sid_sha256: hash(sid.as_bytes()),
|
||||
elevation_flag: elevation.TokenIsElevated,
|
||||
elevation_type: kind,
|
||||
})
|
||||
}
|
||||
fn create(path: &Path, bytes: &[u8]) -> Result<()> {
|
||||
ensure!(bytes.len() <= 16384, "CAPTURE_REPORT_LIMIT");
|
||||
let mut file = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.share_mode(FILE_SHARE_READ)
|
||||
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
|
||||
.open(path)?;
|
||||
let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { zeroed() };
|
||||
ensure!(
|
||||
unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut info) } != 0
|
||||
&& info.dwFileAttributes
|
||||
& (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)
|
||||
== 0
|
||||
&& info.nNumberOfLinks == 1,
|
||||
"CAPTURE_NEW_FILE_IDENTITY"
|
||||
);
|
||||
file.write_all(bytes)?;
|
||||
file.sync_all()?;
|
||||
Ok(())
|
||||
}
|
||||
fn execute() -> Result<()> {
|
||||
let role = *ROLE.get().context("CAPTURE_ROLE")?;
|
||||
let case = *CASE.get().context("CAPTURE_CASE")?;
|
||||
STAGE.store(10, Ordering::SeqCst);
|
||||
let token = token(role)?;
|
||||
let role_sid = ipc::service_sid(role.name())?;
|
||||
// Both fixed fixture SIDs may read the common case directory. Only the
|
||||
// selected fixture SID may write its own role subdirectory.
|
||||
let readers = vec![ipc::service_sid(LS)?, ipc::service_sid(SYSTEM)?];
|
||||
let root = PathBuf::from(BASE);
|
||||
let case_root = root.join(case.to_string());
|
||||
let output = case_root.join(role.tag());
|
||||
let image_path = case_root.join("SignedClockCapture.exe");
|
||||
ensure!(
|
||||
std::env::current_exe()? == image_path,
|
||||
"CAPTURE_FIXED_IMAGE_PATH"
|
||||
);
|
||||
let mut held = vec![
|
||||
ipc::PinnedFile::open(&root, true, &readers, &[], false)?,
|
||||
ipc::PinnedFile::open(&case_root, true, &readers, &[], false)?,
|
||||
ipc::PinnedFile::open(&output, true, &readers, &[role_sid], false)?,
|
||||
];
|
||||
let mut image = ipc::PinnedFile::open(&image_path, false, &readers, &[], false)?;
|
||||
let image_sha256 = image.sha256()?;
|
||||
let image_file = image.identity;
|
||||
held.push(image);
|
||||
for name in ["intent.json", "report.json", "end.json"] {
|
||||
ensure!(!output.join(name).exists(), "CAPTURE_CASE_ALREADY_ENTERED");
|
||||
}
|
||||
let pid = unsafe { GetCurrentProcessId() };
|
||||
let (mut born, mut ended, mut kernel, mut user) = (
|
||||
unsafe { zeroed() },
|
||||
unsafe { zeroed() },
|
||||
unsafe { zeroed() },
|
||||
unsafe { zeroed() },
|
||||
);
|
||||
ensure!(
|
||||
unsafe {
|
||||
GetProcessTimes(
|
||||
GetCurrentProcess(),
|
||||
&mut born,
|
||||
&mut ended,
|
||||
&mut kernel,
|
||||
&mut user,
|
||||
)
|
||||
} != 0,
|
||||
"CAPTURE_PROCESS_BIRTH"
|
||||
);
|
||||
let born = (u64::from(born.dwHighDateTime) << 32) | u64::from(born.dwLowDateTime);
|
||||
STAGE.store(20, Ordering::SeqCst);
|
||||
// Fixed existing read-only CIM boot getter, BEFORE the 250ms sampling
|
||||
// budget; never a caller script or a substitute process-start identity.
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()?;
|
||||
let boot = uuid::Uuid::parse_str(&runtime.block_on(rmm_agent_windows::native::boot_id())?)?;
|
||||
ensure!(
|
||||
!boot.is_nil() && born > 0 && pid > 0,
|
||||
"CAPTURE_NATIVE_IDENTITY"
|
||||
);
|
||||
create(
|
||||
&output.join("intent.json"),
|
||||
&serde_json::to_vec(
|
||||
&serde_json::json!({"schema_version":1,"case_id":case,"role":role.tag(),"pid":pid,"process_birth_filetime":born,"image_sha256":image_sha256,"boot_id":boot,"calibrated":false,"clock_authority":false,"no_repeat":true,"maximum_samples":128,"maximum_capture_ns":250000000}),
|
||||
)?,
|
||||
)?;
|
||||
STAGE.store(30, Ordering::SeqCst);
|
||||
let result = (|| {
|
||||
let captures = signed_clock::diagnostic_capture_series()?;
|
||||
STAGE.store(40, Ordering::SeqCst);
|
||||
let current_token = token_role_recheck(role, &token)?;
|
||||
for file in &mut held {
|
||||
file.check()?;
|
||||
}
|
||||
let report = serde_json::to_vec(
|
||||
&serde_json::json!({"schema_version":1,"case_id":case,"role":role.tag(),"calibrated":false,"clock_authority":false,"read_only_clock":true,"token":current_token,"pid":pid,"process_birth_filetime":born,"image_sha256":image_sha256,"image_file":image_file,"boot_id":boot,"capture":captures}),
|
||||
)?;
|
||||
ensure!(report.len() <= 16384, "CAPTURE_REPORT_LIMIT");
|
||||
create(&output.join("report.json"), &report)?;
|
||||
Ok::<_, anyhow::Error>(hash(&report))
|
||||
})();
|
||||
let end = serde_json::to_vec(
|
||||
&serde_json::json!({"schema_version":1,"case_id":case,"role":role.tag(),"success":result.is_ok(),"stage":STAGE.load(Ordering::SeqCst),"report_sha256":result.as_ref().ok(),"calibrated":false,"clock_authority":false,"no_repeat":true}),
|
||||
)?;
|
||||
create(&output.join("end.json"), &end)?;
|
||||
result?;
|
||||
STAGE.store(50, Ordering::SeqCst);
|
||||
Ok(())
|
||||
}
|
||||
fn token_role_recheck(role: Role, original: &TokenReport) -> Result<TokenReport> {
|
||||
let current = token(role)?;
|
||||
ensure!(
|
||||
serde_json::to_vec(¤t)? == serde_json::to_vec(original)?,
|
||||
"CAPTURE_TOKEN_CHANGED"
|
||||
);
|
||||
Ok(current)
|
||||
}
|
||||
fn status(state: u32, error: u32) {
|
||||
let handle = STATUS.load(Ordering::SeqCst) as SERVICE_STATUS_HANDLE;
|
||||
if handle.is_null() {
|
||||
return;
|
||||
}
|
||||
let value = SERVICE_STATUS {
|
||||
dwServiceType: SERVICE_WIN32_OWN_PROCESS,
|
||||
dwCurrentState: state,
|
||||
dwControlsAccepted: 0,
|
||||
dwWin32ExitCode: error,
|
||||
dwServiceSpecificExitCode: if error == 1066 {
|
||||
STAGE.load(Ordering::SeqCst) as u32
|
||||
} else {
|
||||
0
|
||||
},
|
||||
dwCheckPoint: 0,
|
||||
dwWaitHint: 10000,
|
||||
};
|
||||
// SAFETY: this handle is returned by SCM for this own temporary service.
|
||||
unsafe { SetServiceStatus(handle, &value) };
|
||||
}
|
||||
unsafe extern "system" fn control(
|
||||
_: u32,
|
||||
_: u32,
|
||||
_: *mut std::ffi::c_void,
|
||||
_: *mut std::ffi::c_void,
|
||||
) -> u32 {
|
||||
0
|
||||
}
|
||||
unsafe extern "system" fn service_main(_: u32, _: *mut *mut u16) {
|
||||
let Some(role) = ROLE.get().copied() else {
|
||||
return;
|
||||
};
|
||||
let name = wide(role.name());
|
||||
let handle =
|
||||
unsafe { RegisterServiceCtrlHandlerExW(name.as_ptr(), Some(control), ptr::null_mut()) };
|
||||
if handle.is_null() {
|
||||
return;
|
||||
}
|
||||
STATUS.store(handle as usize, Ordering::SeqCst);
|
||||
status(SERVICE_RUNNING, 0);
|
||||
let result = execute();
|
||||
status(SERVICE_STOPPED, if result.is_ok() { 0 } else { 1066 });
|
||||
}
|
||||
pub fn dispatch() -> Result<()> {
|
||||
let args: Vec<_> = std::env::args().collect();
|
||||
ensure!(
|
||||
args.len() == 4 && args[1] == "--service",
|
||||
"CAPTURE_FIXED_ARGUMENTS"
|
||||
);
|
||||
let case = uuid::Uuid::parse_str(&args[2])?;
|
||||
ensure!(
|
||||
case.get_version_num() == 4 && case.to_string() == args[2],
|
||||
"CAPTURE_CANONICAL_UUID"
|
||||
);
|
||||
let role = match args[3].as_str() {
|
||||
"local-service" => Role::LocalService,
|
||||
"system" => Role::System,
|
||||
_ => anyhow::bail!("CAPTURE_FIXED_ROLE"),
|
||||
};
|
||||
CASE.set(case)
|
||||
.map_err(|_| anyhow::anyhow!("CAPTURE_ALREADY_DISPATCHED"))?;
|
||||
ROLE.set(role)
|
||||
.map_err(|_| anyhow::anyhow!("CAPTURE_ALREADY_DISPATCHED"))?;
|
||||
let mut name = wide(role.name());
|
||||
let table = [
|
||||
SERVICE_TABLE_ENTRYW {
|
||||
lpServiceName: name.as_mut_ptr(),
|
||||
lpServiceProc: Some(service_main),
|
||||
},
|
||||
SERVICE_TABLE_ENTRYW {
|
||||
lpServiceName: ptr::null_mut(),
|
||||
lpServiceProc: None,
|
||||
},
|
||||
];
|
||||
ensure!(
|
||||
unsafe { StartServiceCtrlDispatcherW(table.as_ptr()) } != 0,
|
||||
"CAPTURE_SCM_ONLY"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
#[cfg(all(windows, feature = "system-helper"))]
|
||||
fn main() -> anyhow::Result<()> {
|
||||
probe::dispatch()
|
||||
}
|
||||
#[cfg(not(all(windows, feature = "system-helper")))]
|
||||
fn main() -> anyhow::Result<()> {
|
||||
anyhow::bail!("Windows system-helper build required; no diagnostic clock fallback")
|
||||
}
|
||||
Reference in New Issue
Block a user