From 9307dcd33043fab97e5d8498c5c62a22fc577ee0 Mon Sep 17 00:00:00 2001
From: Simon McVittie <smcv@collabora.com>
Date: Mon, 3 Aug 2020 19:52:52 +0100
Subject: [PATCH] utils: Add pv_get_random_uuid()

This will be used to generate securely-unique socket names that are not
an opportunity for denial of service.

Signed-off-by: Simon McVittie <smcv@collabora.com>
---
 src/utils.c | 31 +++++++++++++++++++++++++++++++
 src/utils.h |  2 ++
 2 files changed, 33 insertions(+)

diff --git a/src/utils.c b/src/utils.c
index 55450d3c4..2fc26db88 100644
--- a/src/utils.c
+++ b/src/utils.c
@@ -544,3 +544,34 @@ pv_async_signal_safe_error (const char *message,
 
   _exit (exit_status);
 }
+
+#define PROC_SYS_KERNEL_RANDOM_UUID "/proc/sys/kernel/random/uuid"
+
+/**
+ * pv_get_random_uuid:
+ * @error: Used to raise an error on failure
+ *
+ * Return a random UUID (RFC 4122 version 4) as a string.
+ * It is a 128-bit quantity, with 122 bits of entropy, and 6 fixed bits
+ * indicating the "variant" (type, 0b10) and "version" (subtype, 0b0100).
+ *
+ * Returns: (transfer full): A random UUID, or %NULL on error
+ */
+gchar *
+pv_get_random_uuid (GError **error)
+{
+  g_autofree gchar *contents = NULL;
+
+  if (!g_file_get_contents (PROC_SYS_KERNEL_RANDOM_UUID,
+                            &contents, NULL, error))
+    return NULL;
+
+  g_strchomp (contents);    /* delete trailing newline */
+
+  /* Format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx */
+  if (strlen (contents) != 36)
+    return glnx_null_throw (error, "%s not in expected format",
+                            PROC_SYS_KERNEL_RANDOM_UUID);
+
+  return g_steal_pointer (&contents);
+}
diff --git a/src/utils.h b/src/utils.h
index 49c065ef3..d4215d0f6 100644
--- a/src/utils.h
+++ b/src/utils.h
@@ -58,3 +58,5 @@ FILE *pv_divert_stdout_to_stderr (GError **error);
 
 void pv_async_signal_safe_error (const char *message,
                                  int exit_status) G_GNUC_NORETURN;
+
+gchar *pv_get_random_uuid (GError **error);
-- 
GitLab