From e97f036af68e2b30db888bb3832ea2cff3cf9198 Mon Sep 17 00:00:00 2001 From: Mingjie Shen Date: Wed, 23 Aug 2023 17:10:39 -0400 Subject: [PATCH] core: fix TOCTOU race condition Separately checking the state of a file before operating on it may allow an attacker to modify the file between the two operations. Signed-off-by: Mingjie Shen --- jim.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/jim.c b/jim.c index c8dc5ce3..46169fdf 100644 --- a/jim.c +++ b/jim.c @@ -11642,8 +11642,14 @@ static Jim_Obj *JimReadTextFile(Jim_Interp *interp, const char *filename) char *buf; int readlen; - if (Jim_Stat(filename, &sb) == -1 || (fd = open(filename, O_RDONLY | O_TEXT, 0666)) < 0) { - Jim_SetResultFormatted(interp, "couldn't read file \"%s\": %s", filename, strerror(errno)); + fd = open(filename, O_RDONLY | O_TEXT, 0666); + if (fd < 0) { + Jim_SetResultFormatted(interp, "couldn't open file \"%s\": %s", filename, strerror(errno)); + return NULL; + } + if (Jim_FileStat(fd, &sb) == -1) { + Jim_SetResultFormatted(interp, "couldn't stat file \"%s\": %s", filename, strerror(errno)); + close(fd); return NULL; } buf = Jim_Alloc(sb.st_size + 1);