aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
//! Removes known sandbox firewall rules while preserving unrelated rules.
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
use windows::Win32::NetworkManagement::WindowsFirewall::INetFwPolicy2;
|
||||
use windows::Win32::NetworkManagement::WindowsFirewall::NetFwPolicy2;
|
||||
use windows::Win32::System::Com::CLSCTX_INPROC_SERVER;
|
||||
use windows::Win32::System::Com::CoCreateInstance;
|
||||
use windows::core::BSTR;
|
||||
|
||||
pub(super) fn cleanup_firewall_rules() -> Result<()> {
|
||||
let policy: INetFwPolicy2 = unsafe {
|
||||
CoCreateInstance(&NetFwPolicy2, /*punkouter*/ None, CLSCTX_INPROC_SERVER)
|
||||
.context("access firewall policy for sandbox uninstall")?
|
||||
};
|
||||
let rules = unsafe { policy.Rules() }.context("access sandbox firewall rules")?;
|
||||
let mut errors = Vec::new();
|
||||
for name in [
|
||||
"codex_sandbox_offline_block_outbound",
|
||||
"codex_sandbox_offline_block_inbound",
|
||||
"codex_sandbox_offline_block_loopback_tcp",
|
||||
"codex_sandbox_offline_block_loopback_udp",
|
||||
"codex_sandbox_offline_allow_loopback_proxy",
|
||||
] {
|
||||
if let Err(error) = unsafe { rules.Remove(&BSTR::from(name)) } {
|
||||
errors.push(format!("remove sandbox firewall rule {name}: {error}"));
|
||||
}
|
||||
}
|
||||
if errors.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(anyhow!(errors.join("; ")))
|
||||
}
|
||||
}
|
||||
185
akode-rs/windows-sandbox-rs/src/uninstall_windows/principals.rs
Normal file
185
akode-rs/windows-sandbox-rs/src/uninstall_windows/principals.rs
Normal file
@@ -0,0 +1,185 @@
|
||||
//! Disables sandbox accounts for cleanup and removes their profiles and principals.
|
||||
//! Callers must restore original flags if preparation for cleanup fails.
|
||||
|
||||
use std::ptr::null;
|
||||
|
||||
use anyhow::Result;
|
||||
use anyhow::bail;
|
||||
use anyhow::ensure;
|
||||
use windows_sys::Win32::Foundation::ERROR_FILE_NOT_FOUND;
|
||||
use windows_sys::Win32::Foundation::ERROR_SUCCESS;
|
||||
use windows_sys::Win32::NetworkManagement::NetManagement as network;
|
||||
use windows_sys::Win32::System::Registry as registry;
|
||||
use windows_sys::Win32::UI::Shell::DeleteProfileW;
|
||||
|
||||
use crate::setup::OFFLINE_USERNAME;
|
||||
use crate::setup::ONLINE_USERNAME;
|
||||
use crate::winutil::local_user_flags;
|
||||
use crate::winutil::resolve_sid;
|
||||
use crate::winutil::set_local_user_flags;
|
||||
use crate::winutil::string_from_sid_bytes;
|
||||
use crate::winutil::to_wide;
|
||||
|
||||
use super::retained_logons::RetainedLogons;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct DisabledSandboxUsers {
|
||||
users: Vec<SandboxUser>,
|
||||
}
|
||||
|
||||
struct SandboxUser {
|
||||
name: &'static str,
|
||||
original_flags: u32,
|
||||
sid: Vec<u8>,
|
||||
}
|
||||
|
||||
impl DisabledSandboxUsers {
|
||||
pub(super) fn disable(&mut self) -> Result<()> {
|
||||
for name in [OFFLINE_USERNAME, ONLINE_USERNAME] {
|
||||
let Some(original_flags) = local_user_flags(name)? else {
|
||||
continue;
|
||||
};
|
||||
let sid = resolve_sid(name)?;
|
||||
|
||||
self.users.push(SandboxUser {
|
||||
name,
|
||||
original_flags,
|
||||
sid,
|
||||
});
|
||||
set_local_user_flags(name, original_flags | network::UF_ACCOUNTDISABLE)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn sids(&self) -> impl Iterator<Item = &[u8]> {
|
||||
self.users.iter().map(|user| user.sid.as_slice())
|
||||
}
|
||||
|
||||
pub(super) fn validate_current(&self) -> Result<()> {
|
||||
for name in [OFFLINE_USERNAME, ONLINE_USERNAME] {
|
||||
let Some(flags) = local_user_flags(name)? else {
|
||||
continue;
|
||||
};
|
||||
let captured = self.users.iter().find(|user| user.name == name);
|
||||
ensure!(
|
||||
captured.is_some_and(|user| resolve_sid(name).is_ok_and(|sid| sid == user.sid))
|
||||
&& flags & network::UF_ACCOUNTDISABLE != 0,
|
||||
"sandbox account changed after being disabled: {name}"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn restore(&self) -> Result<()> {
|
||||
let mut errors = Vec::new();
|
||||
for user in &self.users {
|
||||
if let Err(error) = set_local_user_flags(user.name, user.original_flags)
|
||||
&& error
|
||||
.downcast_ref::<std::io::Error>()
|
||||
.and_then(std::io::Error::raw_os_error)
|
||||
!= Some(network::NERR_UserNotFound as i32)
|
||||
{
|
||||
errors.push(format!("{error:#}"));
|
||||
}
|
||||
}
|
||||
if !errors.is_empty() {
|
||||
bail!("{}", errors.join("; "));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn remove_users(
|
||||
&self,
|
||||
retained: &RetainedLogons,
|
||||
report: impl Fn(&str),
|
||||
) -> Result<()> {
|
||||
let mut errors = Vec::new();
|
||||
for user in &self.users {
|
||||
if retained.contains_sid(&user.sid) {
|
||||
report(&format!(
|
||||
"deferring {} profile and account to runtime cleanup",
|
||||
user.name
|
||||
));
|
||||
continue;
|
||||
}
|
||||
match user.remove() {
|
||||
Ok(()) => report(&format!("removed {} profile and account", user.name)),
|
||||
Err(error) => {
|
||||
report(&format!(
|
||||
"remove {} profile and account: failed, {error:#}",
|
||||
user.name
|
||||
));
|
||||
errors.push(format!("{error:#}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
ensure!(errors.is_empty(), "{}", errors.join("; "));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl SandboxUser {
|
||||
fn remove(&self) -> Result<()> {
|
||||
let Self { name, sid, .. } = self;
|
||||
let sid = string_from_sid_bytes(sid).map_err(anyhow::Error::msg)?;
|
||||
let profile_key = to_wide(format!(
|
||||
r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\{sid}"
|
||||
));
|
||||
let mut key = std::ptr::null_mut();
|
||||
let status = unsafe {
|
||||
registry::RegOpenKeyExW(
|
||||
registry::HKEY_LOCAL_MACHINE,
|
||||
profile_key.as_ptr(),
|
||||
/*uloptions*/ 0,
|
||||
registry::KEY_READ | registry::KEY_WOW64_64KEY,
|
||||
&mut key,
|
||||
)
|
||||
};
|
||||
match status {
|
||||
ERROR_SUCCESS => {
|
||||
unsafe { registry::RegCloseKey(key) };
|
||||
// Keep the account's SID available for retry if its profile is still loaded.
|
||||
if unsafe { DeleteProfileW(to_wide(sid).as_ptr(), null(), null()) } == 0 {
|
||||
bail!(
|
||||
"remove sandbox profile for {name}: {}",
|
||||
std::io::Error::last_os_error()
|
||||
);
|
||||
}
|
||||
}
|
||||
ERROR_FILE_NOT_FOUND => {}
|
||||
status => bail!("open sandbox profile for {name}: {status}"),
|
||||
}
|
||||
remove_sandbox_principal(name)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl DisabledSandboxUsers {
|
||||
// In-memory admission fixture only; this does not resolve or change a local account.
|
||||
pub(super) fn for_token_test(sid: Vec<u8>) -> Self {
|
||||
Self {
|
||||
users: vec![SandboxUser {
|
||||
name: OFFLINE_USERNAME,
|
||||
original_flags: network::UF_ACCOUNTDISABLE,
|
||||
sid,
|
||||
}],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn remove_sandbox_principal(name: &str) -> Result<()> {
|
||||
let name_wide = to_wide(name);
|
||||
let status = if name == "CodexSandboxUsers" {
|
||||
unsafe { network::NetLocalGroupDel(null(), name_wide.as_ptr()) }
|
||||
} else {
|
||||
unsafe { network::NetUserDel(null(), name_wide.as_ptr()) }
|
||||
};
|
||||
match status {
|
||||
network::NERR_Success | network::NERR_GroupNotFound | network::NERR_UserNotFound => Ok(()),
|
||||
status => bail!("remove local sandbox principal {name}: {status}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "principals_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,218 @@
|
||||
//! Exercises profile deletion and its retry boundary with one disposable local user.
|
||||
|
||||
use std::io;
|
||||
use std::os::windows::ffi::OsStringExt;
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::os::windows::io::FromRawHandle;
|
||||
use std::os::windows::io::OwnedHandle;
|
||||
use std::path::PathBuf;
|
||||
use std::ptr::null;
|
||||
use std::ptr::null_mut;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use pretty_assertions::assert_eq;
|
||||
use rand::RngCore;
|
||||
use windows_sys::Win32::Foundation::ERROR_ACCESS_DENIED;
|
||||
use windows_sys::Win32::Foundation::ERROR_FILE_NOT_FOUND;
|
||||
use windows_sys::Win32::Foundation::ERROR_SUCCESS;
|
||||
use windows_sys::Win32::Foundation::WAIT_OBJECT_0;
|
||||
use windows_sys::Win32::NetworkManagement::NetManagement as network;
|
||||
use windows_sys::Win32::System::Registry as registry;
|
||||
use windows_sys::Win32::System::Threading as threading;
|
||||
|
||||
use super::SandboxUser;
|
||||
use crate::winutil::local_user_flags;
|
||||
use crate::winutil::resolve_sid;
|
||||
use crate::winutil::set_local_user_flags;
|
||||
use crate::winutil::string_from_sid_bytes;
|
||||
use crate::winutil::to_wide;
|
||||
|
||||
struct ProfileFixture {
|
||||
user: SandboxUser,
|
||||
process: Option<OwnedHandle>,
|
||||
}
|
||||
|
||||
impl ProfileFixture {
|
||||
fn stop(&mut self) -> Result<()> {
|
||||
if let Some(process) = self.process.take() {
|
||||
let handle = process.as_raw_handle() as _;
|
||||
unsafe {
|
||||
threading::TerminateProcess(handle, /*uexitcode*/ 0)
|
||||
};
|
||||
ensure!(
|
||||
unsafe {
|
||||
threading::WaitForSingleObject(handle, /*dwmilliseconds*/ 10_000)
|
||||
} == WAIT_OBJECT_0,
|
||||
"owned profile fixture did not exit"
|
||||
);
|
||||
drop(process);
|
||||
// User Profile Service unloads the hive after the last owned process exits.
|
||||
let sid = string_from_sid_bytes(&self.user.sid).map_err(anyhow::Error::msg)?;
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
loop {
|
||||
let mut key = std::ptr::null_mut();
|
||||
let status = unsafe {
|
||||
registry::RegOpenKeyExW(
|
||||
registry::HKEY_USERS,
|
||||
to_wide(&sid).as_ptr(),
|
||||
/*uloptions*/ 0,
|
||||
registry::KEY_READ,
|
||||
&mut key,
|
||||
)
|
||||
};
|
||||
if status == ERROR_FILE_NOT_FOUND {
|
||||
break;
|
||||
}
|
||||
ensure!(status == ERROR_SUCCESS, "read owned profile hive: {status}");
|
||||
unsafe { registry::RegCloseKey(key) };
|
||||
ensure!(Instant::now() < deadline, "owned profile did not unload");
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ProfileFixture {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.stop();
|
||||
let result = if self.user.sid.is_empty() {
|
||||
super::remove_sandbox_principal(self.user.name)
|
||||
} else {
|
||||
self.user.remove()
|
||||
};
|
||||
if let Err(error) = result {
|
||||
eprintln!("unable to clean up owned profile fixture: {error:#}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_cleanup_preserves_account_until_profile_can_be_deleted() -> Result<()> {
|
||||
// Production names are static. This one unique name lives for this test process only.
|
||||
let name: &'static str =
|
||||
Box::leak(format!("CodexPrf{:08x}", rand::rngs::OsRng.next_u32()).into_boxed_str());
|
||||
let username = to_wide(name);
|
||||
let password = to_wide(format!("Cdx!a0{:016x}", rand::rngs::OsRng.next_u64()));
|
||||
let user_info = network::USER_INFO_1 {
|
||||
usri1_name: username.as_ptr().cast_mut(),
|
||||
usri1_password: password.as_ptr().cast_mut(),
|
||||
usri1_priv: network::USER_PRIV_USER,
|
||||
usri1_flags: network::UF_NORMAL_ACCOUNT
|
||||
| network::UF_SCRIPT
|
||||
| network::UF_DONT_EXPIRE_PASSWD,
|
||||
..unsafe { std::mem::zeroed() }
|
||||
};
|
||||
let status = unsafe {
|
||||
network::NetUserAdd(
|
||||
null(),
|
||||
/*level*/ 1,
|
||||
(&raw const user_info).cast(),
|
||||
null_mut(),
|
||||
)
|
||||
};
|
||||
if status == ERROR_ACCESS_DENIED {
|
||||
eprintln!(
|
||||
"skipping native profile cleanup test: creating its disposable user requires elevation"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
ensure!(
|
||||
status == network::NERR_Success,
|
||||
"create owned profile fixture: {status}"
|
||||
);
|
||||
let mut fixture = ProfileFixture {
|
||||
user: SandboxUser {
|
||||
name,
|
||||
original_flags: user_info.usri1_flags,
|
||||
sid: Vec::new(),
|
||||
},
|
||||
process: None,
|
||||
};
|
||||
fixture.user.sid = resolve_sid(name)?;
|
||||
let sid = string_from_sid_bytes(&fixture.user.sid).map_err(anyhow::Error::msg)?;
|
||||
let profile_key = to_wide(format!(
|
||||
r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\{sid}"
|
||||
));
|
||||
let system_root = std::env::var_os("SystemRoot").context("SystemRoot is missing")?;
|
||||
let executable =
|
||||
PathBuf::from(&system_root).join(r"System32\WindowsPowerShell\v1.0\powershell.exe");
|
||||
let executable = to_wide(executable);
|
||||
let mut command =
|
||||
to_wide("powershell.exe -NoProfile -NonInteractive -Command Start-Sleep -Seconds 600");
|
||||
let mut startup: threading::STARTUPINFOW = unsafe { std::mem::zeroed() };
|
||||
startup.cb = std::mem::size_of_val(&startup) as u32;
|
||||
let mut process: threading::PROCESS_INFORMATION = unsafe { std::mem::zeroed() };
|
||||
let created = unsafe {
|
||||
threading::CreateProcessWithLogonW(
|
||||
username.as_ptr(),
|
||||
to_wide(".").as_ptr(),
|
||||
password.as_ptr(),
|
||||
threading::LOGON_WITH_PROFILE,
|
||||
executable.as_ptr(),
|
||||
command.as_mut_ptr(),
|
||||
threading::CREATE_NO_WINDOW,
|
||||
null(),
|
||||
to_wide(&system_root).as_ptr(),
|
||||
&startup,
|
||||
&mut process,
|
||||
)
|
||||
};
|
||||
ensure!(
|
||||
created != 0,
|
||||
"start owned profile fixture: {}",
|
||||
io::Error::last_os_error()
|
||||
);
|
||||
fixture.process = Some(unsafe { OwnedHandle::from_raw_handle(process.hProcess as _) });
|
||||
drop(unsafe { OwnedHandle::from_raw_handle(process.hThread as _) });
|
||||
let mut path = [0u16; 32768];
|
||||
let mut length = std::mem::size_of_val(&path) as u32;
|
||||
let status = unsafe {
|
||||
registry::RegGetValueW(
|
||||
registry::HKEY_LOCAL_MACHINE,
|
||||
profile_key.as_ptr(),
|
||||
to_wide("ProfileImagePath").as_ptr(),
|
||||
registry::RRF_RT_REG_SZ | registry::RRF_RT_REG_EXPAND_SZ,
|
||||
null_mut(),
|
||||
path.as_mut_ptr().cast(),
|
||||
&mut length,
|
||||
)
|
||||
};
|
||||
assert_eq!(status, ERROR_SUCCESS);
|
||||
let path = PathBuf::from(std::ffi::OsString::from_wide(
|
||||
&path[..length as usize / 2 - 1],
|
||||
));
|
||||
assert!(path.is_dir());
|
||||
set_local_user_flags(name, user_info.usri1_flags | network::UF_ACCOUNTDISABLE)?;
|
||||
assert!(
|
||||
fixture.user.remove().is_err(),
|
||||
"loaded profile must block deletion"
|
||||
);
|
||||
assert_eq!(resolve_sid(name)?, fixture.user.sid);
|
||||
assert!(path.is_dir());
|
||||
|
||||
fixture.stop()?;
|
||||
fixture.user.remove()?;
|
||||
assert_eq!(local_user_flags(name)?, None);
|
||||
assert!(!path.exists());
|
||||
let mut key = std::ptr::null_mut();
|
||||
let status = unsafe {
|
||||
registry::RegOpenKeyExW(
|
||||
registry::HKEY_LOCAL_MACHINE,
|
||||
profile_key.as_ptr(),
|
||||
/*uloptions*/ 0,
|
||||
registry::KEY_READ,
|
||||
&mut key,
|
||||
)
|
||||
};
|
||||
if status == ERROR_SUCCESS {
|
||||
unsafe { registry::RegCloseKey(key) };
|
||||
}
|
||||
assert_eq!(status, ERROR_FILE_NOT_FOUND);
|
||||
fixture.user.remove()?;
|
||||
Ok(())
|
||||
}
|
||||
231
akode-rs/windows-sandbox-rs/src/uninstall_windows/processes.rs
Normal file
231
akode-rs/windows-sandbox-rs/src/uninstall_windows/processes.rs
Normal file
@@ -0,0 +1,231 @@
|
||||
//! Stops sandbox processes and drains logins except exact, pinned cleanup-owned tokens.
|
||||
|
||||
use std::ffi::c_void;
|
||||
use std::io;
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::os::windows::io::FromRawHandle;
|
||||
use std::os::windows::io::OwnedHandle;
|
||||
use std::ptr::null_mut;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::bail;
|
||||
use windows_sys::Win32::Foundation::ERROR_INVALID_PARAMETER;
|
||||
use windows_sys::Win32::Foundation::ERROR_NO_SUCH_LOGON_SESSION;
|
||||
use windows_sys::Win32::Foundation::HANDLE;
|
||||
use windows_sys::Win32::Foundation::LUID;
|
||||
use windows_sys::Win32::Foundation::STATUS_SUCCESS;
|
||||
use windows_sys::Win32::Foundation::WAIT_OBJECT_0;
|
||||
use windows_sys::Win32::Foundation::WAIT_TIMEOUT;
|
||||
use windows_sys::Win32::Security::Authentication::Identity::LsaEnumerateLogonSessions;
|
||||
use windows_sys::Win32::Security::Authentication::Identity::LsaFreeReturnBuffer;
|
||||
use windows_sys::Win32::Security::Authentication::Identity::LsaGetLogonSessionData;
|
||||
use windows_sys::Win32::Security::Authentication::Identity::LsaNtStatusToWinError;
|
||||
use windows_sys::Win32::Security::Authentication::Identity::SECURITY_LOGON_SESSION_DATA;
|
||||
use windows_sys::Win32::Security::EqualSid;
|
||||
use windows_sys::Win32::Security::TOKEN_QUERY;
|
||||
use windows_sys::Win32::System::RemoteDesktop::WTS_CURRENT_SERVER_HANDLE;
|
||||
use windows_sys::Win32::System::RemoteDesktop::WTS_PROCESS_INFOW;
|
||||
use windows_sys::Win32::System::RemoteDesktop::WTSEnumerateProcessesW;
|
||||
use windows_sys::Win32::System::RemoteDesktop::WTSFreeMemory;
|
||||
use windows_sys::Win32::System::Threading::OpenProcess;
|
||||
use windows_sys::Win32::System::Threading::OpenProcessToken;
|
||||
use windows_sys::Win32::System::Threading::PROCESS_QUERY_LIMITED_INFORMATION;
|
||||
use windows_sys::Win32::System::Threading::PROCESS_SYNCHRONIZE;
|
||||
use windows_sys::Win32::System::Threading::PROCESS_TERMINATE;
|
||||
use windows_sys::Win32::System::Threading::TerminateProcess;
|
||||
use windows_sys::Win32::System::Threading::WaitForSingleObject;
|
||||
|
||||
use super::principals::DisabledSandboxUsers;
|
||||
use super::retained_logons::RetainedLogons;
|
||||
use crate::token::get_user_sid_bytes;
|
||||
|
||||
pub(super) fn stop(users: &DisabledSandboxUsers, retained: &RetainedLogons) -> Result<()> {
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
loop {
|
||||
let processes = sandbox_processes(users)?;
|
||||
for process in &processes {
|
||||
let handle = process.as_raw_handle() as HANDLE;
|
||||
if unsafe {
|
||||
TerminateProcess(handle, /*uexitcode*/ 1)
|
||||
} == 0
|
||||
{
|
||||
let error = io::Error::last_os_error();
|
||||
if unsafe {
|
||||
WaitForSingleObject(handle, /*dwmilliseconds*/ 0)
|
||||
} != WAIT_OBJECT_0
|
||||
{
|
||||
return Err(error).context("stop sandbox process before uninstall");
|
||||
}
|
||||
}
|
||||
}
|
||||
for process in &processes {
|
||||
let remaining = deadline.saturating_duration_since(Instant::now());
|
||||
// The five-second deadline keeps milliseconds within a DWORD.
|
||||
match unsafe {
|
||||
WaitForSingleObject(
|
||||
process.as_raw_handle() as HANDLE,
|
||||
remaining.as_millis() as u32,
|
||||
)
|
||||
} {
|
||||
WAIT_OBJECT_0 => {}
|
||||
WAIT_TIMEOUT => bail!("sandbox process did not exit before the uninstall deadline"),
|
||||
_ => {
|
||||
return Err(io::Error::last_os_error())
|
||||
.context("wait for sandbox process exit");
|
||||
}
|
||||
}
|
||||
}
|
||||
drop(processes);
|
||||
|
||||
// A token can outlive its process or exist before a runner starts. Account disable does
|
||||
// not revoke it, so check for remaining logins before removing protections. Only
|
||||
// explicitly pinned, private SYSTEM-finalizer tokens may remain; no process is exempt.
|
||||
let Some(blocker) = blocking_logon_session(users, retained)? else {
|
||||
return Ok(());
|
||||
};
|
||||
if Instant::now() >= deadline {
|
||||
bail!("sandbox cleanup blocked after the uninstall deadline: {blocker}");
|
||||
}
|
||||
// Repeat to catch descendants created during the previous snapshot.
|
||||
std::thread::sleep(
|
||||
Duration::from_millis(50).min(deadline.saturating_duration_since(Instant::now())),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn sandbox_processes(users: &DisabledSandboxUsers) -> Result<Vec<OwnedHandle>> {
|
||||
let mut process_info = null_mut();
|
||||
let mut count = 0;
|
||||
if unsafe {
|
||||
WTSEnumerateProcessesW(
|
||||
WTS_CURRENT_SERVER_HANDLE,
|
||||
/*reserved*/ 0,
|
||||
/*version*/ 1,
|
||||
&mut process_info,
|
||||
&mut count,
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
return Err(io::Error::last_os_error())
|
||||
.context("enumerate sandbox processes for uninstall");
|
||||
}
|
||||
let process_info = ProcessList(process_info);
|
||||
let mut handles = Vec::new();
|
||||
if count == 0 {
|
||||
return Ok(handles);
|
||||
}
|
||||
for process in unsafe { std::slice::from_raw_parts(process_info.0, count as usize) } {
|
||||
if !is_sandbox_user(users, process.pUserSid) {
|
||||
continue;
|
||||
}
|
||||
let handle = unsafe {
|
||||
OpenProcess(
|
||||
PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_TERMINATE | PROCESS_SYNCHRONIZE,
|
||||
/*binherithandle*/ 0,
|
||||
process.ProcessId,
|
||||
)
|
||||
};
|
||||
if handle.is_null() {
|
||||
let error = io::Error::last_os_error();
|
||||
if error.raw_os_error() == Some(ERROR_INVALID_PARAMETER as i32) {
|
||||
continue;
|
||||
}
|
||||
return Err(error).context("open sandbox process for uninstall");
|
||||
}
|
||||
let handle = unsafe { OwnedHandle::from_raw_handle(handle) };
|
||||
let mut token = std::ptr::null_mut();
|
||||
if unsafe { OpenProcessToken(handle.as_raw_handle() as HANDLE, TOKEN_QUERY, &mut token) }
|
||||
== 0
|
||||
{
|
||||
let error = io::Error::last_os_error();
|
||||
if unsafe {
|
||||
WaitForSingleObject(handle.as_raw_handle() as HANDLE, /*dwmilliseconds*/ 0)
|
||||
} == WAIT_OBJECT_0
|
||||
{
|
||||
continue;
|
||||
}
|
||||
return Err(error).context("identify sandbox process before uninstall");
|
||||
}
|
||||
let token = unsafe { OwnedHandle::from_raw_handle(token) };
|
||||
let sid = unsafe { get_user_sid_bytes(token.as_raw_handle() as HANDLE) }?;
|
||||
// A PID can be reused after enumeration. Check the opened process before terminating it.
|
||||
if users.sids().any(|user_sid| user_sid == sid.as_slice()) {
|
||||
handles.push(handle);
|
||||
}
|
||||
}
|
||||
Ok(handles)
|
||||
}
|
||||
|
||||
fn blocking_logon_session(
|
||||
users: &DisabledSandboxUsers,
|
||||
retained: &RetainedLogons,
|
||||
) -> Result<Option<String>> {
|
||||
let mut count = 0;
|
||||
let mut logons = null_mut();
|
||||
let status = unsafe { LsaEnumerateLogonSessions(&mut count, &mut logons) };
|
||||
if status != STATUS_SUCCESS {
|
||||
bail!("enumerate sandbox logon sessions for uninstall: {status:#x}");
|
||||
}
|
||||
let logons = LsaBuffer(logons.cast());
|
||||
if count == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
for logon in unsafe { std::slice::from_raw_parts(logons.0.cast::<LUID>(), count as usize) } {
|
||||
// LocalSystem uses the reserved logon ID 0:0x3e7 and has no normal logon data.
|
||||
if logon.LowPart == 0x3e7 && logon.HighPart == 0 {
|
||||
continue;
|
||||
}
|
||||
let mut data = null_mut();
|
||||
let status = unsafe { LsaGetLogonSessionData(logon, &mut data) };
|
||||
if status != STATUS_SUCCESS {
|
||||
if unsafe { LsaNtStatusToWinError(status) } == ERROR_NO_SUCH_LOGON_SESSION {
|
||||
continue;
|
||||
}
|
||||
bail!("read sandbox logon session for uninstall: {status:#x}");
|
||||
}
|
||||
// Keep protections when LSA returns no session data.
|
||||
if data.is_null() {
|
||||
return Ok(Some(format!(
|
||||
"LSA returned no data for logon {:08x}:{:08x}",
|
||||
logon.HighPart, logon.LowPart
|
||||
)));
|
||||
}
|
||||
let data = LsaBuffer(data.cast());
|
||||
let data = unsafe { &*data.0.cast::<SECURITY_LOGON_SESSION_DATA>() };
|
||||
// LSA also lists sessions without a user SID, even before sandbox accounts exist.
|
||||
// Only sessions identified as sandbox users are evidence of remaining sandbox tokens.
|
||||
if is_sandbox_user(users, data.Sid) && !retained.contains(*logon) {
|
||||
return Ok(Some(format!(
|
||||
"sandbox logon {:08x}:{:08x} remains (logon type {}, session {})",
|
||||
logon.HighPart, logon.LowPart, data.LogonType, data.Session
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn is_sandbox_user(users: &DisabledSandboxUsers, sid: *mut c_void) -> bool {
|
||||
!sid.is_null()
|
||||
&& users
|
||||
.sids()
|
||||
.any(|user_sid| unsafe { EqualSid(sid, user_sid.as_ptr() as *mut c_void) } != 0)
|
||||
}
|
||||
|
||||
struct ProcessList(*mut WTS_PROCESS_INFOW);
|
||||
|
||||
impl Drop for ProcessList {
|
||||
fn drop(&mut self) {
|
||||
unsafe { WTSFreeMemory(self.0.cast()) };
|
||||
}
|
||||
}
|
||||
|
||||
struct LsaBuffer(*mut c_void);
|
||||
|
||||
impl Drop for LsaBuffer {
|
||||
fn drop(&mut self) {
|
||||
unsafe { LsaFreeReturnBuffer(self.0) };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
//! Pins only cleanup-owned login sessions; every other sandbox login still blocks cleanup.
|
||||
|
||||
use std::io;
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::os::windows::io::BorrowedHandle;
|
||||
use std::os::windows::io::OwnedHandle;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use windows_sys::Win32::Foundation::HANDLE;
|
||||
use windows_sys::Win32::Foundation::LUID;
|
||||
use windows_sys::Win32::Security::GetTokenInformation;
|
||||
use windows_sys::Win32::Security::TOKEN_STATISTICS;
|
||||
use windows_sys::Win32::Security::TokenStatistics;
|
||||
|
||||
use super::principals::DisabledSandboxUsers;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct RetainedLogons {
|
||||
// Keeping each token open prevents its AuthenticationId from being recycled.
|
||||
_tokens: Vec<OwnedHandle>,
|
||||
ids: Vec<LUID>,
|
||||
sids: Vec<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl RetainedLogons {
|
||||
pub(super) fn capture(
|
||||
tokens: &[BorrowedHandle<'_>],
|
||||
users: &DisabledSandboxUsers,
|
||||
) -> Result<Self> {
|
||||
ensure!(tokens.len() <= 2, "too many retained cleanup tokens");
|
||||
let mut retained = Self::default();
|
||||
for token in tokens {
|
||||
let token = token.try_clone_to_owned()?;
|
||||
let handle = token.as_raw_handle() as HANDLE;
|
||||
let sid = unsafe { crate::token::get_user_sid_bytes(handle) }?;
|
||||
ensure!(
|
||||
users.sids().any(|candidate| candidate == sid.as_slice())
|
||||
&& !retained.sids.contains(&sid),
|
||||
"cleanup token does not identify a distinct managed sandbox account"
|
||||
);
|
||||
let mut stats: TOKEN_STATISTICS = unsafe { std::mem::zeroed() };
|
||||
let mut returned = 0;
|
||||
if unsafe {
|
||||
GetTokenInformation(
|
||||
handle,
|
||||
TokenStatistics,
|
||||
(&mut stats as *mut TOKEN_STATISTICS).cast(),
|
||||
std::mem::size_of::<TOKEN_STATISTICS>() as u32,
|
||||
&mut returned,
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
return Err(io::Error::last_os_error()).context("identify retained cleanup login");
|
||||
}
|
||||
ensure!(
|
||||
returned as usize == std::mem::size_of::<TOKEN_STATISTICS>(),
|
||||
"unexpected cleanup token statistics length"
|
||||
);
|
||||
retained.sids.push(sid);
|
||||
retained.ids.push(stats.AuthenticationId);
|
||||
retained._tokens.push(token);
|
||||
}
|
||||
Ok(retained)
|
||||
}
|
||||
|
||||
pub(super) fn contains(&self, id: LUID) -> bool {
|
||||
self.ids
|
||||
.iter()
|
||||
.any(|held| held.LowPart == id.LowPart && held.HighPart == id.HighPart)
|
||||
}
|
||||
|
||||
pub(super) fn contains_sid(&self, sid: &[u8]) -> bool {
|
||||
self.sids.iter().any(|held| held == sid)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "retained_logons_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,109 @@
|
||||
//! Exercises retained-logon admission and ownership using read-only current-process tokens.
|
||||
|
||||
use super::super::principals::DisabledSandboxUsers;
|
||||
use super::RetainedLogons;
|
||||
use crate::token::get_user_sid_bytes;
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::os::windows::io::AsHandle;
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::os::windows::io::FromRawHandle;
|
||||
use std::os::windows::io::OwnedHandle;
|
||||
use windows_sys::Win32::Foundation::HANDLE;
|
||||
use windows_sys::Win32::Foundation::LUID;
|
||||
use windows_sys::Win32::Security::TOKEN_QUERY;
|
||||
use windows_sys::Win32::System::Threading::GetCurrentProcess;
|
||||
use windows_sys::Win32::System::Threading::OpenProcessToken;
|
||||
|
||||
fn current_process_token() -> Result<OwnedHandle> {
|
||||
let mut raw = std::ptr::null_mut();
|
||||
ensure!(
|
||||
unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut raw) } != 0,
|
||||
"open current-process token: {}",
|
||||
std::io::Error::last_os_error()
|
||||
);
|
||||
Ok(unsafe { OwnedHandle::from_raw_handle(raw as _) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matches_only_the_complete_retained_authentication_id() {
|
||||
let retained = RetainedLogons {
|
||||
_tokens: Vec::new(),
|
||||
ids: vec![LUID {
|
||||
LowPart: 17,
|
||||
HighPart: 4,
|
||||
}],
|
||||
sids: Vec::new(),
|
||||
};
|
||||
let observed = [
|
||||
LUID {
|
||||
LowPart: 17,
|
||||
HighPart: 4,
|
||||
},
|
||||
LUID {
|
||||
LowPart: 18,
|
||||
HighPart: 4,
|
||||
},
|
||||
LUID {
|
||||
LowPart: 17,
|
||||
HighPart: 5,
|
||||
},
|
||||
LUID {
|
||||
LowPart: 0,
|
||||
HighPart: 0,
|
||||
},
|
||||
]
|
||||
.map(|id| retained.contains(id));
|
||||
assert_eq!(observed, [true, false, false, false]);
|
||||
assert!(!RetainedLogons::default().contains(LUID {
|
||||
LowPart: 17,
|
||||
HighPart: 4
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_more_than_two_tokens_before_admission() -> Result<()> {
|
||||
let token = current_process_token()?;
|
||||
let error = RetainedLogons::capture(&[token.as_handle(); 3], &DisabledSandboxUsers::default())
|
||||
.err()
|
||||
.expect("three token inputs must be rejected");
|
||||
assert_eq!(error.to_string(), "too many retained cleanup tokens");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_a_token_without_a_captured_managed_sid() -> Result<()> {
|
||||
let token = current_process_token()?;
|
||||
assert!(
|
||||
RetainedLogons::capture(&[token.as_handle()], &DisabledSandboxUsers::default()).is_err()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_distinct_handles_for_the_same_managed_sid() -> Result<()> {
|
||||
let token = current_process_token()?;
|
||||
let sid = unsafe { get_user_sid_bytes(token.as_raw_handle() as HANDLE) }?;
|
||||
let users = DisabledSandboxUsers::for_token_test(sid);
|
||||
let duplicate = token.as_handle().try_clone_to_owned()?;
|
||||
RetainedLogons::capture(&[token.as_handle()], &users)?;
|
||||
assert!(RetainedLogons::capture(&[token.as_handle(), duplicate.as_handle()], &users).is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retained_token_remains_queryable_after_the_borrowed_handle_is_closed() -> Result<()> {
|
||||
let (retained, expected_sid) = {
|
||||
let token = current_process_token()?;
|
||||
let sid = unsafe { get_user_sid_bytes(token.as_raw_handle() as HANDLE) }?;
|
||||
let users = DisabledSandboxUsers::for_token_test(sid.clone());
|
||||
(RetainedLogons::capture(&[token.as_handle()], &users)?, sid)
|
||||
};
|
||||
assert_eq!(retained._tokens.len(), 1);
|
||||
let actual_sid = unsafe { get_user_sid_bytes(retained._tokens[0].as_raw_handle() as HANDLE) }?;
|
||||
assert_eq!(actual_sid, expected_sid);
|
||||
assert!(retained.contains_sid(&expected_sid));
|
||||
assert!(!retained.contains_sid(&[]));
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user