Skip to content

Unsoundness in fn parse_str_field #170

@lwz23

Description

@lwz23

Hello, thank you for your contribution in this project, I an testing our static analysis tool in github's Rust project and I notice the following code:

fn parse_str_field(bytes: &[u8]) -> &str {
    unsafe { from_utf8_unchecked(bytes) }
}

I think there is a unsound problem because this function doesn't varify the bytes is valid and pass it to unsafe function form_utf8_unchecked. It will trigger UB. Although it is a private function, I notice a possible way to call this function from a pub function new.

pub fn new -> fn parse_str_field
// 函数: new
pub fn new(fs_image: &'static [u8]) -> InitramFs {
    let mut image = BytesParser::new(fs_image);
    let mut root_files = HashMap::new();
    let mut num_files = 0;
    let mut loaded_size = 0;
    loop {
        let magic = parse_hex_field(image.consume_bytes(6).unwrap());
        if magic != 0x070701 {
            panic!(
                "initramfs: invalid magic (expected {:x}, got {:x})", 0x070701, magic
            );
        }
................................

As the image use fs_image to contruct BytesParser and the parse_hex_field(image.consume_bytes(6).unwrap()); there is no gerentee that fs_image won't contain non-utf8 bytes. So I believe it is unsound.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions