Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unsoundness in run_cmd #204

Open
lwz23 opened this issue Nov 25, 2024 · 0 comments
Open

Unsoundness in run_cmd #204

lwz23 opened this issue Nov 25, 2024 · 0 comments
Labels
bug Something isn't working

Comments

@lwz23
Copy link

lwz23 commented Nov 25, 2024

Description

The run_cmd function

pub fn run_cmd(line: &[u8]) {
appears to have a potential unsoundness issue when processing invalid UTF-8 sequences. Specifically, the function uses unsafe { core::str::from_utf8_unchecked(line) } to convert a byte slice (line) into a string without verifying that the input is valid UTF-8. If the input contains invalid UTF-8 sequences, this can lead to undefined behavior (UB), as shown in the provided PoC.

pub fn run_cmd(line: &[u8]) {
    let line_str = unsafe { core::str::from_utf8_unchecked(line) };
    let (cmd, args) = split_whitespace(line_str);
    if !cmd.is_empty() {
        for (name, func) in CMD_TABLE {
            if cmd == *name {
                func(args);
                return;
            }
        }
        println!("{}: command not found", cmd);
    }
}

Steps to Reproduce

Here's a minimal reproducible example that demonstrates the issue:

fn main() {
    let invalid_utf8: &[u8] = &[0x80, 0x81, 0x82];
    run_cmd(invalid_utf8);
}

output:

    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.36s
     Running `target\debug\lwz.exe`
thread 'main' panicked at core\src\panicking.rs:221:5:
unsafe precondition(s) violated: hint::unreachable_unchecked must never be reached
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread caused non-unwinding panic. aborting.
error: process didn't exit successfully: `target\debug\lwz.exe` (exit code: 0xc0000409, STATUS_STACK_BUFFER_OVERRUN)

Suggested Fix

  1. The unsoundness can be mitigated by replacing the use of core::str::from_utf8_unchecked with the safer core::str::from_utf8. This change ensures that the function validates the input before attempting the conversion.
  2. Mark run_cmd as 'unsafe' function and write the safety precondition.
@equation314 equation314 added the bug Something isn't working label Nov 25, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants