From eeb88d746389418f2e91c9957a5ad7ba3cd9edc7 Mon Sep 17 00:00:00 2001 From: Kamalesh Babulal Date: Mon, 14 Feb 2022 08:11:56 -0700 Subject: [PATCH] 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 --- src/api.c | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) 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) { -- 2.47.2