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

Compare with Current View Page History

« Previous Version 22 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, 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

In this non-compliant example, an array of characters is appended to the end of a file. However, if the call to fwrite() fails, then write_data() fails to close the open file 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

In this compliant solution, the code is modified to ensure that the DataFile.txt file 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;
}

Risk Assessment

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

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

FIO42-C

2 (medium)

1 (unlikely)

2 (medium)

P4

L3

References

[[Dowd 06]] Chapter 10, "UNIX Processes" (File Descriptor Leaks 582-587)
[CWE 403] UNIX file descriptor leaks

  • No labels