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

Compare with Current View Page History

« Previous Version 33 Next »

Simultaneously opening a file multiple times has implementation-defined behavior. While some platforms may forbid a file simultaneously being opened multiple times, those that allow it may facilitate dangerous race conditions.

Noncompliant Code Example

The following 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() */

  /* ... */
}

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

  /* write logs pertaining to main() */

  do_stuff();

  /* ... */
}

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

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() */

  /* ... */
}

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

  /* write logs pertaining to main() */

  do_stuff(logfile);

  /* ... */
}

Risk Assessment

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

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.

References

[[ISO/IEC 9899:1999]] Section 7.19.3, "Files"
[[MITRE 07]] CWE ID 362, "Race Condition," CWE ID 675, "Duplicate Operations on Resource"


      09. Input Output (FIO)      

  • No labels