brndnmtthws / dryoc

Don't Roll Your Own Crypto: pure-Rust, hard to misuse cryptography library
https://docs.rs/dryoc
MIT License
267 stars 14 forks source link

[Bug]: Trivially Unsound code (out of bounds memory access) #23

Closed jnhev42 closed 1 year ago

jnhev42 commented 1 year ago

What happened?

This code:

impl<const LENGTH: usize> ByteArray<LENGTH> for Vec<u8> {
    #[inline]
    fn as_array(&self) -> &[u8; LENGTH] {
        let arr = self.as_ptr() as *const [u8; LENGTH];
        unsafe { &*arr }
    }
}

will cast Vec's of a size below LENGTH to an array of LENGTH, leading to out-of-bounds reads source link

Version

0.4.0

Which OS are you seeing the problem on?

Linux

Test code

`vec![1, 2].as_array()[2]` <- out of bounds read.
brndnmtthws commented 1 year ago

As a general rule, casting a vec to an array is not a great thing, but it can be convenient. Most of the critical bits use fixed-length arrays (keys, nonces, etc) so while this is indeed a bug, I wouldn't consider it critical.

In any case, thanks for reporting it. I've added an assertion which will trigger an error in both debug and release mode.