cposixfopenstatfstat

Using stat() after fopen() to Avoid TOCTOU Problems?


Title says it all: can one use stat() after fopen() to avoid Time of Check to Time of Use (TOCTOU) race conditions?

Some details:

I am writing a C program that only reads files, but needs to error properly when asked to read a directory. As of right now, it uses open() (with O_RDWR) to generate an error and then checks errno for EISDIR, like so:

int fd = open(path, O_RDWR);

if (fd == -1) {
    if (errno == EISDIR) return PATH_IS_DIR;
    else return FILE_ERR;
}

The problem with the above solution is that this program only needs to read files, so by opening a file with O_RDWR, I might wrongly get a permissions error if the user has read permissions, but not write permissions.

Is it possible to do the following to avoid TOCTOU race conditions?

struct stat pstat;

FILE *f = fopen(path, "r");

if (!f) return FILE_ERR;

if (stat(path, &pstat) == -1) {
    fclose(f);
    return FILE_ERR;
}

if (S_ISDIR(pstat.st_mode)) {
    fclose(f);
    return PATH_IS_DIR;
}

If it is not possible, is there another solution to prevent TOCTOU bugs and also wrong permission errors?


Solution

  • No, the code presented in the question does not avoid a TOCTOU race.

    Testing after use is prone to exactly the same errors as testing before use. In both cases, the name is resolved at two different times, with possibly different results. This is the cause of the race, and it can happen whichever access happens first.

    The only way to avoid this is to open the file once, and use the file descriptor so obtained for any other checks you need. Modern OSes provide interfaces such as fstat() for exactly this purpose.

    If you want to use C's buffered I/O, you can get the file descriptor from a FILE* using fileno() - or you can create a FILE* from a file descriptor using fdopen().

    It requires a very small change to your code:

    # Untested
    
    struct stat pstat;
    
    FILE *f = fopen(path, "r");
    
    if (!f) return FILE_ERR;
    
    if (fstat(fileno(f), &pstat) == -1) {
    //  ^^^^^^^^^^^^^^^                         <-- CHANGED HERE
        fclose(f);
        return FILE_ERR;
    }
    
    if (S_ISDIR(pstat.st_mode)) {
        fclose(f);
        return PATH_IS_DIR;
    }