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

Compare with Current View Page History

« Previous Version 13 Next »

Failing to close files when they are no longer needed may allow attackers to exhaust and possibly manipulate system resources. This phenomenon is typically referred to as file descriptor leakage [CWE 403], although file pointers may also be used as an attack vector. To prevent file descriptor leaks, file pointers and file descriptors should be closed when they are no longer needed.

Non-Compliant Code Example: fopen()

In this non-compliant example, an array of characters is written to the end of a file. However, if fwrite() fails, then write_data() returns -1 in error without properly closing the stream to DataFile.txt.

int write_data(char *data, size_t data_size) {

  FILE * fptr;
  size_t written;

  fptr = fopen("DataFile.txt", "a");

  if (fptr == NULL) {
    /* Handle fopen() error */
  }

  written = fwrite(data, sizeof(char), data_size, fptr);
  if (written < data_size) {
    return -1;
  }

  fclose(fptr);
  return 0;
}

Compliant Solution

To correct this example, the code is modified to ensure DataFile.txt is always closed.

int write_data(char *data, size_t data_size) {

  FILE * fptr;
  size_t written;
  int result = 0;

  fptr = fopen("DataFile.txt", "a");

  if (fptr == NULL) {
    /* Handle fopen() error */
  }

  written = fwrite(data, sizeof(char), data_size, fptr);
  if (written < data_size) {
    result = -1;
  }

  fclose(fptr);
  return result;
}

Non-Compliant Code Example: open()

Compliant Solution

Risk Assessment

Failing to properly close files may allow unintended access to system resources, or exhaust system resources.

References

  • No labels