iSulad/0163-use-RAND_bytes-to-replace-dev-urandom.patch
openeuler-sync-bot 955d185c18 !645 [sync] PR-641: upgrade from upstream
* upgrade from upstream
2023-12-22 01:09:39 +00:00

86 lines
2.7 KiB
Diff

From ba57a3d8c0c26b3792b2daa191a6e76fa546a25d Mon Sep 17 00:00:00 2001
From: zhongtao <zhongtao17@huawei.com>
Date: Sat, 25 Nov 2023 22:25:03 +1400
Subject: [PATCH 163/181] use RAND_bytes to replace /dev/urandom
Signed-off-by: zhongtao <zhongtao17@huawei.com>
---
src/utils/cutils/utils.c | 25 +++++++++----------------
src/utils/cutils/utils.h | 2 ++
2 files changed, 11 insertions(+), 16 deletions(-)
diff --git a/src/utils/cutils/utils.c b/src/utils/cutils/utils.c
index a994731d..46a478b6 100644
--- a/src/utils/cutils/utils.c
+++ b/src/utils/cutils/utils.c
@@ -37,6 +37,7 @@
#include <termios.h> // IWYU pragma: keep
#include <strings.h>
#include <time.h>
+#include <openssl/rand.h>
#include "isula_libutils/log.h"
#include "isula_libutils/json_common.h"
@@ -1274,37 +1275,29 @@ void util_usleep_nointerupt(unsigned long usec)
int util_generate_random_str(char *id, size_t len)
{
- int fd = -1;
- int num = 0;
+#define MAX_RANDOM_BYTES_LEN 100
size_t i;
- const int m = 256;
+ unsigned char random_bytes[MAX_RANDOM_BYTES_LEN] = { 0 };
+ len = len / 2;
- if (id == NULL) {
+ if (id == NULL || len > MAX_RANDOM_BYTES_LEN) {
+ ERROR("Invalid id or len");
return -1;
}
- len = len / 2;
- fd = open("/dev/urandom", O_RDONLY);
- if (fd == -1) {
- ERROR("Failed to open /dev/urandom");
+ if (RAND_bytes((unsigned char *)random_bytes, len) != 1) {
+ ERROR("Failed to get random bytes by RAND_bytes");
return -1;
}
for (i = 0; i < len; i++) {
int nret;
- if (util_read_nointr(fd, &num, sizeof(int)) < 0) {
- ERROR("Failed to read urandom value");
- close(fd);
- return -1;
- }
- unsigned char rs = (unsigned char)(num % m);
+ unsigned char rs = random_bytes[i];
nret = snprintf((id + i * 2), ((len - i) * 2 + 1), "%02x", (unsigned int)rs);
if (nret < 0 || (size_t)nret >= ((len - i) * 2 + 1)) {
ERROR("Failed to snprintf random string");
- close(fd);
return -1;
}
}
- close(fd);
id[i * 2] = '\0';
return 0;
}
diff --git a/src/utils/cutils/utils.h b/src/utils/cutils/utils.h
index bb510062..5a1592fd 100644
--- a/src/utils/cutils/utils.h
+++ b/src/utils/cutils/utils.h
@@ -375,6 +375,8 @@ int util_input_noecho(char *buf, size_t maxlen);
void util_usleep_nointerupt(unsigned long usec);
+// id : random string, notice: the length of id needs to be len + 1
+// len : the length of the random string that needs to be generated, notice: len needs to be an even number
int util_generate_random_str(char *id, size_t len);
int util_check_inherited_exclude_fds(bool closeall, int *fds_to_ignore, size_t len_fds);
--
2.42.0