You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 49 Next »

Opening a file that is already open has implementation-defined behavior. While some platforms may forbid a file simultaneously being opened multiple times, platforms that allow it may facilitate dangerous race conditions.

Noncompliant Code Example

This noncompliant code example logs the program's state at runtime.

void do_stuff(void) {
  FILE *logfile = fopen("log", "a");
  if (logfile == NULL) {
    /* Handle error */
  }

  /* Write logs pertaining to do_stuff() */
  fprintf(logfile, "do_stuff\n");

  /* ... */
}

int main(void) {
  FILE *logfile = fopen("log", "a");
  if (logfile == NULL) {
    /* Handle error */
  }

  /* Write logs pertaining to main() */
  fprintf(logfile, "main\n");

  do_stuff();

  /* ... */
  return 0;
}

However, the file log is opened twice simultaneously. The result is implementation-defined and potentially dangerous.

Implementation Details

On a Linux machine running GCC 4.3.2, this program produces

do_stuff
main

which does not indicate the order in which data was logged.

Compliant Solution

In this compliant solution, a reference to the file pointer is passed as an argument to functions that need to perform operations on that file. This eliminates the need to open the same file multiple times.

void do_stuff(FILE *logfile) {
  /* Write logs pertaining to do_stuff() */
  fprintf(logfile, "do_stuff\n");

  /* ... */
}

int main(void) {
  FILE *logfile = fopen("log", "a");
  if (logfile == NULL) {
    /* Handle error */
  }

  /* Write logs pertaining to main() */
  fprintf(logfile, "main\n");

  do_stuff(logfile);

  /* ... */
  return 0;
}

Implementation Details

On a Linux machine running GCC 4.3.2, this program produces

main
do_stuff

which matches the order in which logging occurred.

Automated Detection

Tool

Version

Checker

Description

LDRA tool suite

9.7.1

75 D

Fully implemented

Risk Assessment

Simultaneously opening a file multiple times can result in abnormal program termination or data integrity violations.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

FIO31-C

medium

probable

high

P4

L3

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

CERT C++ Secure Coding Standard: FIO31-CPP. Do not simultaneously open the same file multiple times

ISO/IEC 9899:2011 Section 7.21.3, "Files"

MITRE CWE: CWE-362, "Race conditions"

MITRE CWE: CWE-675, and "Duplicate operations on resource"

Bibliography


  • No labels