Answer#
A panic is memory safe but, in a server, it ends a thread, a request or the whole process depending on how the program is built. If a client can cause it with one request, it can cause it again and again. That makes every panic reachable from untrusted data a denial-of-service bug.
| Panicking form | Why | Non-panicking form |
|---|---|---|
v[i] | index out of range | v.get(i) returns Option |
&s[a..b] | range not on a character boundary or out of range | s.get(a..b) returns Option |
a / b, a % b | division by zero | a.checked_div(b) |
a + b, a * b | overflow in debug builds | a.checked_add(b), a.checked_mul(b) |
x as u32 | silently truncates (no panic, but wrong) | u32::try_from(x) |
str::from_utf8(b).unwrap() | invalid UTF-8 | match on the Result |
.parse().unwrap() | bad text | match, or ? into your error type |
use std::hint::black_box;
fn main() {
let items = vec![10, 20, 30];
let i: usize = black_box(7);
let text = black_box(String::from("é!"));
let divisor: i32 = black_box(0);
let big: i64 = black_box(5_000_000_000);
println!("{:?}", items.get(i)); // instead of items[i]
println!("{:?}", text.get(0..1)); // instead of &text[0..1]
println!("{:?}", 100i32.checked_div(divisor)); // instead of 100 / divisor
println!("{:?}", u32::try_from(big).is_err()); // instead of big as u32
let bytes = black_box([0xC3u8, 0x28]);
println!("{:?}", std::str::from_utf8(&bytes).is_err()); // instead of from_utf8(..).unwrap()
// What the panicking forms do (message goes to stderr):
let r = std::panic::catch_unwind(|| {
let t = black_box(String::from("é!"));
t[0..1].len()
});
println!("slicing in the middle of a character panics: {}", r.is_err());
}None
None
None
true
true
thread 'main' panicked at src\bin\b31.rs:20:10:
byte index 1 is not a char boundary; it is inside 'é' (bytes 0..2) of `é!`
slicing in the middle of a character panics: trueThe output was shortened by removing blank lines and the backtrace hint. The first five lines are the non-panicking forms; the panic message above the last line is what the plain &text[0..1] form does on a string whose first character is two bytes long.
How to do it#
- Treat
unwrapandexpectas assertions about your own logic, never about input. - Convert untrusted values into checked types at the boundary (see the thread on parsing into types), so inner code can rely on them.
- Search the code for
unwrap(),expect(,[indexing,/andas, in the code paths that handle outside data. Clippy has lints for some of these (clippy::indexing_slicing,clippy::unwrap_used,clippy::arithmetic_side_effects); check the Clippy lint list for the exact names in your version. - Decide what a panic does in your service (see the thread on panics and errors) and test that bad input does not trigger one.
Common mistakes#
- Assuming
#![forbid(unsafe_code)]removes panics. It does not. - Using
catch_unwindas error handling. It is a last line of defence at a boundary, and it does not work withpanic = "abort". - Slicing strings by byte offsets computed from user data.
Related questions#
Is a panic in a thread the end of the program?#
A panic ends that thread. The program continues unless the main thread waits for it and propagates, or unless the profile uses panic = "abort". See the existing thread on when to panic and when to return an error.
What does clippy offer here?#
It has optional lints for indexing, unwrap and arithmetic in its restriction group. They are noisy for ordinary code; enable them on the modules that handle untrusted data.
Sources#
- The Rust Book, "To panic! or Not to panic!": https://doc.rust-lang.org/book/ch09-03-to-panic-or-not-to-panic.html
- Standard library,
str::get: https://doc.rust-lang.org/std/primitive.str.html#method.get - Clippy lint list: https://rust-lang.github.io/rust-clippy/master/index.html