diff mbox series

[BlueZ,V2,5/5] profiles/health: Replace random number generation function

Message ID 20211208223923.519664-6-hj.tedd.an@gmail.com
State New
Headers show
Series Replace random number generation function | expand

Commit Message

Tedd Ho-Jeong An Dec. 8, 2021, 10:39 p.m. UTC
From: Tedd Ho-Jeong An <tedd.an@intel.com>

This patch replaces the rand() function to the getrandom() syscall.

It was reported by the Coverity scan
  rand() should not be used for security-related applications, because
  linear congruential algorithms are too easy to break
---
 profiles/health/hdp.c  | 11 +++++++----
 profiles/health/mcap.c | 17 +++++++++++++++--
 2 files changed, 22 insertions(+), 6 deletions(-)
diff mbox series

Patch

diff --git a/profiles/health/hdp.c b/profiles/health/hdp.c
index 6bc41946f..40b6cc18a 100644
--- a/profiles/health/hdp.c
+++ b/profiles/health/hdp.c
@@ -16,6 +16,7 @@ 
 #include <stdint.h>
 #include <stdbool.h>
 #include <unistd.h>
+#include <sys/random.h>
 
 #include <glib.h>
 
@@ -1484,13 +1485,15 @@  static void destroy_create_dc_data(gpointer data)
 static void *generate_echo_packet(void)
 {
 	uint8_t *buf;
-	int i;
 
 	buf = g_malloc(HDP_ECHO_LEN);
-	srand(time(NULL));
+	if (!buf)
+		return NULL;
 
-	for(i = 0; i < HDP_ECHO_LEN; i++)
-		buf[i] = rand() % UINT8_MAX;
+	if (getrandom(buf, HDP_ECHO_LEN, 0) < 0) {
+		g_free(buf);
+		return NULL;
+	}
 
 	return buf;
 }
diff --git a/profiles/health/mcap.c b/profiles/health/mcap.c
index 5161ef77c..aad0a08a3 100644
--- a/profiles/health/mcap.c
+++ b/profiles/health/mcap.c
@@ -19,6 +19,7 @@ 
 #include <errno.h>
 #include <unistd.h>
 #include <time.h>
+#include <sys/random.h>
 
 #include <glib.h>
 
@@ -1888,6 +1889,7 @@  gboolean mcap_create_mcl(struct mcap_instance *mi,
 {
 	struct mcap_mcl *mcl;
 	struct connect_mcl *con;
+	uint16_t val;
 
 	mcl = find_mcl(mi->mcls, addr);
 	if (mcl) {
@@ -1903,7 +1905,12 @@  gboolean mcap_create_mcl(struct mcap_instance *mi,
 		mcl->state = MCL_IDLE;
 		bacpy(&mcl->addr, addr);
 		set_default_cb(mcl);
-		mcl->next_mdl = (rand() % MCAP_MDLID_FINAL) + 1;
+		if (getrandom(&val, sizeof(val), 0) < 0) {
+			mcap_instance_unref(mcl->mi);
+			g_free(mcl);
+			return FALSE;
+		}
+		mcl->next_mdl = (val % MCAP_MDLID_FINAL) + 1;
 	}
 
 	mcl->ctrl |= MCAP_CTRL_CONN;
@@ -2013,6 +2020,7 @@  static void connect_mcl_event_cb(GIOChannel *chan, GError *gerr,
 	bdaddr_t dst;
 	char address[18], srcstr[18];
 	GError *err = NULL;
+	uint16_t val;
 
 	if (gerr)
 		return;
@@ -2041,7 +2049,12 @@  static void connect_mcl_event_cb(GIOChannel *chan, GError *gerr,
 		mcl->mi = mcap_instance_ref(mi);
 		bacpy(&mcl->addr, &dst);
 		set_default_cb(mcl);
-		mcl->next_mdl = (rand() % MCAP_MDLID_FINAL) + 1;
+		if (getrandom(&val, sizeof(val), 0) < 0) {
+			mcap_instance_unref(mcl->mi);
+			g_free(mcl);
+			goto drop;
+		}
+		mcl->next_mdl = (val % MCAP_MDLID_FINAL) + 1;
 	}
 
 	set_mcl_conf(chan, mcl);