Rules / Rust
SHIELD-RUST-014
Potential integer overflow in allocation size
What it detects
with_capacity/Vec sizing from a multiplication of untrusted values can overflow.
How to fix
Use checked_mul and validate sizes before allocating from untrusted input.
Vulnerable — Shield flags thismatrix.rs
pub fn alloc_matrix(rows: usize, cols: usize) -> Vec<f64> {
// rows and cols are read from the file header.
let mut cells = Vec::with_capacity(rows * cols);
cells.resize(rows * cols, 0.0);
cells
}
Fixed — scans cleanmatrix.rs
const MAX_CELLS: usize = 1_000_000;
pub fn alloc_matrix(rows: usize, cols: usize) -> Option<Vec<f64>> {
let len = rows.checked_mul(cols)?;
if len > MAX_CELLS {
return None;
}
let mut cells = Vec::with_capacity(len);
cells.resize(len, 0.0);
Some(cells)
}
Both snippets are verified against the shipped scanner: the vulnerable one triggers SHIELD-RUST-014, the fixed one does not.