//! Where the service keeps everything. //! //! `%ProgramData%\ProxySuite` on Windows, or `--state-dir` (any platform, for development //! and tests): //! //! ```text //! config.json the configuration, written only by the service //! state.json pins, disabled outbounds, the route mode //! secrets.json what the service generated: the Clash API secret, the hop login //! subscriptions/ each subscription's links as fetched last //! rule-sets/ downloaded geodata and rule sets //! cache/ sing-box's fake IP cache //! run/ the rendered backend configs //! logs/ one log per unit //! bin/ the components (sing-box, xray, winws, …) //! ``` use std::path::{Path, PathBuf}; #[derive(Debug, Clone)] pub struct Paths { pub root: PathBuf, } impl Paths { pub fn new(root: impl Into) -> Self { Self { root: root.into() } } /// `%ProgramData%\ProxySuite`, or `/var/lib/proxy-suite-windows` elsewhere. pub fn platform_default() -> Self { if cfg!(windows) { let base = std::env::var_os("ProgramData").map(PathBuf::from).unwrap_or_else(|| PathBuf::from(r"C:\ProgramData")); Self::new(base.join("ProxySuite")) } else { Self::new("/var/lib/proxy-suite-windows") } } pub fn config(&self) -> PathBuf { self.root.join("config.json") } pub fn state(&self) -> PathBuf { self.root.join("state.json") } pub fn secrets(&self) -> PathBuf { self.root.join("secrets.json") } pub fn subscriptions(&self) -> PathBuf { self.root.join("subscriptions") } pub fn rule_sets(&self) -> PathBuf { self.root.join("rule-sets") } pub fn cache(&self) -> PathBuf { self.root.join("cache") } pub fn run(&self) -> PathBuf { self.root.join("run") } pub fn logs(&self) -> PathBuf { self.root.join("logs") } pub fn bin(&self) -> PathBuf { self.root.join("bin") } /// 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<()> { // Once per process: a second check of a root this process made (and may be writing // its log into) has nothing to learn, and moving it aside then would lose the log. // Only a check that passed counts: a failed one is made again, and fails again. static CHECKED: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); { let mut checked = CHECKED.lock().unwrap_or_else(|e| e.into_inner()); if !checked.contains(&self.root) { #[cfg(windows)] secure::ensure_root(&self.root)?; #[cfg(not(windows))] std::fs::create_dir_all(&self.root)?; checked.push(self.root.clone()); } } for dir in [self.subscriptions(), self.rule_sets(), self.cache(), self.run(), self.logs(), self.bin()] { std::fs::create_dir_all(dir)?; } Ok(()) } } /// Writes `data` to `path` through a temporary file and a rename, so a reader never sees half /// of it and a crash leaves the old one. pub fn write_atomic(path: &Path, data: &[u8]) -> std::io::Result<()> { let tmp = path.with_extension("tmp"); std::fs::write(&tmp, data)?; std::fs::rename(&tmp, path) } /// Whether `path` holds exactly `data` already. pub fn same_content(path: &Path, data: &[u8]) -> bool { std::fs::read(path).is_ok_and(|old| old == data) } #[cfg(windows)] 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::{ CloseHandle, ERROR_ALREADY_EXISTS, ERROR_INVALID_OWNER, ERROR_SUCCESS, GetLastError, HANDLE, INVALID_HANDLE_VALUE, LocalFree, }; use windows_sys::Win32::Security::Authorization::{ ConvertSecurityDescriptorToStringSecurityDescriptorW, ConvertStringSecurityDescriptorToSecurityDescriptorW, GetSecurityInfo, SDDL_REVISION_1, SE_FILE_OBJECT, SetSecurityInfo, }; use windows_sys::Win32::Security::{ 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, }; /// 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 { 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 { 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()); } 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 attrs = SECURITY_ATTRIBUTES { nLength: std::mem::size_of::() 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(), &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 { 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 { 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) }) } } #[cfg(test)] mod tests { use super::*; #[test] fn a_failed_check_is_made_again() { let dir = std::env::temp_dir().join(format!("ps-paths-test-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); // A root that cannot be made: the first call fails, and so must every later one. let root = dir.join("root"); std::fs::write(&root, b"").unwrap(); let paths = Paths::new(&root); assert!(paths.create_all().is_err()); assert!(paths.create_all().is_err()); std::fs::remove_file(&root).unwrap(); paths.create_all().unwrap(); assert!(paths.bin().is_dir()); std::fs::remove_dir_all(&dir).unwrap(); } }