Skip to content

Commit f2cb2b3

Browse files
committed
Swift: Add analyzing-data-flow-in-swift.rst
1 parent 5f0d334 commit f2cb2b3

File tree

2 files changed

+293
-0
lines changed

2 files changed

+293
-0
lines changed
Lines changed: 290 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,290 @@
1+
.. _analyzing-data-flow-in-swift:
2+
3+
Analyzing data flow in Swift
4+
============================
5+
6+
You can use CodeQL to track the flow of data through a Swift 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 Swift 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+
Local data flow
16+
---------------
17+
18+
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.
19+
20+
Using local data flow
21+
~~~~~~~~~~~~~~~~~~~~~
22+
23+
You can use the local data flow library by importing the ``DataFlow`` module. The library uses the class ``Node`` to represent any element through which data can flow.
24+
The ``Node`` class has a number of useful subclasses, such as ``ExprNode`` for expressions and ``ParameterNode`` for parameters. You can map between data flow nodes and expressions/control-flow nodes using the member predicates ``asExpr`` and ``getCfgNode``:
25+
26+
.. code-block:: ql
27+
28+
class Node {
29+
/**
30+
* Gets this node's underlying expression, if any.
31+
*/
32+
Expr asExpr() { none() }
33+
34+
/**
35+
* Gets this data flow node's corresponding control flow node.
36+
*/
37+
ControlFlowNode getCfgNode() { none() }
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+
/** Gets a node corresponding to expression `e`. */
47+
ExprNode exprNode(DataFlowExpr e) { result.asExpr() = e }
48+
49+
/**
50+
* Gets the node corresponding to the value of parameter `p` at function entry.
51+
*/
52+
ParameterNode parameterNode(DataFlowParameter p) { result.getParameter() = p }
53+
54+
There can be multiple data-flow nodes associated with a single expression node in the AST.
55+
56+
The predicate ``localFlowStep(Node nodeFrom, Node nodeTo)`` holds if there is an immediate data flow edge from the node ``nodeFrom`` to the node ``nodeTo``.
57+
You can apply the predicate recursively, by using the ``+`` and ``*`` operators, or you can use the predefined recursive predicate ``localFlow``.
58+
59+
For example, you can find flow from an expression ``source`` to an expression ``sink`` in zero or more local steps:
60+
61+
.. code-block:: ql
62+
63+
DataFlow::localFlow(DataFlow::exprNode(source), DataFlow::exprNode(sink))
64+
65+
Using local taint tracking
66+
~~~~~~~~~~~~~~~~~~~~~~~~~~
67+
68+
Local taint tracking extends local data flow to include flow steps where values are not preserved, for example, string manipulation.
69+
For example:
70+
71+
.. code-block:: swift
72+
73+
temp = x
74+
y = temp + ", " + temp
75+
76+
If ``x`` is a tainted string then ``y`` is also tainted.
77+
78+
The local taint tracking library is in the module ``TaintTracking``.
79+
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``.
80+
You can apply the predicate recursively, by using the ``+`` and ``*`` operators, or you can use the predefined recursive predicate ``localTaint``.
81+
82+
For example, you can find taint propagation from an expression ``source`` to an expression ``sink`` in zero or more local steps:
83+
84+
.. code-block:: ql
85+
86+
TaintTracking::localTaint(DataFlow::exprNode(source), DataFlow::exprNode(sink))
87+
88+
Examples of local data flow
89+
~~~~~~~~~~~~~~~~~~~~~~~~~~~
90+
91+
This query finds the ``format`` argument passed into each call to ``String.init(format:_:)``:
92+
93+
.. code-block:: ql
94+
95+
import swift
96+
97+
from CallExpr call, MethodDecl method
98+
where
99+
call.getStaticTarget() = method and
100+
method.hasQualifiedName("String", "init(format:_:)")
101+
select call.getArgument(0).getExpr()
102+
103+
Unfortunately this will only give the expression in the argument, not the values which could be passed to it.
104+
So we use local data flow to find all expressions that flow into the argument:
105+
106+
.. code-block:: ql
107+
108+
import swift
109+
import codeql.swift.dataflow.DataFlow
110+
111+
from CallExpr call, MethodDecl method, Expr sourceExpr, Expr sinkExpr
112+
where
113+
call.getStaticTarget() = method and
114+
method.hasQualifiedName("String", "init(format:_:)") and
115+
sinkExpr = call.getArgument(0).getExpr() and
116+
DataFlow::localFlow(DataFlow::exprNode(sourceExpr), DataFlow::exprNode(sinkExpr))
117+
select sourceExpr, sinkExpr
118+
119+
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 format:
120+
121+
.. code-block:: ql
122+
123+
import swift
124+
import codeql.swift.dataflow.DataFlow
125+
126+
from CallExpr call, MethodDecl method, ParamDecl sourceParam, Expr sinkExpr
127+
where
128+
call.getStaticTarget() = method and
129+
method.hasQualifiedName("String", "init(format:_:)") and
130+
sinkExpr = call.getArgument(0).getExpr() and
131+
DataFlow::localFlow(DataFlow::parameterNode(sourceParam), DataFlow::exprNode(sinkExpr))
132+
select sourceParam, sinkExpr
133+
134+
The following example finds calls to ``String.init(format:_:)`` where the format string is not a hard-coded string literal:
135+
136+
.. code-block:: ql
137+
138+
import swift
139+
import codeql.swift.dataflow.DataFlow
140+
141+
from CallExpr call, MethodDecl method, Expr sinkExpr
142+
where
143+
call.getStaticTarget() = method and
144+
method.hasQualifiedName("String", "init(format:_:)") and
145+
sinkExpr = call.getArgument(0).getExpr() and
146+
not exists(StringLiteralExpr sourceLiteral |
147+
DataFlow::localFlow(DataFlow::exprNode(sourceLiteral), DataFlow::exprNode(sinkExpr))
148+
)
149+
select call, "Format argument to " + method.getName() + " isn't hard-coded."
150+
151+
Global data flow
152+
----------------
153+
154+
Global data flow tracks data flow throughout the entire program, and is therefore more powerful than local data flow.
155+
However, global data flow is less precise than local data flow, and the analysis typically requires significantly more time and memory to perform.
156+
157+
.. pull-quote:: Note
158+
159+
.. include:: ../reusables/path-problem.rst
160+
161+
Using global data flow
162+
~~~~~~~~~~~~~~~~~~~~~~
163+
164+
You can use the global data flow library by implementing the module ``DataFlow::ConfigSig``:
165+
166+
.. code-block:: ql
167+
168+
import codeql.swift.dataflow.DataFlow
169+
170+
module MyDataFlowConfiguration implements DataFlow::ConfigSig {
171+
predicate isSource(DataFlow::Node source) {
172+
...
173+
}
174+
175+
predicate isSink(DataFlow::Node sink) {
176+
...
177+
}
178+
}
179+
180+
module MyDataFlow = DataFlow::Global<MyDataFlowConfiguration>;
181+
182+
These predicates are defined in the configuration:
183+
184+
- ``isSource`` - defines where data may flow from.
185+
- ``isSink`` - defines where data may flow to.
186+
- ``isBarrier`` - optionally, restricts the data flow.
187+
- ``isAdditionalFlowStep`` - optionally, adds additional flow steps.
188+
189+
The last line (``module MyDataFlow = ...``) performs data flow analysis using the configuration, and its results can be accessed with ``MyDataFlow::flow(DataFlow::Node source, DataFlow::Node sink)``:
190+
191+
.. code-block:: ql
192+
193+
from DataFlow::Node source, DataFlow::Node sink
194+
where MyDataFlow::flow(source, sink)
195+
select source, "Dataflow to $@.", sink, sink.toString()
196+
197+
Using global taint tracking
198+
~~~~~~~~~~~~~~~~~~~~~~~~~~~
199+
200+
Global taint tracking is to global data flow what local taint tracking is to local data flow.
201+
That is, global taint tracking extends global data flow with additional non-value-preserving steps.
202+
The global taint tracking library uses the same configuration module as the global data flow library but taint flow analysis is performed with ``TaintTracking::Global``:
203+
204+
.. code-block:: ql
205+
206+
module MyTaintFlow = TaintTracking::Global<MyDataFlowConfiguration>;
207+
208+
from DataFlow::Node source, DataFlow::Node sink
209+
where MyTaintFlow::flow(source, sink)
210+
select source, "Taint flow to $@.", sink, sink.toString()
211+
212+
Predefined sources and sinks
213+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
214+
215+
The data flow library module ``codeql.swift.dataflow.FlowSources`` contains a number of predefined sources and sinks, providing a good starting point for defining data flow and taint flow based security queries.
216+
217+
- The class ``RemoteFlowSource`` represents data flow from remote network inputs and from other applications.
218+
- The class ``LocalFlowSource`` represents data flow from local user input.
219+
- The class ``FlowSource`` includes both of the above.
220+
221+
Examples of global data flow
222+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
223+
224+
The following global taint-tracking query finds places where a string literal is used in a function call argument called "password".
225+
- Since this is a taint-tracking query, the ``TaintTracking::Global`` module is used.
226+
- The ``isSource`` predicate defines sources as any ``StringLiteralExpr``.
227+
- The ``isSink`` predicate defines sinks as arguments to a ``CallExpr`` called "password".
228+
- The sources and sinks may need tuning to a particular use case, for example if passwords are represented by a type other than ``String`` or passed in arguments of a different name than "password".
229+
230+
.. code-block:: ql
231+
232+
import swift
233+
import codeql.swift.dataflow.DataFlow
234+
import codeql.swift.dataflow.TaintTracking
235+
236+
module ConstantPasswordConfig implements DataFlow::ConfigSig {
237+
predicate isSource(DataFlow::Node node) { node.asExpr() instanceof StringLiteralExpr }
238+
239+
predicate isSink(DataFlow::Node node) {
240+
// any argument called `password`
241+
exists(CallExpr call | call.getArgumentWithLabel("password").getExpr() = node.asExpr())
242+
}
243+
244+
module ConstantPasswordFlow = TaintTracking::Global<ConstantPasswordConfig>;
245+
246+
from DataFlow::Node sourceNode, DataFlow::Node sinkNode
247+
where ConstantPasswordFlow::flow(sourceNode, sinkNode)
248+
select sinkNode, sourceNode, sinkNode,
249+
"The value '" + sourceNode.toString() + "' is used as a constant password."
250+
251+
252+
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.
253+
- Since this is a taint-tracking query, the ``TaintTracking::Global`` module is used.
254+
- The ``isSource`` predicate defines sources as a ``FlowSource`` (remote or local user input).
255+
- The ``isSink`` predicate defines sinks as the first argument in any call to ``Connection.execute(_:)``.
256+
257+
.. code-block:: ql
258+
259+
260+
import swift
261+
import codeql.swift.dataflow.DataFlow
262+
import codeql.swift.dataflow.TaintTracking
263+
import codeql.swift.dataflow.FlowSources
264+
265+
module SqlInjectionConfig implements DataFlow::ConfigSig {
266+
predicate isSource(DataFlow::Node node) { node instanceof FlowSource }
267+
268+
predicate isSink(DataFlow::Node node) {
269+
exists(CallExpr call |
270+
call.getStaticTarget().(MethodDecl).hasQualifiedName("Connection", ["execute(_:)"]) and
271+
call.getArgument(0).getExpr() = node.asExpr()
272+
)
273+
}
274+
}
275+
276+
module SqlInjectionFlow = TaintTracking::Global<SqlInjectionConfig>;
277+
278+
from DataFlow::Node sourceNode, DataFlow::Node sinkNode
279+
where SqlInjectionFlow::flow(sourceNode, sinkNode)
280+
select sinkNode, sourceNode, sinkNode, "This query depends on a $@.", sourceNode,
281+
"user-provided value"
282+
283+
Further reading
284+
---------------
285+
286+
- ":ref:`Exploring data flow with path queries <exploring-data-flow-with-path-queries>`"
287+
288+
289+
.. include:: ../reusables/swift-further-reading.rst
290+
.. include:: ../reusables/codeql-ref-tools-further-reading.rst

docs/codeql/codeql-language-guides/codeql-for-swift.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,8 @@ Experiment and learn how to write effective and efficient queries for CodeQL dat
99
:hidden:
1010

1111
basic-query-for-swift-code
12+
analyzing-data-flow-in-swift
1213

1314
- :doc:`Basic query for Swift code <basic-query-for-swift-code>`: Learn to write and run a simple CodeQL query.
15+
16+
- :doc:`Analyzing data flow in Swift <analyzing-data-flow-in-swift>`: You can use CodeQL to track the flow of data through a Swift program to places where the data is used.

0 commit comments

Comments
 (0)