windows: whitelist-bypass names its files only after plain names

The names were checked only while whitelist-bypass was on, but proxy-ctl
wl names files after them either way: a configuration saved with it off
could name a creator 'C:\...\x' (on Windows a join with an absolute
path replaces the directory) and have the service write or delete a file
of that name as SYSTEM. They are checked on or off now, and every state
file goes through one helper that checks the name again.

Names (of rule sets, groups, profiles, devices, ...) can no longer be
Windows devices either (CON, NUL, COM1, ...): a file named so is the
device.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 5.5 committed 2026-10-27 13:05:22 +03:00
1 parent 610e36a28b
commit b6e54f963d
4 files changed
+76 -18

No files matched your search

+1 -1
View File
@@ -21,7 +21,7 @@ pub use misc::*;
pub use privilege::privileged_changes; pub use privilege::privileged_changes;
pub use proxy::*; pub use proxy::*;
pub use tunnels::*; pub use tunnels::*;
pub use validate::{Issue, Severity, validate}; pub use validate::{Issue, Severity, path_name_ok, validate};
pub use zapret::*; pub use zapret::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
+33 -6
View File
@@ -50,11 +50,20 @@ fn tag_pattern_ok(tag: &str) -> bool {
/// A name that becomes part of a file path, a Windows service name or an adapter name: /// A name that becomes part of a file path, a Windows service name or an adapter name:
/// letters, digits, `.`, `_` and `-`, not starting with a dot, at most 64 characters. /// letters, digits, `.`, `_` and `-`, not starting with a dot, at most 64 characters.
pub(crate) fn path_name_ok(name: &str) -> bool { pub fn path_name_ok(name: &str) -> bool {
!name.is_empty() !name.is_empty()
&& name.len() <= 64 && name.len() <= 64
&& !name.starts_with('.') && !name.starts_with('.')
&& name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')) && name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
&& !windows_device(name)
}
/// CON, NUL, COM1 and the rest: on Windows a file named so (whatever its extension) is the
/// device.
fn windows_device(name: &str) -> bool {
let stem = name.split('.').next().unwrap_or("").to_ascii_uppercase();
matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL")
|| (stem.len() == 4 && (stem.starts_with("COM") || stem.starts_with("LPT")) && stem.as_bytes()[3].is_ascii_digit())
} }
/// A geosite or geoip name: "geolocation-!cn" and "google@cn" among them, never a path /// A geosite or geoip name: "geolocation-!cn" and "google@cn" among them, never a path
@@ -477,13 +486,14 @@ fn tunnels(cfg: &Config, v: &mut Issues) {
} }
let wl = &cfg.whitelist_bypass; let wl = &cfg.whitelist_bypass;
// Checked on or off: `proxy-ctl wl` names files after them either way.
for name in wl.joiners.keys().chain(wl.creators.keys()) {
if !path_name_ok(name) {
v.error(format!("whitelistBypass.{name}"), "a creator or joiner name takes letters, digits, '.', '_' and '-', and no leading dot");
}
}
if wl.enable { if wl.enable {
v.requires(!wl.joiners.is_empty(), proxy_on, "whitelistBypass.joiners", "whitelistBypass.joiners", "proxy.enable = true"); v.requires(!wl.joiners.is_empty(), proxy_on, "whitelistBypass.joiners", "whitelistBypass.joiners", "proxy.enable = true");
for name in wl.joiners.keys().chain(wl.creators.keys()) {
if !path_name_ok(name) {
v.error(format!("whitelistBypass.{name}"), "a creator or joiner name takes letters, digits, '.', '_' and '-', and no leading dot");
}
}
for (name, j) in &wl.joiners { for (name, j) in &wl.joiners {
if j.platform == crate::config::WlPlatform::Vk { if j.platform == crate::config::WlPlatform::Vk {
v.error(format!("whitelistBypass.joiners.{name}.platform"), "VK has no joiner here"); v.error(format!("whitelistBypass.joiners.{name}.platform"), "VK has no joiner here");
@@ -756,6 +766,23 @@ mod tests {
use super::*; use super::*;
use crate::config::{Group, Outbound, RoutingRule}; use crate::config::{Group, Outbound, RoutingRule};
#[test]
fn names_are_plain_file_names_and_never_devices() {
for ok in ["laptop", "wl", "a.b_c-1", "COM", "console", "lpt10", "nul-ish"] {
assert!(path_name_ok(ok), "{ok}");
}
for bad in ["", ".hidden", "a/b", r"a\b", "C:x", "..", "CON", "con.txt", "Nul", "PRN", "aux.json", "COM1", "lpt9.link"] {
assert!(!path_name_ok(bad), "{bad}");
}
}
#[test]
fn whitelist_bypass_names_are_checked_while_it_is_off() {
let mut cfg = Config::default();
cfg.whitelist_bypass.creators.insert(r"C:\Windows\x".into(), serde_json::from_value(serde_json::json!({ "platform": "wbstream" })).unwrap());
assert!(errors(&cfg).iter().any(|e| e.starts_with("whitelistBypass.")), "{:?}", errors(&cfg));
}
fn errors(cfg: &Config) -> Vec<String> { fn errors(cfg: &Config) -> Vec<String> {
validate(cfg) validate(cfg)
.into_iter() .into_iter()
+12 -3
View File
@@ -527,7 +527,10 @@ pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response {
if login.len() > 1 << 20 || serde_json::from_str::<Value>(&login).is_err() { if login.len() > 1 << 20 || serde_json::from_str::<Value>(&login).is_err() {
return Response::err("not a cookies export (or a login): not valid JSON"); return Response::err("not a cookies export (or a login): not valid JSON");
} }
let file = crate::wl::state_dir(s.paths()).join(format!("{name}.cookies.json")); let file = match crate::wl::state_file(s.paths(), &name, ".cookies.json") {
Ok(f) => f,
Err(e) => return Response::err(format!("{e:#}")),
};
if let Err(e) = crate::wl::write_private(&file, login.as_bytes()) { if let Err(e) = crate::wl::write_private(&file, login.as_bytes()) {
return Response::err(format!("{e:#}")); return Response::err(format!("{e:#}"));
} }
@@ -544,7 +547,10 @@ pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response {
Ok(l) if l == link => l, Ok(l) if l == link => l,
_ => return Response::err("a call link is one word: a room id, a slug or a URL"), _ => return Response::err("a call link is one word: a room id, a slug or a URL"),
}; };
let file = crate::wl::state_dir(s.paths()).join(format!("{name}.join")); let file = match crate::wl::state_file(s.paths(), &name, ".join") {
Ok(f) => f,
Err(e) => return Response::err(format!("{e:#}")),
};
if let Err(e) = crate::wl::write_private(&file, format!("{link}\n").as_bytes()) { if let Err(e) = crate::wl::write_private(&file, format!("{link}\n").as_bytes()) {
return Response::err(format!("{e:#}")); return Response::err(format!("{e:#}"));
} }
@@ -559,7 +565,10 @@ pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response {
if c.link_file.is_some() { if c.link_file.is_some() {
return Response::err(format!("{name} rejoins the call its linkFile sets: change that instead")); return Response::err(format!("{name} rejoins the call its linkFile sets: change that instead"));
} }
let file = crate::wl::state_dir(s.paths()).join(format!("{name}.link")); let file = match crate::wl::state_file(s.paths(), &name, ".link") {
Ok(f) => f,
Err(e) => return Response::err(format!("{e:#}")),
};
if let Err(e) = std::fs::remove_file(&file) if let Err(e) = std::fs::remove_file(&file)
&& e.kind() != std::io::ErrorKind::NotFound && e.kind() != std::io::ErrorKind::NotFound
{ {
+30 -8
View File
@@ -29,6 +29,20 @@ fn sessions_dir(paths: &Paths) -> PathBuf {
paths.root.join("whitelist-bypass-sessions") paths.root.join("whitelist-bypass-sessions")
} }
/// `name`'s file in `dir`: a plain name there, checked here again whatever let it through (on
/// Windows, joining an absolute path replaces the directory).
fn named(dir: &Path, name: &str, suffix: &str) -> Result<PathBuf> {
if !ps_core::config::path_name_ok(name) {
bail!("'{name}' is not a creator or joiner name");
}
Ok(dir.join(format!("{name}{suffix}")))
}
/// `name`'s file in the state directory: `.join`, `.cookies.json` or `.link`.
pub fn state_file(paths: &Paths, name: &str, suffix: &str) -> Result<PathBuf> {
named(&state_dir(paths), name, suffix)
}
fn resources(r: WlResources) -> &'static str { fn resources(r: WlResources) -> &'static str {
match r { match r {
WlResources::Moderate => "moderate", WlResources::Moderate => "moderate",
@@ -59,13 +73,13 @@ pub fn units(
proxy_login: Option<(String, String)>, proxy_login: Option<(String, String)>,
) -> (Vec<UnitSpec>, Vec<String>) { ) -> (Vec<UnitSpec>, Vec<String>) {
let w = &cfg.whitelist_bypass; let w = &cfg.whitelist_bypass;
let state = state_dir(paths);
let mut units = Vec::new(); let mut units = Vec::new();
let mut waiting = Vec::new(); let mut waiting = Vec::new();
for (i, (tag, j)) in w.joiners.iter().enumerate() { for (i, (tag, j)) in w.joiners.iter().enumerate() {
let port = ports::WL_JOINER_BASE + i as u16; let port = ports::WL_JOINER_BASE + i as u16;
// The link `wl join` gave wins over linkFile. // The link `wl join` gave wins over linkFile.
let link = std::fs::read_to_string(state.join(format!("{tag}.join"))) let link = state_file(paths, tag, ".join")
.and_then(|f| Ok(std::fs::read_to_string(f)?))
.ok() .ok()
.or_else(|| j.link_file.as_ref().and_then(|f| std::fs::read_to_string(f).ok())) .or_else(|| j.link_file.as_ref().and_then(|f| std::fs::read_to_string(f).ok()))
.and_then(|t| clean_link(&t).ok()); .and_then(|t| clean_link(&t).ok());
@@ -102,7 +116,7 @@ pub fn units(
/// The call a creator made and keeps rejoining: the last line it wrote. /// The call a creator made and keeps rejoining: the last line it wrote.
pub fn last_link(paths: &Paths, name: &str) -> Option<String> { pub fn last_link(paths: &Paths, name: &str) -> Option<String> {
let text = std::fs::read_to_string(state_dir(paths).join(format!("{name}.link"))).ok()?; let text = std::fs::read_to_string(state_file(paths, name, ".link").ok()?).ok()?;
text.lines().map(str::trim).rfind(|l| !l.is_empty()).map(str::to_owned) text.lines().map(str::trim).rfind(|l| !l.is_empty()).map(str::to_owned)
} }
@@ -129,12 +143,11 @@ fn creator(
proxy_login: Option<(String, String)>, proxy_login: Option<(String, String)>,
) -> Result<Option<UnitSpec>> { ) -> Result<Option<UnitSpec>> {
let program = program(&format!("headless-{}-creator", c.platform.as_str()))?; let program = program(&format!("headless-{}-creator", c.platform.as_str()))?;
let state = state_dir(paths);
let sessions = sessions_dir(paths); let sessions = sessions_dir(paths);
std::fs::create_dir_all(&state)?; std::fs::create_dir_all(state_dir(paths))?;
std::fs::create_dir_all(&sessions)?; std::fs::create_dir_all(&sessions)?;
let given = state.join(format!("{name}.cookies.json")); let given = state_file(paths, name, ".cookies.json")?;
let cookies = sessions.join(format!("{name}.cookies.json")); let cookies = named(&sessions, name, ".cookies.json")?;
// A login `wl auth` left replaces the working copy, then goes. // A login `wl auth` left replaces the working copy, then goes.
if given.is_file() { if given.is_file() {
write_private(&cookies, &std::fs::read(&given)?)?; write_private(&cookies, &std::fs::read(&given)?)?;
@@ -147,7 +160,7 @@ fn creator(
if !cookies.is_file() { if !cookies.is_file() {
return Ok(None); return Ok(None);
} }
let links = state.join(format!("{name}.link")); let links = state_file(paths, name, ".link")?;
// linkFile's call, or the last one it made (empty: it makes one). // linkFile's call, or the last one it made (empty: it makes one).
let link = match &c.link_file { let link = match &c.link_file {
Some(f) => clean_link(&std::fs::read_to_string(f).with_context(|| format!("reading {f}"))?)?, Some(f) => clean_link(&std::fs::read_to_string(f).with_context(|| format!("reading {f}"))?)?,
@@ -196,4 +209,13 @@ mod tests {
assert!(clean_link(" \n").is_err()); assert!(clean_link(" \n").is_err());
assert!(clean_link("a\u{7}b").is_err()); assert!(clean_link("a\u{7}b").is_err());
} }
#[test]
fn files_are_only_plain_names_in_the_state_directory() {
let paths = Paths::new("state");
assert_eq!(state_file(&paths, "laptop", ".link").unwrap(), std::path::Path::new("state/whitelist-bypass/laptop.link"));
for bad in [r"C:\Windows\System32\x", "/etc/x", "../x", "..", "a/b", r"a\b", "CON", "nul", "COM1", ""] {
assert!(state_file(&paths, bad, ".link").is_err(), "{bad}");
}
}
} }