forked from PoliEcho-holding-org/kern
random numer generation
This commit is contained in:
@@ -0,0 +1,8 @@
|
||||
#ifndef _RANDOM_H
|
||||
#define _RANDOM_H
|
||||
|
||||
#include <types.h>
|
||||
void rand_init();
|
||||
|
||||
extern uint64_t (*get_random_number)();
|
||||
#endif
|
||||
@@ -0,0 +1,52 @@
|
||||
#include "kernel.h"
|
||||
#include <system.h>
|
||||
#include <types.h>
|
||||
|
||||
uint64_t (*get_random_number)();
|
||||
|
||||
// this starting value it truly random i have thrown a dice few times
|
||||
uint64_t LFSR = 61113534451;
|
||||
|
||||
// RDSEED may be backdoored by NSA
|
||||
extern uint64_t rand_rdrand();
|
||||
asm(".intel_syntax noprefix\n"
|
||||
".global rand_rdrand\n"
|
||||
"rand_rdrand:"
|
||||
" rdrand rax\n"
|
||||
" ret\n"
|
||||
".att_syntax prefix\n");
|
||||
|
||||
uint64_t rand_software() {
|
||||
uint64_t lsb = LFSR & 1;
|
||||
LFSR >>= 1;
|
||||
if (lsb) {
|
||||
LFSR ^= 0x800000000000000DULL;
|
||||
}
|
||||
return LFSR;
|
||||
}
|
||||
|
||||
void rand_init() {
|
||||
uint32_t eax = 1, ebx = 0, ecx = 0, edx = 0;
|
||||
cpuid(&eax, &ebx, &ecx, &edx);
|
||||
|
||||
// check for RDRAND
|
||||
if ((ecx >> 30) & 1) {
|
||||
get_random_number = rand_rdrand;
|
||||
} else {
|
||||
printk("[\e[33mWARNING\e[0m] RDRAND not available falling back "
|
||||
"to software\n");
|
||||
// check for RDSEED
|
||||
if ((ebx >> 18) & 1) {
|
||||
asm(".intel_syntax noprefix\n"
|
||||
"rdseed %0\n"
|
||||
".att_syntax prefix\n"
|
||||
: "=r"(LFSR));
|
||||
} else {
|
||||
printk("[\e[\e[33mWARNING\e[0m] RDSEED not available "
|
||||
"falling back "
|
||||
"to developers dice trows\n");
|
||||
}
|
||||
get_random_number = rand_software;
|
||||
}
|
||||
printk("[\e[32mINFO\e[0m] RNG initialized!\n");
|
||||
}
|
||||
Reference in New Issue
Block a user