-
Notifications
You must be signed in to change notification settings - Fork 1.9k
CPP: Add query for CWE-570 detect and handle memory allocation errors. #5010
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
9071ba2
Add files via upload
ihsinme 20e19ec
Add files via upload
ihsinme 8737c14
Update WrongInDetectingAndHandlingMemoryAllocationErrors.cpp
ihsinme bec0064
Update test.cpp
ihsinme 25de82c
Apply suggestions from code review
ihsinme 5d163b4
Update WrongInDetectingAndHandlingMemoryAllocationErrors.qhelp
ihsinme 16d058f
Update WrongInDetectingAndHandlingMemoryAllocationErrors.ql
ihsinme bdfdcbd
Update WrongInDetectingAndHandlingMemoryAllocationErrors.ql
ihsinme c8eeb5f
Update WrongInDetectingAndHandlingMemoryAllocationErrors.ql
ihsinme bdbf5a4
Apply suggestions from code review
ihsinme 2b946ae
Update WrongInDetectingAndHandlingMemoryAllocationErrors.ql
ihsinme 2131f35
Update WrongInDetectingAndHandlingMemoryAllocationErrors.ql
ihsinme a43167f
Update WrongInDetectingAndHandlingMemoryAllocationErrors.qhelp
ihsinme 43045c1
Update WrongInDetectingAndHandlingMemoryAllocationErrors.ql
ihsinme File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
35 changes: 35 additions & 0 deletions
35
...c/experimental/Security/CWE/CWE-570/WrongInDetectingAndHandlingMemoryAllocationErrors.cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| // BAD: on memory allocation error, the program terminates. | ||
| void badFunction(const int *source, std::size_t length) noexcept { | ||
| int * dest = new int[length]; | ||
| std::memset(dest, 0, length); | ||
| // .. | ||
| } | ||
| // GOOD: memory allocation error will be handled. | ||
| void goodFunction(const int *source, std::size_t length) noexcept { | ||
| try { | ||
| int * dest = new int[length]; | ||
| } catch(std::bad_alloc) { | ||
| // ... | ||
| } | ||
| std::memset(dest, 0, length); | ||
| // .. | ||
| } | ||
| // BAD: memory allocation error will not be handled. | ||
| void badFunction(const int *source, std::size_t length) noexcept { | ||
| try { | ||
| int * dest = new (std::nothrow) int[length]; | ||
| } catch(std::bad_alloc) { | ||
| // ... | ||
| } | ||
| std::memset(dest, 0, length); | ||
| // .. | ||
| } | ||
| // GOOD: memory allocation error will be handled. | ||
| void goodFunction(const int *source, std::size_t length) noexcept { | ||
| int * dest = new (std::nothrow) int[length]; | ||
| if (!dest) { | ||
| return; | ||
| } | ||
| std::memset(dest, 0, length); | ||
| // .. | ||
| } | ||
27 changes: 27 additions & 0 deletions
27
...experimental/Security/CWE/CWE-570/WrongInDetectingAndHandlingMemoryAllocationErrors.qhelp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| <!DOCTYPE qhelp PUBLIC | ||
| "-//Semmle//qhelp//EN" | ||
| "qhelp.dtd"> | ||
| <qhelp> | ||
| <overview> | ||
| <p>When using the <code>new</code> operator to allocate memory, you need to pay attention to the different ways of detecting errors. <code>::operator new(std::size_t)</code> throws an exception on error, whereas <code>::operator new(std::size_t, const std::nothrow_t &)</code> returns zero on error. The programmer can get confused and check the error that occurs when allocating memory incorrectly. That can lead to an unhandled program termination or to a violation of the program logic.</p> | ||
|
|
||
| </overview> | ||
| <recommendation> | ||
|
|
||
| <p>Use the correct error detection method corresponding with the memory allocation.</p> | ||
|
|
||
| </recommendation> | ||
| <example> | ||
| <p>The following example demonstrates various approaches to detecting memory allocation errors using the <code>new</code> operator.</p> | ||
| <sample src="WrongInDetectingAndHandlingMemoryAllocationErrors.cpp" /> | ||
|
|
||
| </example> | ||
| <references> | ||
|
|
||
| <li> | ||
| CERT C++ Coding Standard: | ||
| <a href="https://wiki.sei.cmu.edu/confluence/display/cplusplus/MEM52-CPP.+Detect+and+handle+memory+allocation+errors">MEM52-CPP. Detect and handle memory allocation errors</a>. | ||
| </li> | ||
|
|
||
| </references> | ||
| </qhelp> |
87 changes: 87 additions & 0 deletions
87
...rc/experimental/Security/CWE/CWE-570/WrongInDetectingAndHandlingMemoryAllocationErrors.ql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| /** | ||
| * @name Detect And Handle Memory Allocation Errors | ||
ihsinme marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| * @description --::operator new(std::size_t) throws an exception on error, and ::operator new(std::size_t, const std::nothrow_t &) returns zero on error. | ||
| * --the programmer can get confused when check the error that occurs when allocating memory incorrectly. | ||
| * @kind problem | ||
| * @id cpp/detect-and-handle-memory-allocation-errors | ||
| * @problem.severity warning | ||
| * @precision medium | ||
| * @tags correctness | ||
| * security | ||
| * external/cwe/cwe-570 | ||
| */ | ||
|
|
||
| import cpp | ||
|
|
||
| /** | ||
| * Lookup if condition compare with 0 | ||
| */ | ||
| class IfCompareWithZero extends IfStmt { | ||
| IfCompareWithZero() { | ||
| this.getCondition().(EQExpr).getAChild().getValue() = "0" | ||
| or | ||
| this.getCondition().(NEExpr).getAChild().getValue() = "0" and | ||
| this.hasElse() | ||
ihsinme marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| or | ||
| this.getCondition().(NEExpr).getAChild().getValue() = "0" and | ||
| this.getThen().getAChild*() instanceof ReturnStmt | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * lookup for calls to `operator new`, with incorrect error handling. | ||
| */ | ||
| class WrongCheckErrorOperatorNew extends FunctionCall { | ||
| Expr exp; | ||
|
|
||
| WrongCheckErrorOperatorNew() { | ||
| this = exp.(NewOrNewArrayExpr).getAChild().(FunctionCall) and | ||
| ( | ||
| this.getTarget().hasGlobalOrStdName("operator new") | ||
| or | ||
| this.getTarget().hasGlobalOrStdName("operator new[]") | ||
| ) | ||
| } | ||
|
|
||
| /** | ||
| * Holds if handler `try ... catch` exists. | ||
| */ | ||
| predicate isExistsTryCatchBlock() { | ||
| exists(TryStmt ts | this.getEnclosingStmt() = ts.getStmt().getAChild*()) | ||
| } | ||
|
|
||
| /** | ||
| * Holds if results call `operator new` check in `operator if`. | ||
| */ | ||
| predicate isExistsIfCondition() { | ||
| exists(IfCompareWithZero ifc, AssignExpr aex, Initializer it | | ||
| // call `operator new` directly from the condition of `operator if`. | ||
| this = ifc.getCondition().getAChild*() | ||
| or | ||
| // check results call `operator new` with variable appropriation | ||
| postDominates(ifc, this) and | ||
| aex.getAChild() = exp and | ||
| ifc.getCondition().getAChild().(VariableAccess).getTarget() = | ||
| aex.getLValue().(VariableAccess).getTarget() | ||
| or | ||
| // check results call `operator new` with declaration variable | ||
| postDominates(ifc, this) and | ||
| exp = it.getExpr() and | ||
| it.getDeclaration() = ifc.getCondition().getAChild().(VariableAccess).getTarget() | ||
| ) | ||
ihsinme marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| /** | ||
| * Holds if `(std::nothrow)` exists in call `operator new`. | ||
| */ | ||
| predicate isExistsNothrow() { this.getAChild().toString() = "nothrow" } | ||
| } | ||
|
|
||
| from WrongCheckErrorOperatorNew op | ||
| where | ||
| // use call `operator new` with `(std::nothrow)` and checking error using `try ... catch` block and not `operator if` | ||
| op.isExistsNothrow() and not op.isExistsIfCondition() and op.isExistsTryCatchBlock() | ||
| or | ||
| // use call `operator new` without `(std::nothrow)` and checking error using `operator if` and not `try ... catch` block | ||
| not op.isExistsNothrow() and not op.isExistsTryCatchBlock() and op.isExistsIfCondition() | ||
ihsinme marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| select op, "memory allocation error check is incorrect or missing" | ||
5 changes: 5 additions & 0 deletions
5
...urity/CWE/CWE-570/semmle/tests/WrongInDetectingAndHandlingMemoryAllocationErrors.expected
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| | test.cpp:30:15:30:26 | call to operator new[] | memory allocation error check is incorrect or missing | | ||
| | test.cpp:38:9:38:20 | call to operator new[] | memory allocation error check is incorrect or missing | | ||
| | test.cpp:50:13:50:38 | call to operator new[] | memory allocation error check is incorrect or missing | | ||
| | test.cpp:51:22:51:47 | call to operator new[] | memory allocation error check is incorrect or missing | | ||
| | test.cpp:53:18:53:43 | call to operator new[] | memory allocation error check is incorrect or missing | |
1 change: 1 addition & 0 deletions
1
...Security/CWE/CWE-570/semmle/tests/WrongInDetectingAndHandlingMemoryAllocationErrors.qlref
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| experimental/Security/CWE/CWE-570/WrongInDetectingAndHandlingMemoryAllocationErrors.ql |
97 changes: 97 additions & 0 deletions
97
cpp/ql/test/experimental/query-tests/Security/CWE/CWE-570/semmle/tests/test.cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| #define NULL ((void*)0) | ||
| class exception {}; | ||
|
|
||
| namespace std{ | ||
| struct nothrow_t {}; | ||
| typedef unsigned long size_t; | ||
| class bad_alloc{ | ||
| const char* what() const throw(); | ||
| }; | ||
| extern const std::nothrow_t nothrow; | ||
| } | ||
|
|
||
| using namespace std; | ||
|
|
||
| void* operator new(std::size_t _Size); | ||
| void* operator new[](std::size_t _Size); | ||
| void* operator new( std::size_t count, const std::nothrow_t& tag ); | ||
| void* operator new[]( std::size_t count, const std::nothrow_t& tag ); | ||
|
|
||
| void badNew_0_0() | ||
| { | ||
| while (true) { | ||
| new int[100]; // BAD [NOT DETECTED] | ||
| if(!(new int[100])) // BAD [NOT DETECTED] | ||
| return; | ||
| } | ||
| } | ||
| void badNew_0_1() | ||
| { | ||
| int * i = new int[100]; // BAD | ||
| if(i == 0) | ||
| return; | ||
| if(!i) | ||
| return; | ||
| if(i == NULL) | ||
| return; | ||
| int * j; | ||
| j = new int[100]; // BAD | ||
| if(j == 0) | ||
| return; | ||
| if(!j) | ||
| return; | ||
| if(j == NULL) | ||
| return; | ||
| } | ||
| void badNew_1_0() | ||
| { | ||
| try { | ||
| while (true) { | ||
| new(std::nothrow) int[100]; // BAD | ||
| int* p = new(std::nothrow) int[100]; // BAD | ||
| int* p1; | ||
| p1 = new(std::nothrow) int[100]; // BAD | ||
| } | ||
| } catch (const exception &){//const std::bad_alloc& e) { | ||
| // std::cout << e.what() << '\n'; | ||
| } | ||
| } | ||
| void badNew_1_1() | ||
| { | ||
| while (true) { | ||
| int* p = new(std::nothrow) int[100]; // BAD [NOT DETECTED] | ||
| new(std::nothrow) int[100]; // BAD [NOT DETECTED] | ||
| } | ||
| } | ||
|
|
||
| void goodNew_0_0() | ||
| { | ||
| try { | ||
| while (true) { | ||
| new int[100]; // GOOD | ||
| } | ||
| } catch (const exception &){//const std::bad_alloc& e) { | ||
| // std::cout << e.what() << '\n'; | ||
| } | ||
| } | ||
|
|
||
| void goodNew_1_0() | ||
| { | ||
| while (true) { | ||
| int* p = new(std::nothrow) int[100]; // GOOD | ||
| if (p == nullptr) { | ||
| // std::cout << "Allocation returned nullptr\n"; | ||
| break; | ||
| } | ||
| int* p1; | ||
| p1 = new(std::nothrow) int[100]; // GOOD | ||
| if (p1 == nullptr) { | ||
| // std::cout << "Allocation returned nullptr\n"; | ||
| break; | ||
| } | ||
| if (new(std::nothrow) int[100] == nullptr) { // GOOD | ||
| // std::cout << "Allocation returned nullptr\n"; | ||
| break; | ||
| } | ||
| } | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.