windows: protect the state directory, names that become files, logs

The state directory gets a protected DACL (SYSTEM and Administrators)
at every start; on Windows programs run only from its bin\, never from
PATH; rule-set and geodata names are validated before they become file
names, and checked again where they do; logs need the secrets scope.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 5.5 committed 2026-10-26 23:16:40 +03:00
1 parent 41c8ed4406
commit d678976c2d
6 files changed
+96 -3

No files matched your search

@@ -57,6 +57,15 @@ pub(crate) fn path_name_ok(name: &str) -> bool {
&& name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
}
/// A geosite or geoip name: "geolocation-!cn" and "google@cn" among them, never a path
/// (upstream's routing-render.jq `geo`).
pub(crate) fn geo_name_ok(name: &str) -> bool {
!name.is_empty()
&& name.len() <= 64
&& !name.starts_with('.')
&& name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '!' | '@' | '.' | '_' | '-'))
}
fn profile_name_ok(name: &str) -> bool {
let mut chars = name.chars();
matches!(chars.next(), Some(c) if c.is_ascii_lowercase() || c.is_ascii_digit())
@@ -167,6 +176,25 @@ fn proxy(cfg: &Config, v: &mut Issues) {
}
}
}
let mut geo_lists: Vec<(String, &crate::config::RouteMatch)> = vec![
("proxy.routing.proxy".into(), &p.routing.proxy),
("proxy.routing.direct".into(), &p.routing.direct),
("proxy.routing.block".into(), &p.routing.block),
];
geo_lists.extend(p.routing.rules.iter().enumerate().map(|(i, r)| (format!("proxy.routing.rules.{i}"), &r.matches)));
geo_lists.extend(p.outbounds.iter().enumerate().map(|(i, o)| (format!("proxy.outbounds.{i}.routing"), &o.routing)));
for (path, m) in geo_lists {
for name in m.geosites.iter().chain(&m.geoips) {
if !geo_name_ok(name) {
v.error(&path, format!("'{name}' is not a geosite or geoip name: letters, digits, '!', '@', '.', '_' and '-'"));
}
}
}
for name in p.routing.rule_sets.keys() {
if !path_name_ok(name) {
v.error(format!("proxy.routing.ruleSets.{name}"), "a rule set name takes letters, digits, '.', '_' and '-', and no leading dot");
}
}
if !p.routing.rule_sets.is_empty() && !sing_box {
v.error("proxy.routing.ruleSets", "rule sets need the sing-box or hybrid backend");
}
+1
View File
@@ -31,5 +31,6 @@ windows-sys = { workspace = true, features = [
"Win32_Foundation",
"Win32_Security",
"Win32_System_JobObjects",
"Win32_Security_Authorization",
"Win32_System_Threading",
] }
+2 -1
View File
@@ -132,7 +132,8 @@ fn scope_of(req: &Request) -> Option<Scope> {
Request::ConfigSet { .. } => Some(Scope::Config),
Request::Pin { .. } | Request::Mode { .. } | Request::RuleSetsUpdate => Some(Scope::Routing),
Request::Disable { .. } | Request::SubsUpdate { .. } | Request::Test { .. } => Some(Scope::Outbounds),
Request::RenderedConfig => Some(Scope::Secrets),
// Backend logs name the sites visited (at info), and errors may quote what was dialled.
Request::RenderedConfig | Request::Logs { .. } => Some(Scope::Secrets),
Request::Restart { .. } | Request::Start { .. } | Request::Stop { .. } => Some(Scope::Services),
_ => None,
}
+6 -1
View File
@@ -14,13 +14,18 @@ impl Components {
Self { bin }
}
/// The program `name` (without `.exe`) of `component`.
/// The program `name` (without `.exe`) of `component`. On Windows only the protected
/// `bin\` counts: what the service runs, it runs as SYSTEM, and PATH may hold a directory
/// any user can write.
pub fn find(&self, component: &str, name: &str) -> Option<PathBuf> {
let file = if cfg!(windows) { format!("{name}.exe") } else { name.to_owned() };
let installed = self.bin.join(component).join(&file);
if installed.is_file() {
return Some(installed);
}
if cfg!(windows) {
return None;
}
let path = std::env::var_os("PATH")?;
std::env::split_paths(&path).map(|dir| dir.join(&file)).find(|p| p.is_file())
}
+50 -1
View File
@@ -65,8 +65,14 @@ 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.
pub fn create_all(&self) -> std::io::Result<()> {
for dir in [self.root.clone(), self.subscriptions(), self.rule_sets(), self.cache(), self.run(), self.logs(), self.bin()] {
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)?;
}
Ok(())
@@ -85,3 +91,46 @@ pub fn write_atomic(path: &Path, data: &[u8]) -> std::io::Result<()> {
pub fn same_content(path: &Path, data: &[u8]) -> bool {
std::fs::read(path).is_ok_and(|old| old == data)
}
/// A protected DACL on `dir`, inherited by everything below it: full control for SYSTEM and
/// Administrators, nothing for anyone else.
#[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::Security::Authorization::{
ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1, SE_FILE_OBJECT, SetNamedSecurityInfoW,
};
use windows_sys::Win32::Security::{
DACL_SECURITY_INFORMATION, GetSecurityDescriptorDacl, PROTECTED_DACL_SECURITY_INFORMATION, ACL,
};
let sddl: Vec<u16> = "D:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)".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 {
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 rc = SetNamedSecurityInfoW(
path.as_ptr(),
SE_FILE_OBJECT,
DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
null_mut(),
null_mut(),
dacl,
null_mut(),
);
LocalFree(sd);
if rc != ERROR_SUCCESS {
return Err(std::io::Error::from_raw_os_error(rc as i32));
}
}
Ok(())
}
+9
View File
@@ -304,7 +304,13 @@ pub async fn update_rule_sets(shared: &Shared, missing_only: bool) -> Vec<(Strin
};
let mut results = Vec::new();
let mut changed = false;
// A tag becomes a file name: the configuration is validated, but this writes as SYSTEM.
let safe = |tag: &str| !tag.is_empty() && !tag.starts_with('.') && tag.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '!' | '@' | '.' | '_' | '-'));
for w in wanted.iter().filter(|w| w.dns_copy_of.is_none()) {
if !safe(&w.tag) {
results.push((w.tag.clone(), Err("not a name a file may have".into())));
continue;
}
if missing_only && have.contains_key(&w.tag) {
continue;
}
@@ -318,6 +324,9 @@ pub async fn update_rule_sets(shared: &Shared, missing_only: bool) -> Vec<(Strin
// The DNS copies, from what was fetched.
for w in wanted.iter().filter(|w| w.dns_copy_of.is_some()) {
let of = w.dns_copy_of.as_deref().unwrap();
if !safe(&w.tag) || !safe(of) {
continue;
}
let src_json = dir.join(format!("{of}.json"));
let src_srs = dir.join(format!("{of}.srs"));
let dest = dir.join(format!("{}.json", w.tag));