upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMoonEyes <ducoinbenjamin@yahoo.fr>2026-12-02 13:22:25 +0000
committerGitHub <noreply@github.com>2026-12-02 13:22:25 +0000
commit69cd4106ce292abdeba319787daeac0f2a5aa6ea (patch)
treeb001092de8b52cc6ca1a2d246b2e43235f44f3b9
parent64d0d5398b58b16eb5edecd458d3f87395e457aa (diff)
parent856615ce739cebed14c2ddc83cb5e5108aaadfb2 (diff)
Merge pull request #3051 from imShangLi/fix/d3d12-lua-require-inside-folderHEADmainHEAD
D3D12-LUA-LINKS-STAY-IN-THE-FOLDER: require and the script refuse a link that leads out
-rw-r--r--d3d12/crates/leonida-lua/src/api.rs44
-rw-r--r--d3d12/crates/leonida-lua/src/manifest.rs18
-rw-r--r--d3d12/crates/leonida-lua/src/runtime.rs5
-rw-r--r--d3d12/crates/leonida-lua/src/tests.rs152
-rw-r--r--docs/lua-modding.md2
5 files changed, 192 insertions, 29 deletions
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 @@
4 4
5use std::cell::RefCell; 5use std::cell::RefCell;
6use std::collections::HashSet; 6use std::collections::HashSet;
7use std::path::{Path, PathBuf}; 7use std::path::Path;
8use std::rc::Rc; 8use std::rc::Rc;
9use std::time::Instant; 9use std::time::Instant;
10 10
@@ -16,7 +16,7 @@ use mlua::{Function, IntoLua, Lua, LuaString, MultiValue, Result, Table, Value,
16 16
17use crate::input::BUTTONS; 17use crate::input::BUTTONS;
18use crate::keys; 18use crate::keys;
19use crate::manifest::safe_relative; 19use crate::manifest;
20use crate::memory::{self, Pattern}; 20use crate::memory::{self, Pattern};
21use crate::platform::Platform; 21use crate::platform::Platform;
22use crate::runtime::{Event, Handler, ItemDef, MAX_HANDLERS, PageDef, Shared}; 22use crate::runtime::{Event, Handler, ItemDef, MAX_HANDLERS, PageDef, Shared};
@@ -80,14 +80,23 @@ fn require(lua: &Lua, env: &Table, folder: &Path) -> Result<Function> {
80 return Err(err(format!("loop while requiring `{name}`"))); 80 return Err(err(format!("loop while requiring `{name}`")));
81 } 81 }
82 let path = name.replace('.', "/"); 82 let path = name.replace('.', "/");
83 // A module is a file of the mod's own folder: a link that leads out
84 // of it is refused, like the files the mod reads.
85 let mut refusal = None;
83 let found = [format!("{path}.lua"), format!("{path}/init.lua")] 86 let found = [format!("{path}.lua"), format!("{path}/init.lua")]
84 .into_iter() 87 .into_iter()
85 .filter_map(|rel| safe_relative(&rel).ok()) 88 .filter_map(|rel| match manifest::inside(&folder, &rel) {
86 .map(|rel| folder.join(rel)) 89 Ok(p) => Some(p),
90 Err(why) => {
91 refusal.get_or_insert(why);
92 None
93 }
94 })
87 .find(|p| p.is_file()); 95 .find(|p| p.is_file());
88 let result = (|| { 96 let result = (|| {
89 let file = found 97 let file = found.ok_or_else(|| {
90 .ok_or_else(|| err(format!("module `{name}` not found in the mod's folder")))?; 98 err(refusal.unwrap_or_else(|| format!("module `{name}` not found in the mod's folder")))
99 })?;
91 let size = std::fs::metadata(&file).map_err(err)?.len(); 100 let size = std::fs::metadata(&file).map_err(err)?.len();
92 if size > crate::manifest::MAX_SCRIPT { 101 if size > crate::manifest::MAX_SCRIPT {
93 return Err(err(format!("module `{name}` is too large"))); 102 return Err(err(format!("module `{name}` is too large")));
@@ -479,25 +488,8 @@ fn leonida(lua: &Lua, shared: &Rc_<Shared>, idx: usize, folder: &Path) -> Result
479 Ok(t) 488 Ok(t)
480} 489}
481 490
482/// `root` joined with a plain relative `name`, checked not to leave it.
483fn inside(root: &Path, name: &str) -> std::result::Result<PathBuf, String> {
484 let rel = safe_relative(name)?;
485 let path = root.join(rel);
486 // A link or junction inside the folder must not lead out of it.
487 let canon_root = std::fs::canonicalize(root).map_err(|e| format!("the mod's folder: {e}"))?;
488 let mut probe = path.as_path();
489 while !probe.exists() {
490 probe = probe.parent().ok_or("no such folder")?;
491 }
492 let canon = std::fs::canonicalize(probe).map_err(|e| e.to_string())?;
493 if !canon.starts_with(&canon_root) {
494 return Err(format!("`{name}` leads out of the mod's folder"));
495 }
496 Ok(path)
497}
498
499fn read_file(root: &Path, name: &str) -> std::result::Result<Vec<u8>, String> { 491fn read_file(root: &Path, name: &str) -> std::result::Result<Vec<u8>, String> {
500 let path = inside(root, name)?; 492 let path = manifest::inside(root, name)?;
501 let meta = std::fs::metadata(&path).map_err(|e| format!("{name}: {e}"))?; 493 let meta = std::fs::metadata(&path).map_err(|e| format!("{name}: {e}"))?;
502 if !meta.is_file() || meta.len() > MAX_READ { 494 if !meta.is_file() || meta.len() > MAX_READ {
503 return Err(format!("{name} is not a file of at most {MAX_READ} bytes")); 495 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
520 { 512 {
521 return Err(format!("`{name}` cannot be written by a mod")); 513 return Err(format!("`{name}` cannot be written by a mod"));
522 } 514 }
523 let path = inside(root, name)?; 515 let path = manifest::inside(root, name)?;
524 if let Some(parent) = path.parent() { 516 if let Some(parent) = path.parent() {
525 std::fs::create_dir_all(parent).map_err(|e| format!("{name}: {e}"))?; 517 std::fs::create_dir_all(parent).map_err(|e| format!("{name}: {e}"))?;
526 } 518 }
527 // Again, now that the folders exist. 519 // Again, now that the folders exist.
528 let path = inside(root, name)?; 520 let path = manifest::inside(root, name)?;
529 std::fs::write(&path, data).map_err(|e| format!("{name}: {e}")) 521 std::fs::write(&path, data).map_err(|e| format!("{name}: {e}"))
530} 522}
531 523
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> {
72 Ok(()) 72 Ok(())
73} 73}
74 74
75/// `root` joined with a plain relative `name`, checked not to leave it: a
76/// link or junction inside the folder must not lead out of it.
77pub fn inside(root: &Path, name: &str) -> Result<PathBuf, String> {
78 let rel = safe_relative(name)?;
79 let path = root.join(rel);
80 // A link or junction inside the folder must not lead out of it.
81 let canon_root = std::fs::canonicalize(root).map_err(|e| format!("the mod's folder: {e}"))?;
82 let mut probe = path.as_path();
83 while !probe.exists() {
84 probe = probe.parent().ok_or("no such folder")?;
85 }
86 let canon = std::fs::canonicalize(probe).map_err(|e| e.to_string())?;
87 if !canon.starts_with(&canon_root) {
88 return Err(format!("`{name}` leads out of the mod's folder"));
89 }
90 Ok(path)
91}
92
75/// Whether `path` is a plain relative path of ordinary names (no `..`, no 93/// Whether `path` is a plain relative path of ordinary names (no `..`, no
76/// root, no drive, no stream or reserved device syntax): what a mod may name 94/// root, no drive, no stream or reserved device syntax): what a mod may name
77/// inside its folder. 95/// 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 {
250 } 250 }
251 251
252 fn run_script(&mut self, idx: usize, folder: &Path, script: &str) -> Result<(), String> { 252 fn run_script(&mut self, idx: usize, folder: &Path, script: &str) -> Result<(), String> {
253 let rel = manifest::safe_relative(script)?; 253 // The script is a file of the mod's own folder: a link that leads out
254 let path = folder.join(rel); 254 // of it is refused, like the files the mod reads.
255 let path = manifest::inside(folder, script)?;
255 let len = std::fs::metadata(&path) 256 let len = std::fs::metadata(&path)
256 .map_err(|e| format!("cannot read {script}: {e}"))? 257 .map_err(|e| format!("cannot read {script}: {e}"))?
257 .len(); 258 .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
@@ -938,6 +938,158 @@ fn require_loads_the_mods_own_modules_once() {
938} 938}
939 939
940#[test] 940#[test]
941fn a_link_out_of_the_mods_folder_is_not_a_module_and_not_a_script() {
942 // A link that leads out of the mod's folder: the file it names is read
943 // and run by the old code.
944 let dir = folder(&[(
945 "a",
946 JSON,
947 r#"
948 leonida.log("req", pcall(require, "helper"))
949 "#,
950 )]);
951 let at = dir.path().join("a");
952 let outside = dir.path().join("outside.lua");
953 std::fs::write(&outside, "return {answer = function() return 42 end}").unwrap();
954 if !link(&outside, &at.join("helper.lua")) {
955 // No rights to make a link here: nothing to check.
956 return;
957 }
958 let fake = Fake::new();
959 let mut rt = Runtime::new(fake.clone(), Config::default()).unwrap();
960 rt.load_dir(dir.path());
961 let log = fake.of("a");
962 assert!(
963 log[0].starts_with("req false ") && log[0].contains("leads out of the mod's folder"),
964 "{log:?}"
965 );
966
967 // The same for the script the manifest names. The mod is made by hand: the script the manifest
968 // names is the link, so there is no file of that name to write first.
969 let dir = tempfile::tempdir().unwrap();
970 let at = dir.path().join("b");
971 std::fs::create_dir_all(&at).unwrap();
972 std::fs::write(at.join("mod.json"), JSON).unwrap();
973 let script = dir.path().join("script.lua");
974 std::fs::write(&script, "leonida.log('ran')").unwrap();
975 if !link(&script, &at.join("main.lua")) {
976 return;
977 }
978 let fake = Fake::new();
979 let mut rt = Runtime::new(fake.clone(), Config::default()).unwrap();
980 rt.load_dir(dir.path());
981 let log = fake.of("b");
982 assert!(
983 log.len() == 1 && log[0].contains("`main.lua` leads out of the mod's folder"),
984 "{log:?}"
985 );
986 assert_eq!(
987 status(&rt, "b"),
988 crate::runtime::Status::Failed("`main.lua` leads out of the mod's folder".to_owned())
989 );
990}
991
992#[test]
993fn a_directory_link_out_of_the_mods_folder_is_not_a_module_and_not_a_script() {
994 // A directory link that leads out of the mod's folder (a symlink to a folder on Unix, a junction on
995 // Windows): the module under it is read and run by the old code. A junction needs no rights on
996 // Windows, where a file symlink does, so this case runs there too.
997 let dir = folder(&[(
998 "a",
999 JSON,
1000 r#"
1001 leonida.log("req", pcall(require, "lib.helper"))
1002 "#,
1003 )]);
1004 let at = dir.path().join("a");
1005 let outside = dir.path().join("outside");
1006 std::fs::create_dir_all(&outside).unwrap();
1007 std::fs::write(
1008 outside.join("helper.lua"),
1009 "return {answer = function() return 42 end}",
1010 )
1011 .unwrap();
1012 if !dir_link(&outside, &at.join("lib")) {
1013 // No rights to make a link here: nothing to check.
1014 return;
1015 }
1016 let fake = Fake::new();
1017 let mut rt = Runtime::new(fake.clone(), Config::default()).unwrap();
1018 rt.load_dir(dir.path());
1019 let log = fake.of("a");
1020 assert!(
1021 log[0].starts_with("req false ") && log[0].contains("leads out of the mod's folder"),
1022 "{log:?}"
1023 );
1024
1025 // The same for the script the manifest names.
1026 let dir = tempfile::tempdir().unwrap();
1027 let at = dir.path().join("b");
1028 std::fs::create_dir_all(&at).unwrap();
1029 std::fs::write(at.join("mod.json"), r#"{"script": "lib/main.lua"}"#).unwrap();
1030 let outside = dir.path().join("outside");
1031 std::fs::create_dir_all(&outside).unwrap();
1032 std::fs::write(outside.join("main.lua"), "leonida.log('ran')").unwrap();
1033 if !dir_link(&outside, &at.join("lib")) {
1034 return;
1035 }
1036 let fake = Fake::new();
1037 let mut rt = Runtime::new(fake.clone(), Config::default()).unwrap();
1038 rt.load_dir(dir.path());
1039 let log = fake.of("b");
1040 assert!(
1041 log.len() == 1 && log[0].contains("`lib/main.lua` leads out of the mod's folder"),
1042 "{log:?}"
1043 );
1044 assert_eq!(
1045 status(&rt, "b"),
1046 crate::runtime::Status::Failed("`lib/main.lua` leads out of the mod's folder".to_owned())
1047 );
1048}
1049
1050/// A link from `link` to `target`, when this machine allows one.
1051fn link(target: &std::path::Path, link: &std::path::Path) -> bool {
1052 #[cfg(unix)]
1053 {
1054 std::os::unix::fs::symlink(target, link).is_ok()
1055 }
1056 #[cfg(windows)]
1057 {
1058 std::os::windows::fs::symlink_file(target, link).is_ok()
1059 }
1060 #[cfg(not(any(unix, windows)))]
1061 {
1062 let _ = (target, link);
1063 false
1064 }
1065}
1066
1067/// A link from `link` to the folder `target`, when this machine allows one. On Windows a junction
1068/// (`mklink /J`), which needs no rights; on Unix a symlink to the folder.
1069fn dir_link(target: &std::path::Path, link: &std::path::Path) -> bool {
1070 #[cfg(unix)]
1071 {
1072 std::os::unix::fs::symlink(target, link).is_ok()
1073 }
1074 #[cfg(windows)]
1075 {
1076 std::process::Command::new("cmd")
1077 .args(["/C", "mklink", "/J"])
1078 .arg(link)
1079 .arg(target)
1080 .stdout(std::process::Stdio::null())
1081 .status()
1082 .map(|s| s.success())
1083 .unwrap_or(false)
1084 }
1085 #[cfg(not(any(unix, windows)))]
1086 {
1087 let _ = (target, link);
1088 false
1089 }
1090}
1091
1092#[test]
941fn only_enabled_lua_mods_are_loaded() { 1093fn only_enabled_lua_mods_are_loaded() {
942 let dir = folder(&[ 1094 let dir = folder(&[
943 ("on", JSON, "leonida.log('on')"), 1095 ("on", JSON, "leonida.log('on')"),
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
165 165
166Files: only the mod's own folder, plain relative paths (no `..`, drive letters, streams or reserved device names; a 166Files: only the mod's own folder, plain relative paths (no `..`, drive letters, streams or reserved device names; a
167link that leads out is refused), reads up to 4 MiB, writes up to 1 MiB, never `mod.json` or a program (`.exe`, `.dll`, 167link that leads out is refused), reads up to 4 MiB, writes up to 1 MiB, never `mod.json` or a program (`.exe`, `.dll`,
168`.bat`, ...). There is no `io`. 168`.bat`, ...). There is no `io`. The rule holds for `require` and for the script the manifest names, too.
169 169
170## The sandbox 170## The sandbox
171 171