forked from Consensys/mythril
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmyth
executable file
·395 lines (321 loc) · 15.8 KB
/
myth
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
#!/usr/bin/env python3
"""mythril.py: Bug hunting on the Ethereum blockchain
http://www.github.com/b-mueller/mythril
"""
from json.decoder import JSONDecodeError
import logging
import json
import sys
import argparse
import os
import re
from ethereum import utils
from solc.exceptions import SolcError
import solc
from mythril.ether import util
from mythril.ether.contractstorage import get_persistent_storage
from mythril.ether.ethcontract import ETHContract
from mythril.ether.soliditycontract import SolidityContract
from mythril.rpc.client import EthJsonRpc
from mythril.ipc.client import EthIpc
from mythril.rpc.exceptions import ConnectionError
from mythril.support import signatures
from mythril.support.truffle import analyze_truffle_project
from mythril.support.loader import DynLoader
from mythril.exceptions import CompilerError, NoContractFoundError
from mythril.analysis.symbolic import SymExecWrapper
from mythril.analysis.callgraph import generate_graph
from mythril.analysis.security import fire_lasers
from mythril.analysis.report import Report
def searchCallback(code_hash, code, addresses, balances):
print("Matched contract with code hash " + code_hash)
for i in range(0, len(addresses)):
print("Address: " + addresses[i] + ", balance: " + str(balances[i]))
def exitWithError(format, message):
if format == 'text' or format == 'markdown':
print(message)
else:
result = {'success': False, 'error': str(message), 'issues': []}
print(json.dumps(result))
sys.exit()
parser = argparse.ArgumentParser(description='Security analysis of Ethereum smart contracts')
parser.add_argument("solidity_file", nargs='*')
commands = parser.add_argument_group('commands')
commands.add_argument('-g', '--graph', help='generate a control flow graph', metavar='OUTPUT_FILE')
commands.add_argument('-x', '--fire-lasers', action='store_true', help='detect vulnerabilities, use with -c, -a or solidity file(s)')
commands.add_argument('-t', '--truffle', action='store_true', help='analyze a truffle project (run from project dir)')
commands.add_argument('-d', '--disassemble', action='store_true', help='print disassembly')
inputs = parser.add_argument_group('input arguments')
inputs.add_argument('-c', '--code', help='hex-encoded bytecode string ("6060604052...")', metavar='BYTECODE')
inputs.add_argument('-a', '--address', help='pull contract from the blockchain', metavar='CONTRACT_ADDRESS')
inputs.add_argument('-l', '--dynld', action='store_true', help='auto-load dependencies from the blockchain')
outputs = parser.add_argument_group('output formats')
outputs.add_argument('-o', '--outform', choices=['text', 'markdown', 'json'], default='text', help='report output format', metavar='<text/json>')
outputs.add_argument('--verbose-report', action='store_true', help='Include debugging information in report')
database = parser.add_argument_group('local contracts database')
database.add_argument('--init-db', action='store_true', help='initialize the contract database')
database.add_argument('-s', '--search', help='search the contract database', metavar='EXPRESSION')
utilities = parser.add_argument_group('utilities')
utilities.add_argument('--xrefs', action='store_true', help='get xrefs from a contract')
utilities.add_argument('--hash', help='calculate function signature hash', metavar='SIGNATURE')
utilities.add_argument('--storage', help='read state variables from storage index, use with -a', metavar='INDEX,NUM_SLOTS,[array]')
utilities.add_argument('--solv', help='specify solidity compiler version. If not present, will try to install it (Experimental)', metavar='SOLV')
options = parser.add_argument_group('options')
options.add_argument('-m', '--modules', help='Comma-separated list of security analysis modules', metavar='MODULES')
options.add_argument('--sync-all', action='store_true', help='Also sync contracts with zero balance')
options.add_argument('--max-depth', type=int, default=12, help='Maximum recursion depth for symbolic execution')
options.add_argument('--solc-args', help='Extra arguments for solc')
options.add_argument('--phrack', action='store_true', help='Phrack-style call graph')
options.add_argument('--enable-physics', action='store_true', help='enable graph physics simulation')
options.add_argument('-v', type=int, help='log level (0-2)', metavar='LOG_LEVEL')
rpc = parser.add_argument_group('RPC options')
rpc.add_argument('--rpc', help='connect via RPC', metavar='HOST:PORT')
rpc.add_argument('--rpctls', type=bool, default=False, help='RPC connection over TLS')
rpc.add_argument('--ganache', action='store_true', help='Preset: local Ganache')
rpc.add_argument('-i', '--infura-mainnet', action='store_true', help='Preset: Infura Node service (Mainnet)')
rpc.add_argument('--infura-rinkeby', action='store_true', help='Preset: Infura Node service (Rinkeby)')
rpc.add_argument('--infura-kovan', action='store_true', help='Preset: Infura Node service (Kovan)')
rpc.add_argument('--infura-ropsten', action='store_true', help='Preset: Infura Node service (Ropsten)')
# Get config values
args = parser.parse_args()
try:
mythril_dir = os.environ['MYTHRIL_DIR']
except KeyError:
mythril_dir = os.path.join(os.path.expanduser('~'), ".mythril")
# Detect unsupported combinations of command line args
if args.dynld and not args.address:
exitWithError(args.outform, "Dynamic loader can be used in on-chain analysis mode only (-a).")
# Initialize data directory and signature database
if not os.path.exists(mythril_dir):
logging.info("Creating mythril data directory")
os.mkdir(mythril_dir)
# If no function signature file exists, create it. Function signatures from Solidity source code are added automatically.
signatures_file = os.path.join(mythril_dir, 'signatures.json')
sigs = {}
if not os.path.exists(signatures_file):
logging.info("No signature database found. Creating empty database: " + signatures_file + "\n" +
"Consider replacing it with the pre-initialized database at https://raw.githubusercontent.com/ConsenSys/mythril/master/signatures.json")
with open(signatures_file, 'a') as f:
json.dump({}, f)
with open(signatures_file) as f:
try:
sigs = json.load(f)
except JSONDecodeError as e:
exitWithError(args.outform, "Invalid JSON in signatures file " + signatures_file + "\n" + str(e))
# Parse cmdline args
if not (args.search or args.init_db or args.hash or args.disassemble or args.graph or args.xrefs or args.fire_lasers or args.storage or args.truffle):
parser.print_help()
sys.exit()
if args.v:
if 0 <= args.v < 3:
logging.basicConfig(level=[logging.NOTSET, logging.INFO, logging.DEBUG][args.v])
else:
exitWithError(args.outform, "Invalid -v value, you can find valid values in usage")
if args.hash:
print("0x" + utils.sha3(args.hash)[:4].hex())
sys.exit()
if args.truffle:
try:
analyze_truffle_project(args)
except FileNotFoundError:
print("Build directory not found. Make sure that you start the analysis from the project root, and that 'truffle compile' has executed successfully.")
sys.exit()
# Figure out solc binary and version
# Only proper versions are supported. No nightlies, commits etc (such as available in remix)
if args.solv:
version = args.solv
# tried converting input to semver, seemed not necessary so just slicing for now
if version == str(solc.main.get_solc_version())[:6]:
logging.info('Given version matches installed version')
try:
solc_binary = os.environ['SOLC']
except KeyError:
solc_binary = 'solc'
else:
if util.solc_exists(version):
logging.info('Given version is already installed')
else:
try:
solc.install_solc('v' + version)
except SolcError:
exitWithError(args.outform, "There was an error when trying to install the specified solc version")
solc_binary = os.path.join(os.environ['HOME'], ".py-solc/solc-v" + version, "bin/solc")
logging.info("Setting the compiler to " + str(solc_binary))
else:
try:
solc_binary = os.environ['SOLC']
except KeyError:
solc_binary = 'solc'
# Establish RPC/IPC connection if necessary
eth = None
if args.address or args.init_db:
if args.infura_mainnet:
eth = EthJsonRpc('mainnet.infura.io', 443, True)
elif args.infura_rinkeby:
eth = EthJsonRpc('rinkeby.infura.io', 443, True)
elif args.infura_kovan:
eth = EthJsonRpc('kovan.infura.io', 443, True)
elif args.infura_ropsten:
eth = EthJsonRpc('ropsten.infura.io', 443, True)
elif args.ganache:
eth = EthJsonRpc('localhost', 7545, False)
elif args.rpc:
try:
host, port = args.rpc.split(":")
except ValueError:
exitWithError(args.outform, "Invalid RPC argument, use HOST:PORT")
else:
tls = args.rpctls
eth = EthJsonRpc(host, int(port), tls)
else:
try:
eth = EthIpc()
except Exception as e:
exitWithError(args.outform, "IPC initialization failed. Please verify that your local Ethereum node is running, or use the -i flag to connect to INFURA. \n" + str(e))
# Database search ops
if args.search or args.init_db:
contract_storage = get_persistent_storage(mythril_dir)
if args.search:
try:
contract_storage.search(args.search, searchCallback)
except SyntaxError:
exitWithError(args.outform, "Syntax error in search expression.")
elif args.init_db:
try:
contract_storage.initialize(eth, args.sync_all)
except FileNotFoundError as e:
exitWithError(args.outform, "Error syncing database over IPC: " + str(e))
except ConnectionError as e:
exitWithError(args.outform, "Could not connect to RPC server. Make sure that your node is running and that RPC parameters are set correctly.")
sys.exit()
# Load / compile input contracts
contracts = []
address = None
if args.code:
address = util.get_indexed_address(0)
contracts.append(ETHContract(args.code, name="MAIN"))
# Get bytecode from a contract address
elif args.address:
address = args.address
if not re.match(r'0x[a-fA-F0-9]{40}', args.address):
exitWithError(args.outform, "Invalid contract address. Expected format is '0x...'.")
try:
code = eth.eth_getCode(args.address)
except FileNotFoundError as e:
exitWithError(args.outform, "IPC error: " + str(e))
except ConnectionError as e:
exitWithError(args.outform, "Could not connect to RPC server. Make sure that your node is running and that RPC parameters are set correctly.")
except Exception as e:
exitWithError(args.outform, "IPC / RPC error: " + str(e))
else:
if code == "0x":
exitWithError(args.outform, "Received an empty response from eth_getCode. Check the contract address and verify that you are on the correct chain.")
else:
contracts.append(ETHContract(code, name=args.address))
# Compile Solidity source file(s)
elif args.solidity_file:
address = util.get_indexed_address(0)
if args.graph and len(args.solidity_file) > 1:
exitWithError(args.outform, "Cannot generate call graphs from multiple input files. Please do it one at a time.")
for file in args.solidity_file:
if ":" in file:
file, contract_name = file.split(":")
else:
contract_name = None
file = os.path.expanduser(file)
try:
signatures.add_signatures_from_file(file, sigs)
contract = SolidityContract(file, contract_name, solc_args=args.solc_args)
logging.info("Analyzing contract %s:%s" % (file, contract.name))
except FileNotFoundError:
exitWithError(args.outform, "Input file not found: " + file)
except CompilerError as e:
exitWithError(args.outform, e)
except NoContractFoundError:
logging.info("The file " + file + " does not contain a compilable contract.")
else:
contracts.append(contract)
# Save updated function signatures
with open(signatures_file, 'w') as f:
json.dump(sigs, f)
else:
exitWithError(args.outform, "No input bytecode. Please provide EVM code via -c BYTECODE, -a ADDRESS, or -i SOLIDITY_FILES")
# Commands
if args.storage:
if not args.address:
exitWithError(args.outform, "To read storage, provide the address of a deployed contract with the -a option.")
else:
(position, length) = (0, 1)
try:
params = args.storage.split(",")
if len(params) >= 4:
exitWithError(args.outform, "Invalid number of parameters.")
if len(params) >= 1:
position = int(params[0])
if len(params) >= 2:
length = int(params[1])
if len(params) == 3 and params[2] == "array":
position_formatted = str(position).zfill(64)
position = int(utils.sha3(position_formatted), 16)
except ValueError:
exitWithError(args.outform, "Invalid storage index. Please provide a numeric value.")
try:
if length == 1:
print("{}: {}".format(position, eth.eth_getStorageAt(args.address, position)))
else:
for i in range(position, position + length):
print("{}: {}".format(hex(i), eth.eth_getStorageAt(args.address, i)))
except FileNotFoundError as e:
exitWithError(args.outform, "IPC error: " + str(e))
except ConnectionError as e:
exitWithError(args.outform, "Could not connect to RPC server. Make sure that your node is running and that RPC parameters are set correctly.")
elif args.disassemble:
easm_text = contracts[0].get_easm()
sys.stdout.write(easm_text)
elif args.xrefs:
print("\n".join(contracts[0].get_xrefs()))
elif args.graph or args.fire_lasers:
if not contracts:
exitWithError(args.outform, "input files do not contain any valid contracts")
if args.graph:
if args.dynld:
sym = SymExecWrapper(contracts[0], address, dynloader=DynLoader(eth), max_depth=args.max_depth)
else:
sym = SymExecWrapper(contracts[0], address, max_depth=args.max_depth)
html = generate_graph(sym, args.enable_physics, args.phrack)
try:
with open(args.graph, "w") as f:
f.write(html)
except Exception as e:
exitWithError(args.outform, "Error saving graph: " + str(e))
else:
all_issues = []
for contract in contracts:
if args.dynld:
sym = SymExecWrapper(contract, address, dynloader=DynLoader(eth), max_depth=args.max_depth)
else:
sym = SymExecWrapper(contract, address, max_depth=args.max_depth)
if args.modules:
issues = fire_lasers(sym, args.modules.split(","))
else:
issues = fire_lasers(sym)
if type(contract) == SolidityContract:
for issue in issues:
if issue.pc:
codeinfo = contract.get_source_info(issue.pc)
issue.filename = codeinfo.filename
issue.code = codeinfo.code
issue.lineno = codeinfo.lineno
all_issues += issues
# Finally, output the results
report = Report(args.verbose_report)
for issue in all_issues:
report.append_issue(issue)
outputs = {
'json': report.as_json(),
'text': report.as_text() or "The analysis was completed successfully. No issues were detected.",
'markdown': report.as_markdown() or "The analysis was completed successfully. No issues were detected."
}
print(outputs[args.outform])
else:
parser.print_help()