Просмотр исходного кода

LibC: add arc4random* using new getrandom syscall

Serenity is really not production ready; I shouldn't have to warn
you not to trust the RNG here. This is for compatibility with
software expecting the interface.

arc4random does expose an annoying flaw with the syscall I want
to discuss with Kling though.
Calvin Buckley 5 лет назад
Родитель
Сommit
aa42f56210
2 измененных файлов с 30 добавлено и 0 удалено
  1. 26 0
      Libraries/LibC/stdlib.cpp
  2. 4 0
      Libraries/LibC/stdlib.h

+ 26 - 0
Libraries/LibC/stdlib.cpp

@@ -505,3 +505,29 @@ unsigned long long strtoull(const char* str, char** endptr, int base)
     return value;
 }
 
+// Serenity's PRNG is not cryptographically secure. Do not rely on this for
+// any real crypto! These functions (for now) are for compatibility.
+// TODO: In the future, rand can be made determinstic and this not.
+uint32_t arc4random(void)
+{
+    char buf[4];
+    // XXX: RandomDevice does return a uint32_t but the syscall works with
+    // a byte at a time. It could be better optimzied for this use case
+    // while remaining generic.
+    syscall(SC_getrandom, buf, 4, 0);
+    return *(uint32_t*)buf;
+}
+
+void arc4random_buf(void* buffer, size_t buffer_size)
+{
+    // arc4random_buf should never fail, but user supplied buffers could fail.
+    // However, if the user passes a garbage buffer, that's on them.
+    syscall(SC_getrandom, buffer, buffer_size, 0);
+}
+
+uint32_t arc4random_uniform(uint32_t max_bounds)
+{
+    // XXX: Should actually apply special rules for uniformity; avoid what is
+    // called "modulo bias".
+    return arc4random() % max_bounds;
+}

+ 4 - 0
Libraries/LibC/stdlib.h

@@ -54,6 +54,10 @@ void srand(unsigned seed);
 long int random();
 void srandom(unsigned seed);
 
+uint32_t arc4random(void);
+void arc4random_buf(void*, size_t);
+uint32_t arc4random_uniform(uint32_t);
+
 typedef struct {
     int quot;
     int rem;