Main Content

CWE Rule 363

Race Condition Enabling Link Following

Since R2026a

Description

Race Condition Enabling Link Following

Polyspace Implementation

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

Examples

expand all

Issue

This issue occurs when you check a status of a file or folder before using it, resulting in a race condition where the file can be replaced before it is accessed.

Risk

An attacker can access and manipulate your file between checking the status of the file and using the 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

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

#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);
        }
    }
}
Correction — Open Then Check

One possible correction is to open the file, and then check its 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");  //Compliant
        if (f) {
            print_tofile(f);
            fclose(f);
        }
    }
}

Check Information

Category: Others
PQL Name: std.cwe_native.R363

Version History

Introduced in R2026a