Rust secure coding¶
Rust's ownership model prevents many memory mistakes in safe code, but it does not authorize requests, validate paths or separate shell instructions from untrusted text. This is an educational Rust standard-library guide. Verified Offensive360 Rust product-adapter support is not established here; confirm available analyzers before relying on a scan for Rust coverage.
Avoid an unnecessary shell¶
This Unix-oriented example prints a supplied string with the system printf program. Assume text is an untrusted &str; the surrounding function returns std::io::Result<()>. Production applications should choose approved executable paths and bound output and execution time.
Unsafe: construct a shell command with the input.
use std::process::Command;
let output = Command::new("/bin/sh")
.arg("-c")
.arg(format!("printf '%s' '{}'", text))
.output()?;
Safer: pass the text as one argument to a fixed program.
use std::process::Command;
let output = Command::new("/usr/bin/printf")
.arg("%s")
.arg(text)
.output()?;
The safer call does not introduce a shell interpreter, and the fixed format makes the final argument data for this program. Check that the absolute path is valid on your target system. Rust's Command documentation describes argument passing and platform differences. Other executables can interpret arguments as options or expressions, so validate them according to the actual program's interface. Windows batch-file behavior needs a separate review.
Check the fix¶
Run only the safer version in a local fixture with Demo label; still text. Assert a successful exit status and stdout exactly equal to the input. Repeat with apostrophes and whitespace. Check output.status.success() in application code; successfully starting a process does not mean the program succeeded.
For web services, parameterize SQL, enforce object ownership and constrain file access. Review unsafe blocks and foreign-function interfaces separately from ordinary application logic. Memory-safe code can still return another user's data or send a request to an unapproved destination.
Continue with command injection, SQL injection, file path injection and hardcoded credentials. The example is intentionally narrow and does not require a vulnerable service or any production target.