Race condition with stat and mkdir in sequence

2019-07-24 17:20发布

问题:

Coverity complains of . toctou: Calling function mkdir that uses DIR after a check function. This can cause a time-of-check, time-of-use race condition

if (stat(DIR, &st) != 0)
{
    if (mkdir(DIR, 0755) < 0)
    {
        return ERROR;
    }
}

Is it good enough to change the code to ,I was using stat only for file exist check

if (mkdir(NDUID_DIR, 0755) < 0)
{
    if(errno != EEXIST)
    {
        return ERROR;
    }
}

Is there a better way to fix the code?

回答1:

Both of your snippets appear to be incorrect and/or incomplete.

On OpenBSD, sys_mkdir would return -1, and set errno to EEXIST when the target file is present. However, that doesn't guarantee that the target file is a directory -- an existing regular file would still result in mkdir(2) returning the exact same EEXIST.

For guidance of the widely accepted approach, take a look at how mkdir(1) -p option is implemented across the BSDs (bin/mkdir/mkdir.c#mkpath in OpenBSD and NetBSD), all of which, on mkdir(2)'s error, appear to immediately call stat(2) to subsequently run the S_ISDIR macro to ensure that the existing file is a directory, and not just any other type of a file.