Main Content

CWE Rule 367

Time-of-check Time-of-use (TOCTOU) Race Condition

Since R2024a

Description

Rule Description

The product checks the state of a resource before using that resource, but the resource's state can change between the check and the use in a way that invalidates the results of the check. This can cause the product to perform invalid actions when the resource is in an unexpected state.

Polyspace Implementation

The rule checker checks for File access between time of check and use (TOCTOU).

Examples

expand all

Issue

This issue occurs when a race condition happens between checking the existence of a file or folder, and using the file or folder.

Risk

An attacker can access and manipulate your file between your check for the file and your use of a file. Symbolic links are particularly risky because an attacker can change where your symbolic link points.

Fix

Before using a file, do not check its status. Instead, use the file and check the results afterward.

Example — Check File Before Using
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

extern void print_tofile(FILE* f);

void toctou(char * log_path) {
    if (access(log_path, W_OK)==0) {
        FILE* f = fopen(log_path, "w"); //Noncompliant
        if (f) {
            print_tofile(f);
            fclose(f);
        }
    }
}

In this example, before opening and using the file, the function checks if the file exists. However, an attacker can change the file between the first and second lines of the function.

Correction — Open Then Check

One possible correction is to open the file, and then check the existence and contents afterward.

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

extern void print_tofile(FILE* f);

void toctou(char * log_path) {
    int fd = open(log_path, O_WRONLY);
    if (fd!=-1) {
        FILE *f = fdopen(fd, "w");
        if (f) {
            print_tofile(f);
            fclose(f);
        }
    }
}

Check Information

Category: Concurrency Issues

Version History

Introduced in R2024a