use anyhow::{Context, Result};
use std::ffi::c_void;
use windows::Win32::Foundation::{CloseHandle, HANDLE, LUID};
use windows::Win32::Security::{
AdjustTokenPrivileges, LUID_AND_ATTRIBUTES, LookupPrivilegeValueW, SE_PRIVILEGE_REMOVED,
TOKEN_ADJUST_PRIVILEGES, TOKEN_PRIVILEGES, TOKEN_QUERY,
};
use windows::Win32::System::JobObjects::{
AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_ACTIVE_PROCESS,
JOBOBJECT_BASIC_LIMIT_INFORMATION, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
JobObjectExtendedLimitInformation, SetInformationJobObject,
};
use windows::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
const ERROR_NOT_ALL_ASSIGNED: u32 = 1300;
const PRIVILEGES_TO_REMOVE: &[&str] = &[
"SeDebugPrivilege", "SeTakeOwnershipPrivilege", "SeBackupPrivilege", "SeRestorePrivilege", "SeCreateTokenPrivilege", "SeAssignPrimaryTokenPrivilege", "SeLoadDriverPrivilege", "SeTcbPrivilege", "SeRemoteShutdownPrivilege", "SeImpersonatePrivilege", ];
pub(super) struct RestrictedTokenResult {
pub privileges_removed: bool,
pub privileges_removed_count: u32,
pub succeeded: bool,
pub message: String,
}
pub(super) struct JobObjectResult {
pub applied: bool,
pub message: String,
}
pub(super) fn remove_dangerous_privileges() -> Result<RestrictedTokenResult> {
unsafe {
let mut token_handle = HANDLE::default();
OpenProcessToken(
GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
&mut token_handle,
)
.context("Failed to open process token")?;
let mut removed_count = 0u32;
let mut messages = Vec::new();
for priv_name in PRIVILEGES_TO_REMOVE {
match remove_single_privilege(token_handle, priv_name) {
Ok(true) => {
removed_count += 1;
log::debug!("Removed privilege: {}", priv_name);
}
Ok(false) => {
log::debug!("Privilege not present: {}", priv_name);
}
Err(e) => {
let msg = format!("Failed to remove {}: {}", priv_name, e);
log::warn!("{}", msg);
messages.push(msg);
}
}
}
let _ = CloseHandle(token_handle);
let message = if removed_count > 0 {
format!(
"{} privilege(s) removed{}",
removed_count,
if messages.is_empty() {
String::new()
} else {
format!("; {}", messages.join("; "))
}
)
} else if messages.is_empty() {
"No dangerous privileges were held".to_string()
} else {
messages.join("; ")
};
Ok(RestrictedTokenResult {
privileges_removed: removed_count > 0,
privileges_removed_count: removed_count,
succeeded: messages.is_empty(),
message,
})
}
}
unsafe fn remove_single_privilege(token: HANDLE, privilege_name: &str) -> Result<bool> {
unsafe {
let wide_name: Vec<u16> = privilege_name
.encode_utf16()
.chain(std::iter::once(0))
.collect();
let mut luid = LUID::default();
if LookupPrivilegeValueW(None, windows::core::PCWSTR(wide_name.as_ptr()), &mut luid)
.is_err()
{
return Ok(false);
}
let tp = TOKEN_PRIVILEGES {
PrivilegeCount: 1,
Privileges: [LUID_AND_ATTRIBUTES {
Luid: luid,
Attributes: SE_PRIVILEGE_REMOVED,
}],
};
if AdjustTokenPrivileges(token, false, Some(&tp), 0, None, None).is_err() {
return Err(anyhow::anyhow!(
"AdjustTokenPrivileges failed for {}",
privilege_name
));
}
let last_error = windows::Win32::Foundation::GetLastError();
if last_error.0 == ERROR_NOT_ALL_ASSIGNED {
return Ok(false);
}
Ok(true)
}
}
pub(super) fn apply_job_object() -> Result<JobObjectResult> {
unsafe {
let job = CreateJobObjectW(None, None).context("Failed to create job object")?;
let info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION {
BasicLimitInformation: JOBOBJECT_BASIC_LIMIT_INFORMATION {
LimitFlags: JOB_OBJECT_LIMIT_ACTIVE_PROCESS,
ActiveProcessLimit: 1,
..Default::default()
},
..Default::default()
};
SetInformationJobObject(
job,
JobObjectExtendedLimitInformation,
&info as *const _ as *const c_void,
std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
)
.context("Failed to set job object limits")?;
AssignProcessToJobObject(job, GetCurrentProcess())
.context("Failed to assign process to job object")?;
log::debug!("Job object applied: child process creation blocked");
Ok(JobObjectResult {
applied: true,
message: "Job object applied: child process creation blocked".to_string(),
})
}
}