Skip to content

Commit

Permalink
fix: improve file checks for procfs knobs
Browse files Browse the repository at this point in the history
CodeQL checks flagged this pattern as a TOCTOU race.

Signed-off-by: Robin H. Johnson <[email protected]>
  • Loading branch information
robbat2 committed Jan 2, 2025
1 parent f60e47c commit 945a580
Showing 1 changed file with 15 additions and 8 deletions.
23 changes: 15 additions & 8 deletions privsep-linux.c
Original file line number Diff line number Diff line change
Expand Up @@ -183,25 +183,32 @@ static int set_interface_var(const char *iface, const char *var, const char *nam

/* No path traversal */
if (!iface[0] || !strcmp(iface, ".") || !strcmp(iface, "..") || strchr(iface, '/'))
goto cleanup;
goto errmsg;

/* If the file does NOT exist, do NOT create it; this is not an error, as we have to support old & new names */
if (access(spath, F_OK) != 0)
goto cleanup;

fp = fopen(spath, "w");
if (!fp) {
if (name)
flog(LOG_ERR, "failed to set %s (%u) for %s: %s", name, val, iface, strerror(errno));
goto cleanup;
}
// recheck to avoid TOCTOU anyway
int fd = open(spath, O_WRONLY, S_IRWXU);

Check failure

Code scanning / CodeQL

Time-of-check time-of-use filesystem race condition High

The
filename
being operated upon was previously
checked
, but the underlying file may have been changed since then.
if (fd == -1)
goto errmsg;

fp = fdopen(fd, "w");
if (!fp)
goto errmsg;

if (0 > fprintf(fp, "%u", val)) {
goto cleanup;
goto errmsg;
}

retval = 0;

errmsg:
if (name && retval != 0)
flog(LOG_ERR, "failed to set %s (%u) for %s: %s", name, val, iface, strerror(errno));
cleanup:

if (fp)
fclose(fp);

Expand Down

0 comments on commit 945a580

Please sign in to comment.