Skip to content

Commit f3e4f94

Browse files
committed
Rust: add documentation
1 parent c70decb commit f3e4f94

File tree

13 files changed

+410
-6
lines changed

13 files changed

+410
-6
lines changed
Lines changed: 300 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,300 @@
1+
.. _analyzing-data-flow-in-rust:
2+
3+
Analyzing data flow in Rust
4+
=============================
5+
6+
You can use CodeQL to track the flow of data through a Rust program to places where the data is used.
7+
8+
About this article
9+
------------------
10+
11+
This article describes how data flow analysis is implemented in the CodeQL libraries for Rust and includes examples to help you write your own data flow queries.
12+
The following sections describe how to use the libraries for local data flow, global data flow, and taint tracking.
13+
For a more general introduction to modeling data flow, see ":ref:`About data flow analysis <about-data-flow-analysis>`."
14+
15+
.. include:: ../reusables/new-data-flow-api.rst
16+
17+
Local data flow
18+
---------------
19+
20+
Local data flow tracks the flow of data within a single method or callable. Local data flow is easier, faster, and more precise than global data flow. Before looking at more complex tracking, you should always consider local tracking because it is sufficient for many queries.
21+
22+
Using local data flow
23+
~~~~~~~~~~~~~~~~~~~~~
24+
25+
You can use the local data flow library by importing the ``codeql.rust.dataflow.DataFlow`` module. The library uses the class ``Node`` to represent any element through which data can flow.
26+
``Node``\ s are divided into expression nodes (``ExprNode``) and parameter nodes (``ParameterNode``).
27+
You can map a data flow ``ParameterNode`` to its corresponding ``Parameter`` AST node using the ``asParameter`` member predicate.
28+
Similarly, you can use the ``asExpr`` member predicate to map a data flow ``ExprNode`` to its corresponding ``ExprCfgNode`` in the control-flow library.
29+
30+
.. code-block:: ql
31+
32+
class Node {
33+
/** Gets the expression corresponding to this node, if any. */
34+
CfgNodes::ExprCfgNode asExpr() { ... }
35+
36+
/** Gets the parameter corresponding to this node, if any. */
37+
Parameter asParameter() { ... }
38+
39+
...
40+
}
41+
42+
You can use the predicates ``exprNode`` and ``parameterNode`` to map from expressions and parameters to their data-flow node:
43+
44+
.. code-block:: ql
45+
46+
/**
47+
* Gets a node corresponding to expression `e`.
48+
*/
49+
ExprNode exprNode(CfgNodes::ExprCfgNode e) { ... }
50+
51+
/**
52+
* Gets the node corresponding to the value of parameter `p` at function entry.
53+
*/
54+
ParameterNode parameterNode(Parameter p) { ... }
55+
56+
Note that since ``asExpr`` and ``exprNode`` map between data-flow and control-flow nodes, you then need to call the ``getExpr`` member predicate on the control-flow node to map to the corresponding AST node,
57+
for example, by writing ``node.asExpr().getExpr()``.
58+
A control-flow graph considers every way control can flow through code, consequently, there can be multiple data-flow and control-flow nodes associated with a single expression node in the AST.
59+
60+
The predicate ``localFlowStep(Node nodeFrom, Node nodeTo)`` holds if there is an immediate data flow edge from the node ``nodeFrom`` to the node ``nodeTo``.
61+
You can apply the predicate recursively, by using the ``+`` and ``*`` operators, or you can use the predefined recursive predicate ``localFlow``.
62+
63+
For example, you can find flow from an expression ``source`` to an expression ``sink`` in zero or more local steps:
64+
65+
.. code-block:: ql
66+
67+
DataFlow::localFlow(source, sink)
68+
69+
Using local taint tracking
70+
~~~~~~~~~~~~~~~~~~~~~~~~~~
71+
72+
Local taint tracking extends local data flow to include flow steps where values are not preserved, for example, string manipulation.
73+
For example:
74+
75+
.. code-block:: rust
76+
77+
let y: String = "Hello ".to_owned() + x
78+
79+
If ``x`` is a tainted string then ``y`` is also tainted.
80+
81+
The local taint tracking library is in the module ``TaintTracking``.
82+
Like local data flow, a predicate ``localTaintStep(DataFlow::Node nodeFrom, DataFlow::Node nodeTo)`` holds if there is an immediate taint propagation edge from the node ``nodeFrom`` to the node ``nodeTo``.
83+
You can apply the predicate recursively, by using the ``+`` and ``*`` operators, or you can use the predefined recursive predicate ``localTaint``.
84+
85+
For example, you can find taint propagation from an expression ``source`` to an expression ``sink`` in zero or more local steps:
86+
87+
.. code-block:: ql
88+
89+
TaintTracking::localTaint(source, sink)
90+
91+
92+
Using local sources
93+
~~~~~~~~~~~~~~~~~~~
94+
95+
When exploring local data flow or taint propagation between two expressions as above, you would normally constrain the expressions to be relevant to your investigation.
96+
The next section gives some concrete examples, but first it's helpful to introduce the concept of a local source.
97+
98+
A local source is a data-flow node with no local data flow into it.
99+
As such, it is a local origin of data flow, a place where a new value is created.
100+
This includes parameters (which only receive values from global data flow) and most expressions (because they are not value-preserving).
101+
The class ``LocalSourceNode`` represents data-flow nodes that are also local sources.
102+
It comes with a useful member predicate ``flowsTo(DataFlow::Node node)``, which holds if there is local data flow from the local source to ``node``.
103+
104+
Examples of local data flow
105+
~~~~~~~~~~~~~~~~~~~~~~~~~~~
106+
107+
This query finds the argument passed in each call to ``File::create``:
108+
109+
.. code-block:: ql
110+
111+
import rust
112+
113+
from CallExpr call
114+
where call.getStaticTarget().(Function).getCanonicalPath() = "<std::fs::File>::create"
115+
select call.getArg(0)
116+
117+
Unfortunately this will only give the expression in the argument, not the values which could be passed to it.
118+
So we use local data flow to find all expressions that flow into the argument:
119+
120+
.. code-block:: ql
121+
122+
import rust
123+
import codeql.rust.dataflow.DataFlow
124+
125+
from CallExpr call, DataFlow::ExprNode source, DataFlow::ExprNode sink
126+
where
127+
call.getStaticTarget().(Function).getCanonicalPath() = "<std::fs::File>::create" and
128+
sink.asExpr().getExpr() = call.getArg(0) and
129+
DataFlow::localFlow(source, sink)
130+
select source, sink
131+
132+
We can vary the source, for example, making the source the parameter of a function rather than an expression. The following query finds where a parameter is used for the file creation:
133+
134+
.. code-block:: ql
135+
136+
import rust
137+
import codeql.rust.dataflow.DataFlow
138+
139+
from CallExpr call, Method method, ParamDecl sourceParam, Expr sinkExpr
140+
where
141+
call.getStaticTarget() = method and
142+
method.hasQualifiedName("String", "init(format:_:)") and
143+
sinkExpr = call.getArgument(0).getExpr() and
144+
DataFlow::localFlow(DataFlow::parameterNode(sourceParam), DataFlow::exprNode(sinkExpr))
145+
select sourceParam, sinkExpr
146+
147+
The following example finds calls to ``String.init(format:_:)`` where the format string is not a hard-coded string literal:
148+
149+
.. code-block:: ql
150+
151+
import rust
152+
import codeql.rust.dataflow.DataFlow
153+
154+
from CallExpr call, Method method, DataFlow::Node sinkNode
155+
where
156+
call.getStaticTarget() = method and
157+
method.hasQualifiedName("String", "init(format:_:)") and
158+
sinkNode.asExpr() = call.getArgument(0).getExpr() and
159+
not exists(StringLiteralExpr sourceLiteral |
160+
DataFlow::localFlow(DataFlow::exprNode(sourceLiteral), sinkNode)
161+
)
162+
select call, "Format argument to " + method.getName() + " isn't hard-coded."
163+
164+
Global data flow
165+
----------------
166+
167+
Global data flow tracks data flow throughout the entire program, and is therefore more powerful than local data flow.
168+
However, global data flow is less precise than local data flow, and the analysis typically requires significantly more time and memory to perform.
169+
170+
.. pull-quote:: Note
171+
172+
.. include:: ../reusables/path-problem.rst
173+
174+
Using global data flow
175+
~~~~~~~~~~~~~~~~~~~~~~
176+
177+
We can use the global data flow library by implementing the signature ``DataFlow::ConfigSig`` and applying the module ``DataFlow::Global<ConfigSig>``:
178+
179+
.. code-block:: ql
180+
181+
import codeql.rust.dataflow.DataFlow
182+
183+
module MyDataFlowConfiguration implements DataFlow::ConfigSig {
184+
predicate isSource(DataFlow::Node source) {
185+
...
186+
}
187+
188+
predicate isSink(DataFlow::Node sink) {
189+
...
190+
}
191+
}
192+
193+
module MyDataFlow = DataFlow::Global<MyDataFlowConfiguration>;
194+
195+
These predicates are defined in the configuration:
196+
197+
- ``isSource`` - defines where data may flow from.
198+
- ``isSink`` - defines where data may flow to.
199+
- ``isBarrier`` - optional, defines where data flow is blocked.
200+
- ``isAdditionalFlowStep`` - optional, adds additional flow steps.
201+
202+
The last line (``module MyDataFlow = ...``) instantiates the parameterized module for data flow analysis by passing the configuration to the parameterized module. Data flow analysis can then be performed using ``MyDataFlow::flow(DataFlow::Node source, DataFlow::Node sink)``:
203+
204+
.. code-block:: ql
205+
206+
from DataFlow::Node source, DataFlow::Node sink
207+
where MyDataFlow::flow(source, sink)
208+
select source, "Dataflow to $@.", sink, sink.toString()
209+
210+
Using global taint tracking
211+
~~~~~~~~~~~~~~~~~~~~~~~~~~~
212+
213+
Global taint tracking is to global data flow what local taint tracking is to local data flow.
214+
That is, global taint tracking extends global data flow with additional non-value-preserving steps.
215+
The global taint tracking library uses the same configuration module as the global data flow library. You can perform taint flow analysis using ``TaintTracking::Global``:
216+
217+
.. code-block:: ql
218+
219+
module MyTaintFlow = TaintTracking::Global<MyDataFlowConfiguration>;
220+
221+
from DataFlow::Node source, DataFlow::Node sink
222+
where MyTaintFlow::flow(source, sink)
223+
select source, "Taint flow to $@.", sink, sink.toString()
224+
225+
Predefined sources
226+
~~~~~~~~~~~~~~~~~~
227+
228+
The data flow library module ``codeql.rust.dataflow.FlowSources`` contains a number of predefined sources that you can use to write security queries to track data flow and taint flow.
229+
230+
- The class ``RemoteFlowSource`` represents data flow from remote network inputs and from other applications.
231+
- The class ``LocalFlowSource`` represents data flow from local user input.
232+
- The class ``FlowSource`` includes both of the above.
233+
234+
Examples of global data flow
235+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
236+
237+
The following global taint-tracking query finds places where a string literal is used in a function call argument named "password".
238+
- Since this is a taint-tracking query, the ``TaintTracking::Global`` module is used.
239+
- The ``isSource`` predicate defines sources as any ``StringLiteralExpr``.
240+
- The ``isSink`` predicate defines sinks as arguments to a ``CallExpr`` called "password".
241+
- The sources and sinks may need tuning to a particular use, for example, if passwords are represented by a type other than ``String`` or passed in arguments of a different name than "password".
242+
243+
.. code-block:: ql
244+
245+
import rust
246+
import codeql.rust.dataflow.DataFlow
247+
import codeql.rust.dataflow.TaintTracking
248+
249+
module ConstantPasswordConfig implements DataFlow::ConfigSig {
250+
predicate isSource(DataFlow::Node node) { node.asExpr() instanceof StringLiteralExpr }
251+
252+
predicate isSink(DataFlow::Node node) {
253+
// any argument called `password`
254+
exists(CallExpr call | call.getArgumentWithLabel("password").getExpr() = node.asExpr())
255+
}
256+
257+
module ConstantPasswordFlow = TaintTracking::Global<ConstantPasswordConfig>;
258+
259+
from DataFlow::Node sourceNode, DataFlow::Node sinkNode
260+
where ConstantPasswordFlow::flow(sourceNode, sinkNode)
261+
select sinkNode, "The value $@ is used as a constant password.", sourceNode, sourceNode.toString()
262+
263+
264+
The following global taint-tracking query finds places where a value from a remote or local user input is used as an argument to the SQLite ``Connection.execute(_:)`` function.
265+
- Since this is a taint-tracking query, the ``TaintTracking::Global`` module is used.
266+
- The ``isSource`` predicate defines sources as a ``FlowSource`` (remote or local user input).
267+
- The ``isSink`` predicate defines sinks as the first argument in any call to ``Connection.execute(_:)``.
268+
269+
.. code-block:: ql
270+
271+
import rust
272+
import codeql.rust.dataflow.DataFlow
273+
import codeql.rust.dataflow.TaintTracking
274+
import codeql.rust.dataflow.FlowSources
275+
276+
module SqlInjectionConfig implements DataFlow::ConfigSig {
277+
predicate isSource(DataFlow::Node node) { node instanceof FlowSource }
278+
279+
predicate isSink(DataFlow::Node node) {
280+
exists(CallExpr call |
281+
call.getStaticTarget().(Method).hasQualifiedName("Connection", "execute(_:)") and
282+
call.getArgument(0).getExpr() = node.asExpr()
283+
)
284+
}
285+
}
286+
287+
module SqlInjectionFlow = TaintTracking::Global<SqlInjectionConfig>;
288+
289+
from DataFlow::Node sourceNode, DataFlow::Node sinkNode
290+
where SqlInjectionFlow::flow(sourceNode, sinkNode)
291+
select sinkNode, "This query depends on a $@.", sourceNode, "user-provided value"
292+
293+
Further reading
294+
---------------
295+
296+
- `Exploring data flow with path queries <https://docs.github.com/en/code-security/codeql-for-vs-code/getting-started-with-codeql-for-vs-code/exploring-data-flow-with-path-queries>`__ in the GitHub documentation.
297+
298+
299+
.. include:: ../reusables/rust-further-reading.rst
300+
.. include:: ../reusables/codeql-ref-tools-further-reading.rst
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
2+
.. _codeql-for-rust:
3+
4+
CodeQL for Rust
5+
=========================
6+
7+
Experiment and learn how to write effective and efficient queries for CodeQL databases generated from Rust code.
8+
9+
.. toctree::
10+
:hidden:
11+
12+
codeql-library-for-rust
13+
analyzing-data-flow-in-rust
14+
15+
- :doc:`CodeQL library for Rust <codeql-library-for-rust>`: When you're analyzing Rust code, you can make use of the large collection of classes in the CodeQL library for Rust.
16+
- :doc:`Analyzing data flow in Ruby <analyzing-data-flow-in-rust>`: You can use CodeQL to track the flow of data through a Rust program to places where the data is used.
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
.. _codeql-library-for-rust:
2+
3+
CodeQL library for Rust
4+
=================================
5+
6+
When you're analyzing Rust code, you can make use of the large collection of classes in the CodeQL library for Rust.
7+
8+
Overview
9+
--------
10+
11+
CodeQL ships with a library for analyzing Rust code. The classes in this library present the data from a CodeQL database in an object-oriented form and provide
12+
abstractions and predicates to help you with common analysis tasks.
13+
14+
The library is implemented as a set of CodeQL modules, that is, files with the extension ``.qll``. The
15+
module `rust.qll <https://github.com/github/codeql/blob/main/rust/ql/lib/rust.qll>`__ imports most other standard library modules, so you can include the complete
16+
library by beginning your query with:
17+
18+
.. code-block:: ql
19+
20+
import rust
21+
22+
The CodeQL libraries model various aspects of Rust code. The above import includes the abstract syntax tree (AST) library, which is used for locating program elements,
23+
to match syntactic elements in the source code. This can be used for example to find values, patterns and structures.
24+
25+
The control flow graph (CFG) is imported using
26+
27+
.. code-block:: ql
28+
29+
import codeql.rust.controlflow.ControlFlowGraph
30+
31+
The CFG models the control flow between statements and expressions, for example whether one expression can
32+
be evaluated before another expression, or whether an expression "dominates" another one, meaning that all paths to an
33+
expression must flow through another expression first.
34+
35+
The data flow library is imported using
36+
37+
.. code-block:: ql
38+
39+
import codeql.rust.dataflow.DataFlow
40+
41+
Data flow tracks the flow of data through the program, including through function calls (interprocedural data flow) and between steps in a job or workflow.
42+
Data flow is particularly useful for security queries, where untrusted data flows to vulnerable parts of the program
43+
to exploit it. Related to data flow, is the taint-tracking library, which finds how data can *influence* other values
44+
in a program, even when it is not copied exactly.
45+
46+
To summarize, the main Rust library modules are:
47+
48+
.. list-table:: Main Rust library modules
49+
:header-rows: 1
50+
51+
* - Import
52+
- Description
53+
* - ``rust``
54+
- The standard Rust library
55+
* - ``codeql.rust.elements``
56+
- The abstract syntax tree library (also imported by `rust.qll`)
57+
* - ``codeql.rust.controlflow.ControlFlowGraph``
58+
- The control flow graph library
59+
* - ``codeql.rust.dataflow.DataFlow``
60+
- The data flow library
61+
* - ``codeql.rust.dataflow.TaintTracking``
62+
- The taint tracking library

docs/codeql/codeql-language-guides/index.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,5 @@ Experiment and learn how to write effective and efficient queries for CodeQL dat
1515
codeql-for-javascript
1616
codeql-for-python
1717
codeql-for-ruby
18+
codeql-for-rust
1819
codeql-for-swift

docs/codeql/codeql-overview/codeql-tools.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@ maintained by GitHub are:
3939
- ``codeql/python-all`` (`changelog <https://github.com/github/codeql/tree/codeql-cli/latest/python/ql/lib/CHANGELOG.md>`__, `source <https://github.com/github/codeql/tree/codeql-cli/latest/python/ql/lib>`__)
4040
- ``codeql/ruby-queries`` (`changelog <https://github.com/github/codeql/tree/codeql-cli/latest/ruby/ql/src/CHANGELOG.md>`__, `source <https://github.com/github/codeql/tree/codeql-cli/latest/ruby/ql/src>`__)
4141
- ``codeql/ruby-all`` (`changelog <https://github.com/github/codeql/tree/codeql-cli/latest/ruby/ql/lib/CHANGELOG.md>`__, `source <https://github.com/github/codeql/tree/codeql-cli/latest/ruby/ql/lib>`__)
42+
- ``codeql/rust-queries`` (`changelog <https://github.com/github/codeql/tree/codeql-cli/latest/rust/ql/src/CHANGELOG.md>`__, `source <https://github.com/github/codeql/tree/codeql-cli/latest/rust/ql/src>`__)
43+
- ``codeql/rust-all`` (`changelog <https://github.com/github/codeql/tree/codeql-cli/latest/rust/ql/lib/CHANGELOG.md>`__, `source <https://github.com/github/codeql/tree/codeql-cli/latest/rust/ql/lib>`__)
4244
- ``codeql/swift-queries`` (`changelog <https://github.com/github/codeql/tree/codeql-cli/latest/swift/ql/src/CHANGELOG.md>`__, `source <https://github.com/github/codeql/tree/codeql-cli/latest/swift/ql/src>`__)
4345
- ``codeql/swift-all`` (`changelog <https://github.com/github/codeql/tree/codeql-cli/latest/swift/ql/lib/CHANGELOG.md>`__, `source <https://github.com/github/codeql/tree/codeql-cli/latest/swift/ql/lib>`__)
4446

0 commit comments

Comments
 (0)