diff --git a/d3d12/crates/leonida-lua/src/api.rs b/d3d12/crates/leonida-lua/src/api.rs index cee5a0441..34f1bdb16 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 77ba72b6c..d1c30e67b 100644 --- a/d3d12/crates/leonida-lua/src/tests.rs +++ b/d3d12/crates/leonida-lua/src/tests.rs @@ -937,6 +937,158 @@ 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. 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")) { + 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("`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)] + { + 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 + } +} + +/// 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(&[ diff --git a/docs/lua-modding.md b/docs/lua-modding.md index 9adb0fe15..aad61470c 100644 --- a/docs/lua-modding.md +++ b/docs/lua-modding.md @@ -165,7 +165,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