-
Notifications
You must be signed in to change notification settings - Fork 1.8k
C++: Add an experimental query for surprising lifetimes from range-based for loops #15939
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
MathiasVP
merged 11 commits into
github:main
from
MathiasVP:experimental-surprising-lifetimes-for-range-based-for-loop
Mar 18, 2024
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
f7c29e6
C++: Expose some previously private classes from our models so they c…
MathiasVP 23cf997
C++: Add a new experimental query ' cpp/iterator-to-expired-container'.
MathiasVP 3a8db49
C++: Add tests for 'cpp/iterator-to-expired-container'.
MathiasVP a8718f9
C++: Add qhelp for 'cpp/iterator-to-expired-container'.
MathiasVP e23e3d7
C++: Run tests without the extractor and analysis changes.
MathiasVP 575af1a
Merge branch 'main' into experimental-surprising-lifetimes-for-range-…
MathiasVP 457d71d
Update cpp/ql/src/experimental/Security/CWE/CWE-416/IteratorToExpired…
MathiasVP 7b6accd
Update cpp/ql/src/experimental/Security/CWE/CWE-416/IteratorToExpired…
MathiasVP 668239f
C++: Convert tabs to spaces.
MathiasVP e373341
C++: Add more tests.
MathiasVP b944f3b
C++: Fix FP.
MathiasVP 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
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
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
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
53 changes: 53 additions & 0 deletions
53
cpp/ql/src/experimental/Security/CWE/CWE-416/IteratorToExpiredContainer.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,53 @@ | ||
<!DOCTYPE qhelp PUBLIC | ||
"-//Semmle//qhelp//EN" | ||
"qhelp.dtd"> | ||
<qhelp> | ||
<overview> | ||
<p> | ||
Using an iterator owned by a container after the lifetime of the container has expired can lead to undefined behavior. | ||
This is because the iterator may be invalidated when the container is destroyed, and dereferencing an invalidated iterator is undefined behavior. | ||
These problems can be hard to spot due to C++'s complex rules for temporary object lifetimes and their extensions. | ||
</p> | ||
|
||
</overview> | ||
<recommendation> | ||
|
||
<p> | ||
Never create an iterator to a temporary container when the iterator is expected to be used after the container's lifetime has expired. | ||
</p> | ||
|
||
</recommendation> | ||
<example> | ||
<p> | ||
|
||
</p> | ||
|
||
<p> | ||
The rules for lifetime extension ensures that the code in <code>lifetime_of_temp_extended</code> is well-defined. This is because the | ||
lifetime of the temporary container returned by <code>get_vector</code> is extended to the end of the loop. However, prior to C++23, | ||
the lifetime extension rules do not ensure that the container returned by <code>get_vector</code> is extended in <code>lifetime_of_temp_not_extended</code>. | ||
This is because the temporary container is not bound to a rvalue reference. | ||
</p> | ||
<sample src="IteratorToExpiredContainerExtendedLifetime.cpp" /> | ||
|
||
</example> | ||
<references> | ||
|
||
<li>CERT C Coding Standard: | ||
<a href="https://wiki.sei.cmu.edu/confluence/display/c/MEM30-C.+Do+not+access+freed+memory">MEM30-C. Do not access freed memory</a>.</li> | ||
<li> | ||
OWASP: | ||
<a href="https://owasp.org/www-community/vulnerabilities/Using_freed_memory">Using freed memory</a>. | ||
</li> | ||
<li> | ||
<a href="https://github.com/isocpp/CppCoreGuidelines/blob/master/docs/Lifetime.pdf">Lifetime safety: Preventing common dangling</a> | ||
</li> | ||
<li> | ||
<a href="https://en.cppreference.com/w/cpp/container">Containers library</a> | ||
</li> | ||
<li> | ||
<a href="https://en.cppreference.com/w/cpp/language/range-for">Range-based for loop (since C++11)</a> | ||
</li> | ||
|
||
</references> | ||
</qhelp> |
103 changes: 103 additions & 0 deletions
103
cpp/ql/src/experimental/Security/CWE/CWE-416/IteratorToExpiredContainer.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,103 @@ | ||
/** | ||
* @name Iterator to expired container | ||
* @description Using an iterator owned by a container whose lifetime has expired may lead to unexpected behavior. | ||
* @kind problem | ||
* @precision high | ||
* @id cpp/iterator-to-expired-container | ||
* @problem.severity warning | ||
* @tags reliability | ||
* security | ||
* external/cwe/cwe-416 | ||
* external/cwe/cwe-664 | ||
*/ | ||
|
||
// IMPORTANT: This query does not currently find anything since it relies on extractor and analysis improvements that hasn't yet been released | ||
import cpp | ||
import semmle.code.cpp.ir.IR | ||
import semmle.code.cpp.dataflow.new.DataFlow | ||
import semmle.code.cpp.models.implementations.StdContainer | ||
import semmle.code.cpp.models.implementations.StdMap | ||
import semmle.code.cpp.models.implementations.Iterator | ||
|
||
/** | ||
* A configuration to track flow from a temporary variable to the qualifier of | ||
* a destructor call | ||
*/ | ||
module TempToDestructorConfig implements DataFlow::ConfigSig { | ||
predicate isSource(DataFlow::Node source) { | ||
source.asInstruction().(VariableAddressInstruction).getIRVariable() instanceof IRTempVariable | ||
} | ||
|
||
predicate isSink(DataFlow::Node sink) { | ||
sink.asOperand().(ThisArgumentOperand).getCall().getStaticCallTarget() instanceof Destructor | ||
} | ||
} | ||
|
||
module TempToDestructorFlow = DataFlow::Global<TempToDestructorConfig>; | ||
|
||
/** | ||
* Gets a `DataFlow::Node` that represents a temporary that will be destroyed | ||
* by a call to a destructor, or a `DataFlow::Node` that will transitively be | ||
* destroyed by a call to a destructor. | ||
* | ||
* For the latter case, consider something like: | ||
* ``` | ||
* std::vector<std::vector<int>> get_2d_vector(); | ||
* auto& v = get_2d_vector()[0]; | ||
* ``` | ||
* Given the above, this predicate returns the node corresponding | ||
* to `get_2d_vector()[0]` since the temporary `get_2d_vector()` gets | ||
* destroyed by a call to `std::vector<std::vector<int>>::~vector`, | ||
* and thus the result of `get_2d_vector()[0]` is also an invalid reference. | ||
*/ | ||
DataFlow::Node getADestroyedNode() { | ||
exists(TempToDestructorFlow::PathNode destroyedTemp | destroyedTemp.isSource() | | ||
result = destroyedTemp.getNode() | ||
or | ||
exists(CallInstruction call | | ||
result.asInstruction() = call and | ||
DataFlow::localFlow(destroyedTemp.getNode(), | ||
DataFlow::operandNode(call.getThisArgumentOperand())) | ||
| | ||
call.getStaticCallTarget() instanceof StdSequenceContainerAt or | ||
call.getStaticCallTarget() instanceof StdMapAt | ||
) | ||
) | ||
} | ||
|
||
predicate isSinkImpl(DataFlow::Node sink, FunctionCall fc) { | ||
exists(CallInstruction call | | ||
call = sink.asOperand().(ThisArgumentOperand).getCall() and | ||
fc = call.getUnconvertedResultExpression() and | ||
call.getStaticCallTarget() instanceof BeginOrEndFunction | ||
) | ||
} | ||
|
||
/** | ||
* Flow from any destroyed object to the qualifier of a `begin` or `end` call | ||
*/ | ||
module DestroyedToBeginConfig implements DataFlow::ConfigSig { | ||
predicate isSource(DataFlow::Node source) { source = getADestroyedNode() } | ||
|
||
predicate isSink(DataFlow::Node sink) { isSinkImpl(sink, _) } | ||
|
||
DataFlow::FlowFeature getAFeature() { | ||
// By blocking argument-to-parameter flow we ensure that we don't enter a | ||
// function body where the temporary outlives anything inside the function. | ||
// This prevents false positives in cases like: | ||
// ```cpp | ||
// void foo(const std::vector<int>& v) { | ||
// for(auto x : v) { ... } // this is fine since v outlives the loop | ||
// } | ||
// ... | ||
// foo(create_temporary()) | ||
// ``` | ||
result instanceof DataFlow::FeatureHasSinkCallContext | ||
} | ||
} | ||
|
||
module DestroyedToBeginFlow = DataFlow::Global<DestroyedToBeginConfig>; | ||
|
||
from DataFlow::Node source, DataFlow::Node sink, FunctionCall beginOrEnd | ||
where DestroyedToBeginFlow::flow(source, sink) and isSinkImpl(sink, beginOrEnd) | ||
select source, "This object is destroyed before $@ is called.", beginOrEnd, beginOrEnd.toString() |
20 changes: 20 additions & 0 deletions
20
cpp/ql/src/experimental/Security/CWE/CWE-416/IteratorToExpiredContainerExtendedLifetime.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,20 @@ | ||
#include <vector> | ||
|
||
std::vector<int> get_vector(); | ||
|
||
void use(int); | ||
|
||
void lifetime_of_temp_extended() { | ||
for(auto x : get_vector()) { | ||
use(x); // GOOD: The lifetime of the vector returned by `get_vector()` is extended until the end of the loop. | ||
} | ||
} | ||
|
||
// Writes the the values of `v` to an external log and returns it unchanged. | ||
const std::vector<int>& log_and_return_argument(const std::vector<int>& v); | ||
|
||
void lifetime_of_temp_not_extended() { | ||
for(auto x : log_and_return_argument(get_vector())) { | ||
use(x); // BAD: The lifetime of the vector returned by `get_vector()` is not extended, and the behavior is undefined. | ||
} | ||
} |
Empty file.
1 change: 1 addition & 0 deletions
1
cpp/ql/test/experimental/query-tests/Security/CWE/CWE-416/IteratorToExpiredContainer.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-416/IteratorToExpiredContainer.ql |
Oops, something went wrong.
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.