-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdata_dependency.py
More file actions
435 lines (370 loc) · 14.6 KB
/
Copy pathdata_dependency.py
File metadata and controls
435 lines (370 loc) · 14.6 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
"""
Compute the data depenency between all the SSA variables
"""
from collections import defaultdict
from typing import Union, Set, Dict, TYPE_CHECKING
from slither.core.declarations import (
Contract,
Enum,
Function,
SolidityFunction,
SolidityVariable,
SolidityVariableComposed,
Structure,
)
from slither.core.variables.variable import Variable
from slither.slithir.operations import Index, OperationWithLValue, InternalCall
from slither.slithir.variables import (
Constant,
LocalIRVariable,
ReferenceVariable,
ReferenceVariableSSA,
StateIRVariable,
TemporaryVariableSSA,
TupleVariableSSA,
)
from slither.core.solidity_types.type import Type
if TYPE_CHECKING:
from slither.core.compilation_unit import SlitherCompilationUnit
###################################################################################
###################################################################################
# region User APIs
###################################################################################
###################################################################################
def is_dependent(
variable: Variable,
source: Variable,
context: Union[Contract, Function],
only_unprotected: bool = False,
) -> bool:
"""
Args:
variable (Variable)
source (Variable)
context (Contract|Function)
only_unprotected (bool): True only unprotected function are considered
Returns:
bool
"""
assert isinstance(context, (Contract, Function))
if isinstance(variable, Constant):
return False
if variable == source:
return True
context_dict = context.context
if only_unprotected:
return (
variable in context_dict[KEY_NON_SSA_UNPROTECTED]
and source in context_dict[KEY_NON_SSA_UNPROTECTED][variable]
)
return variable in context_dict[KEY_NON_SSA] and source in context_dict[KEY_NON_SSA][variable]
def is_dependent_ssa(
variable: Variable,
source: Variable,
context: Union[Contract, Function],
only_unprotected: bool = False,
) -> bool:
"""
Args:
variable (Variable)
taint (Variable)
context (Contract|Function)
only_unprotected (bool): True only unprotected function are considered
Returns:
bool
"""
assert isinstance(context, (Contract, Function))
context_dict = context.context
if isinstance(variable, Constant):
return False
if variable == source:
return True
if only_unprotected:
return (
variable in context_dict[KEY_SSA_UNPROTECTED]
and source in context_dict[KEY_SSA_UNPROTECTED][variable]
)
return variable in context_dict[KEY_SSA] and source in context_dict[KEY_SSA][variable]
GENERIC_TAINT = {
SolidityVariableComposed("msg.sender"),
SolidityVariableComposed("msg.value"),
SolidityVariableComposed("msg.data"),
SolidityVariableComposed("tx.origin"),
}
def is_tainted(variable, context, only_unprotected=False, ignore_generic_taint=False):
"""
Args:
variable
context (Contract|Function)
only_unprotected (bool): True only unprotected function are considered
Returns:
bool
"""
assert isinstance(context, (Contract, Function))
assert isinstance(only_unprotected, bool)
if isinstance(variable, Constant):
return False
compilation_unit = context.compilation_unit
taints = compilation_unit.context[KEY_INPUT]
if not ignore_generic_taint:
taints |= GENERIC_TAINT
return variable in taints or any(
is_dependent(variable, t, context, only_unprotected) for t in taints
)
def is_tainted_ssa(variable, context, only_unprotected=False, ignore_generic_taint=False):
"""
Args:
variable
context (Contract|Function)
only_unprotected (bool): True only unprotected function are considered
Returns:
bool
"""
assert isinstance(context, (Contract, Function))
assert isinstance(only_unprotected, bool)
if isinstance(variable, Constant):
return False
compilation_unit = context.compilation_unit
taints = compilation_unit.context[KEY_INPUT_SSA]
if not ignore_generic_taint:
taints |= GENERIC_TAINT
return variable in taints or any(
is_dependent_ssa(variable, t, context, only_unprotected) for t in taints
)
def get_dependencies(
variable: Variable,
context: Union[Contract, Function],
only_unprotected: bool = False,
) -> Set[Variable]:
"""
Return the variables for which `variable` depends on.
:param variable: The target
:param context: Either a function (interprocedural) or a contract (inter transactional)
:param only_unprotected: True if consider only protected functions
:return: set(Variable)
"""
assert isinstance(context, (Contract, Function))
assert isinstance(only_unprotected, bool)
if only_unprotected:
return context.context[KEY_NON_SSA_UNPROTECTED].get(variable, set())
return context.context[KEY_NON_SSA].get(variable, set())
def get_all_dependencies(
context: Union[Contract, Function], only_unprotected: bool = False
) -> Dict[Variable, Set[Variable]]:
"""
Return the dictionary of dependencies.
:param context: Either a function (interprocedural) or a contract (inter transactional)
:param only_unprotected: True if consider only protected functions
:return: Dict(Variable, set(Variable))
"""
assert isinstance(context, (Contract, Function))
assert isinstance(only_unprotected, bool)
if only_unprotected:
return context.context[KEY_NON_SSA_UNPROTECTED]
return context.context[KEY_NON_SSA]
def get_dependencies_ssa(
variable: Variable,
context: Union[Contract, Function],
only_unprotected: bool = False,
) -> Set[Variable]:
"""
Return the variables for which `variable` depends on (SSA version).
:param variable: The target (must be SSA variable)
:param context: Either a function (interprocedural) or a contract (inter transactional)
:param only_unprotected: True if consider only protected functions
:return: set(Variable)
"""
assert isinstance(context, (Contract, Function))
assert isinstance(only_unprotected, bool)
if only_unprotected:
return context.context[KEY_SSA_UNPROTECTED].get(variable, set())
return context.context[KEY_SSA].get(variable, set())
def get_all_dependencies_ssa(
context: Union[Contract, Function], only_unprotected: bool = False
) -> Dict[Variable, Set[Variable]]:
"""
Return the dictionary of dependencies.
:param context: Either a function (interprocedural) or a contract (inter transactional)
:param only_unprotected: True if consider only protected functions
:return: Dict(Variable, set(Variable))
"""
assert isinstance(context, (Contract, Function))
assert isinstance(only_unprotected, bool)
if only_unprotected:
return context.context[KEY_SSA_UNPROTECTED]
return context.context[KEY_SSA]
# endregion
###################################################################################
###################################################################################
# region Module constants
###################################################################################
###################################################################################
KEY_SSA = "DATA_DEPENDENCY_SSA"
KEY_NON_SSA = "DATA_DEPENDENCY"
# Only for unprotected functions
KEY_SSA_UNPROTECTED = "DATA_DEPENDENCY_SSA_UNPROTECTED"
KEY_NON_SSA_UNPROTECTED = "DATA_DEPENDENCY_UNPROTECTED"
KEY_INPUT = "DATA_DEPENDENCY_INPUT"
KEY_INPUT_SSA = "DATA_DEPENDENCY_INPUT_SSA"
# endregion
###################################################################################
###################################################################################
# region Debug
###################################################################################
###################################################################################
def pprint_dependency(context):
print("#### SSA ####")
context = context.context
for k, values in context[KEY_SSA].items():
print("{} ({}):".format(k, id(k)))
for v in values:
print("\t- {}".format(v))
print("#### NON SSA ####")
for k, values in context[KEY_NON_SSA].items():
print("{} ({}):".format(k, hex(id(k))))
for v in values:
print("\t- {} ({})".format(v, hex(id(v))))
# endregion
###################################################################################
###################################################################################
# region Analyses
###################################################################################
###################################################################################
def compute_dependency(compilation_unit: "SlitherCompilationUnit"):
compilation_unit.context[KEY_INPUT] = set()
compilation_unit.context[KEY_INPUT_SSA] = set()
for contract in compilation_unit.contracts:
compute_dependency_contract(contract, compilation_unit)
def compute_dependency_contract(contract, compilation_unit: "SlitherCompilationUnit"):
# This just prevents the function from recomputing things
#if KEY_SSA in contract.context:
# return
contract.context[KEY_SSA] = dict()
contract.context[KEY_SSA_UNPROTECTED] = dict()
for function in contract.functions + contract.modifiers:
compute_dependency_function(function)
propagate_function(contract, function, KEY_SSA, KEY_NON_SSA)
propagate_function(contract, function, KEY_SSA_UNPROTECTED, KEY_NON_SSA_UNPROTECTED)
# pylint: disable=expression-not-assigned
if function.visibility in ["public", "external"]:
[compilation_unit.context[KEY_INPUT].add(p) for p in function.parameters]
[compilation_unit.context[KEY_INPUT_SSA].add(p) for p in function.parameters_ssa]
propagate_contract(contract, KEY_SSA, KEY_NON_SSA)
propagate_contract(contract, KEY_SSA_UNPROTECTED, KEY_NON_SSA_UNPROTECTED)
def propagate_function(contract, function, context_key, context_key_non_ssa):
transitive_close_dependencies(function, context_key, context_key_non_ssa)
# Propage data dependency
data_depencencies = function.context[context_key]
for (key, values) in data_depencencies.items():
if not key in contract.context[context_key]:
contract.context[context_key][key] = set(values)
else:
contract.context[context_key][key].union(values)
def transitive_close_dependencies(context, context_key, context_key_non_ssa):
# transitive closure
changed = True
keys = context.context[context_key].keys()
while changed:
changed = False
to_add = defaultdict(set)
[ # pylint: disable=expression-not-assigned
[
to_add[key].update(context.context[context_key][item] - {key} - items)
for item in items & keys
]
for key, items in context.context[context_key].items()
]
for k, v in to_add.items():
# Because we dont have any check on the update operation
# We might update an empty set with an empty set
if v:
changed = True
context.context[context_key][k] |= v
context.context[context_key_non_ssa] = convert_to_non_ssa(context.context[context_key])
def propagate_contract(contract, context_key, context_key_non_ssa):
transitive_close_dependencies(contract, context_key, context_key_non_ssa)
def add_dependency(lvalue, function, ir, is_protected):
if not lvalue in function.context[KEY_SSA]:
function.context[KEY_SSA][lvalue] = set()
if not is_protected:
function.context[KEY_SSA_UNPROTECTED][lvalue] = set()
if isinstance(ir, Index):
read = [ir.variable_left]
elif isinstance(ir, InternalCall):
read = ir.function.return_values_ssa
else:
read = ir.read
# pylint: disable=expression-not-assigned
[function.context[KEY_SSA][lvalue].add(v) for v in read if not isinstance(v, Constant)]
if not is_protected:
[
function.context[KEY_SSA_UNPROTECTED][lvalue].add(v)
for v in read
if not isinstance(v, Constant)
]
""" This only function that I am changing """
def compute_dependency_function(function):
# This just prevents the function from recomputing things
#if KEY_SSA in function.context:
# return
function.context[KEY_SSA] = dict()
function.context[KEY_SSA_UNPROTECTED] = dict()
is_protected = function.is_protected()
for node in function.nodes:
for ir in node.irs_ssa:
"""BEGIN: Code I have added """
transactional_expression = False
for keyword in ["transfer"]:
if keyword in str(ir.expression):
transactional_expression = True
break
if not transactional_expression:
continue
"""END: Code I have added """
if isinstance(ir, OperationWithLValue) and ir.lvalue:
if isinstance(ir.lvalue, LocalIRVariable) and ir.lvalue.is_storage:
continue
if isinstance(ir.lvalue, ReferenceVariable):
lvalue = ir.lvalue.points_to
if lvalue:
add_dependency(lvalue, function, ir, is_protected)
add_dependency(ir.lvalue, function, ir, is_protected)
function.context[KEY_NON_SSA] = convert_to_non_ssa(function.context[KEY_SSA])
function.context[KEY_NON_SSA_UNPROTECTED] = convert_to_non_ssa(
function.context[KEY_SSA_UNPROTECTED]
)
def convert_variable_to_non_ssa(v):
if isinstance(
v,
(
LocalIRVariable,
StateIRVariable,
TemporaryVariableSSA,
ReferenceVariableSSA,
TupleVariableSSA,
),
):
return v.non_ssa_version
assert isinstance(
v,
(
Constant,
SolidityVariable,
Contract,
Enum,
SolidityFunction,
Structure,
Function,
Type,
),
)
return v
def convert_to_non_ssa(data_depencies):
# Need to create new set() as its changed during iteration
ret = dict()
for (k, values) in data_depencies.items():
var = convert_variable_to_non_ssa(k)
if not var in ret:
ret[var] = set()
ret[var] = ret[var].union({convert_variable_to_non_ssa(v) for v in values})
return ret