From: Kamalesh Babulal Date: Sat, 15 Jul 2023 06:34:11 +0000 (+0530) Subject: src/api.c: fix TOCTOU in cg_get_procname_from_proc_cmdline() X-Git-Tag: v3.1.0~9 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=d6d14e8b7ba28966dfd00a6471e9b2667b77705c;p=thirdparty%2Flibcgroup.git src/api.c: fix TOCTOU in cg_get_procname_from_proc_cmdline() Fix a TOCTOU issue, reported by Coverity tool: CID 258283 (#1 of 1): Time of check time of use (TOCTOU)1. fs_check_call: Calling function readlink to perform check on path Coverity gets confused when a char array is re-used for constructing different paths and complains about TOCTOU for unrelated paths, fix it by using different char arrays for different path, as a side effect it also improves the readability of the code. Signed-off-by: Kamalesh Babulal Signed-off-by: Tom Hromatka --- diff --git a/src/api.c b/src/api.c index 979a7d56..72d44b9e 100644 --- a/src/api.c +++ b/src/api.c @@ -5720,25 +5720,26 @@ static int cg_get_procname_from_proc_status(pid_t pid, char **procname_status) static int cg_get_procname_from_proc_cmdline(pid_t pid, const char *pname_status, char **pname_cmdline) { + char pid_cwd_path[FILENAME_MAX]; + char pid_cmd_path[FILENAME_MAX]; char buf_pname[FILENAME_MAX]; char buf_cwd[FILENAME_MAX]; - char path[FILENAME_MAX]; int ret = ECGFAIL; int len = 0; int c = 0; FILE *f; memset(buf_cwd, '\0', sizeof(buf_cwd)); - sprintf(path, "/proc/%d/cwd", pid); + sprintf(pid_cwd_path, "/proc/%d/cwd", pid); - if (readlink(path, buf_cwd, sizeof(buf_cwd)) < 0) + if (readlink(pid_cwd_path, buf_cwd, sizeof(buf_cwd)) < 0) return ECGROUPNOTEXIST; /* readlink doesn't append a null */ buf_cwd[FILENAME_MAX - 1] = '\0'; - sprintf(path, "/proc/%d/cmdline", pid); - f = fopen(path, "re"); + sprintf(pid_cmd_path, "/proc/%d/cmdline", pid); + f = fopen(pid_cmd_path, "re"); if (!f) return ECGROUPNOTEXIST; @@ -5778,13 +5779,13 @@ static int cg_get_procname_from_proc_cmdline(pid_t pid, const char *pname_status strcat(buf_cwd, "/"); strcat(buf_cwd, buf_pname); - if (!realpath(buf_cwd, path)) { + if (!realpath(buf_cwd, pid_cmd_path)) { last_errno = errno; ret = ECGOTHER; break; } - *pname_cmdline = strdup(path); + *pname_cmdline = strdup(pid_cmd_path); if (*pname_cmdline == NULL) { last_errno = errno; ret = ECGOTHER;