Rules / Rust
SHIELD-RUST-012
Path traversal via user-controlled file path
What it detects
Opening a format!-built path can escape the intended directory (../).
How to fix
Canonicalize the path and verify it stays within an allowed base directory.
Vulnerable — Shield flags thisuploads.rs
use std::fs;
pub fn read_upload(name: &str) -> std::io::Result<String> {
// `name` comes from the request path, e.g. "report.txt" or "../../etc/passwd".
fs::read_to_string(format!("/srv/uploads/{}", name))
}
Fixed — scans cleanuploads.rs
use std::fs;
use std::io::{Error, ErrorKind};
use std::path::Path;
pub fn read_upload(name: &str) -> std::io::Result<String> {
let base = Path::new("/srv/uploads").canonicalize()?;
let path = base.join(name).canonicalize()?;
if !path.starts_with(&base) {
return Err(Error::new(ErrorKind::PermissionDenied, "path escapes upload dir"));
}
fs::read_to_string(&path)
}
Both snippets are verified against the shipped scanner: the vulnerable one triggers SHIELD-RUST-012, the fixed one does not.