Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 59 additions & 9 deletions d3d12/crates/leonida-lua/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -509,15 +509,20 @@ fn write_file(root: &Path, name: &str, data: &[u8]) -> std::result::Result<(), S
if data.len() > MAX_WRITE {
return Err(format!("a write is at most {MAX_WRITE} bytes"));
}
let lower = name.to_ascii_lowercase();
let extension = lower.rsplit_once('.').map_or("", |(_, e)| e);
if lower == "mod.json"
|| [
"exe", "dll", "bat", "cmd", "com", "ps1", "vbs", "msi", "scr", "lnk", "sys", "reg",
"hta", "jar",
]
.contains(&extension)
{
let rel = safe_relative(name)?;
let file_name = rel.file_name().and_then(|f| f.to_str());
let is_manifest = rel.parent().is_none_or(|p| p.as_os_str().is_empty())
&& file_name.is_some_and(|f| f.eq_ignore_ascii_case("mod.json"));
let blocked_extension = file_name
.and_then(|f| f.rsplit_once('.'))
.is_some_and(|(_, e)| {
[
"exe", "dll", "bat", "cmd", "com", "ps1", "vbs", "msi", "scr", "lnk", "sys", "reg",
"hta", "jar",
]
.contains(&e.to_ascii_lowercase().as_str())
});
if is_manifest || blocked_extension {
return Err(format!("`{name}` cannot be written by a mod"));
}
let path = inside(root, name)?;
Expand Down Expand Up @@ -915,3 +920,48 @@ fn memory_table(lua: &Lua, shared: &Rc_<Shared>, platform: &Rc<dyn Platform>) ->
)?;
Ok(m)
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn write_file_blocks_manifest_and_executables_after_path_normalization() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("mod.json"), r#"{"name":"orig"}"#).unwrap();

for bad in [
"mod.json",
"MOD.JSON",
"mod.json/",
"mod.json/.",
"evil.exe",
"evil.exe/",
"evil.exe/.",
".exe",
".exe/",
"sub/.bat",
"sub/.ps1/.",
"sub/evil.dll/",
"sub/evil.bat/.",
"sub/./evil.ps1",
] {
assert!(
write_file(dir.path(), bad, b"pwned").is_err(),
"`{bad}` must be refused by write_file"
);
}

assert_eq!(
std::fs::read_to_string(dir.path().join("mod.json")).unwrap(),
r#"{"name":"orig"}"#
);
assert!(!dir.path().join("evil.exe").exists());
assert!(!dir.path().join(".exe").exists());
assert!(!dir.path().join("sub").join(".bat").exists());
assert!(!dir.path().join("sub").join(".ps1").exists());
assert!(!dir.path().join("sub").join("evil.dll").exists());
assert!(!dir.path().join("sub").join("evil.bat").exists());
assert!(!dir.path().join("sub").join("evil.ps1").exists());
}
}
Loading