Skip to content

BitVec::repeat violates exception safety, leading to use of uninitialized memory #313

Description

@Evian-Zhang

Hello, we are security researchers targeting Rust security. By running our tool in this repository, we found a soundness issue. This report is written by 100% human. We promise that all you read will never be generated by LLM.

bitvec/src/vec.rs

Lines 77 to 97 in 5fb8550

/// Creates a new bit-vector by repeating a bit for the desired length.
///
/// ## Examples
///
/// ```rust
/// use bitvec::prelude::*;
///
/// let zeros = BitVec::<u8, Msb0>::repeat(false, 50);
/// let ones = BitVec::<u16, Lsb0>::repeat(true, 50);
/// ```
#[inline]
pub fn repeat(bit: bool, len: usize) -> Self {
let mut out = Self::with_capacity(len);
unsafe {
out.set_len(len);
out.as_raw_mut_slice().fill_with(|| {
BitStore::new(if bit { !<T::Mem>::ZERO } else { <T::Mem>::ZERO })
});
}
out
}

In BitVec::repeat, after calling set_len on the bitvec, BitStore::new is called repeatedly to fill the newly created slots. However, this function is a generic function that can be controlled by user. So if user calls panic in BitStore::new, the slots will not be filled. Users can therefore access those uninitialized slots in safe context.

This is a typical pattern as suggested in the Rustonomicon, and as suggested by that chapter, to fix it, we can set length after filling the slots.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions