FAQ - Help and questions

Which operations on untrusted data can panic, and what are the non-panicking alternatives?

#security#panics#robustnesspublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Indexing a slice, slicing a string, dividing by zero, plain integer arithmetic in debug builds and unwrap on parsed input can all panic. Use get, str get, checked_div, try_from, checked arithmetic and match on Result instead, so bad input is an error you handle, not an outage an attacker can repeat.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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 formWhyNon-panicking form
v[i]index out of rangev.get(i) returns Option
&s[a..b]range not on a character boundary or out of ranges.get(a..b) returns Option
a / b, a % bdivision by zeroa.checked_div(b)
a + b, a * boverflow in debug buildsa.checked_add(b), a.checked_mul(b)
x as u32silently truncates (no panic, but wrong)u32::try_from(x)
str::from_utf8(b).unwrap()invalid UTF-8match on the Result
.parse().unwrap()bad textmatch, or ? into your error type
src/main.rsrust
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());
}
text
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: true

The 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#

  1. Treat unwrap and expect as assertions about your own logic, never about input.
  2. Convert untrusted values into checked types at the boundary (see the thread on parsing into types), so inner code can rely on them.
  3. Search the code for unwrap(), expect(, [ indexing, / and as, 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.
  4. 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_unwind as error handling. It is a last line of defence at a boundary, and it does not work with panic = "abort".
  • Slicing strings by byte offsets computed from user data.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet