windows: the component manager, verified programs, a Wine test
components.json pins sing-box, XRay, Flowseal's zapret, bol-van's winws2 bundle with nfqws2-keenetic's strategies, and tg-ws-proxy (built with the release): release assets by archive hash, commit snapshots by the hash of every file taken. The service installs them (admin only), staged and swapped in, refusing archive paths that leave the directory, and checks each program against the hashes recorded at install before running it. stage-components does the same for building a release. The state root is created with its protected descriptor in one call, or, existing, checked through a handle that does not follow links. tools/wine-e2e.sh runs the Windows build under Wine: the service, the named pipe, impersonation, the component check, rendering and the supervisor all work; Wine lacks an iphlpapi call sing-box needs, so proxying itself needs real Windows. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b878dd93db
commit
68b496cafa
10 files changed
+709
-81
No files matched your search
@@ -65,21 +65,16 @@ impl Paths {
|
||||
self.root.join("bin")
|
||||
}
|
||||
|
||||
/// Creates the tree and, on Windows, keeps its root to SYSTEM and Administrators: it
|
||||
/// holds the secrets and the programs the service runs as SYSTEM. Everyone else goes
|
||||
/// through the API.
|
||||
/// Creates the tree. On Windows its root is SYSTEM's: created with a protected DACL
|
||||
/// (SYSTEM and Administrators only) in the same call, or, when it exists, checked through a
|
||||
/// handle that does not follow reparse points. A root that is a link, has another owner, or
|
||||
/// lets anyone else in is moved aside, never adopted: ProgramData lets any user make
|
||||
/// folders, and the service runs what is under `bin\` as SYSTEM.
|
||||
pub fn create_all(&self) -> std::io::Result<()> {
|
||||
// A root someone else made first (ProgramData lets any user make folders) is theirs to
|
||||
// fill with programs this service would run: it is moved aside, not adopted.
|
||||
#[cfg(windows)]
|
||||
if self.root.exists() && !owned_by_system_or_admins(&self.root)? {
|
||||
let aside = self.root.with_extension(format!("untrusted-{}", std::process::id()));
|
||||
tracing::warn!("{} is not owned by SYSTEM or Administrators; moving it to {}", self.root.display(), aside.display());
|
||||
std::fs::rename(&self.root, &aside)?;
|
||||
}
|
||||
secure::ensure_root(&self.root)?;
|
||||
#[cfg(not(windows))]
|
||||
std::fs::create_dir_all(&self.root)?;
|
||||
#[cfg(windows)]
|
||||
protect(&self.root)?;
|
||||
for dir in [self.subscriptions(), self.rule_sets(), self.cache(), self.run(), self.logs(), self.bin()] {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
@@ -100,77 +95,252 @@ pub fn same_content(path: &Path, data: &[u8]) -> bool {
|
||||
std::fs::read(path).is_ok_and(|old| old == data)
|
||||
}
|
||||
|
||||
/// Whether `dir`'s owner is SYSTEM or Administrators.
|
||||
#[cfg(windows)]
|
||||
fn owned_by_system_or_admins(dir: &Path) -> std::io::Result<bool> {
|
||||
mod secure {
|
||||
use std::ffi::c_void;
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::path::Path;
|
||||
use std::ptr::null_mut;
|
||||
use windows_sys::Win32::Foundation::{ERROR_SUCCESS, LocalFree};
|
||||
use windows_sys::Win32::Security::Authorization::{GetNamedSecurityInfoW, SE_FILE_OBJECT};
|
||||
use windows_sys::Win32::Security::{
|
||||
IsWellKnownSid, OWNER_SECURITY_INFORMATION, WinBuiltinAdministratorsSid, WinLocalSystemSid,
|
||||
};
|
||||
let path: Vec<u16> = dir.as_os_str().encode_wide().chain(Some(0)).collect();
|
||||
let mut owner: *mut c_void = null_mut();
|
||||
let mut sd: *mut c_void = null_mut();
|
||||
// SAFETY: NUL-terminated path; the owner points into sd, freed after use.
|
||||
unsafe {
|
||||
let rc = GetNamedSecurityInfoW(
|
||||
path.as_ptr(), SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION, &mut owner, null_mut(), null_mut(), null_mut(), &mut sd,
|
||||
);
|
||||
if rc != ERROR_SUCCESS {
|
||||
return Err(std::io::Error::from_raw_os_error(rc as i32));
|
||||
}
|
||||
let ok = IsWellKnownSid(owner, WinLocalSystemSid) != 0 || IsWellKnownSid(owner, WinBuiltinAdministratorsSid) != 0;
|
||||
LocalFree(sd);
|
||||
Ok(ok)
|
||||
}
|
||||
}
|
||||
|
||||
/// SYSTEM as the owner and a protected DACL on `dir`, inherited by everything below it: full
|
||||
/// control for SYSTEM and Administrators, nothing for anyone else, and (OWNER RIGHTS) nothing
|
||||
/// implicit for whoever owns a file below it.
|
||||
#[cfg(windows)]
|
||||
fn protect(dir: &Path) -> std::io::Result<()> {
|
||||
use std::ffi::c_void;
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::ptr::null_mut;
|
||||
use windows_sys::Win32::Foundation::{LocalFree, ERROR_SUCCESS};
|
||||
use windows_sys::Win32::Foundation::{
|
||||
CloseHandle, ERROR_ALREADY_EXISTS, ERROR_INVALID_OWNER, ERROR_SUCCESS, GetLastError, HANDLE, INVALID_HANDLE_VALUE, LocalFree,
|
||||
};
|
||||
use windows_sys::Win32::Security::Authorization::{
|
||||
ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1, SE_FILE_OBJECT, SetNamedSecurityInfoW,
|
||||
ConvertSecurityDescriptorToStringSecurityDescriptorW, ConvertStringSecurityDescriptorToSecurityDescriptorW,
|
||||
GetSecurityInfo, SDDL_REVISION_1, SE_FILE_OBJECT, SetSecurityInfo,
|
||||
};
|
||||
use windows_sys::Win32::Security::{
|
||||
ACL, DACL_SECURITY_INFORMATION, GetSecurityDescriptorDacl, GetSecurityDescriptorOwner, OWNER_SECURITY_INFORMATION,
|
||||
PROTECTED_DACL_SECURITY_INFORMATION,
|
||||
ACL, DACL_SECURITY_INFORMATION, GetSecurityDescriptorDacl, IsWellKnownSid,
|
||||
OWNER_SECURITY_INFORMATION, PROTECTED_DACL_SECURITY_INFORMATION, SECURITY_ATTRIBUTES, WinBuiltinAdministratorsSid,
|
||||
WinLocalSystemSid,
|
||||
};
|
||||
use windows_sys::Win32::Storage::FileSystem::{
|
||||
BY_HANDLE_FILE_INFORMATION, CreateDirectoryW, CreateFileW, FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_REPARSE_POINT,
|
||||
FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE,
|
||||
GetFileInformationByHandle, OPEN_EXISTING, READ_CONTROL, WRITE_DAC, WRITE_OWNER,
|
||||
};
|
||||
|
||||
let sddl: Vec<u16> = "O:SYD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;RC;;;OW)".encode_utf16().chain(Some(0)).collect();
|
||||
let path: Vec<u16> = dir.as_os_str().encode_wide().chain(Some(0)).collect();
|
||||
let mut sd: *mut c_void = null_mut();
|
||||
// SAFETY: NUL-terminated inputs; the descriptor is freed below, and the DACL points into it.
|
||||
unsafe {
|
||||
if ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl.as_ptr(), SDDL_REVISION_1, &mut sd, null_mut()) == 0 {
|
||||
/// SYSTEM and Administrators may do anything; the owner gets nothing implicit (OWNER
|
||||
/// RIGHTS: read-control only); nothing is inherited from ProgramData.
|
||||
const DACL: &str = "D:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;RC;;;OW)";
|
||||
|
||||
fn wide(s: &std::ffi::OsStr) -> Vec<u16> {
|
||||
s.encode_wide().chain(Some(0)).collect()
|
||||
}
|
||||
|
||||
struct Descriptor(*mut c_void);
|
||||
impl Drop for Descriptor {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: allocated by ConvertStringSecurityDescriptorToSecurityDescriptorW.
|
||||
unsafe { LocalFree(self.0) };
|
||||
}
|
||||
}
|
||||
|
||||
/// The descriptor, with SYSTEM as owner when `system_owner` (only SYSTEM itself, or a
|
||||
/// process holding SeRestorePrivilege, may name another owner than itself).
|
||||
fn descriptor(system_owner: bool) -> std::io::Result<Descriptor> {
|
||||
let text = if system_owner { format!("O:SY{DACL}") } else { DACL.to_owned() };
|
||||
let sddl = wide(text.as_ref());
|
||||
let mut sd = null_mut();
|
||||
// SAFETY: a NUL-terminated string; the descriptor is freed by Descriptor.
|
||||
if unsafe { ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl.as_ptr(), SDDL_REVISION_1, &mut sd, null_mut()) } == 0 {
|
||||
return Err(std::io::Error::last_os_error());
|
||||
}
|
||||
let (mut present, mut defaulted) = (0, 0);
|
||||
let mut dacl: *mut ACL = null_mut();
|
||||
GetSecurityDescriptorDacl(sd, &mut present, &mut dacl, &mut defaulted);
|
||||
let mut owner: *mut c_void = null_mut();
|
||||
GetSecurityDescriptorOwner(sd, &mut owner, &mut defaulted);
|
||||
let rc = SetNamedSecurityInfoW(
|
||||
path.as_ptr(),
|
||||
SE_FILE_OBJECT,
|
||||
OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
|
||||
owner,
|
||||
null_mut(),
|
||||
dacl,
|
||||
null_mut(),
|
||||
);
|
||||
LocalFree(sd);
|
||||
Ok(Descriptor(sd))
|
||||
}
|
||||
|
||||
struct Handle(HANDLE);
|
||||
impl Drop for Handle {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: ours, closed once.
|
||||
unsafe { CloseHandle(self.0) };
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ensure_root(root: &Path) -> std::io::Result<()> {
|
||||
if let Some(parent) = root.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
let mut system_owner = true;
|
||||
for attempt in 0..4 {
|
||||
let sd = descriptor(system_owner)?;
|
||||
let mut attrs = SECURITY_ATTRIBUTES {
|
||||
nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
|
||||
lpSecurityDescriptor: sd.0,
|
||||
bInheritHandle: 0,
|
||||
};
|
||||
let path = wide(root.as_os_str());
|
||||
// SAFETY: NUL-terminated path; attrs outlives the call.
|
||||
if unsafe { CreateDirectoryW(path.as_ptr(), &mut attrs) } != 0 {
|
||||
return Ok(());
|
||||
}
|
||||
// SAFETY: plain call.
|
||||
match unsafe { GetLastError() } {
|
||||
ERROR_ALREADY_EXISTS => {}
|
||||
// Not SYSTEM (an administrator's console): the directory is the caller's own.
|
||||
ERROR_INVALID_OWNER if system_owner => {
|
||||
system_owner = false;
|
||||
continue;
|
||||
}
|
||||
_ => return Err(std::io::Error::last_os_error()),
|
||||
}
|
||||
match check_existing(root, &sd)? {
|
||||
true => return Ok(()),
|
||||
false => {
|
||||
let aside = root.with_extension(format!("untrusted-{}-{attempt}", std::process::id()));
|
||||
tracing::warn!("{} is not SYSTEM's own; moving it to {}", root.display(), aside.display());
|
||||
// A rename moves a link itself, never what it points at.
|
||||
std::fs::rename(root, &aside)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(std::io::Error::other(format!("{} keeps being taken over", root.display())))
|
||||
}
|
||||
|
||||
/// Whether the existing `root` may be used: a real directory (no link), owned by SYSTEM
|
||||
/// or Administrators, letting no one else in. It then gets the protected DACL again.
|
||||
fn check_existing(root: &Path, sd: &Descriptor) -> std::io::Result<bool> {
|
||||
let path = wide(root.as_os_str());
|
||||
// SAFETY: NUL-terminated path; the handle is closed by Handle.
|
||||
let h = unsafe {
|
||||
CreateFileW(
|
||||
path.as_ptr(),
|
||||
READ_CONTROL | WRITE_DAC | WRITE_OWNER,
|
||||
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
|
||||
null_mut(),
|
||||
OPEN_EXISTING,
|
||||
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
|
||||
null_mut(),
|
||||
)
|
||||
};
|
||||
if h == INVALID_HANDLE_VALUE {
|
||||
return Err(std::io::Error::last_os_error());
|
||||
}
|
||||
let h = Handle(h);
|
||||
let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
|
||||
// SAFETY: a live handle and a zeroed struct to fill.
|
||||
if unsafe { GetFileInformationByHandle(h.0, &mut info) } == 0 {
|
||||
return Err(std::io::Error::last_os_error());
|
||||
}
|
||||
if info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 || info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY == 0 {
|
||||
return Ok(false);
|
||||
}
|
||||
let mut owner = null_mut();
|
||||
let mut current = null_mut();
|
||||
// SAFETY: the handle is live; owner points into `current`, freed below.
|
||||
let rc = unsafe {
|
||||
GetSecurityInfo(
|
||||
h.0, SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, &mut owner, null_mut(), null_mut(), null_mut(), &mut current,
|
||||
)
|
||||
};
|
||||
if rc != ERROR_SUCCESS {
|
||||
return Err(std::io::Error::from_raw_os_error(rc as i32));
|
||||
}
|
||||
// SAFETY: owner is a SID inside `current`. The service's own account counts: whoever
|
||||
// runs the service could change its files anyway.
|
||||
let trusted_owner = unsafe {
|
||||
IsWellKnownSid(owner, WinLocalSystemSid) != 0 || IsWellKnownSid(owner, WinBuiltinAdministratorsSid) != 0 || is_own_user(owner)
|
||||
};
|
||||
let closed = only_trusted_aces(current, own_sid_string().as_deref());
|
||||
// SAFETY: allocated by GetSecurityInfo.
|
||||
unsafe { LocalFree(current) };
|
||||
if !trusted_owner || !closed {
|
||||
tracing::warn!("existing root: trusted owner {trusted_owner}, closed DACL {closed}");
|
||||
return Ok(false);
|
||||
}
|
||||
// Ours: the protected DACL again, on this same handle.
|
||||
let (mut present, mut defaulted) = (0, 0);
|
||||
let mut dacl: *mut ACL = null_mut();
|
||||
// SAFETY: the DACL points into sd, alive for the call.
|
||||
let rc = unsafe {
|
||||
GetSecurityDescriptorDacl(sd.0, &mut present, &mut dacl, &mut defaulted);
|
||||
SetSecurityInfo(h.0, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION, null_mut(), null_mut(), dacl, null_mut())
|
||||
};
|
||||
if rc != ERROR_SUCCESS {
|
||||
return Err(std::io::Error::from_raw_os_error(rc as i32));
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Whether `sid` is this process's own account.
|
||||
#[allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
fn is_own_user(sid: *mut c_void) -> bool {
|
||||
use windows_sys::Win32::Security::{EqualSid, GetTokenInformation, TOKEN_QUERY, TOKEN_USER, TokenUser};
|
||||
use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
|
||||
let mut token: HANDLE = null_mut();
|
||||
// SAFETY: the current process's token, closed below; buf is as long as said.
|
||||
unsafe {
|
||||
if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) == 0 {
|
||||
return false;
|
||||
}
|
||||
let token = Handle(token);
|
||||
let mut buf = vec![0u8; 256];
|
||||
let mut len = 0;
|
||||
if GetTokenInformation(token.0, TokenUser, buf.as_mut_ptr() as *mut c_void, buf.len() as u32, &mut len) == 0 {
|
||||
return false;
|
||||
}
|
||||
let user = &*(buf.as_ptr() as *const TOKEN_USER);
|
||||
EqualSid(user.User.Sid, sid) != 0
|
||||
}
|
||||
}
|
||||
|
||||
/// This process's account as an SDDL SID string.
|
||||
fn own_sid_string() -> Option<String> {
|
||||
use windows_sys::Win32::Security::Authorization::ConvertSidToStringSidW;
|
||||
use windows_sys::Win32::Security::{GetTokenInformation, TOKEN_QUERY, TOKEN_USER, TokenUser};
|
||||
use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
|
||||
let mut token: HANDLE = null_mut();
|
||||
// SAFETY: the current process's token, closed by Handle; buf as long as said; the
|
||||
// string LocalFree'd.
|
||||
unsafe {
|
||||
if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) == 0 {
|
||||
return None;
|
||||
}
|
||||
let token = Handle(token);
|
||||
let mut buf = vec![0u8; 256];
|
||||
let mut len = 0;
|
||||
if GetTokenInformation(token.0, TokenUser, buf.as_mut_ptr() as *mut c_void, buf.len() as u32, &mut len) == 0 {
|
||||
return None;
|
||||
}
|
||||
let user = &*(buf.as_ptr() as *const TOKEN_USER);
|
||||
let mut text = null_mut();
|
||||
if ConvertSidToStringSidW(user.User.Sid, &mut text) == 0 {
|
||||
return None;
|
||||
}
|
||||
let s = wide_to_string(text);
|
||||
LocalFree(text as *mut c_void);
|
||||
Some(s)
|
||||
}
|
||||
}
|
||||
|
||||
/// SAFETY: `p` is a NUL-terminated wide string.
|
||||
unsafe fn wide_to_string(p: *const u16) -> String {
|
||||
let mut n = 0;
|
||||
// SAFETY: as the caller promises.
|
||||
unsafe {
|
||||
while *p.add(n) != 0 {
|
||||
n += 1;
|
||||
}
|
||||
String::from_utf16_lossy(std::slice::from_raw_parts(p, n))
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a descriptor's DACL allows only SYSTEM, Administrators, OWNER RIGHTS and this
|
||||
/// process's own account, inherited entries included (any deny entry is fine).
|
||||
fn only_trusted_aces(sd: *mut c_void, own: Option<&str>) -> bool {
|
||||
let mut text = null_mut();
|
||||
// SAFETY: a valid descriptor in; the string out is LocalFree'd.
|
||||
if unsafe { ConvertSecurityDescriptorToStringSecurityDescriptorW(sd, SDDL_REVISION_1, DACL_SECURITY_INFORMATION, &mut text, null_mut()) } == 0 {
|
||||
return false;
|
||||
}
|
||||
// SAFETY: a NUL-terminated wide string from the call above.
|
||||
let s = unsafe { wide_to_string(text) };
|
||||
unsafe { LocalFree(text as *mut c_void) };
|
||||
tracing::debug!("existing root's DACL: {s}");
|
||||
let Some(dacl) = s.strip_prefix("D:") else { return false };
|
||||
dacl.split('(').skip(1).all(|ace| {
|
||||
let fields: Vec<&str> = ace.trim_end_matches(')').split(';').collect();
|
||||
fields.len() >= 6 && (fields[0] != "A" || matches!(fields[5], "SY" | "BA" | "OW") || Some(fields[5]) == own)
|
||||
})
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Reference in new issue
Block a user