use crate::command::Command;
use crate::error::Error;
#[skuld::test]
fn the_stream_reading_subsumes_the_shell_reading() {
let mut missed = Vec::new();
for_every_string(6, |probe| {
if super::streams::is_batch_by_shell(probe) && !super::is_batch_program(probe) {
missed.push(probe.to_string());
}
});
assert_eq!(
missed,
Vec::<String>::new(),
"the shell reads these as batch names and the stream reading let them through"
);
}
#[skuld::test]
fn reject_batch_path_on_windows_refuses_every_spelling_that_reaches_a_batch_file() {
use std::path::Path;
for probe in [
"x.bat",
"x.CMD",
r"C:\dir\x.bat",
"x.bat ",
"x.bat.",
r"x.bat\y\..",
"x.bat/y/..",
r"C:\dir\x.bat\y\..",
r"..\x.bat\y\..",
r"x.cmd\y\..",
r"y\x.bat\...\..",
r"y\x.bat\.. \..",
r"y\x.bat\ \..",
r"y\x.bat\. \..",
r"x.bat\...",
r"x.bat\ ",
r"x.bat\.. .",
"x.bat:s",
"x.bat:",
"x.bat: ",
"C:x.bat:s",
"x.exe:payload.bat",
"x.exe:payload.bat:",
"x.exe:payload.bat:$DATA",
".bat",
r"\\srv\x.bat",
r"\\srv\x.bat\..",
"//srv/x.bat/..",
r"\/srv\x.cmd\..",
"\\\\srv\\x.bat\\.. ",
r"\\srv\x.bat\y\..\..",
r"\\srv\x.bat \..",
r"\\srv\x.bat.\..",
r"\\srv\x.bat:s\..",
r"\\srv\x.bat\y\..\..\..",
r"\\srv\share\x.bat\y\..",
r"\\server",
r"\\...\x.bat\y\..",
r"\\x.bat\y\..",
r"\\.\x.bat\y\..",
"//?/x.bat/y/..",
r"\\.\C:\..\..\x.bat",
"//?/C:/dir/x.bat.",
r"\\?/C:\dir\x.bat.",
"//?/C:/dir/x.bat/y/..",
r"\\.\x.bat\..",
r"\\.\C:\..",
r"\\.\y\..",
r"\\.\x.bat\y\..\..",
"//./y/..",
"//?/C:/..",
r"\\?/C:\..",
] {
assert!(
super::reject_batch_path_on(Path::new(probe), true).is_err(),
"{probe:?} reaches a batch file on Windows"
);
}
for probe in [
"x.exe",
"batch",
"x.batch",
r"C:\dir\tool.exe",
r"C:\dir\x.bat\..",
r"x.bat\y\...",
r"x.bat\y\.. .",
r"x.bat\y\....",
r"x.bat\y\.. ..",
r"x.bat\y\ ",
r"x.bat\y\.. ",
r"x.bat\y\.. ",
r"a\...\..\b",
r"x.bat\y\...\..",
r"x.bat\y\.. \..",
r"a\...\..",
r"x\ ",
r"\\server\share",
r"\\server\share\..",
r"\\server\share\x.bat\..",
r"\\server\share\tool.exe",
r"\\.\C:\x.bat\..",
r"\\.\pipe\x.bat\..",
r"\\.\C:",
"//./C:/...",
r"\\.\C:\tool.exe",
"//?/C:/dir/tool.exe",
] {
assert!(
super::reject_batch_path_on(Path::new(probe), true).is_ok(),
"{probe:?} names no batch file and must stay spawnable"
);
}
}
#[skuld::test]
fn reject_batch_path_on_windows_refuses_a_path_that_names_no_file_of_its_own() {
use std::path::Path;
for probe in [
r"x\..",
"..",
".",
r"a\b\..\..",
r"x.bat\..",
"x.bat/..",
" ..",
"....",
r" \ ",
r"\x\..",
r"C:\x\..",
"x:.",
"C:",
"c:",
"",
"/",
r"C:\",
] {
assert!(
super::reject_batch_path_on(Path::new(probe), true).is_err(),
"{probe:?} names no file of its own and resolves to a directory Windows picks"
);
}
}
#[skuld::test]
fn the_refusal_advises_the_fix_for_the_reason_it_refused() {
use std::path::Path;
let detail = |probe: &str| match super::reject_batch_path_on(Path::new(probe), true) {
Err(Error::Unsupported { detail, .. }) => detail,
other => panic!("{probe:?} must be refused, got {other:?}"),
};
for probe in [
r"x.bat\y\..",
"x.bat",
r"C:\bin\x.exe:p.bat",
r"\\?\C:\x.bat",
r"x.bat\...\..",
] {
assert!(
detail(probe).contains("cmd.exe batch escaping is not implemented"),
"{probe:?} reaches a batch file, so it must advise the cmd.exe route: {}",
detail(probe)
);
}
let invalid = |probe: &str| invalid_input_message(super::reject_batch_path_on(Path::new(probe), true));
for probe in [r"x\..", ".", "C:", r"\\.\x.bat\..", ""] {
assert!(
invalid(probe).contains("names no file of its own"),
"{probe:?} names no file, so it must advise naming the executable: {}",
invalid(probe)
);
}
assert!(
invalid(r"\\?\C:\dir\..").contains("never normalised"),
"a verbatim `..` must not be explained by the current directory: {}",
invalid(r"\\?\C:\dir\..")
);
}
#[skuld::test]
fn a_drive_prefix_is_one_only_at_the_front_of_the_path() {
use std::path::Path;
for probe in ["C:", "c:", "a:", r"C:\", "x:."] {
assert!(
super::reject_batch_path_on(Path::new(probe), true).is_err(),
"{probe:?} is a bare drive prefix and names no file"
);
}
for probe in [r"C:\bin\a:", r"bin\a:", r"bin\C:", "x.exe:", r"\a:"] {
assert!(
super::reject_batch_path_on(Path::new(probe), true).is_ok(),
"{probe:?} names a file and must stay spawnable"
);
}
for probe in [r"C:\bin\a.bat:", r"C:\bin\x.exe:p.bat"] {
assert!(
super::reject_batch_path_on(Path::new(probe), true).is_err(),
"{probe:?} still reaches a batch file"
);
}
}
#[skuld::test]
fn any_one_utf16_unit_before_a_colon_is_a_drive_prefix() {
use std::path::Path;
for probe in [
"1:",
"1:.",
"1:..",
r"1:\",
r"1:\x.bat\..",
"é:",
"é:..",
".:",
"::",
"\u{FFFD}:..",
] {
assert!(
super::reject_batch_path_on(Path::new(probe), true).is_err(),
"{probe:?} is drive-relative and names no file"
);
}
for probe in ["é:x.bat", r"1:\x.bat", "1:x.bat:s", r"\\.\é:\..\x.bat"] {
assert!(
super::reject_batch_path_on(Path::new(probe), true).is_err(),
"{probe:?} reaches a batch file"
);
}
for probe in [
"𝒳:..",
"𝒳:",
r"x\1:",
r"x\é:..",
r"\\.\é:",
r"1:\tool.exe",
r"é:\tool.exe",
] {
assert!(
super::reject_batch_path_on(Path::new(probe), true).is_ok(),
"{probe:?} names a file that is no batch file"
);
}
assert_eq!(
super::streams::ntfs_stream_names("é:x.bat:s").collect::<Vec<_>>(),
["x.bat", "s"]
);
assert_eq!(super::streams::ntfs_stream_names("𝒳:x").collect::<Vec<_>>(), ["𝒳", "x"]);
}
#[cfg(windows)]
#[skuld::test]
fn a_lone_surrogate_before_a_colon_is_a_drive_prefix() {
use std::os::windows::ffi::OsStringExt;
let wide: Vec<u16> = [0xD800].into_iter().chain(":..".encode_utf16()).collect();
let probe = std::ffi::OsString::from_wide(&wide);
assert!(
super::reject_batch_path_on(std::path::Path::new(&probe), true).is_err(),
"a lone surrogate is one unit, so this is drive-relative and names no file"
);
}
#[skuld::test]
fn a_verbatim_path_is_judged_the_way_std_judges_one() {
use std::path::Path;
for probe in [
r"\\?\C:\x.bat",
r"\\?\C:\dir\x.CMD",
r"\\?\C:\dir\x.exe:p.bat",
r"\\?\UNC\server\share\x.bat",
] {
assert!(
super::reject_batch_path_on(Path::new(probe), true).is_err(),
"{probe:?} is what std hands to cmd.exe"
);
}
for probe in [r"\\?\C:\dir\..", r"\\?\C:\.."] {
assert!(
super::reject_batch_path_on(Path::new(probe), true).is_err(),
"{probe:?} names no file even verbatim"
);
}
for probe in [r"\\?\C:\x.bat.", r"\\?\C:\x.bat "] {
assert!(
super::reject_batch_path_on(Path::new(probe), true).is_err(),
"{probe:?} trims to a batch name"
);
}
for probe in [
r"\\?\C:\dir\....",
r"\\?\C:\dir\...",
r"\\?\C:\dir\ ",
r"\\?\C:\dir\x ",
r"\\?\C:\dir\tool.exe",
r"\\?\C:\dir\.",
r"\\?\C:\dir\",
] {
assert!(
super::reject_batch_path_on(Path::new(probe), true).is_ok(),
"{probe:?} is a loadable image on a measured Windows runner"
);
}
for plain in [r"C:\x.bat.", r"C:\x.bat "] {
assert!(
super::reject_batch_path_on(Path::new(plain), true).is_err(),
"{plain:?} still resolves to the batch file"
);
}
for stream in [
r"C:\x.bat:s",
r"C:\x.bat:",
r"C:\x.bat::$DATA",
r"C:\x.bat.:s",
r"C:\x.exe:p.bat:$DATA",
] {
for probe in [stream.to_string(), format!(r"\\?\{stream}")] {
assert!(
super::reject_batch_path_on(Path::new(&probe), true).is_err(),
"{probe:?} is refused until kernelbase is measured"
);
}
}
for probe in [r"\\?\C:\x.exe:s", r"\\?\C:\dir\x.exe::$DATA"] {
assert!(
super::reject_batch_path_on(Path::new(probe), true).is_ok(),
"{probe:?} is a stream of no batch file"
);
}
}
#[skuld::test]
fn reject_batch_path_on_posix_refuses_nothing_but_a_nul() {
use std::path::Path;
for probe in [
"x.bat",
"x.CMD",
"dir/x.bat",
"x.exe:payload.bat",
r"x.bat\y\..",
r"C:\dir\x.bat",
r"\\?\C:\x.bat",
r"\\srv\x.bat\..",
"report.cmd:archived",
"x.bat ",
"backup.cmd.",
".bat",
"",
"/",
".",
"x/..",
] {
assert!(
super::reject_batch_path_on(Path::new(probe), false).is_ok(),
"{probe:?} is a legal POSIX program token and must stay spawnable"
);
}
}
#[skuld::test]
fn the_refusal_advises_a_route_that_is_not_itself_refused() {
let err = super::reject_batch_path_on(std::path::Path::new("x.bat"), true)
.expect_err("the first token of `commandline(\"x.bat --flag\")` is refused");
let Error::Unsupported { detail, .. } = &err else {
panic!("got {err:?}")
};
assert!(
!detail.contains("use .commandline() to pass"),
"the message advises the very call that just failed: {detail}"
);
super::reject_batch_path_on(std::path::Path::new("cmd.exe"), true).expect("the advised route must not be refused");
#[cfg(windows)]
{
let mut looped = Command::new();
looped.commandline("x.bat --flag");
crate::child::spawn::build_std_command(&looped).expect_err("commandline() alone is still gated");
let mut advised = Command::new();
advised
.executable("cmd.exe")
.commandline(r#"cmd.exe /c "x.bat" --flag"#);
assert!(crate::child::spawn::routes_to_raw_backend(&advised));
crate::child::spawn::windows_raw::reject_batch_program(&advised)
.expect("the advised route must not be refused");
}
}
fn with_interior_nul(prefix: &str, suffix: &str) -> std::ffi::OsString {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStringExt;
let mut bytes = prefix.as_bytes().to_vec();
bytes.push(0);
bytes.extend_from_slice(suffix.as_bytes());
std::ffi::OsString::from_vec(bytes)
}
#[cfg(windows)]
{
use std::os::windows::ffi::OsStringExt;
let units: Vec<u16> = prefix.encode_utf16().chain([0]).chain(suffix.encode_utf16()).collect();
std::ffi::OsString::from_wide(&units)
}
}
fn extension_of(token: &std::ffi::OsStr) -> Option<String> {
std::path::Path::new(token)
.extension()
.map(|e| e.to_string_lossy().into_owned())
}
fn unsupported_op<T: std::fmt::Debug>(r: Result<T, Error>) -> String {
match r {
Err(Error::Unsupported { op, .. }) => op,
other => panic!("expected Unsupported, got {other:?}"),
}
}
fn invalid_input_message<T: std::fmt::Debug>(r: Result<T, Error>) -> String {
match r {
Err(Error::Io(e)) if e.kind() == std::io::ErrorKind::InvalidInput => e.to_string(),
other => panic!("expected Io(InvalidInput), got {other:?}"),
}
}
fn on_win32(token: &std::ffi::OsStr) -> Result<(), Error> {
super::reject_batch_path_on(std::path::Path::new(token), true)
}
fn on_posix(token: &std::ffi::OsStr) -> Result<(), Error> {
super::reject_batch_path_on(std::path::Path::new(token), false)
}
#[skuld::test]
fn an_interior_nul_is_refused_on_the_win32_verdict_too() {
let nul_then_bat = with_interior_nul("setup", ".bat");
let bat_then_nul = with_interior_nul("setup.bat", "junk");
assert_eq!(extension_of(&nul_then_bat), Some("bat".to_owned()));
assert_ne!(extension_of(&bat_then_nul), Some("bat".to_owned()));
for token in [&nul_then_bat, &bat_then_nul] {
let msg = invalid_input_message(on_win32(token));
assert!(msg.contains("NUL"), "the refusal must name the NUL: {msg}");
assert!(
!msg.contains('\0'),
"the refusal must not carry a raw NUL into logs: {msg:?}"
);
}
}
#[skuld::test]
fn a_nul_bearing_program_is_diagnosed_as_a_nul_off_win32() {
for token in [
with_interior_nul("x.bat", "junk"),
with_interior_nul("x", ".bat"),
with_interior_nul("/usr/bin/ls", "junk"),
] {
let msg = invalid_input_message(on_posix(&token));
for wrong in ["cmd.exe", "CVE-2024-24576", "windows", "Win32"] {
assert!(
!msg.contains(wrong),
"a POSIX refusal must not mention {wrong:?}: {msg}"
);
}
assert!(msg.contains("NUL"), "the refusal must name the NUL: {msg}");
assert!(
!msg.contains('\0'),
"the refusal must not carry a raw NUL into logs: {msg:?}"
);
}
}
#[skuld::test]
fn each_verdict_gives_the_nul_refusal_its_own_reason() {
let bat_then_nul = with_interior_nul("x.bat", "junk");
assert!(invalid_input_message(on_win32(&bat_then_nul)).contains("truncate"));
assert!(!invalid_input_message(on_posix(&bat_then_nul)).contains("truncate"));
}
#[skuld::test]
fn the_gate_wrapper_asks_for_this_hosts_verdict() {
let bat_then_nul = with_interior_nul("setup.bat", "junk");
let nul_then_bat = with_interior_nul("setup", ".bat");
let via_host = |t: &std::ffi::OsStr| super::reject_batch_path(std::path::Path::new(t));
let clean_bat = std::ffi::OsString::from(r"C:\tools\setup.bat");
if cfg!(windows) {
assert!(unsupported_op(via_host(&clean_bat)).contains("setup.bat"));
} else {
assert!(via_host(&clean_bat).is_ok(), "no cmd.exe here to blame");
}
for token in [&bat_then_nul, &nul_then_bat] {
let msg = invalid_input_message(via_host(token));
assert!(msg.contains("NUL"), "the refusal must name the NUL: {msg}");
}
}
#[skuld::test]
fn a_clean_batch_program_is_a_win32_verdict_only() {
let token = std::ffi::OsString::from(r"C:\tools\setup.bat");
assert!(unsupported_op(on_win32(&token)).contains("setup.bat"));
assert!(
on_posix(&token).is_ok(),
"off Win32 a .bat is judged by the host that will actually run it"
);
}
#[cfg(unix)]
#[skuld::test]
fn a_posix_host_runs_its_own_executable_named_bat() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().expect("tempdir");
let script = dir.path().join("deploy.bat");
{
let _guard = crate::child::spawn::spawn_lock();
std::fs::write(&script, "#!/bin/sh\nexit 7\n").expect("write");
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).expect("chmod");
}
let mut c = Command::new();
c.args([script.as_os_str()]);
let child = c.spawn().expect("a .bat this host can run must not be refused");
assert_eq!(
child.wait().expect("wait").code(),
Some(7),
"the host ran the script, so its own exit code must come back"
);
}
#[skuld::test]
fn the_std_backend_judges_the_program_token_the_caller_named() {
let mut c = Command::new();
c.args([with_interior_nul(r"C:\tools\setup.bat", "junk")]);
let msg = invalid_input_message(crate::child::spawn::build_std_command(&c));
assert!(
!msg.contains('\0'),
"the refusal must not carry a raw NUL into logs: {msg:?}"
);
}
#[skuld::test]
fn the_std_backend_does_not_blame_the_batch_vector_for_a_truncated_prefix() {
let mut c = Command::new();
c.args([with_interior_nul(r"C:\tools\setup", ".bat")]);
invalid_input_message(crate::child::spawn::build_std_command(&c));
}
#[skuld::test]
fn the_gate_wrapper_carries_the_hosts_verdict_into_the_win32_only_spellings() {
use std::path::Path;
let trailing_space = super::reject_batch_path(Path::new("x.bat "));
let leading_dot_only = super::reject_batch_path(Path::new(".bat"));
if cfg!(windows) {
assert!(
trailing_space.is_err(),
"Windows must refuse `x.bat ` — NTFS reaches x.bat"
);
assert!(
leading_dot_only.is_err(),
"Windows must refuse `.bat` — PathFindExtension reads .bat"
);
} else {
assert!(
trailing_space.is_ok(),
"POSIX must keep `x.bat ` spawnable — a legal filename"
);
assert!(
leading_dot_only.is_ok(),
"POSIX must keep `.bat` spawnable — no extension there"
);
}
}
const ALPHABET: [char; 12] = ['x', '.', 'b', 'a', 't', 'c', 'm', 'd', ' ', ':', '\\', '/'];
fn for_every_string(max_len: u32, mut probe: impl FnMut(&str)) {
let mut buf = String::new();
for len in 0..=max_len {
for mut index in 0..ALPHABET.len().pow(len) {
buf.clear();
for _ in 0..len {
buf.push(ALPHABET[index % ALPHABET.len()]);
index /= ALPHABET.len();
}
probe(&buf);
}
}
}
pub(super) fn the_extension_rule_this_replaced(prog: &std::path::Path) -> bool {
let Some(name) = prog.file_name() else { return false };
let name = name.to_string_lossy();
match name.rfind('.') {
None | Some(0) => false,
Some(dot) => {
let ext = name[dot + 1..].to_ascii_lowercase();
ext == "bat" || ext == "cmd"
}
}
}
pub(super) fn verbatim_extension_rule_this_replaced(text: &str) -> bool {
let name = text.rsplit('\\').next().expect("rsplit yields at least one piece");
match name.rfind('.') {
None | Some(0) => false,
Some(dot) => {
let ext = name[dot + 1..].to_ascii_lowercase();
ext == "bat" || ext == "cmd"
}
}
}
#[skuld::test]
fn the_gate_never_accepts_what_the_rule_it_replaced_refused() {
let mut newly_accepted = Vec::new();
let mut posix_refused = Vec::new();
let mut batch_accepted = Vec::new();
for_every_string(5, |probe| {
let path = std::path::Path::new(probe);
let replaced = the_extension_rule_this_replaced(path);
let windows = super::reject_batch_path_on(path, true).is_err();
if replaced && !windows {
newly_accepted.push(probe.to_string());
}
if super::reject_batch_path_on(path, false).is_err() {
posix_refused.push(probe.to_string());
}
if (probe.ends_with(".bat") || probe.ends_with(".cmd")) && !windows {
batch_accepted.push(probe.to_string());
}
});
assert_eq!(newly_accepted, Vec::<String>::new(), "refused before, accepted now");
assert_eq!(
posix_refused,
Vec::<String>::new(),
"the POSIX verdict refuses nothing but a NUL"
);
assert_eq!(
batch_accepted,
Vec::<String>::new(),
"accepted a name ending in a batch extension"
);
}
#[skuld::test]
fn a_normalised_batch_path_is_refused_by_suffix_on_every_stream_piece() {
for p in [
r"C:\t\.bat",
r"C:\t\SETUP.CMD",
r"C:\t\x.exe:payload.bat",
r"C:\t\x.bat::$DATA",
r"C:\t\x.bat.:s",
r"C:\t\x.bat :s",
r"C:\t\x.bat.",
r"C:\t\x.bat ",
r"C:\t\x.cmd. .",
r"C:\t\a/x.bat.",
] {
for probe in [p.to_string(), format!(r"\\?\{p}")] {
assert_eq!(
unsupported_op(super::reject_batch_path_on(std::path::Path::new(&probe), true)),
format!("running {probe}")
);
}
}
for p in [
r"C:\t\setup.exe",
r"C:\t\setup.bat.exe",
r"C:\t.bat\setup.exe",
r"C:\t\batch",
] {
for probe in [p.to_string(), format!(r"\\?\{p}")] {
assert!(
super::reject_batch_path_on(std::path::Path::new(&probe), true).is_ok(),
"{probe}"
);
}
}
}
#[cfg(windows)]
fn std_routed(args: &[&str], lines: &[&str]) -> Vec<(String, Command)> {
let mut out = Vec::new();
for &n in args {
let mut c = Command::new();
c.args([n]);
out.push((format!("args([{n:?}])"), c));
}
for &l in lines {
let mut c = Command::new();
c.commandline(l);
out.push((format!("commandline({l:?})"), c));
}
for (via, c) in &out {
assert!(
!crate::child::spawn::routes_to_raw_backend(c),
"{via} must take the std route"
);
}
out
}
#[cfg(windows)]
#[skuld::test]
fn the_std_route_refuses_a_batch_only_normalisation_exposes() {
for (via, c) in std_routed(&["x.bat.", "x.bat ", ".bat"], &["x.bat. a&b"]) {
match crate::child::spawn::build_std_command(&c) {
Err(Error::Unsupported { .. }) => {}
other => panic!("{via}: expected Unsupported, got {:?}", other.map(|_| "a command")),
}
}
}
#[cfg(windows)]
#[skuld::test]
fn the_std_route_accepts_an_exe_named_like_a_batch() {
for (via, c) in std_routed(&["x.bat.exe", "tool.exe"], &["x.bat.exe a&b"]) {
if let Err(e) = crate::child::spawn::build_std_command(&c) {
panic!("{via}: {e:?}");
}
}
}