Main Content

CWE Rule 689

Permission Race Condition During Resource Copy

Since R2026a

Description

The product, while copying or cloning a resource, does not set the resource's permissions or access control until the copy is complete, leaving the resource exposed to other spheres while the copy is taking place

Polyspace Implementation

This checker checks for File opened without setting access permissions.

Examples

expand all

Issue

File opened without setting access permissions occurs when you open a file without explicitly specifying access permissions on the file. You might be doing one of the following:

  • You might be opening a file using a function such as fopen() that does not support specifying access permissions.

  • You might be opening a file using a function such as fopen_s() or open() (POSIX®) that supports access permissions, but you do not set appropriate access permissions at the time of file opening.

Risk

Opening a file without specifying access permissions could result in unprivileged access to the file.

Fix

To avoid unprivileged access, do the following at the time of file opening:

  • Avoid using file-opening functions such as fopen() that does not support specifying access permissions. Use alternative functions such as fopen_s() (supported since C11).

  • When using file opening functions, explicitly specify access permissions. For instance:

    • When using the function fopen_s(), make sure that the access mode argument (third argument) does not start with the character u. The character u in the access mode specifier indicates that the file is opened with default access permissions.

    • When using the POSIX function open(), make sure to specify a third argument that sets file permissions. Alternatively, you can use functions such as umask() to mask specific file permission bits when opening files.

Example — Use of fopen_s() with Default File Permissions


#include <stdio.h>

void writeContentsToFile (const char *fileName, const char* newContents) {
        FILE *fp;
        int res = fopen_s (&fp, fileName, "uw"); // Noncompliant
        if (res != 0){
            // Write contents to file
        }
}

In this example, the function fopen_s() opens a file using an access mode argument uw that begins with the character u. This mode argument indicates that the opened file has default access permissions, and might allow unprivileged access.

Correction — Restrict Access Permissions Using Mode Argument

Omit the character u from the access mode argument when opening a file using fopen_s().


#include <errno.h>
#include <stdio.h>

void writeContentsToFile (const char *fileName, const char* newContents) {
        FILE *fp;
        int res = fopen_s (&fp, fileName, "wx"); // Compliant
        if (res != 0){
            // Write contents to file
        }
}

Check Information

Category: Others
PQL Name: std.cwe_native.R689

Version History

Introduced in R2026a