Skip to content

D3D12-LUA-WRITE-FILE-PATH-NORMALIZATION: check mod.json and blocked extensions on normalized path - #2683

Open
bobcatchris wants to merge 4 commits into
ProjectLeonida:mainfrom
bobcatchris:fix/d3d12-lua-write-file-path-normalization
Open

bobcatchris wants to merge 4 commits into
ProjectLeonida:mainfrom
bobcatchris:fix/d3d12-lua-write-file-path-normalization

Conversation

@bobcatchris

Copy link
Copy Markdown
Contributor

Claimed in #2570 as D3D12-LUA-WRITE-FILE-PATH-NORMALIZATION (#issuecomment-7266797979).

What and why

In d3d12/crates/leonida-lua/src/api.rs, write_file() validated lower == "mod.json" and the executable extension deny-list (exe, dll, bat, cmd, com, ps1, vbs, msi, scr, lnk, sys, reg, hta, jar) against the raw name string before inside() called safe_relative(name).

Because Rust's Path::components() strips trailing / and interior ., a mod could pass "mod.json/", "mod.json/.", "evil.exe/", "evil.exe/.", "sub/evil.dll/", or "sub/evil.bat/." — bypassing both checks and overwriting mod.json or writing blocked executables directly into the mod folder.

This change normalizes name with safe_relative(name)? first and checks the normalized relative path's file_name() (when at the mod root) and extension() case-insensitively.

Verification (Red -> Green)

Hardware / OS: native Windows 11 Pro (10.0.26200), pinned toolchain rustc 1.98.1.

  • Red (before fix): api::tests::write_file_blocks_manifest_and_executables_after_path_normalization failed immediately on "mod.json/" (mod.json/ was allowed and overwrote mod.json).
  • Green (after fix, on main 40e7fe69d):
    • cargo test -p leonida-lua --lib — 36 passed; 0 failed (0.50s).
    • 0 clippy warnings in api.rs.
    • python -I scripts/check_no_game_data.py d3d12/crates/leonida-lua/src/api.rs — PASS.

AI-assisted: Antigravity (Gemini 4 Neon)

…normalized path (D3D12-LUA-WRITE-FILE-PATH-NORMALIZATION)

write_file() previously checked lower == "mod.json" and the blocked
executable extension list against the raw name string before
safe_relative() normalized Path::components(). Because Path::components()
strips trailing '/' and interior '.', names such as "mod.json/",
"mod.json/.", "evil.exe/", or "sub/evil.dll/." bypassed both checks
and wrote mod.json or blocked executables into the mod folder.

Normalize with safe_relative(name) first and inspect the normalized
relative path's file_name() and extension() instead. Includes a Red ->
Green unit test covering all bypass forms.

AI-assisted: Antigravity (Gemini 4 Neon)
@OreoFR

OreoFR commented Nov 30, 2026 •

Copy link
Copy Markdown
Collaborator

Verified by OreoFR on macOS 27.2.1, Apple M5, Rust 1.98.1 (cargo test -p leonida-lua), main 182d0c1, PR head 8f7f04d. MEASURED:

  • red (main's api.rs + only this PR's #[cfg(test)] mod tests): 35 passed, 1 failed: write_file_blocks_manifest_and_executables_after_path_normalization panics at the first trailing-slash case: "mod.json/ must be refused by write_file". So on main write_file returns Ok for mod.json/ (the name check runs on the raw string, before normalization); I did not check what it then wrote.
  • green (main + this PR, merge --no-ff): 36/36 passed.
  • Merges cleanly with main and with [integration] PageMirror, GPU detile, async queue & RDNA2->SPIR-V performance stack (INTEGRATION-PERF-CPU-GPU-R6) #2566 (git merge-tree).

Not covered: Windows path forms (backslashes, drive letters, alternate data streams); this ran on macOS, where only / separates.

AI-assisted: Claude Code

@MoonEyes

Copy link
Copy Markdown
Collaborator

@bobcatchris could you merge current main into this branch (a merge, no rebase or force-push) so CI runs again?

OreoFR's red/green (macOS) is on the current head 8f7f04d2f. What is in the way is CI on that head, which is red on semantic-tests and ran on an older base. On main at 4014af7f, CI was green except macos. I have not checked whether each red here comes from main or from this PR, so the new run should tell.

The merge changes the head, so the red/green will need to be run again on the new one.

AI-assisted: yes

@bobcatchris

Copy link
Copy Markdown
Contributor Author

@MoonEyes merged current main (d367675c7) into this branch (a merge, no rebase or force-push). New head 910468f42; the merge was clean, and the diff against main is still only d3d12/crates/leonida-lua/src/api.rs.

Checked on the new head (Windows 11, Ryzen 7 7800X3D, Rust 1.98.1, cargo test --locked --offline -p leonida-lua): 36 passed, 0 failed. python -I scripts/check_no_game_data.py on api.rs found nothing.

cargo clippy --no-deps -p leonida-lua --all-targets -- -D warnings still reports 3 warnings in the library (input.rs Keys/Pads Default, memory.rs:94 is_multiple_of) and 2 in the tests (tests.rs:356, :370 byte string). They are all in files this PR does not touch, so they are not from this change.

OreoFR's red/green is on the old head 8f7f04d2f and will need to be run again on 910468f42.

AI-assisted: Claude Sonnet 5.5

@MoonEyes

Copy link
Copy Markdown
Collaborator

@OreoFR could you run your red/green again on the new head 910468f42? @bobcatchris merged main (d367675c7) into the branch, CI is green on all 5 checks there, and your run was on the previous head 8f7f04d2f. A check of the Windows path forms (backslashes, drive letters), which your comment lists as not covered, would help too if someone has a Windows machine.

AI-assisted: yes

@Kal0s-design

Copy link
Copy Markdown
Contributor

Native Windows red/green on the new head 910468f42, plus the Windows path forms MoonEyes asked about. Merged onto current main f44904d21 (56547254f). Windows 11, NTFS, MSVC x64, Rust 1.98.1, cargo test -p leonida-lua --lib.

  • Red: main + only this PR's test module: 35 passed, 1 failed, `mod.json/` must be refused by write_file. On Windows that call returns Ok and does overwrite mod.json (the probe below reads it back as the new bytes).
  • Green: main + this PR: 36 passed, 0 failed.

A local probe (not part of the PR) calls write_file on a fresh temp folder holding mod.json, then reads mod.json back and lists what was created:

name main this PR
mod.json/, evil.exe/./ Ok, mod.json overwritten / evil.exe written refused
mod.json\, C:mod.json, C:\x\mod.json, \?\C:\x, mod.json:x, evil.exe::$DATA refused (safe_relative: \ and :) refused
evil.exe., evil.exe , evil.exe. ., nul.txt, sub/../mod.json, ./mod.json, evil.EXE, EVIL~1.EXE refused refused
MOD~1.JSO, mod~1.jso Ok, mod.json overwritten Ok, mod.json overwritten
mod.jſon (U+017F), COM¹.txt, LPT², CONIN$, CONOUT$ Ok, a separate ordinary file of that name same

So with the backslash, drive, stream and trailing-dot/space forms all caught, the one Windows form that still reaches the manifest is its 8.3 short name. NTFS gives mod.json the alias MOD~1.JSO when short names are on for the volume (they are for the temp folder here). The name passes safe_relative and the checks this PR adds (its own name isn't mod.json, and jso isn't on the list), and Windows resolves it to mod.json. That's outside this PR's trailing-slash scope. One way to close it would be to check the name of the file the path resolves to when it exists, e.g. canonicalize it and run the manifest/extension checks on that file_name, or to refuse a component containing ~ followed by a digit. I'd leave that choice to you, as a follow-up item or here.

The U+017F and superscript-digit device names came out as ordinary files on this Windows build, with no device opened and nothing aliased.

GPUs tested: n/a (CPU/file-system tests). AI-assisted: yes.

@Kal0s-design

Copy link
Copy Markdown
Contributor

@bobcatchris on the 8.3 short-name case from my check above (MOD~1.JSO → mod.json): I put a fix on top of this branch, Kal0s-design@1772676d1 (branch fix/lua-write-file-short-names, claimed in #2570 as D3D12-LUA-WRITE-FILE-SHORT-NAMES). When the path leads to an existing file, write_file checks it again by the name it has (canonicalized, relative to the mod's folder), with your manifest/extension rules moved into one not_writable function. A test fails on this PR's code and passes with it; it skips on volumes without 8.3 names. leonida-lua lib: 37 passed. Feel free to cherry-pick it here if you'd rather have it in one PR; otherwise I'll open it with Depends on: #2683 when I have a slot.

AI-assisted: yes

@bobcatchris

Copy link
Copy Markdown
Contributor Author

@Kal0s-design thanks for the check and the fix. I will not cherry-pick it: this PR stays at the trailing-slash scope it was verified at, and an 8.3 short name is a different input that deserves its own red/green. Please open yours as D3D12-LUA-WRITE-FILE-SHORT-NAMES with \Depends on: #2683; I will not touch that function in the meantime.

AI-assisted: Claude Sonnet 5.5

@Kal0s-design

Copy link
Copy Markdown
Contributor

@bobcatchris understood, thanks. I'll open D3D12-LUA-WRITE-FILE-SHORT-NAMES as its own PR with Depends on: #2683 once this account has a free PR slot, with its own red/green.

AI-assisted: yes

@KelboLive KelboLive left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at 910468f42 on Windows 11 in an own worktree. The claim holds: both gates now run on safe_relative(name) (api.rs:512-530), so mod.json/ and evil.exe/ are caught after normalization, and restoring the raw-string deny-list makes the new test fail on evil.exe/ — the mutant is killed. cargo test -p leonida-lua is 36/36, check_no_game_data passes, and merge-tree is clean (590 behind main, but api.rs has not changed since the merge base).

One regression introduced by the rewrite: Path::extension() returns None when the name is only a dot plus the extension, so .exe, sub/.bat and .ps1 are writable again. I verified it by adding .exe to the test's bad list — it fails — while the old rsplit_once('.') refused them, and Windows itself treats .exe as extension exe. Fix: derive the suffix from the normalized file name's last .-separated segment (or reject a leading-dot component outright) and add .exe / sub/.exe cases to the same test. The 8.3 short-name (MOD~1.JSO) case can stay in the follow-up where it already is.

Everything else about the change is right: normalization before both gates, the top-level case-insensitive mod.json check, and inside() still doing the escape/link check afterwards.

@imShangLi

Copy link
Copy Markdown
Contributor

VERIFY-2683 — Linux, Rust 1.98.1 (the pinned toolchain), no GPU device, no game files

Verdict: PASS, and this one closes a hole that lets a mod do two things it is not allowed to do. On main, a mod can overwrite its own mod.json and create .exe/.dll files inside its folder; after this pull request both are refused. I demonstrated the before and after.

Head 910468f4, base the current main 88a9f133, merge base d367675c, 1 commit, 1 file, +55/−9: d3d12/crates/leonida-lua/src/api.rs.

1. What was wrong

write_file checked the blocklist against the name as given:

let lower = name.to_ascii_lowercase();
let extension = lower.rsplit_once('.').map_or("", |(_, e)| e);
if lower == "mod.json" || [ "exe", "dll", "bat", … ].contains(&extension) { … }

rsplit_once('.') on "evil.exe/" gives the extension "exe/" — with the trailing slash still on it — and "exe/" is not in the list. The path itself was normalised later, by inside() → safe_relative(), which drops a trailing slash and a trailing /.:

// crates/leonida-lua/src/manifest.rs:78
pub fn safe_relative(path: &str) -> Result<PathBuf, String> { … }
// `Path::components()` normalises "." away and ignores a trailing separator,
// so "mod.json/." and "mod.json/" both come out as the single component "mod.json".

So the check looked at one string and the write went to another.

2. What that let a mod do — measured on main

I put main's production code back (only the blocked-check reverted, the pull request's test kept) and called write_file directly:

write_file("mod.json/")        -> Ok(())
write_file("mod.json/.")       -> Ok(())
write_file("evil.exe/")        -> Ok(())
write_file("sub/evil.dll/.")   -> Ok(())
manifest 现在是: "pwned"
  evil.exe 存在吗: true
  sub/evil.dll 存在吗: true

The mod's own manifest was overwritten with the bytes the mod chose, and an .exe and a .dll were created in its folder — the two things the blocklist exists to prevent.

With the pull request's code, the same calls:

write_file("mod.json/")        -> Err("`mod.json/` cannot be written by a mod")
write_file("mod.json/.")       -> Err("`mod.json/.` cannot be written by a mod")
write_file("evil.exe/")        -> Err("`evil.exe/` cannot be written by a mod")
write_file("sub/evil.dll/.")   -> Err("`sub/evil.dll/.` cannot be written by a mod")
manifest 现在是: "{\"name\":\"orig\"}"
  evil.exe 存在吗: false
  sub/evil.dll 存在吗: false

3. The fix

The check now runs on the normalised path:

let rel = safe_relative(name)?;
let is_manifest = rel.parent().is_none_or(|p| p.as_os_str().is_empty())
    && rel.file_name().and_then(|f| f.to_str())
        .is_some_and(|f| f.eq_ignore_ascii_case("mod.json"));
let blocked_extension = rel.extension().and_then(|e| e.to_str()).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(…); }

Two details worth naming:

  • safe_relative(name)? before the check means a name that is not a plain relative path is refused there and then, rather than slipping past the blocklist and being rejected later by inside(). That is the same function inside() uses, so the check and the write now agree on what the path is.
  • is_manifest requires the manifest name to be the last component with no parent, so sub/mod.json is not treated as the manifest (only the root one is), and mod.json is matched case-insensitively — MOD.JSON is caught, which the old lower == "mod.json" also caught, but the new one keeps that for the normalised name.

4. Red and green, and the discrimination

python -I scripts/red_green.py pr2683 --crate leonida-lua (the repository's own red/green tool):

verdict: "red then green"
red_to_green: leonida_lua::api::tests::write_file_blocks_manifest_and_executables_after_path_normalization
regressions:  []
pass_on_both: 40

and by hand, with only the production change reverted:

thread 'api::tests::write_file_blocks_manifest_and_executables_after_path_normalization' panicked:
`mod.json/` must be refused by write_file
test result: FAILED. 0 passed; 1 failed

With the pull request's code the whole crate is 36 passed, 0 failed.

5. What I did not check

  • Windows. Linux (Fedora 45, x86_64) with the pinned toolchain (rustc 1.98.1). The behaviour is path handling, which is the same on both, but the reserved-device names and the \\ rejection in safe_relative are Windows-specific and I did not exercise them.
  • The other entry points into the mod's folder. I checked write_file only. The pull request's own test also asserts that the files were not created, which covers the write path; I did not look for a second way in (the manifest's other fields, the script path, the platform interface).
  • Whether mod.json is meant to be writable at all. I took the blocklist at face value: the manifest is the file that decides what the mod may do, so a mod rewriting it is a privilege problem whichever side of the line the maintainer draws it.
  • The rest of the workspace — leonida-gpu, leonida-hle and leonida-loader do not build on Linux for reasons that predate this pull request (upstream: "The crates are Windows-only today … Linux follows Linux: build leonida.exe and run it under Proton or Wine #2577"), so I ran leonida-lua on its own.
  • cargo clippy (already failing on main, run as a report by the workflow) and cargo fmt (left out of the d3d12 workflow).

AI-assisted: MiniMax M3.1 Flash.

@bobcatchris

Copy link
Copy Markdown
Contributor Author

@KelboLive Fixed in b24edaa99 (after merging main, no rebase/force-push):

  • Replaced rel.extension() with file_name.and_then(|f| f.rsplit_once('.')) on the safe_relative-normalized path so leading-dot executable names (.exe, .exe/, sub/.bat, sub/.ps1/.) are refused again.
  • Added .exe, .exe/, sub/.bat, and sub/.ps1/. to write_file_blocks_manifest_and_executables_after_path_normalization.
  • Verified locally on Windows (Rust 1.98.1): cargo test --locked -p leonida-lua (41 passed, 0 failed) and python -I scripts/check_no_game_data.py (clean).

AI-assisted: Gemini 4 Neon (including an independent read-only reviewer pass).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants