forked from github/codeql-coding-standards
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCloseFilesWhenTheyAreNoLongerNeeded.ql
More file actions
69 lines (64 loc) · 2.35 KB
/
CloseFilesWhenTheyAreNoLongerNeeded.ql
File metadata and controls
69 lines (64 loc) · 2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
* @id cpp/cert/close-files-when-they-are-no-longer-needed
* @name FIO51-CPP: Close files when they are no longer needed
* @description Failing to properly close files may allow an attacker to exhaust system resources.
* @kind problem
* @precision high
* @problem.severity error
* @tags external/cert/id/fio51-cpp
* correctness
* security
* external/cert/obligation/rule
*/
import cpp
import codingstandards.cpp.cert
import codingstandards.cpp.standardlibrary.CStdLib
import codingstandards.cpp.standardlibrary.FileStreams
import codingstandards.cpp.standardlibrary.Exceptions
/**
* Model calls that terminate the program execution
*/
class ExplicitTerminationCall extends FunctionCall {
ExplicitTerminationCall() {
getTarget() instanceof StdTerminate or
getTarget() instanceof StdQuickExit or
getTarget() instanceof StdAbort or
getTarget() instanceof Std_Exit
}
}
/**
* Model accesses to the fstream underlying file buffer
*/
predicate filebufAccess(ControlFlowNode node, FileStreamSource fss) {
node = fss or
node.(OpenFunctionCall).getFStream() = fss.getAUse() or
//insertion or extraction operator calls
node.(InsertionOperatorCall).getFStream() = fss.getAUse() or
node.(ExtractionOperatorCall).getFStream() = fss.getAUse() or
// Methods inherited from istream or ostream that access the file stream.
// Exclude is_open as it is not a filebuf access
any(IOStreamFunctionCall call | node = call and not call.getTarget().hasName("is_open"))
.getFStream() = fss.getAUse()
}
/**
* Paths reaching program termination without a call to close
*/
ControlFlowNode reachesTermination(ExplicitTerminationCall tc, FileStreamSource fss) {
result = tc
or
exists(ControlFlowNode mid |
mid = reachesTermination(tc, fss) and
result = mid.getAPredecessor() and
not filebufAccess(mid, fss) and
//Stop recursion on close or destructor
not result.(CloseFunctionCall).getFStream() = fss.getAUse() and
not result.(DestructorCall).getQualifier() = fss.getAUse()
)
}
from FileStreamSource fss, ControlFlowNode node, ExplicitTerminationCall tc
where
not isExcluded(tc, IOPackage::closeFilesWhenTheyAreNoLongerNeededQuery()) and
node = reachesTermination(tc, fss) and
filebufAccess(node, fss)
select tc, "The execution terminates without closing the `fstream` last accessed in $@.", node,
node.toString()