From d9d1a10b262c3a6ac01844002e15d1bf9ab90981 Mon Sep 17 00:00:00 2001 From: sinanmohd Date: Thu, 11 Apr 2024 19:22:06 +0530 Subject: c: check string truncation when using snprintf --- src/libnpass/libnpass.c | 15 ++++++++++----- src/libnpass/util.c | 2 +- src/npass/npass.c | 8 +++++--- 3 files changed, 16 insertions(+), 9 deletions(-) diff --git a/src/libnpass/libnpass.c b/src/libnpass/libnpass.c index 538fe03..34b95ec 100644 --- a/src/libnpass/libnpass.c +++ b/src/libnpass/libnpass.c @@ -38,6 +38,7 @@ static int is_storeobj(struct dirent *dir); static int set_pass_dir(void) { + int r; const char *env; env = getenv("PASSWORD_STORE_DIR"); @@ -48,15 +49,19 @@ static int set_pass_dir(void) env = getenv("XDG_DATA_HOME"); if (env) { - snprintf(pass_dir, sizeof(pass_dir), "%s/%s", env, - DEF_PASS_DIR); + r = snprintf(pass_dir, sizeof(pass_dir), "%s/%s", env, + DEF_PASS_DIR); + if ((size_t)r > sizeof(pass_dir)) + err_ret(PASS_STORE_INV, "path exceeded PATH_MAX"); return 0; } env = getenv("HOME"); if (env) { - snprintf(pass_dir, sizeof(pass_dir), "%s/%s/%s", env, - ".local/share", DEF_PASS_DIR); + r = snprintf(pass_dir, sizeof(pass_dir), "%s/%s/%s", env, + ".local/share", DEF_PASS_DIR); + if ((size_t)r > sizeof(pass_dir)) + err_ret(PASS_STORE_INV, "path exceeded PATH_MAX"); return 0; } @@ -179,7 +184,7 @@ int readstore(DIR *dirp, struct store *s) return EOF; } - strncpy(s->name, dir->d_name, sizeof(s->name) - 1); + strcpy(s->name, dir->d_name); switch (dir->d_type) { case DT_DIR: s->type = PASS_STORE_DIR; diff --git a/src/libnpass/util.c b/src/libnpass/util.c index 182f117..c17c4ac 100644 --- a/src/libnpass/util.c +++ b/src/libnpass/util.c @@ -46,7 +46,7 @@ int r_rmdir(const char *prefix_path, char *rm_path) return 0; r = snprintf(abs_path, sizeof(abs_path), "%s/%s", prefix_path, rm_path); - if (r > (int)sizeof(abs_path)) + if ((size_t)r >= sizeof(abs_path)) err_ret(1, "path exceeded PATH_MAX"); r = rmdir(abs_path); diff --git a/src/npass/npass.c b/src/npass/npass.c index f3ed9ac..a38b202 100644 --- a/src/npass/npass.c +++ b/src/npass/npass.c @@ -60,7 +60,7 @@ static int ls(const char *path, size_t depth) { void *p; char *prefix; - int i, j, len; + int i, j, len, r; struct store *stor; char new_path[PATH_MAX]; static depth_state_t *depth_state; @@ -98,8 +98,10 @@ static int ls(const char *path, size_t depth) if (stor[i].type == PASS_STORE_DIR) { printf("%s %s%s%s\n", prefix, BLUE, stor[i].name, NCOL); - snprintf(new_path, sizeof(new_path), "%s/%s", - (path) ? path : "", stor[i].name); + r = snprintf(new_path, sizeof(new_path), "%s/%s", + (path) ? path : "", stor[i].name); + if ((size_t)r >= sizeof(new_path)) + err_ret(1, "%s", "path exceeded PATH_MAX"); ls(new_path, depth + 1); } else { printf("%s %s\n", prefix, stor[i].name); -- cgit v1.2.3