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

Compare with Current View Page History

« Previous Version 5 Next »

A call to the fopen() or freopen() function must be matched with a call to fclose() before the lifetime of the last pointer object that stores the return value of the call has ended.

Noncompliant Code Example

This code example is noncompliant because the resource allocated by the call to fopen() is not closed before function open_secure_data_file() returns.

#include <stdio.h>
 
int open_secure_data_file(const char *filename) {
  FILE *f = fopen(filename, "r"); 
  if (NULL == f) {
    return -1;
  }

  /* ... */

  return 0;
}

Compliant Solution

In this compliant solution, f is closed before returning to the caller:

#include <stdio.h>
 
int open_secure_data_file(const char *filename) {
  FILE *f = fopen(filename, "r"); 
  if (NULL == f) {
    return -1;
  }

  /* ... */

  if (0 != fclose(f)) {
    return -1;
  }
  return 0;
}

Noncompliant Code Example (POSIX)

This code example is noncompliant because the resource allocated by the call to open() is not closed before function open_secure_data_file() returns.

#include <stdio.h>
#include <fcntl.h>
 
int open_secure_data_file(const char *filename) {
  int fd = open( filename, O_WRONLY | O_CREAT, S_IRUSR);
  if (-1 == fd){
    return -1
  }

  /* ... */

  return 0;
}

Compliant Solution (POSIX)

In this compliant solution, fd is closed before returning to the caller:

#include <stdio.h>
#include <fcntl.h>
 
int open_secure_data_file(const char *filename) {
  int fd = open(filename, O_WRONLY | O_CREAT, S_IRUSR);
  if (-1 == fd){
    return -1
  }

  /* ... */

  if (0 != close(fd)) {
    return -1;
  }
  return 0;
}

Risk Assessment

Failing to properly close files may allow an attacker to exhaust system resources and increases the risk that data written into in-memory file buffers will not be flushed in the event of abnormal program termination. .

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

FIO42-C

Medium

Unlikely

Medium

P4

L3

Automated Detection

Tool

Version

Checker

Description

Compass/ROSE

   

Fortify SCA

5.0

 

Can detect violations of this rule with CERT C Rule Pack

Klocwork

2024.1

RH.LEAK

 

LDRA tool suite

9.7.1

49 D

Fully implemented

Related Vulnerabilities

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

Related Guidelines

Bibliography

[IEEE Std 1003.1:2013]XSH, System Interfaces, open

 


 

  • No labels