diff --git a/windows/crates/ps-core/src/components.rs b/windows/crates/ps-core/src/components.rs new file mode 100644 index 0000000..ecec089 --- /dev/null +++ b/windows/crates/ps-core/src/components.rs @@ -0,0 +1,122 @@ +//! The components: the backend programs the service runs, pinned by version and hash +//! (`windows/components.json`). Each is fetched from its project's own Windows release and +//! verified before anything from it runs. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Manifest { + pub components: BTreeMap, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Component { + pub version: String, + pub license: String, + pub homepage: String, + /// Built with the release, not fetched from a source of its own. + #[serde(default)] + pub bundled: bool, + pub sources: Vec, +} + +/// One archive and what to take from it. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Source { + pub url: String, + /// The archive's SHA-256, where the archive is stable (a release asset). + #[serde(default)] + pub sha256: Option, + /// The leading path every taken entry has, removed. + #[serde(default)] + pub strip: String, + /// Where below the component's directory the entries go. + #[serde(default)] + pub dest: String, + /// Only these entries (exact paths, or directories ending in `/`). + #[serde(default)] + pub include: Option>, + /// Not these. + #[serde(default)] + pub exclude: Vec, + /// Exactly these entries, each with its SHA-256: for an archive that is not byte-stable + /// (a commit snapshot), what is verified is what is taken. + #[serde(default)] + pub files: Option>, +} + +/// The manifest this build pins. +pub fn manifest() -> Manifest { + serde_json::from_str(include_str!("../../../components.json")).expect("components.json is valid") +} + +fn matches(list: &[String], rel: &str) -> bool { + list.iter().any(|p| if p.ends_with('/') { rel.starts_with(p.as_str()) } else { rel == p }) +} + +/// A relative path made of plain names only: no root, no drive, no `..`, no `.`. +pub fn safe_relative(rel: &str) -> bool { + !rel.is_empty() + && !rel.starts_with(['/', '\\']) + && !rel.contains(':') + && rel.split(['/', '\\']).all(|part| !part.is_empty() && part != "." && part != "..") +} + +impl Source { + /// Where an archive entry goes below the component's directory, or `None` to leave it. + pub fn place(&self, entry: &str) -> Option { + if entry.ends_with('/') { + return None; + } + let rel = entry.strip_prefix(self.strip.as_str())?; + if let Some(files) = &self.files { + if !files.contains_key(rel) { + return None; + } + } + if let Some(include) = &self.include { + if !matches(include, rel) { + return None; + } + } + if matches(&self.exclude, rel) { + return None; + } + let out = format!("{}{rel}", self.dest); + safe_relative(&out).then_some(out) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_manifest_reads_and_places_entries() { + let m = manifest(); + let sb = &m.components["sing-box"].sources[0]; + assert_eq!(sb.place("sing-box-1.14.4-windows-amd64/sing-box.exe").as_deref(), Some("sing-box.exe")); + assert_eq!(sb.place("other/sing-box.exe"), None); + let z = &m.components["zapret"].sources[0]; + assert_eq!(z.place("zapret-discord-youtube-1.10.4/bin/winws.exe").as_deref(), Some("bin/winws.exe")); + assert_eq!(z.place("zapret-discord-youtube-1.10.4/service.bat"), None); + assert_eq!(z.place("zapret-discord-youtube-1.10.4/utils/targets.txt"), None); + let k = &m.components["zapret2"].sources[1]; + assert_eq!(k.place(&format!("{}nfqws2.conf", k.strip)).as_deref(), Some("keenetic/nfqws2.conf")); + assert!(m.components["tg-ws-proxy"].bundled); + } + + #[test] + fn archive_paths_cannot_leave_the_directory() { + for bad in ["../x", "a/../b", "/etc/x", "C:/x", "a\\..\\b", "", "a//b"] { + assert!(!safe_relative(bad), "{bad}"); + } + assert!(safe_relative("bin/winws.exe")); + let s = Source { url: String::new(), sha256: None, strip: "p/".into(), dest: String::new(), include: None, exclude: vec![], files: None }; + assert_eq!(s.place("p/../../evil.exe"), None); + } +} diff --git a/windows/crates/ps-core/src/lib.rs b/windows/crates/ps-core/src/lib.rs index e6ddbe3..3a34272 100644 --- a/windows/crates/ps-core/src/lib.rs +++ b/windows/crates/ps-core/src/lib.rs @@ -4,6 +4,7 @@ //! subscription parsing, and the sing-box and XRay configs the service runs. Nothing here //! touches the network, the file system or processes; the service does that. +pub mod components; pub mod config; pub mod derived; pub mod duration; diff --git a/windows/crates/ps-service/Cargo.toml b/windows/crates/ps-service/Cargo.toml index 7e5267c..7b03b19 100644 --- a/windows/crates/ps-service/Cargo.toml +++ b/windows/crates/ps-service/Cargo.toml @@ -32,5 +32,6 @@ windows-sys = { workspace = true, features = [ "Win32_Security", "Win32_System_JobObjects", "Win32_Security_Authorization", + "Win32_Storage_FileSystem", "Win32_System_Threading", ] } diff --git a/windows/crates/ps-service/src/api.rs b/windows/crates/ps-service/src/api.rs index 5176dcf..423e97f 100644 --- a/windows/crates/ps-service/src/api.rs +++ b/windows/crates/ps-service/src/api.rs @@ -428,7 +428,58 @@ pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response { Response::ok(json!(out)) } - Request::Components | Request::ComponentsInstall { .. } => Response::err("the component manager is not there yet"), + Request::Components => { + let s = shared.lock().await; + let bin = s.paths().bin(); + let list: Vec = ps_core::components::manifest() + .components + .iter() + .map(|(name, c)| { + json!({ + "name": name, + "version": c.version, + "installed": crate::install::installed_version(&bin, name), + "license": c.license, + "homepage": c.homepage, + "bundled": c.bundled, + }) + }) + .collect(); + Response::ok(json!(list)) + } + + Request::ComponentsInstall { names } => { + // Programs the service runs as SYSTEM: an administrator's call, whatever the scopes. + if !peer.admin { + return Response::err("installing components needs an administrator"); + } + let manifest = ps_core::components::manifest(); + let wanted: Vec = if names.is_empty() { + manifest.components.iter().filter(|(_, c)| !c.bundled).map(|(n, _)| n.clone()).collect() + } else { + names + }; + let (bin, cache, routes) = { + let s = shared.lock().await; + (s.paths().bin(), s.paths().root.join("downloads"), s.fetch_routes(true)) + }; + let mut results = Vec::new(); + for name in wanted { + let Some(comp) = manifest.components.get(&name) else { + results.push(json!({ "name": name, "error": "no such component" })); + continue; + }; + // What runs from it must let go of its files first. + shared.lock().await.sup.stop_all().await; + let r = crate::install::install(&bin, &name, comp, &routes, &cache).await; + results.push(match r { + Ok(()) => json!({ "name": name, "version": comp.version }), + Err(e) => json!({ "name": name, "error": format!("{e:#}") }), + }); + } + let _ = shared.lock().await.apply().await; + Response::ok(json!(results)) + } } } diff --git a/windows/crates/ps-service/src/components.rs b/windows/crates/ps-service/src/components.rs index 5f561e8..747acc2 100644 --- a/windows/crates/ps-service/src/components.rs +++ b/windows/crates/ps-service/src/components.rs @@ -3,15 +3,37 @@ //! The service installs each into `bin\\` (the component manager); a program //! found there wins. Elsewhere (development on Linux) the one on PATH is taken. +use std::collections::HashMap; use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::time::SystemTime; pub struct Components { bin: PathBuf, + /// Programs verified, by path, with the size and time they had then. + verified: Mutex>, } impl Components { pub fn new(bin: PathBuf) -> Self { - Self { bin } + Self { bin, verified: Mutex::new(HashMap::new()) } + } + + /// `find`, and for an installed one, the check that it is what was installed. + pub fn program(&self, component: &str, name: &str) -> anyhow::Result { + let path = self + .find(component, name) + .ok_or_else(|| anyhow::anyhow!("{component} is not installed (proxy-ctl components install {component})"))?; + let dir = self.bin.join(component); + if path.starts_with(&dir) { + let meta = std::fs::metadata(&path)?; + let stamp = (meta.len(), meta.modified()?); + if self.verified.lock().unwrap().get(&path) != Some(&stamp) { + crate::install::verify(&dir, &path)?; + self.verified.lock().unwrap().insert(path.clone(), stamp); + } + } + Ok(path) } /// The program `name` (without `.exe`) of `component`. On Windows only the protected @@ -30,14 +52,15 @@ impl Components { std::env::split_paths(&path).map(|dir| dir.join(&file)).find(|p| p.is_file()) } - pub fn sing_box(&self) -> Option { - self.find("sing-box", "sing-box") + pub fn sing_box(&self) -> anyhow::Result { + self.program("sing-box", "sing-box") } - pub fn xray(&self) -> Option { - self.find("xray", "xray") + pub fn xray(&self) -> anyhow::Result { + self.program("xray", "xray") } + #[allow(dead_code)] pub fn bin_dir(&self) -> &Path { &self.bin } diff --git a/windows/crates/ps-service/src/install.rs b/windows/crates/ps-service/src/install.rs new file mode 100644 index 0000000..ed6508c --- /dev/null +++ b/windows/crates/ps-service/src/install.rs @@ -0,0 +1,170 @@ +//! Installing components: download, verify, extract, swap in. + +use std::io::Read; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result, bail}; +use ps_core::components::{Component, Source}; +use sha2::{Digest, Sha256}; + +use crate::fetch; + +fn hex(data: &[u8]) -> String { + let mut h = Sha256::new(); + h.update(data); + h.finalize().iter().map(|b| format!("{b:02x}")).collect() +} + +/// The archive of `src`, from `cache` if it holds a verified copy, else downloaded there. +pub async fn archive(src: &Source, routes: &[fetch::Route], cache: &Path) -> Result> { + std::fs::create_dir_all(cache)?; + let key = hex(src.url.as_bytes()); + let cached = cache.join(&key[..32]); + if let Ok(data) = std::fs::read(&cached) { + if src.sha256.as_ref().is_none_or(|want| hex(&data) == *want) { + return Ok(data); + } + } + let mut last = None; + for route in routes { + match fetch::get(&src.url, route, 512 * 1024 * 1024).await { + Ok(data) => { + if let Some(want) = &src.sha256 { + let got = hex(&data); + if got != *want { + bail!("{} has SHA-256 {got}, not the pinned {want}", src.url); + } + } + crate::paths::write_atomic(&cached, &data)?; + return Ok(data); + } + Err(e) => last = Some(e), + } + } + Err(last.unwrap_or_else(|| anyhow::anyhow!("no way to fetch it")).context(format!("fetching {}", src.url))) +} + +/// Extracts what `src` takes from `data` into `dest`, verifying each file it pins. +pub fn extract(src: &Source, data: &[u8], dest: &Path) -> Result { + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(data)).context("not a zip archive")?; + let mut seen = std::collections::BTreeSet::new(); + let mut n = 0; + for i in 0..zip.len() { + let mut entry = zip.by_index(i)?; + let name = entry.name().to_owned(); + let Some(rel) = src.place(&name) else { continue }; + let mut body = Vec::with_capacity(entry.size() as usize); + entry.read_to_end(&mut body)?; + if let Some(files) = &src.files { + let in_archive = name.strip_prefix(src.strip.as_str()).unwrap_or(&name); + let want = &files[in_archive]; + let got = hex(&body); + if got != *want { + bail!("{in_archive} has SHA-256 {got}, not the pinned {want}"); + } + seen.insert(in_archive.to_owned()); + } + let out = dest.join(&rel); + if let Some(parent) = out.parent() { + std::fs::create_dir_all(parent)?; + } + std::fs::write(&out, &body).with_context(|| format!("writing {}", out.display()))?; + n += 1; + } + if let Some(files) = &src.files { + let missing: Vec<&String> = files.keys().filter(|f| !seen.contains(*f)).collect(); + if !missing.is_empty() { + bail!("the archive lacks {}", missing.iter().map(|s| s.as_str()).collect::>().join(", ")); + } + } + Ok(n) +} + +/// The version of `name` installed under `bin`. +pub fn installed_version(bin: &Path, name: &str) -> Option { + std::fs::read_to_string(bin.join(name).join(".version")).ok().map(|s| s.trim().to_owned()) +} + +/// Puts `comp` into `bin\\`: staged next to it, then swapped in whole, so a failure +/// leaves what was there. +pub async fn install(bin: &Path, name: &str, comp: &Component, routes: &[fetch::Route], cache: &Path) -> Result<()> { + if comp.bundled { + bail!("{name} comes with the release and is not fetched on its own"); + } + let staging = bin.join(format!("{name}.staging")); + let _ = std::fs::remove_dir_all(&staging); + std::fs::create_dir_all(&staging)?; + for src in &comp.sources { + let data = archive(src, routes, cache).await?; + let n = extract(src, &data, &staging).with_context(|| format!("unpacking {}", src.url))?; + if n == 0 { + bail!("nothing in {} matched", src.url); + } + } + std::fs::write(staging.join(".version"), &comp.version)?; + // What was installed, by hash: checked again before anything from it runs. + let mut files = std::collections::BTreeMap::new(); + record(&staging, &staging, &mut files)?; + std::fs::write(staging.join(".files.json"), serde_json::to_vec_pretty(&files)?)?; + swap(bin, name, &staging) +} + +fn record(root: &Path, dir: &Path, out: &mut std::collections::BTreeMap) -> Result<()> { + for entry in std::fs::read_dir(dir)? { + let entry = entry?; + let path = entry.path(); + let ty = entry.file_type()?; + if ty.is_dir() { + record(root, &path, out)?; + } else if ty.is_file() { + let rel = path.strip_prefix(root)?.to_string_lossy().replace('\\', "/"); + if !rel.starts_with('.') { + out.insert(rel, hex(&std::fs::read(&path)?)); + } + } + } + Ok(()) +} + +/// Whether `program` (below `bin\\`) still has the hash it was installed with. +pub fn verify(component_dir: &Path, program: &Path) -> Result<()> { + let files: std::collections::BTreeMap = serde_json::from_slice( + &std::fs::read(component_dir.join(".files.json")).context("no record of what was installed (reinstall it)")?, + )?; + let rel = program.strip_prefix(component_dir)?.to_string_lossy().replace('\\', "/"); + let want = files.get(&rel).with_context(|| format!("{rel} was not installed with the component"))?; + let got = hex(&std::fs::read(program)?); + if got != *want { + bail!("{} has changed since it was installed (SHA-256 {got}); reinstall the component", program.display()); + } + Ok(()) +} + +fn swap(bin: &Path, name: &str, staging: &Path) -> Result<()> { + let target = bin.join(name); + let old: PathBuf = bin.join(format!("{name}.old")); + let _ = std::fs::remove_dir_all(&old); + if target.exists() { + std::fs::rename(&target, &old).with_context(|| format!("moving the old {name} aside (is it running?)"))?; + } + if let Err(e) = std::fs::rename(staging, &target) { + let _ = std::fs::rename(&old, &target); + return Err(e).context(format!("putting {name} in place")); + } + let _ = std::fs::remove_dir_all(&old); + Ok(()) +} + +/// For the release: every component that has sources, into `to\\`, with a cache. +pub async fn stage(to: &Path, cache: &Path, only: &[String]) -> Result<()> { + let manifest = ps_core::components::manifest(); + std::fs::create_dir_all(to)?; + for (name, comp) in &manifest.components { + if comp.bundled || (!only.is_empty() && !only.contains(name)) { + continue; + } + println!("{name} {}", comp.version); + install(to, name, comp, &[fetch::Route::Direct], cache).await.with_context(|| format!("staging {name}"))?; + } + Ok(()) +} diff --git a/windows/crates/ps-service/src/main.rs b/windows/crates/ps-service/src/main.rs index e41c455..67d99f7 100644 --- a/windows/crates/ps-service/src/main.rs +++ b/windows/crates/ps-service/src/main.rs @@ -7,6 +7,7 @@ mod api; mod clash; mod components; mod fetch; +mod install; #[cfg(windows)] mod job; mod paths; @@ -46,6 +47,15 @@ enum Command { Install, /// Remove the Windows service. Uninstall, + /// For building a release: fetch and verify every component into DIR. + #[command(hide = true)] + StageComponents { + #[arg(long)] + to: PathBuf, + #[arg(long)] + cache: PathBuf, + only: Vec, + }, } fn address(arg: Option) -> Address { @@ -103,13 +113,19 @@ fn main() -> Result<()> { .with_env_filter(tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into())) .with_writer(std::io::stderr) .init(); + if let Some(Command::StageComponents { to, cache, only }) = &args.command { + let _ = rustls::crypto::ring::default_provider().install_default(); + let rt = tokio::runtime::Runtime::new()?; + return rt.block_on(install::stage(to, cache, only)); + } match args.command { #[cfg(windows)] Some(Command::Install) => return winsvc::install(), #[cfg(windows)] Some(Command::Uninstall) => return winsvc::uninstall(), #[cfg(not(windows))] - Some(_) => anyhow::bail!("there are no services to install off Windows; use --console"), + Some(Command::Install | Command::Uninstall) => anyhow::bail!("there are no services to install off Windows; use --console"), + Some(Command::StageComponents { .. }) => unreachable!(), None => {} } if args.console || !cfg!(windows) { diff --git a/windows/crates/ps-service/src/paths.rs b/windows/crates/ps-service/src/paths.rs index d18ade4..fd7f5b4 100644 --- a/windows/crates/ps-service/src/paths.rs +++ b/windows/crates/ps-service/src/paths.rs @@ -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 { +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 = 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 = "O:SYD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;RC;;;OW)".encode_utf16().chain(Some(0)).collect(); - let path: Vec = 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 { + 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()); } - 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::() 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 { + 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) + }) } - Ok(()) } diff --git a/windows/crates/ps-service/src/service.rs b/windows/crates/ps-service/src/service.rs index 9cff2bf..4a2ce3d 100644 --- a/windows/crates/ps-service/src/service.rs +++ b/windows/crates/ps-service/src/service.rs @@ -79,7 +79,7 @@ impl Service { let cfg = self.cfg(); let mut direct = Vec::new(); if cfg.proxy.backend == Backend::Hybrid { - if let Some(x) = self.comps.xray() { + if let Ok(x) = self.comps.xray() { direct.push(x.to_string_lossy().into_owned()); } } @@ -139,8 +139,8 @@ impl Service { let backend = self.cfg().proxy.backend; let main_program = match backend { - Backend::Xray => self.comps.xray().context("xray is not installed")?, - _ => self.comps.sing_box().context("sing-box is not installed (proxy-ctl components install)")?, + Backend::Xray => self.comps.xray()?, + _ => self.comps.sing_box()?, }; let main_json = serde_json::to_vec_pretty(rendered.sing_box.as_ref().or(rendered.xray.as_ref()).unwrap())?; let main_path = run.join(if backend == Backend::Xray { "xray.json" } else { "sing-box.json" }); @@ -175,7 +175,7 @@ impl Service { match (backend, &rendered.xray) { (Backend::Hybrid, Some(sidecar)) => { - let xray = self.comps.xray().context("xray is not installed; the hybrid backend needs it")?; + let xray = self.comps.xray().context("the hybrid backend needs xray")?; let json = serde_json::to_vec_pretty(sidecar)?; let path = run.join("xray-sidecar.json"); if !same_content(&path, &json) { @@ -297,7 +297,7 @@ pub async fn update_rule_sets(shared: &Shared, missing_only: bool) -> Vec<(Strin render::wanted_rule_sets(s.cfg()), s.store.rule_set_files(), s.paths().rule_sets(), - s.comps.sing_box(), + s.comps.sing_box().ok(), s.fetch_routes(true), s.fetch_routes(false), ) diff --git a/windows/tools/wine-e2e.sh b/windows/tools/wine-e2e.sh new file mode 100755 index 0000000..09ce495 --- /dev/null +++ b/windows/tools/wine-e2e.sh @@ -0,0 +1,74 @@ +#!/usr/bin/env bash +# The Windows build, end to end, under Wine: proxy-suite-service.exe supervising the real +# sing-box.exe, proxy-ctl.exe adding an outbound over the named pipe, a page fetched through +# the local proxy from a Shadowsocks server on the Linux side. +# +# nix develop --command nix shell nixpkgs#wineWow64Packages.stable -c tools/wine-e2e.sh STAGE_DIR +# +# STAGE_DIR: components staged by `proxy-suite-service stage-components` (needs sing-box). +# +# Wine 11 lacks iphlpapi!InitializeIpInterfaceEntry, which sing-box calls as it starts: the +# test then stops there, having checked everything of ours up to it. +set -euo pipefail +cd "$(dirname "$0")/.." +STAGE=${1:?staged components directory} +WORK=$(mktemp -d) +export WINEPREFIX=${WINEPREFIX:-$WORK/prefix} WINEDEBUG=-all +trap 'wineserver -k 2>/dev/null || true; kill $(jobs -p) 2>/dev/null || true; rm -rf "$WORK"' EXIT + +cargo xwin build -q -p ps-service -p ps-ctl --target x86_64-pc-windows-msvc +E=target/x86_64-pc-windows-msvc/debug +port() { python3 -c 'import socket;s=socket.socket();s.bind(("127.0.0.1",0));print(s.getsockname()[1])'; } +SS=$(port) WEB=$(port) PROXY=$(port) CLASH=$(port) TEST=$(port) +KEY=$(python3 -c "import base64;print(base64.b64encode(b'k'*16).decode())") + +# The web server and the Shadowsocks server, on Linux, which knows web.test as loopback. +mkdir -p "$WORK/www" && echo -n hello-through-windows > "$WORK/www/index.html" +python3 -m http.server -b 127.0.0.1 -d "$WORK/www" "$WEB" >/dev/null 2>&1 & +cat > "$WORK/server.json" </dev/null 2>&1 & + +PIPE='\\.\pipe\pse2e' +ROOT="$WINEPREFIX/drive_c/pse2e" +ctl() { wine "$E/proxy-ctl.exe" --socket "$PIPE" "$@"; } +start() { + wine "$E/proxy-suite-service.exe" --console --state-dir 'C:\pse2e' --socket "$PIPE" >>"$WORK/service.log" 2>&1 & + for _ in $(seq 40); do ctl status >/dev/null 2>&1 && return; sleep 0.5; done + echo "the service did not come up"; cat "$WORK/service.log"; exit 1 +} +# The service makes its own state directory (it refuses one someone else made), then gets +# sing-box as the component manager installs it, and a configuration. +start +wineserver -k; sleep 1 +# What Windows has and a fresh Wine prefix lacks: sing-box's network monitor reads it. +for key in Tcpip Tcpip6; do + wine reg add "HKLM\\SYSTEM\\CurrentControlSet\\Services\\$key\\Parameters\\Interfaces" /f >/dev/null 2>&1 +done +wineserver -w +cp -r "$STAGE/sing-box" "$ROOT/bin/" +cat > "$ROOT/config.json" </dev/null | grep -q 'proxy: active' && break; sleep 0.5; done +ctl status +BODY=$(curl -s --max-time 10 --retry 10 --retry-delay 1 --retry-all-errors --socks5-hostname "127.0.0.1:$PROXY" "http://web.test:$WEB/" || true) +if [ "$BODY" = hello-through-windows ]; then + echo "OK: a page through proxy-suite-service.exe and sing-box.exe under Wine" +elif ctl logs -n 400 2>/dev/null | grep -q "InitializeIpInterfaceEntry procedure in iphlpapi.dll"; then + # Wine's iphlpapi lacks what sing-box's network monitor calls at start, TUN or not: + # everything up to sing-box itself (the service, its pipe, the component's hash, the + # rendered and checked config, the supervisor) worked; proxying needs real Windows. + echo "OK up to sing-box: Wine lacks iphlpapi!InitializeIpInterfaceEntry, which sing-box needs to run" + exit 0 +else + echo "FAIL: got '$BODY'"; ctl logs -n 400 > "$WORK/units.log" 2>&1 || true; grep -m1 -B2 -A12 "panic\|FATAL" "$WORK/units.log" || tail -40 "$WORK/units.log"; exit 1 +fi