Skip to content

Instantly share code, notes, and snippets.

@colmmacc
Created November 21, 2019 17:55
Show Gist options
  • Save colmmacc/034f86227cfb0f8ec34193fd56ed78e8 to your computer and use it in GitHub Desktop.
Save colmmacc/034f86227cfb0f8ec34193fd56ed78e8 to your computer and use it in GitHub Desktop.
extern crate sha2;
extern crate nix;
extern crate libc;
use sha2::{Sha256, Digest};
use nix::request_code_write;
use std::os::unix::prelude::*;
use std::os::raw::c_int;
use std::fs::File;
use std::mem;
fn main() -> Result<(), Error> {
// Get 256-bits of entropy from a function that returns a Sha2 object
let hash = match get_hash_with_entropy() {
Ok(hash) => hash,
Err(error) => {
panic!("Could not get hash: {:?}", error)
},
};
// Open /dev/random, since we want to add entropy to it
let random = match File::open("/dev/random") {
Ok(random) => random,
Err(error) => {
panic!("Could not open /dev/random: {:?}", error)
},
};
// We want to add at least 256-bits of entropy
const ENTROPY_BITS : usize = 256;
const ENTROPY_BYTES : usize = ENTROPY_BITS / 8;
// Clone of the C rand_pool_info struct for the RNDADDENTROPY ioctl()
// See the manpage on /dev/random
#[repr(C)]
struct RandPoolInfo {
entropy_count: c_int,
bufsize: c_int,
buffer: [u8; ENTROPY_BYTES],
}
// Set up a struct with 256-bits of entropy
let mut entropy = RandPoolInfo{ entropy_count: ENTROPY_BITS as i32,
bufsize: ENTROPY_BYTES as i32,
buffer: [0; ENTROPY_BYTES] };
entropy.buffer.copy_from_slice(&hash.result());
// Add the entropy to the kernel
unsafe {
// The paramaters to request_code_write come from the definition of RNDADDENTROPY
//
// _IOW( 'R', 0x03, int [2] )
//
// The parameters here become 'R', 0x03, and the size of the 3rd parameter in bytes.
let r = libc::ioctl(random.as_raw_fd(), request_code_write!(b'R', 0x03, 2 * mem::size_of::<c_int>()), &mut entropy);
if r < 0 {
panic!("Could not add entropy. Are you running as root?");
}
}
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment