265 lines
9.5 KiB
Rust
265 lines
9.5 KiB
Rust
//! Temporary, read-only readiness service. Separate from the permanent agent;
|
|
//! no network/RMM jobs, no clock setting, no W32Time ACL/service changes.
|
|
#[path = "../src/clock.rs"]
|
|
mod clock;
|
|
#[cfg(windows)]
|
|
mod service {
|
|
use anyhow::{Result, ensure};
|
|
use std::{
|
|
io::Write,
|
|
mem::{size_of, zeroed},
|
|
path::PathBuf,
|
|
ptr,
|
|
sync::{
|
|
OnceLock,
|
|
atomic::{AtomicUsize, Ordering},
|
|
},
|
|
time::Duration,
|
|
};
|
|
use windows_sys::Win32::{
|
|
Foundation::CloseHandle,
|
|
Security::*,
|
|
System::{
|
|
Services::*,
|
|
Threading::{GetCurrentProcess, OpenProcessToken},
|
|
},
|
|
};
|
|
const NAME: &str = "RmmWindowsClockReadiness";
|
|
static CASE: OnceLock<uuid::Uuid> = OnceLock::new();
|
|
static HANDLE: AtomicUsize = AtomicUsize::new(0);
|
|
static STAGE: AtomicUsize = AtomicUsize::new(0);
|
|
fn wide(s: &str) -> Vec<u16> {
|
|
s.encode_utf16().chain(Some(0)).collect()
|
|
}
|
|
#[derive(serde::Serialize)]
|
|
struct TokenEvidence {
|
|
user_sid: &'static str,
|
|
elevation_flag: u32,
|
|
elevation_type: i32,
|
|
administrator_member: bool,
|
|
system_user: bool,
|
|
}
|
|
fn token() -> Result<TokenEvidence> {
|
|
STAGE.store(10, Ordering::SeqCst);
|
|
let mut handle = ptr::null_mut();
|
|
ensure!(
|
|
unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut handle) } != 0,
|
|
"READINESS_TOKEN"
|
|
);
|
|
let result = (|| {
|
|
STAGE.store(11, Ordering::SeqCst);
|
|
let mut size = 0;
|
|
unsafe {
|
|
GetTokenInformation(handle, TokenUser, ptr::null_mut(), 0, &mut size);
|
|
}
|
|
ensure!(size > 0 && size <= 4096, "READINESS_TOKEN_SIZE");
|
|
let mut user = vec![0usize; (size as usize).div_ceil(size_of::<usize>())];
|
|
ensure!(
|
|
unsafe {
|
|
GetTokenInformation(
|
|
handle,
|
|
TokenUser,
|
|
user.as_mut_ptr().cast(),
|
|
size,
|
|
&mut size,
|
|
)
|
|
} != 0,
|
|
"READINESS_TOKEN_USER"
|
|
);
|
|
STAGE.store(12, Ordering::SeqCst);
|
|
let info = unsafe { &*user.as_ptr().cast::<TOKEN_USER>() };
|
|
ensure!(
|
|
unsafe { IsWellKnownSid(info.User.Sid, WinLocalServiceSid) } != 0,
|
|
"READINESS_NOT_LOCAL_SERVICE"
|
|
);
|
|
STAGE.store(13, Ordering::SeqCst);
|
|
let mut elevation: TOKEN_ELEVATION = unsafe { zeroed() };
|
|
ensure!(
|
|
unsafe {
|
|
GetTokenInformation(
|
|
handle,
|
|
TokenElevation,
|
|
(&mut elevation as *mut TOKEN_ELEVATION).cast(),
|
|
size_of::<TOKEN_ELEVATION>() as u32,
|
|
&mut size,
|
|
)
|
|
} != 0,
|
|
"READINESS_ELEVATED"
|
|
);
|
|
STAGE.store(14, Ordering::SeqCst);
|
|
let mut elevation_type: TOKEN_ELEVATION_TYPE = 0;
|
|
ensure!(
|
|
unsafe {
|
|
GetTokenInformation(
|
|
handle,
|
|
TokenElevationType,
|
|
(&mut elevation_type as *mut TOKEN_ELEVATION_TYPE).cast(),
|
|
size_of::<TOKEN_ELEVATION_TYPE>() as u32,
|
|
&mut size,
|
|
)
|
|
} != 0,
|
|
"READINESS_ELEVATION_TYPE"
|
|
);
|
|
let mut admin_sid = [0u64; 9];
|
|
let mut admin_size = 72;
|
|
ensure!(
|
|
unsafe {
|
|
CreateWellKnownSid(
|
|
WinBuiltinAdministratorsSid,
|
|
ptr::null_mut(),
|
|
admin_sid.as_mut_ptr().cast(),
|
|
&mut admin_size,
|
|
)
|
|
} != 0,
|
|
"READINESS_ADMIN_SID"
|
|
);
|
|
let mut admin = 0;
|
|
ensure!(
|
|
unsafe {
|
|
CheckTokenMembership(ptr::null_mut(), admin_sid.as_mut_ptr().cast(), &mut admin)
|
|
} != 0,
|
|
"READINESS_ADMIN_CHECK"
|
|
);
|
|
Ok(TokenEvidence {
|
|
user_sid: "S-1-5-19",
|
|
elevation_flag: elevation.TokenIsElevated,
|
|
elevation_type,
|
|
administrator_member: admin != 0,
|
|
system_user: unsafe { IsWellKnownSid(info.User.Sid, WinLocalSystemSid) } != 0,
|
|
})
|
|
})();
|
|
unsafe {
|
|
CloseHandle(handle);
|
|
}
|
|
result
|
|
}
|
|
fn run() -> Result<()> {
|
|
let token = token()?;
|
|
STAGE.store(20, Ordering::SeqCst);
|
|
let case = CASE.get().unwrap();
|
|
let root =
|
|
PathBuf::from(r"C:\ProgramData\RustDiscoveryClockReadiness").join(case.to_string());
|
|
ensure!(root.is_dir() && !root.is_symlink(), "READINESS_ROOT");
|
|
// Preserve the actual token proof before entering foreign RPC code.
|
|
let mut token_file = std::fs::OpenOptions::new()
|
|
.write(true)
|
|
.create_new(true)
|
|
.open(root.join("token.json"))?;
|
|
token_file.write_all(&serde_json::to_vec(&token)?)?;
|
|
token_file.sync_all()?;
|
|
let endpoints = super::clock::endpoint_report();
|
|
let mut endpoint_file = std::fs::OpenOptions::new()
|
|
.write(true)
|
|
.create_new(true)
|
|
.open(root.join("endpoints.json"))?;
|
|
endpoint_file.write_all(&serde_json::to_vec(&endpoints)?)?;
|
|
endpoint_file.sync_all()?;
|
|
let clock = super::clock::NativeClock::new();
|
|
STAGE.store(30, Ordering::SeqCst);
|
|
let pipe = super::clock::named_pipe_diagnostic();
|
|
let first = clock.report();
|
|
std::thread::sleep(Duration::from_millis(750));
|
|
STAGE.store(31, Ordering::SeqCst);
|
|
let second = clock.report();
|
|
let identity_controls = super::clock::identity_controls();
|
|
STAGE.store(40, Ordering::SeqCst);
|
|
let data = serde_json::to_vec_pretty(
|
|
&serde_json::json!({"schema":1,"case_id":case,"service_name":NAME,"token_sid":"S-1-5-19","elevated":token.elevation_flag!=0,"token":token,"endpoints":endpoints,"named_pipe_diagnostic":pipe,"identity_controls":identity_controls,"source":"MS-W32T:4.1:Opnum6:ncalrpc:SID19:W32Time:V5_descriptor:MUTUAL_AUTH:WINNT:PKT_PRIVACY","read_only":true,"samples":[first,second]}),
|
|
)?;
|
|
ensure!(data.len() < 16384, "READINESS_REPORT_SIZE");
|
|
STAGE.store(41, Ordering::SeqCst);
|
|
let mut file = std::fs::OpenOptions::new()
|
|
.write(true)
|
|
.create_new(true)
|
|
.open(root.join("result.json"))?;
|
|
STAGE.store(42, Ordering::SeqCst);
|
|
file.write_all(&data)?;
|
|
STAGE.store(43, Ordering::SeqCst);
|
|
file.sync_all()?;
|
|
STAGE.store(44, Ordering::SeqCst);
|
|
Ok(())
|
|
}
|
|
fn status(state: u32, error: u32) {
|
|
let handle = HANDLE.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,
|
|
};
|
|
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 main(_: u32, _: *mut *mut u16) {
|
|
let name = wide(NAME);
|
|
let handle =
|
|
unsafe { RegisterServiceCtrlHandlerExW(name.as_ptr(), Some(control), ptr::null_mut()) };
|
|
if handle.is_null() {
|
|
return;
|
|
}
|
|
HANDLE.store(handle as usize, Ordering::SeqCst);
|
|
status(SERVICE_RUNNING, 0);
|
|
let result = run();
|
|
if result.is_ok() {
|
|
std::thread::sleep(Duration::from_secs(2));
|
|
}
|
|
status(SERVICE_STOPPED, if result.is_ok() { 0 } else { 1066 });
|
|
}
|
|
pub fn dispatch() -> Result<()> {
|
|
let args: Vec<_> = std::env::args().collect();
|
|
ensure!(
|
|
args.len() == 3 && args[1] == "--service",
|
|
"READINESS_SERVICE_ONLY"
|
|
);
|
|
let case = uuid::Uuid::parse_str(&args[2])?;
|
|
ensure!(case.get_version_num() == 4, "READINESS_CASE_UUID");
|
|
CASE.set(case).unwrap();
|
|
let mut name = wide(NAME);
|
|
let table = [
|
|
SERVICE_TABLE_ENTRYW {
|
|
lpServiceName: name.as_mut_ptr(),
|
|
lpServiceProc: Some(main),
|
|
},
|
|
SERVICE_TABLE_ENTRYW {
|
|
lpServiceName: ptr::null_mut(),
|
|
lpServiceProc: None,
|
|
},
|
|
];
|
|
ensure!(
|
|
unsafe { StartServiceCtrlDispatcherW(table.as_ptr()) } != 0,
|
|
"READINESS_SCM"
|
|
);
|
|
Ok(())
|
|
}
|
|
}
|
|
#[cfg(windows)]
|
|
fn main() -> anyhow::Result<()> {
|
|
service::dispatch()
|
|
}
|
|
#[cfg(not(windows))]
|
|
fn main() {
|
|
println!(
|
|
"{}",
|
|
serde_json::to_string(&serde_json::json!({"clock":clock::NativeClock::new().report(),"endpoints":clock::endpoint_report(),"named_pipe_diagnostic":clock::named_pipe_diagnostic(),"identity_controls":clock::identity_controls()})).unwrap()
|
|
);
|
|
}
|