//! Typed local reboot provider. The caller must durably consume the original //! signed attempt and keep the independent helper gate before `request`. #[cfg(any(windows, test))] use rmm_agent_core::auth::Outcome; #[cfg(any(windows, test))] use uuid::Uuid; #[cfg(any(windows, test))] fn report(previous_boot: Uuid, accepted: bool, native_error: u32) -> Outcome { Outcome { state: if accepted { "awaiting_reboot" } else { "failed" } .into(), stdout: vec![], stderr: vec![], exit_code: None, output_truncated: false, reboot_required: false, error_code: if accepted { "EFFECT_REQUIRES_RECONCILIATION" } else { "WINDOWS_REBOOT_REQUEST_REJECTED" } .into(), evidence: serde_json::json!({"provider":"windows.shutdown/1","previous_boot_id":previous_boot,"postconditions_passed":false, "native_request_accepted":accepted,"native_error":native_error,"not_started":!accepted,"force_apps_closed":false,"local_machine_only":true, "announcement_seconds":rmm_domain::windows_reboot::ANNOUNCEMENT_SECONDS,"reconnect_timeout_seconds":rmm_domain::windows_reboot::RECONNECT_SECONDS, "automatic_retry":false,"success_requires_authenticated_new_boot":true}), } } #[cfg(windows)] mod native { use super::*; use anyhow::{Result, ensure}; use std::{ mem::{size_of, zeroed}, ptr, }; use windows_sys::Win32::{ Foundation::{ CloseHandle, ERROR_INSUFFICIENT_BUFFER, GetLastError, HANDLE, LUID, SetLastError, }, Security::{ AdjustTokenPrivileges, GetTokenInformation, LUID_AND_ATTRIBUTES, LookupPrivilegeValueW, SE_PRIVILEGE_ENABLED, SE_SHUTDOWN_NAME, TOKEN_ADJUST_PRIVILEGES, TOKEN_PRIVILEGES, TOKEN_QUERY, TokenPrivileges, }, System::{ Shutdown::{ InitiateSystemShutdownExW, SHTDN_REASON_FLAG_PLANNED, SHTDN_REASON_MAJOR_APPLICATION, SHTDN_REASON_MINOR_MAINTENANCE, }, Threading::{GetCurrentProcess, OpenProcessToken}, }, }; struct Token(HANDLE); impl Drop for Token { fn drop(&mut self) { unsafe { CloseHandle(self.0); } } } fn open(access: u32) -> Result { let mut raw = ptr::null_mut(); ensure!( unsafe { OpenProcessToken(GetCurrentProcess(), access, &mut raw) } != 0, "REBOOT_TOKEN_OPEN" ); Ok(Token(raw)) } fn luid() -> Result { let mut id = unsafe { zeroed() }; ensure!( unsafe { LookupPrivilegeValueW(ptr::null(), SE_SHUTDOWN_NAME, &mut id) } != 0, "REBOOT_PRIVILEGE_NAME" ); Ok(id) } fn present(token: &Token, wanted: &LUID) -> Result { let mut size = 0; unsafe { GetTokenInformation(token.0, TokenPrivileges, ptr::null_mut(), 0, &mut size); } ensure!( unsafe { GetLastError() } == ERROR_INSUFFICIENT_BUFFER && (4..=65536).contains(&size), "REBOOT_PRIVILEGE_SIZE" ); let mut bytes = vec![0u64; (size as usize).div_ceil(8)]; ensure!( unsafe { GetTokenInformation( token.0, TokenPrivileges, bytes.as_mut_ptr().cast(), size, &mut size, ) } != 0, "REBOOT_PRIVILEGE_READ" ); let p = bytes.as_ptr().cast::(); let count = unsafe { (*p).PrivilegeCount } as usize; let offset = std::mem::offset_of!(TOKEN_PRIVILEGES, Privileges); ensure!( offset .checked_add( count .checked_mul(size_of::()) .ok_or_else(|| anyhow::anyhow!("REBOOT_PRIVILEGE_OVERFLOW"))? ) .is_some_and(|v| v <= size as usize), "REBOOT_PRIVILEGE_BOUNDS" ); let entries = unsafe { std::slice::from_raw_parts( ptr::addr_of!((*p).Privileges).cast::(), count, ) }; Ok(entries .iter() .any(|x| x.Luid.LowPart == wanted.LowPart && x.Luid.HighPart == wanted.HighPart)) } /// Read only; does not enable a privilege, call Shutdown or create a job. pub fn privilege_available() -> Result { present(&open(TOKEN_QUERY)?, &luid()?) } struct Privilege<'a> { token: &'a Token, previous: TOKEN_PRIVILEGES, restore: bool, } impl<'a> Privilege<'a> { fn enable(token: &'a Token, id: LUID) -> Result { let change = TOKEN_PRIVILEGES { PrivilegeCount: 1, Privileges: [LUID_AND_ATTRIBUTES { Luid: id, Attributes: SE_PRIVILEGE_ENABLED, }], }; let mut previous = unsafe { zeroed() }; let mut len = 0; unsafe { SetLastError(0); } ensure!( unsafe { AdjustTokenPrivileges( token.0, 0, &change, size_of::() as u32, &mut previous, &mut len, ) } != 0 && unsafe { GetLastError() } == 0, "REBOOT_PRIVILEGE_ENABLE" ); Ok(Self { token, previous, restore: true, }) } fn restore(&mut self) -> Result<()> { if self.restore { ensure!( unsafe { AdjustTokenPrivileges( self.token.0, 0, &self.previous, 0, ptr::null_mut(), ptr::null_mut(), ) } != 0, "REBOOT_PRIVILEGE_RESTORE" ); self.restore = false; } Ok(()) } } impl Drop for Privilege<'_> { fn drop(&mut self) { let _ = self.restore(); } } pub(crate) struct Prepared { token: Token, luid: LUID, } impl Prepared { pub fn prepare(job: &rmm_domain::jobs::JobPayload) -> Result { ensure!( rmm_domain::windows_reboot::supported(job), "WINDOWS_REBOOT_FIXED_PROFILE_REQUIRED" ); let token = open(TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES)?; let luid = luid()?; ensure!( present(&token, &luid)?, "WINDOWS_REBOOT_PRIVILEGE_UNAVAILABLE" ); Ok(Self { token, luid }) } pub fn request( self, previous_boot: Uuid, mut last_gate: impl FnMut() -> Result<()>, ) -> Result { last_gate()?; let mut privilege = Privilege::enable(&self.token, self.luid)?; last_gate()?; // No remote target, free command, force flag, clock setter or retry. let message: Vec = "RustDiscovery: genehmigter Neustart" .encode_utf16() .chain(Some(0)) .collect(); let accepted = unsafe { InitiateSystemShutdownExW( ptr::null(), message.as_ptr(), rmm_domain::windows_reboot::ANNOUNCEMENT_SECONDS, 0, 1, SHTDN_REASON_FLAG_PLANNED | SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_MINOR_MAINTENANCE, ) } != 0; let code = if accepted { 0 } else { unsafe { GetLastError() } }; let restored = privilege.restore(); if accepted && restored.is_err() { return Ok(Outcome { evidence: serde_json::json!({"provider":"windows.shutdown/1","previous_boot_id":previous_boot,"native_request_accepted":true,"postconditions_passed":false,"automatic_retry":false}), ..Outcome::unknown("WINDOWS_REBOOT_ACCEPTED_PRIVILEGE_RESTORE_UNCONFIRMED") }); } restored?; Ok(report(previous_boot, accepted, code)) } } } #[cfg(windows)] pub(crate) use native::Prepared; #[cfg(windows)] pub use native::privilege_available; #[cfg(test)] mod tests { use super::*; #[test] fn native_acceptance_requires_new_boot_instead_of_claiming_success_or_retry() { let boot = Uuid::new_v4(); let accepted = report(boot, true, 0); assert_eq!(accepted.state, "awaiting_reboot"); assert!(!accepted.reboot_required); assert_eq!(accepted.evidence["previous_boot_id"], boot.to_string()); assert_eq!(accepted.evidence["postconditions_passed"], false); assert_eq!(accepted.evidence["force_apps_closed"], false); let denied = report(boot, false, 1314); assert_eq!(denied.state, "failed"); assert_eq!(denied.evidence["not_started"], true); assert_eq!(denied.evidence["automatic_retry"], false); } }