Modified to use /dev/urandom instead of random()
[platform/core/connectivity/net-config.git] / src / wifi-key-encryption.c
index a34ac97..13391d3 100755 (executable)
@@ -18,6 +18,9 @@
  */
 
 #include <stdlib.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
 #include <glib.h>
 #include <ckmc/ckmc-type.h>
 #include <ckmc/ckmc-manager.h>
@@ -30,6 +33,7 @@
 #define KEY_ALIAS      "connman_wifi_passphrase"
 #define IV_ALIAS       "connman_wifi_enciv"
 #define AAD_ALIAS      "connman_wifi_gcmaad"
+#define URANDOM                "/dev/urandom"
 
 #define PASSPHRASE     "Passphrase"
 #define RND_LENGTH     32
@@ -47,15 +51,33 @@ static char* err_str;
 static int err;
 
 
-static void __netconfig_generate_random_bytes(unsigned char* bytes, int len)
+static int __netconfig_generate_random_bytes(unsigned char* bytes, int len)
 {
-       int i = 0;
-
-       srandom(time(NULL));
-
-       while (len--)
-               bytes[i++] = (unsigned char)random();
+       int urfd = -1;
+       int r;
+
+       if (len <= 0)
+               return 0;
+
+       urfd = open(URANDOM, O_RDONLY);
+       if (urfd < 0) {
+               ERR("Could not open "URANDOM);
+               return 0;
+       } else {
+               r = read(urfd, bytes, len);
+               if (r < 0) {
+                       ERR("Could not read from "URANDOM);
+                       close(urfd);
+                       return 0;
+               } else if (r != len) {
+                       ERR("Short read from "URANDOM);
+                       close(urfd);
+                       return 0;
+               }
+       }
 
+       close(urfd);
+       return 1;
 }
 
 static void __netconfig_convert_hexstr_to_bytes(gchar* hexstr, int hlen, gchar* bin)
@@ -110,7 +132,8 @@ static void*  __netconfig_set_param_list_aes_gcm(ckmc_param_list_h param)
                policy.extractable = true;
                policy.password = NULL;
 
-               __netconfig_generate_random_bytes(rnd, RND_LENGTH);
+               if (!__netconfig_generate_random_bytes(rnd, RND_LENGTH))
+                       return NULL;
 
                CKMC_ERROR_HANDLING(
                                ckmc_buffer_new(rnd, RND_LENGTH, &iv_buf),
@@ -128,7 +151,10 @@ static void*  __netconfig_set_param_list_aes_gcm(ckmc_param_list_h param)
                policy.extractable = true;
                policy.password = NULL;
 
-               __netconfig_generate_random_bytes(aad, RND_LENGTH);
+               if (!__netconfig_generate_random_bytes(aad, RND_LENGTH)) {
+                       ckmc_buffer_free(iv_buf);
+                       return NULL;
+               }
 
                CKMC_ERROR_HANDLING(
                                ckmc_buffer_new(aad, RND_LENGTH, &aad_buf),