Skip to content

Commit

Permalink
Fix an infinite loop and a range check in getentropy. (#96)
Browse files Browse the repository at this point in the history
`getentropy` can fill up 256 buffers, but not larger.
  • Loading branch information
sunfishcode committed Dec 12, 2023
1 parent 38444de commit a902a11
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions c-scape/src/rand_.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ unsafe extern "C" fn getentropy(ptr: *mut c_void, len: usize) -> i32 {
return 0;
}

if len >= 256 {
if len > 256 {
set_errno(Errno(libc::EIO));
return -1;
}
Expand All @@ -41,7 +41,7 @@ unsafe extern "C" fn getentropy(ptr: *mut c_void, len: usize) -> i32 {

let mut filled = 0usize;

while !buf.is_empty() {
while filled < buf.len() {
match rustix::rand::getrandom_uninit(&mut buf[filled..], flags) {
Ok((init, _uninit)) => filled += init.len(),
Err(rustix::io::Errno::INTR) => {}
Expand All @@ -54,3 +54,17 @@ unsafe extern "C" fn getentropy(ptr: *mut c_void, len: usize) -> i32 {

0
}

#[cfg(any(target_os = "android", target_os = "linux"))]
#[test]
fn test_getentropy() {
unsafe {
let mut buf = [0; 257];
assert_eq!(getentropy(buf.as_mut_ptr().cast(), 257), -1);
assert_eq!(errno::errno().0, libc::EIO);

let mut buf = [0; 257];
assert_eq!(getentropy(buf.as_mut_ptr().cast(), 256), 0);
assert!(buf.iter().any(|b| *b != 0));
}
}

0 comments on commit a902a11

Please sign in to comment.