Kingdom: Code Quality

Poor code quality leads to unpredictable behavior. From a user's perspective that often manifests itself as poor usability. For an attacker it provides an opportunity to stress the system in unexpected ways.

Undefined Behavior: File Pointer Use After Close

Abstract
The application uses a file operation on a closed file pointer.
Explanation
Performing file operations on a system FILE object after its associated stream is closed results in undefined behavior. Depending on the specific C compiler in use, the file operation can cause a system crash or even potentially result in modification or reading of the same or different file.

Example 1: The following code shows an attempt to read a system FILE object after the corresponding stream is closed.


FILE *sysfile = fopen(test.file, "r+");
res = fclose(sysfile);
if(res == 0){
printf("%c", getc(sysfile));
}


Because the getc() function runs after the file stream for sysfile is closed, getc() results in undefined behavior and can cause a system crash or potential modification or reading of the same or different file.
References
[1] Standards Mapping - Common Weakness Enumeration CWE ID 910
[2] Standards Mapping - Motor Industry Software Reliability Association (MISRA) C Guidelines 2012 Rule 22.6
desc.controlflow.cpp.undefined_behavior_file_pointer_use_after_close