From: Kamalesh Babulal Date: Mon, 14 Feb 2022 15:11:56 +0000 (-0700) Subject: api.c: Fix TOCTOU race cgroup_get_cg_type() X-Git-Tag: v3.0~199 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=eeb88d746389418f2e91c9957a5ad7ba3cd9edc7;p=thirdparty%2Flibcgroup.git api.c: Fix TOCTOU race cgroup_get_cg_type() Fix a TOCTOU race condition, that checks for file existence versus file open in cgroup_get_cg_type() by opening the file and check for errno for file existence. Reported-by: LGTM Signed-off-by: Kamalesh Babulal Signed-off-by: Tom Hromatka --- diff --git a/src/api.c b/src/api.c index ab24fdb3..83e68522 100644 --- a/src/api.c +++ b/src/api.c @@ -1550,23 +1550,20 @@ static int cgroup_get_cg_type(const char * const path, char * const type, char cg_type[LL_MAX]; int len, err = 0; FILE *fp = NULL; - struct stat st; - int stat_ret; snprintf(cg_type_path, FILENAME_MAX, "%scgroup.type", path); - /* file cgroup.type, doesn't exist for root cgroup. */ - stat_ret = stat(cg_type_path, &st); - if (stat_ret != 0) { - snprintf(type, type_sz, "cgroup.procs"); - goto out; - } - fp = fopen(cg_type_path, "re"); if (!fp) { - cgroup_warn("Warning: failed to open file %s: %s\n", - cg_type_path, strerror(errno)); - err = ECGOTHER; - goto out; + if (errno == ENOENT) { + /* file cgroup.type, doesn't exist for root cgroup. */ + snprintf(type, type_sz, "cgroup.procs"); + goto out; + } else { + cgroup_warn("Warning: failed to open file %s: %s\n", + cg_type_path, strerror(errno)); + err = ECGOTHER; + goto out; + } } if (fgets(cg_type, LL_MAX, fp) == NULL) {