Get the random value from /dev/urandom 13/299113/2
authorilho kim <ilho159.kim@samsung.com>
Wed, 20 Sep 2023 04:02:36 +0000 (13:02 +0900)
committerilho kim <ilho159.kim@samsung.com>
Wed, 20 Sep 2023 04:12:10 +0000 (13:12 +0900)
g_random_int() is not appropriate for cryptographic purposes

Change-Id: Ic60520c50b5f3fe82b12b25e5e8c372149a11e74
Signed-off-by: ilho kim <ilho159.kim@samsung.com>
plugin/app2sd/server/app2sd_internals_utils.c

index 678ace0..59219e6 100644 (file)
@@ -343,6 +343,19 @@ char *_app2sd_execute_command(const char *argv[])
 
 }
 
+static int generate_random_num(unsigned short* buf, int len) {
+       int fd = open("/dev/urandom", O_RDONLY);
+       if (fd < 0)
+               return -1;
+
+       if (read(fd, buf, len) < 0)
+               return -1;
+
+       close(fd);
+
+       return 0;
+}
+
 /*
 * This is a simple password generator
 * return: On success, it will return the password, else NULL.
@@ -354,6 +367,12 @@ char *_app2sd_generate_password(void)
                "!\"#$%&()*+,-./0123456789:;<=>?@ABCDE" \
                "FGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
        int i;
+       unsigned short rand_nums[PASSWD_LEN];
+
+       if (generate_random_num(rand_nums, sizeof(rand_nums)) < 0) {
+               _E("Failed to read random data");
+               return NULL;
+       }
 
        /* include null byte */
        passwd = (char *)malloc(sizeof(char) * (PASSWD_LEN + 1));
@@ -363,7 +382,7 @@ char *_app2sd_generate_password(void)
        }
 
        for (i = 0; i < PASSWD_LEN; i++)
-               passwd[i] = charset[g_random_int() % ASCII_PASSWD_CHAR];
+               passwd[i] = charset[rand_nums[i] % ASCII_PASSWD_CHAR];
        passwd[i] = '\0';
 
        return passwd;