i have to make a device driver that returns a random number between 1 – 50 and am confused on how the buffer for my device driver works, and how to go about getting it to behave like /dev/random.
i made a test program to see how /dev/random works:
int test_read = open("/dev/random", O_RDONLY);
int get_random_num(void) {
unsigned int random_num;
read(test_read, &random_num, sizeof(random_num));
return (random_num % 50) + 1;
}
and then this is my device driver’s read function(concised version):
my_random_read(struct file* file, char* buf,
size_t count, loff_t* ppos)
{
unsigned int random_num;
get_random_bytes(&random_num, 1);
int my_num = 1 + (random_num % 50)
int* my_num_pointer = &my_num;
copy_to_user(buf, my_num_pointer, count);
}
when i run my tester on QEMU i get -1074311964 : /
how can i make it so that all i would have to do is replace /dev/random with /dev/my_random??
this is how i’m reading from /dev/my_random:
read(test_read, &random_number, sizeof(random_number), 0);
You’re using
get_random_bytes()incorrectly. The second parameter is the number of bytes, not words:You’re further returning private kernel memory to userspace:
You’ve performed no validations on
count— you only have one, maybe two, bytes of actual random data here. The rest of the data is garbage stack data and you’ve leaked it to userspace here. This is a security flaw — the kernel should not leak uninitialized data to userspace. (It might be garbage to rely on it yourself but an attacker that asks for ten pages of data from/dev/randomshould not get raw kernel memory.)