From e32da83804c7efe15827f073072b6a19214248b1 Mon Sep 17 00:00:00 2001 From: imShangLi Date: Wed, 2 Dec 2026 13:31:21 +0800 Subject: [PATCH 1/3] D3D12-LUA-LINKS-STAY-IN-THE-FOLDER: require and the script refuse a link that leads out require() joined the module name to the mod's folder and asked is_file(), which follows links, and the manifest's script was read the same way: a link inside the folder led to a file outside it, which was then run as Lua in the mod's environment. leonida.read_file and write_file already refused that through inside(); the check now lives in manifest::inside() and every path to a file of the mod's own folder goes through it. --- d3d12/crates/leonida-lua/src/api.rs | 44 +++++++---------- d3d12/crates/leonida-lua/src/manifest.rs | 18 +++++++ d3d12/crates/leonida-lua/src/runtime.rs | 5 +- d3d12/crates/leonida-lua/src/tests.rs | 62 ++++++++++++++++++++++++ 4 files changed, 101 insertions(+), 28 deletions(-) diff --git a/d3d12/crates/leonida-lua/src/api.rs b/d3d12/crates/leonida-lua/src/api.rs index 2294c43ce..59e1f163c 100644 --- a/d3d12/crates/leonida-lua/src/api.rs +++ b/d3d12/crates/leonida-lua/src/api.rs @@ -4,7 +4,7 @@ use std::cell::RefCell; use std::collections::HashSet; -use std::path::{Path, PathBuf}; +use std::path::Path; use std::rc::Rc; use std::time::Instant; @@ -16,7 +16,7 @@ use mlua::{Function, IntoLua, Lua, LuaString, MultiValue, Result, Table, Value, use crate::input::BUTTONS; use crate::keys; -use crate::manifest::safe_relative; +use crate::manifest; use crate::memory::{self, Pattern}; use crate::platform::Platform; use crate::runtime::{Event, Handler, ItemDef, MAX_HANDLERS, PageDef, Shared}; @@ -80,14 +80,23 @@ fn require(lua: &Lua, env: &Table, folder: &Path) -> Result { return Err(err(format!("loop while requiring `{name}`"))); } let path = name.replace('.', "/"); + // A module is a file of the mod's own folder: a link that leads out + // of it is refused, like the files the mod reads. + let mut refusal = None; let found = [format!("{path}.lua"), format!("{path}/init.lua")] .into_iter() - .filter_map(|rel| safe_relative(&rel).ok()) - .map(|rel| folder.join(rel)) + .filter_map(|rel| match manifest::inside(&folder, &rel) { + Ok(p) => Some(p), + Err(why) => { + refusal.get_or_insert(why); + None + } + }) .find(|p| p.is_file()); let result = (|| { - let file = found - .ok_or_else(|| err(format!("module `{name}` not found in the mod's folder")))?; + let file = found.ok_or_else(|| { + err(refusal.unwrap_or_else(|| format!("module `{name}` not found in the mod's folder"))) + })?; let size = std::fs::metadata(&file).map_err(err)?.len(); if size > crate::manifest::MAX_SCRIPT { return Err(err(format!("module `{name}` is too large"))); @@ -479,25 +488,8 @@ fn leonida(lua: &Lua, shared: &Rc_, idx: usize, folder: &Path) -> Result Ok(t) } -/// `root` joined with a plain relative `name`, checked not to leave it. -fn inside(root: &Path, name: &str) -> std::result::Result { - let rel = safe_relative(name)?; - let path = root.join(rel); - // A link or junction inside the folder must not lead out of it. - let canon_root = std::fs::canonicalize(root).map_err(|e| format!("the mod's folder: {e}"))?; - let mut probe = path.as_path(); - while !probe.exists() { - probe = probe.parent().ok_or("no such folder")?; - } - let canon = std::fs::canonicalize(probe).map_err(|e| e.to_string())?; - if !canon.starts_with(&canon_root) { - return Err(format!("`{name}` leads out of the mod's folder")); - } - Ok(path) -} - fn read_file(root: &Path, name: &str) -> std::result::Result, String> { - let path = inside(root, name)?; + let path = manifest::inside(root, name)?; let meta = std::fs::metadata(&path).map_err(|e| format!("{name}: {e}"))?; if !meta.is_file() || meta.len() > MAX_READ { return Err(format!("{name} is not a file of at most {MAX_READ} bytes")); @@ -520,12 +512,12 @@ fn write_file(root: &Path, name: &str, data: &[u8]) -> std::result::Result<(), S { return Err(format!("`{name}` cannot be written by a mod")); } - let path = inside(root, name)?; + let path = manifest::inside(root, name)?; if let Some(parent) = path.parent() { std::fs::create_dir_all(parent).map_err(|e| format!("{name}: {e}"))?; } // Again, now that the folders exist. - let path = inside(root, name)?; + let path = manifest::inside(root, name)?; std::fs::write(&path, data).map_err(|e| format!("{name}: {e}")) } diff --git a/d3d12/crates/leonida-lua/src/manifest.rs b/d3d12/crates/leonida-lua/src/manifest.rs index 9e0382b6e..bf006bb3e 100644 --- a/d3d12/crates/leonida-lua/src/manifest.rs +++ b/d3d12/crates/leonida-lua/src/manifest.rs @@ -72,6 +72,24 @@ fn check_script_path(path: &str) -> Result<(), String> { Ok(()) } +/// `root` joined with a plain relative `name`, checked not to leave it: a +/// link or junction inside the folder must not lead out of it. +pub fn inside(root: &Path, name: &str) -> Result { + let rel = safe_relative(name)?; + let path = root.join(rel); + // A link or junction inside the folder must not lead out of it. + let canon_root = std::fs::canonicalize(root).map_err(|e| format!("the mod's folder: {e}"))?; + let mut probe = path.as_path(); + while !probe.exists() { + probe = probe.parent().ok_or("no such folder")?; + } + let canon = std::fs::canonicalize(probe).map_err(|e| e.to_string())?; + if !canon.starts_with(&canon_root) { + return Err(format!("`{name}` leads out of the mod's folder")); + } + Ok(path) +} + /// Whether `path` is a plain relative path of ordinary names (no `..`, no /// root, no drive, no stream or reserved device syntax): what a mod may name /// inside its folder. diff --git a/d3d12/crates/leonida-lua/src/runtime.rs b/d3d12/crates/leonida-lua/src/runtime.rs index fb4d0f8cb..393b0ca7c 100644 --- a/d3d12/crates/leonida-lua/src/runtime.rs +++ b/d3d12/crates/leonida-lua/src/runtime.rs @@ -250,8 +250,9 @@ impl Runtime { } fn run_script(&mut self, idx: usize, folder: &Path, script: &str) -> Result<(), String> { - let rel = manifest::safe_relative(script)?; - let path = folder.join(rel); + // The script is a file of the mod's own folder: a link that leads out + // of it is refused, like the files the mod reads. + let path = manifest::inside(folder, script)?; let len = std::fs::metadata(&path) .map_err(|e| format!("cannot read {script}: {e}"))? .len(); diff --git a/d3d12/crates/leonida-lua/src/tests.rs b/d3d12/crates/leonida-lua/src/tests.rs index 748c557ec..89e1c34c1 100644 --- a/d3d12/crates/leonida-lua/src/tests.rs +++ b/d3d12/crates/leonida-lua/src/tests.rs @@ -891,6 +891,68 @@ fn require_loads_the_mods_own_modules_once() { ); } +#[test] +fn a_link_out_of_the_mods_folder_is_not_a_module_and_not_a_script() { + // A link that leads out of the mod's folder: the file it names is read + // and run by the old code. + let dir = folder(&[( + "a", + JSON, + r#" + leonida.log("req", pcall(require, "helper")) + "#, + )]); + let at = dir.path().join("a"); + let outside = dir.path().join("outside.lua"); + std::fs::write(&outside, "return {answer = function() return 42 end}").unwrap(); + if !link(&outside, &at.join("helper.lua")) { + // No rights to make a link here: nothing to check. + return; + } + let fake = Fake::new(); + let mut rt = Runtime::new(fake.clone(), Config::default()).unwrap(); + rt.load_dir(dir.path()); + let log = fake.of("a"); + assert!( + log[0].starts_with("req false ") && log[0].contains("leads out of the mod's folder"), + "{log:?}" + ); + + // The same for the script the manifest names. + let dir = folder(&[("b", JSON, "leonida.log('ran')")]); + let at = dir.path().join("b"); + let script = dir.path().join("script.lua"); + std::fs::write(&script, "leonida.log('ran')").unwrap(); + if !link(&script, &at.join("main.lua")) { + return; + } + let fake = Fake::new(); + let mut rt = Runtime::new(fake.clone(), Config::default()).unwrap(); + rt.load_dir(dir.path()); + assert_eq!(fake.of("b"), Vec::::new()); + assert_eq!( + status(&rt, "b"), + crate::runtime::Status::Failed("`main.lua` leads out of the mod's folder".to_owned()) + ); +} + +/// A link from `link` to `target`, when this machine allows one. +fn link(target: &std::path::Path, link: &std::path::Path) -> bool { + #[cfg(unix)] + { + std::os::unix::fs::symlink(target, link).is_ok() + } + #[cfg(windows)] + { + std::os::windows::fs::symlink_file(target, link).is_ok() + } + #[cfg(not(any(unix, windows)))] + { + let _ = (target, link); + false + } +} + #[test] fn only_enabled_lua_mods_are_loaded() { let dir = folder(&[ From 9d962894ce37a3f60976df59a8f7345fefb25f2a Mon Sep 17 00:00:00 2001 From: imShangLi Date: Wed, 2 Dec 2026 13:43:13 +0800 Subject: [PATCH 2/3] D3D12-LUA-LINKS-STAY-IN-THE-FOLDER: the doc says the rule holds for require too --- docs/lua-modding.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/lua-modding.md b/docs/lua-modding.md index 6dbfc92bb..c6592be53 100644 --- a/docs/lua-modding.md +++ b/docs/lua-modding.md @@ -159,7 +159,7 @@ require("helper") -- helper.lua (or helper/init.lua; dots are folders) o Files: only the mod's own folder, plain relative paths (no `..`, drive letters, streams or reserved device names; a link that leads out is refused), reads up to 4 MiB, writes up to 1 MiB, never `mod.json` or a program (`.exe`, `.dll`, -`.bat`, ...). There is no `io`. +`.bat`, ...). There is no `io`. The rule holds for `require` and for the script the manifest names, too. ## The sandbox From 856615ce739cebed14c2ddc83cb5e5108aaadfb2 Mon Sep 17 00:00:00 2001 From: imShangLi Date: Wed, 2 Dec 2026 16:26:56 +0800 Subject: [PATCH 3/3] D3D12-LUA-LINKS-STAY-IN-THE-FOLDER: the link tests run on Windows too A directory link (a symlink to a folder on Unix, a junction on Windows) that leads out of the mod's folder is refused too, and a junction needs no rights on Windows, where a file symlink does: the case runs there instead of skipping. The manifest half of the file-link test never ran: `folder()` writes a `main.lua` into the mod, so the link could not be made and the test returned early. The mod is made by hand there now, and the script the manifest names is the link. --- d3d12/crates/leonida-lua/src/tests.rs | 96 ++++++++++++++++++++++++++- 1 file changed, 93 insertions(+), 3 deletions(-) diff --git a/d3d12/crates/leonida-lua/src/tests.rs b/d3d12/crates/leonida-lua/src/tests.rs index 89e1c34c1..67343196d 100644 --- a/d3d12/crates/leonida-lua/src/tests.rs +++ b/d3d12/crates/leonida-lua/src/tests.rs @@ -918,9 +918,12 @@ fn a_link_out_of_the_mods_folder_is_not_a_module_and_not_a_script() { "{log:?}" ); - // The same for the script the manifest names. - let dir = folder(&[("b", JSON, "leonida.log('ran')")]); + // The same for the script the manifest names. The mod is made by hand: the script the manifest + // names is the link, so there is no file of that name to write first. + let dir = tempfile::tempdir().unwrap(); let at = dir.path().join("b"); + std::fs::create_dir_all(&at).unwrap(); + std::fs::write(at.join("mod.json"), JSON).unwrap(); let script = dir.path().join("script.lua"); std::fs::write(&script, "leonida.log('ran')").unwrap(); if !link(&script, &at.join("main.lua")) { @@ -929,13 +932,75 @@ fn a_link_out_of_the_mods_folder_is_not_a_module_and_not_a_script() { let fake = Fake::new(); let mut rt = Runtime::new(fake.clone(), Config::default()).unwrap(); rt.load_dir(dir.path()); - assert_eq!(fake.of("b"), Vec::::new()); + let log = fake.of("b"); + assert!( + log.len() == 1 && log[0].contains("`main.lua` leads out of the mod's folder"), + "{log:?}" + ); assert_eq!( status(&rt, "b"), crate::runtime::Status::Failed("`main.lua` leads out of the mod's folder".to_owned()) ); } +#[test] +fn a_directory_link_out_of_the_mods_folder_is_not_a_module_and_not_a_script() { + // A directory link that leads out of the mod's folder (a symlink to a folder on Unix, a junction on + // Windows): the module under it is read and run by the old code. A junction needs no rights on + // Windows, where a file symlink does, so this case runs there too. + let dir = folder(&[( + "a", + JSON, + r#" + leonida.log("req", pcall(require, "lib.helper")) + "#, + )]); + let at = dir.path().join("a"); + let outside = dir.path().join("outside"); + std::fs::create_dir_all(&outside).unwrap(); + std::fs::write( + outside.join("helper.lua"), + "return {answer = function() return 42 end}", + ) + .unwrap(); + if !dir_link(&outside, &at.join("lib")) { + // No rights to make a link here: nothing to check. + return; + } + let fake = Fake::new(); + let mut rt = Runtime::new(fake.clone(), Config::default()).unwrap(); + rt.load_dir(dir.path()); + let log = fake.of("a"); + assert!( + log[0].starts_with("req false ") && log[0].contains("leads out of the mod's folder"), + "{log:?}" + ); + + // The same for the script the manifest names. + let dir = tempfile::tempdir().unwrap(); + let at = dir.path().join("b"); + std::fs::create_dir_all(&at).unwrap(); + std::fs::write(at.join("mod.json"), r#"{"script": "lib/main.lua"}"#).unwrap(); + let outside = dir.path().join("outside"); + std::fs::create_dir_all(&outside).unwrap(); + std::fs::write(outside.join("main.lua"), "leonida.log('ran')").unwrap(); + if !dir_link(&outside, &at.join("lib")) { + return; + } + let fake = Fake::new(); + let mut rt = Runtime::new(fake.clone(), Config::default()).unwrap(); + rt.load_dir(dir.path()); + let log = fake.of("b"); + assert!( + log.len() == 1 && log[0].contains("`lib/main.lua` leads out of the mod's folder"), + "{log:?}" + ); + assert_eq!( + status(&rt, "b"), + crate::runtime::Status::Failed("`lib/main.lua` leads out of the mod's folder".to_owned()) + ); +} + /// A link from `link` to `target`, when this machine allows one. fn link(target: &std::path::Path, link: &std::path::Path) -> bool { #[cfg(unix)] @@ -953,6 +1018,31 @@ fn link(target: &std::path::Path, link: &std::path::Path) -> bool { } } +/// A link from `link` to the folder `target`, when this machine allows one. On Windows a junction +/// (`mklink /J`), which needs no rights; on Unix a symlink to the folder. +fn dir_link(target: &std::path::Path, link: &std::path::Path) -> bool { + #[cfg(unix)] + { + std::os::unix::fs::symlink(target, link).is_ok() + } + #[cfg(windows)] + { + std::process::Command::new("cmd") + .args(["/C", "mklink", "/J"]) + .arg(link) + .arg(target) + .stdout(std::process::Stdio::null()) + .status() + .map(|s| s.success()) + .unwrap_or(false) + } + #[cfg(not(any(unix, windows)))] + { + let _ = (target, link); + false + } +} + #[test] fn only_enabled_lua_mods_are_loaded() { let dir = folder(&[