emulator: Replace random number generation function
authorTedd Ho-Jeong An <tedd.an@intel.com>
Wed, 8 Dec 2021 22:39:19 +0000 (14:39 -0800)
committerAyush Garg <ayush.garg@samsung.com>
Fri, 11 Mar 2022 13:38:38 +0000 (19:08 +0530)
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

Signed-off-by: Anuj Jain <anuj01.jain@samsung.com>
Signed-off-by: Ayush Garg <ayush.garg@samsung.com>
emulator/le.c
emulator/phy.c

index 07a44c5..f8f313f 100755 (executable)
@@ -20,6 +20,7 @@
 #include <sys/socket.h>
 #include <sys/un.h>
 #include <sys/uio.h>
+#include <sys/random.h>
 #include <time.h>
 
 #include "lib/bluetooth.h"
@@ -503,11 +504,17 @@ static void send_adv_pkt(struct bt_le *hci, uint8_t channel)
 
 static unsigned int get_adv_delay(void)
 {
+       unsigned int val;
+
        /* The advertising delay is a pseudo-random value with a range
         * of 0 ms to 10 ms generated for each advertising event.
         */
-       srand(time(NULL));
-       return (rand() % 11);
+       if (getrandom(&val, sizeof(val), 0) < 0) {
+               /* If it fails to get the random number, use a static value */
+               val = 5;
+       }
+
+       return (val % 11);
 }
 
 static void adv_timeout_callback(int id, void *user_data)
index 2f53d72..42e808c 100755 (executable)
@@ -18,6 +18,7 @@
 #include <stdlib.h>
 #include <string.h>
 #include <sys/socket.h>
+#include <sys/random.h>
 #include <netinet/in.h>
 #include <netinet/ip.h>
 #include <time.h>
@@ -172,8 +173,13 @@ struct bt_phy *bt_phy_new(void)
        mainloop_add_fd(phy->rx_fd, EPOLLIN, phy_rx_callback, phy, NULL);
 
        if (!get_random_bytes(&phy->id, sizeof(phy->id))) {
-               srandom(time(NULL));
-               phy->id = random();
+               if (getrandom(&phy->id, sizeof(phy->id), 0) < 0) {
+                       mainloop_remove_fd(phy->rx_fd);
+                       close(phy->tx_fd);
+                       close(phy->rx_fd);
+                       free(phy);
+                       return NULL;
+               }
        }
 
        bt_phy_send(phy, BT_PHY_PKT_NULL, NULL, 0);