From: Tom Hromatka Date: Wed, 19 Jan 2022 17:47:04 +0000 (-0700) Subject: api.c: Fix TOCTOU race in cgroup_get_procs() X-Git-Tag: v2.0.1~4^2 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=7518ef32a4ff83890054c6df0c8da1da150fc815;p=thirdparty%2Flibcgroup.git api.c: Fix TOCTOU race in cgroup_get_procs() codeql flagged a potential race between the time-of-check and time-of-use (CWE-367) of the cgroup.procs file in cgroup_get_procs(). Signed-off-by: Tom Hromatka (cherry picked from commit 57da48f9deb77c82e46cf347b029f438638e9ad1) --- diff --git a/src/api.c b/src/api.c index 1cadc73f..8f7a28c4 100644 --- a/src/api.c +++ b/src/api.c @@ -5445,11 +5445,16 @@ int cgroup_get_procs(char *name, char *controller, pid_t **pids, int *size) cg_build_path(name, cgroup_path, controller); strncat(cgroup_path, "/cgroup.procs", FILENAME_MAX-strlen(cgroup_path)); - /* - * This kernel does have support for cgroup.procs - */ - if (access(cgroup_path, F_OK)) - return ECGROUPUNSUPP; + procs = fopen(cgroup_path, "r"); + if (!procs) { + last_errno = errno; + *pids = NULL; + *size = 0; + if (errno == ENOENT) + return ECGROUPUNSUPP; + else + return ECGOTHER; + } /* * Keep doubling the memory allocated if needed @@ -5457,15 +5462,7 @@ int cgroup_get_procs(char *name, char *controller, pid_t **pids, int *size) tmp_list= malloc(sizeof(pid_t) * tot_procs); if (!tmp_list) { last_errno = errno; - return ECGOTHER; - } - - procs = fopen(cgroup_path, "r"); - if (!procs) { - last_errno = errno; - free(tmp_list); - *pids = NULL; - *size = 0; + fclose(procs); return ECGOTHER; }