From 78f439a218a79d0a1fa0cf3f606bcf021a4c4a61 Mon Sep 17 00:00:00 2001 From: Disconnect3d Date: Fri, 18 Feb 2022 15:59:06 +0100 Subject: [PATCH] Avoid TOCTOU in linenoiseHistorySave Before this commit the `linenoiseHistorySave` performed `fopen(filename, ...)` and `chmod(filename, ...)` and this creates a time of use vs time of check vulnerability. I have not checked whether this can be exploited, but the fix is trivial here: we can just use `fchmod` with the opened file descriptor and this is what this commit changes :). Btw this was found with https://codeql.github.com/ and its https://codeql.github.com/codeql-query-help/cpp/cpp-toctou-race-condition/ rule when scanning a bigger project that used linenoise as a dependency. --- linenoise.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/linenoise.c b/linenoise.c index cfe51e76..bad0f3f8 100644 --- a/linenoise.c +++ b/linenoise.c @@ -1194,7 +1194,7 @@ int linenoiseHistorySave(const char *filename) { fp = fopen(filename,"w"); umask(old_umask); if (fp == NULL) return -1; - chmod(filename,S_IRUSR|S_IWUSR); + fchmod(fp,S_IRUSR|S_IWUSR); for (j = 0; j < history_len; j++) fprintf(fp,"%s\n",history[j]); fclose(fp);