]> git.ipfire.org Git - thirdparty/chrony.git/commitdiff
util: add function to generate random bytes
authorMiroslav Lichvar <mlichvar@redhat.com>
Tue, 10 Nov 2015 15:46:40 +0000 (16:46 +0100)
committerMiroslav Lichvar <mlichvar@redhat.com>
Mon, 16 Nov 2015 09:26:14 +0000 (10:26 +0100)
Add a function to fill a buffer with random bytes which uses a better
PRNG than random(). Use arc4random() if it's available on the system.
Fall back to reading from /dev/urandom, which should be available on
all currently supported systems.

configure
util.c
util.h

index e9e596ddc0bc2442ead54c442c68917755349b25..16fdf8dc9222e426c2fb87d822d05ee43deb5e37 100755 (executable)
--- a/configure
+++ b/configure
@@ -567,6 +567,10 @@ then
   MYCFLAGS="$MYCFLAGS -pthread"
 fi
 
+if test_code 'arc4random_buf()' 'stdlib.h' '' '' 'arc4random_buf(NULL, 0);'; then
+  add_def HAVE_ARC4RANDOM
+fi
+
 timepps_h=""
 if [ $feat_refclock = "1" ] && [ $feat_pps = "1" ]; then
   if test_code '<sys/timepps.h>' 'sys/timepps.h' '' '' ''; then
diff --git a/util.c b/util.c
index 247037cac3802676351c593e5468abed20d65aee..f6a77275ff834149909be4f23bed1e76ebacd0c7 100644 (file)
--- a/util.c
+++ b/util.c
@@ -1070,3 +1070,23 @@ UTI_CheckDirPermissions(const char *path, mode_t perm, uid_t uid, gid_t gid)
 
   return 1;
 }
+
+/* ================================================== */
+
+#define DEV_URANDOM "/dev/urandom"
+
+void
+UTI_GetRandomBytes(void *buf, unsigned int len)
+{
+#ifdef HAVE_ARC4RANDOM
+  arc4random_buf(buf, len);
+#else
+  static FILE *f = NULL;
+  if (!f)
+    f = fopen(DEV_URANDOM, "r");
+  if (!f)
+    LOG_FATAL(LOGF_Util, "Can't open %s : %s", DEV_URANDOM, strerror(errno));
+  if (fread(buf, 1, len, f) != len)
+    LOG_FATAL(LOGF_Util, "Can't read from %s", DEV_URANDOM);
+#endif
+}
diff --git a/util.h b/util.h
index d3fa9e7b924e248e62d9049e9cff0acbad555cad..0a49fe6fd28aae43736372b2c7b6d9b09f15ac86 100644 (file)
--- a/util.h
+++ b/util.h
@@ -144,4 +144,7 @@ extern int UTI_CreateDirAndParents(const char *path, mode_t mode, uid_t uid, gid
    permissions and its uid/gid must match the specified values. */
 extern int UTI_CheckDirPermissions(const char *path, mode_t perm, uid_t uid, gid_t gid);
 
+/* Fill buffer with random bytes */
+extern void UTI_GetRandomBytes(void *buf, unsigned int len);
+
 #endif /* GOT_UTIL_H */