From e4b6decf72a91453bc8d31b4b15e7aed923c56d2 Mon Sep 17 00:00:00 2001 From: Dirk Engling Date: Sat, 24 Oct 2026 01:45:53 +0200 Subject: Add a new facility that handles entropy abstraction --- ot_random.c | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 ot_random.c (limited to 'ot_random.c') diff --git a/ot_random.c b/ot_random.c new file mode 100644 index 0000000..3fae876 --- /dev/null +++ b/ot_random.c @@ -0,0 +1,53 @@ +/* This software was written by Dirk Engling + It is considered beerware. Prost. Skol. Cheers or whatever. + + $id$ */ + +/* System */ +#include +#include + +/* Opentracker */ +#include "ot_random.h" + +#ifdef WANT_INSECURE_RANDOM_FALLBACK + +#warning WANT_INSECURE_RANDOM_FALLBACK builds without arc4random. UDP connection ids become predictable and announces can be forged. Do not ship this. + +#include + +void random_init(void) { +#ifdef WANT_DEV_RANDOM + srandomdev(); +#else + srandom(time(NULL)); +#endif +} + +/* random() yields 31 bits, so one draw can never set the top bit. Combine + two of them rather than hand out a value that is quietly half as wide as + its type claims. */ +uint32_t random_uint32(void) { return ((uint32_t)random() << 16) ^ (uint32_t)random(); } + +void random_bytes(void *buf, size_t len) { + uint8_t *out = buf; + /* random() leaves the top bit clear and its lowest bits are the weakest, + so take a byte from the middle of each draw */ + while (len--) + *out++ = (uint8_t)(random() >> 8); +} + +#else + +#if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__) && !defined(__DragonFly__) && !defined(__APPLE__) && \ + !(defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 36))) +#include +#endif + +void random_init(void) {} + +uint32_t random_uint32(void) { return arc4random(); } + +void random_bytes(void *buf, size_t len) { arc4random_buf(buf, len); } + +#endif -- cgit v1.3