Skip to content

locate panics (slice index underflow) on a 1-byte --database file #716

Closed

Description

@leeewee

Summary

Running locate -d <file> <pattern> against a database file that is exactly one byte long panics and exits 101. DbReader::check_db reads one byte, then read_until(b'\0', ...) into a Vec that ends up empty (EOF, nothing appended); buf.len() - 1 underflows to usize::MAX and &buf[..usize::MAX] is an out-of-bounds slice. A graceful implementation should treat the too-short input as an unrecognized database format and exit non-zero, not abort.

Steps to reproduce

$ printf 'X' > /tmp/db_1byte.bin
$ ./target/release/locate -d /tmp/db_1byte.bin foo
thread 'main' panicked at src/locate/mod.rs:494:43:
range end index 18446744073709551615 out of range for slice of length 0
$ echo $?
101

uutils locate panics with a slice BoundsCheck and exits 101. The release profile has no overflow-checks, so buf.len() - 1 wraps to usize::MAX instead of aborting on the subtraction; the out-of-bounds slice then panics. Boundary behavior: a 0-byte file is handled gracefully (the first read_exact fails -> None -> exit 1); a >=2-byte file leaves buf non-empty and is safe; only the exact 1-byte case crashes. The path is reachable via the user-controlled -d/--database argument.

Root cause

// src/locate/mod.rs:483
fn check_db(reader: &mut BufReader<File>) -> Option<DbFormat> {
    let mut buf = [0];
    let Ok(_) = reader.read_exact(&mut buf) else {
        return None;
    };
    let mut buf = Vec::new();
    let Ok(_) = reader.read_until(b'\0', &mut buf) else {
        return None;
    };

    // drop nul byte when matching
    match String::from_utf8_lossy(&buf[..buf.len() - 1]).as_ref() {

When the file is exactly 1 byte, the initial read_exact consumes it, then read_until hits EOF immediately and appends nothing, leaving buf empty. buf.len() - 1 underflows to usize::MAX, and &buf[..usize::MAX] is out-of-bounds. The fix is to guard the empty case before slicing — e.g. if buf.is_empty() { return None; } (no valid LOCATE02 header), or use buf.split_last() / buf.strip_suffix(b"\0") instead of buf.len() - 1.

Found by source-audit of uutils/findutils.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions