From 50300f846fc1861efe01c104a7ce9c483e3afcf1 Mon Sep 17 00:00:00 2001 From: Leah Rowe Date: Thu, 19 Mar 2026 08:07:47 +0000 Subject: util/nvmutil: hardened mkstemp 200 retries, not 100. and open with O_NOFOLLOW and O_CLOEXEC check X on mkstemp support more than 6 X in mkstemp make PATH_LEN 4096 1024 is a bit low make default mkstemp length 4096 Signed-off-by: Leah Rowe --- util/nvmutil/include/common.h | 4 ++-- util/nvmutil/lib/file.c | 42 +++++++++++++++++++++++++++++++----------- 2 files changed, 33 insertions(+), 13 deletions(-) (limited to 'util') diff --git a/util/nvmutil/include/common.h b/util/nvmutil/include/common.h index 4173ca6e..8e8ee96c 100644 --- a/util/nvmutil/include/common.h +++ b/util/nvmutil/include/common.h @@ -35,7 +35,7 @@ int fchmod(int fd, mode_t mode); #define MAX_CMD_LEN 50 #ifndef PATH_LEN -#define PATH_LEN 1024 +#define PATH_LEN 4096 #endif #define OFF_ERR 0 @@ -421,7 +421,7 @@ const char *getnvmprogname(void); */ char *new_tmpfile(int *fd, int local, const char *path); -int x_i_mkstemp(char *template); +int mkstemp_n(char *template); char *x_c_tmpdir(void); int close_on_eintr(int fd); int fsync_on_eintr(int fd); diff --git a/util/nvmutil/lib/file.c b/util/nvmutil/lib/file.c index 408562dc..406c4618 100644 --- a/util/nvmutil/lib/file.c +++ b/util/nvmutil/lib/file.c @@ -310,7 +310,7 @@ new_tmpfile(int *fd, int local, const char *path) dest[tmppath_len] = '\0'; - fd_tmp = x_i_mkstemp(dest); + fd_tmp = mkstemp_n(dest); if (fd_tmp == -1) goto err_new_tmpfile; @@ -421,36 +421,56 @@ x_c_tmpdir(void) */ int -x_i_mkstemp(char *template) +mkstemp_n(char *template) { int fd; - int i, j; + unsigned long i, j; unsigned long len; char *p; - char ch[] = + unsigned long xc = 0; + + static char ch[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; unsigned long r; + unsigned long max_len = +#ifndef PATH_LEN + 4096; +#else + (PATH_LEN); +#endif - len = xstrxlen(template, PATH_LEN); + len = xstrxlen(template, max_len); - /* find trailing XXXXXX */ - if (len < 6) + if (len < 6) { + errno = EINVAL; return -1; + } + + p = template + len; - p = template + len - 6; + while (p > template && p[-1] == 'X') { + --p; + ++xc; + } + + if (xc < 6) { + errno = EINVAL; + return -1; + } - for (i = 0; i < 100; i++) { + for (i = 0; i < 200; i++) { - for (j = 0; j < 6; j++) { + for (j = 0; j < xc; j++) { r = rlong(); p[j] = ch[(unsigned long)(r >> 1) % (sizeof(ch) - 1)]; } - fd = open(template, O_RDWR | O_CREAT | O_EXCL, 0600); + fd = open(template, + O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600); if (fd >= 0) return fd; -- cgit v1.2.1