]> xenbits.xensource.com Git - xen.git/commitdiff
libxl: add libxl__random_bytes() which fills a buffer with random bytes
authorDavid Vrabel <david.vrabel@citrix.com>
Wed, 18 Jun 2014 16:12:51 +0000 (17:12 +0100)
committerIan Campbell <ian.campbell@citrix.com>
Fri, 27 Jun 2014 13:13:21 +0000 (14:13 +0100)
The random bytes are obtained from /dev/urandom and are suitable for
almost all uses (except for generating long-lived secure keys).

Documentation suggests that /dev/urandom is widely available on Unix-like
systems (such FreeBSD and NetBSD).

A public libxl_random_bytes() (or similar) could be trivially added,
if this required in the future.

Signed-off-by: David Vrabel <david.vrabel@citrix.com>
Acked-by: Ian Campbell <ian.campbell@citrix.com>
tools/libxl/libxl_internal.h
tools/libxl/libxl_utils.c

index a0d4f241d42c6bb8f87fd3dcafcd005e0d681e17..a9343e8dcea432d3217616044457619e7d42b0fc 100644 (file)
@@ -3180,6 +3180,8 @@ int libxl__uint64_parse_json(libxl__gc *gc, const libxl__json_object *o,
 int libxl__string_parse_json(libxl__gc *gc, const libxl__json_object *o,
                              char **p);
 
+int libxl__random_bytes(libxl__gc *gc, uint8_t *buf, size_t len);
+
 #endif
 
 /*
index 16b734efd033c666da30743771a7e77392a42ff5..0001ab8f17bcc6d1395698f44f205ccf7f7f8e9e 100644 (file)
@@ -1013,6 +1013,28 @@ int libxl_domid_valid_guest(uint32_t domid)
     return domid > 0 && domid < DOMID_FIRST_RESERVED;
 }
 
+/*
+ * Fill @buf with @len random bytes.
+ */
+int libxl__random_bytes(libxl__gc *gc, uint8_t *buf, size_t len)
+{
+    static const char *dev = "/dev/urandom";
+    int fd;
+    int ret;
+
+    fd = open(dev, O_RDONLY | O_CLOEXEC);
+    if (fd < 0) {
+        LOGE(ERROR, "failed to open \"%s\"", dev);
+        return ERROR_FAIL;
+    }
+
+    ret = libxl_read_exactly(CTX, fd, buf, len, dev, NULL);
+
+    close(fd);
+
+    return ret;
+}
+
 /*
  * Local variables:
  * mode: C