-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcli
More file actions
executable file
·330 lines (271 loc) · 7.69 KB
/
Copy pathcli
File metadata and controls
executable file
·330 lines (271 loc) · 7.69 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
#!/usr/bin/env python
# Copyright 2013 anthony cantor
# This file is part of sefi.
#
# sefi is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# sefi is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with sefi. If not, see <http://www.gnu.org/licenses/>.
import argparse
import sys
import os.path
import logging
import sefi
import sefi.log
import sefi.matcher
import sefi.disassembler
import sefi.container
import sefi.elf
def opt_parser():
parser = argparse.ArgumentParser(description='search binary data for sequences of instructions')
parser.add_argument(
'file',
nargs='?',
type=argparse.FileType('r'),
help='file to search. if no file is given, stdin will be used',
default=False
)
parser.add_argument(
'-v',
'--verbose',
action='count',
help='print debug output. repeat to increase verbosity.',
default=0
)
parser.add_argument(
'-n',
'--n',
metavar='N',
type=int,
help='search backwards from gadget terminator for N bytes. default: 20',
default=20
)
parser.add_argument(
'-g',
'--gadget',
metavar='REGEXP',
action='append',
help='search for gadgets ending in an instruction that matches REGEXP. ' + \
'note: REGEXP will have to match the specific output style of ' + \
'whichever disassembler backend is being used (though the match ' + \
'is not case sensitive)',
default=[]
)
parser.add_argument(
'--ret',
action='store_true',
help='search for gadgets ending with a RET instruction.'
)
parser.add_argument(
'--jmp-reg',
action='store_true',
help='search for gadgets ending with a "JMP %%reg" instruction.'
)
parser.add_argument(
'--call-reg',
action='store_true',
help='search for gadgets ending with a "CALL %%reg" instruction.'
)
parser.add_argument(
'--all',
action='store_true',
help='equivalent to passing --ret, --jmp-reg, and --call-reg.'
)
parser.add_argument(
'--d-backend',
metavar='NAME',
help='use NAME as the disassembler backend. note: the backend ' + \
'may or may not support the architecture of the input file. ' + \
'valid backends: %s' % (
", ".join(sefi.disassembler.backend_names())
)
)
parser.add_argument(
'-d',
'--disassemble',
nargs='?',
action='append',
metavar='SYMBOL',
help='disassemble SYMBOL. pass -d more than once ' + \
'with different symbols to disassemble more than one ' + \
'symbol. if no symbols are provided, all executable ' + \
'segments will be disassembled.'
)
parser.add_argument(
'--uncond-flow',
action='store_true',
help='allow unconditional control flow in gadgets. default: False.',
default=False
)
parser.add_argument(
'--cond-flow',
action='store_true',
help='allow conditional control flow in gadgets. default: False.',
default=False
)
"""
TODO: parser.add_argument(
'--raw',
action='store_true',
help='treat the input as raw executable bytes (by default the input is parsed as an elf executable).'
)
"""
return parser
class SefiCliErr(Exception):
pass
class MissingOption(SefiCliErr):
pass
class NotImplemented(SefiCliErr):
pass
def validate_options(options):
if len(options.gadget) < 1 and \
not options.ret and \
not options.jmp_reg and \
not options.call_reg and \
not options.all and \
not options.disassemble:
raise MissingOption("you must specify at least one gadget " + \
"specification: -g, --ret, --jmp-reg, " + \
"--call-reg, --all or -d")
def run(options):
validate_options(options)
lgr = logging.getLogger("sefi")
if options.verbose >= 2:
lgr.setLevel(logging.DEBUG)
elif options.verbose == 1:
lgr.setLevel(logging.INFO)
else:
lgr.setLevel(logging.ERROR)
ch = logging.StreamHandler()
ch.setLevel(lgr.level)
lgr.addHandler(ch)
sefi.log.set_logger(lgr)
if not options.file:
sys.stderr.write("using stdin as input file\n")
#elftools needs to be able to seek
#so we need to make stdin a normal file
with open("/tmp/sefi-stdin", "w") as f:
f.write(sys.stdin.read())
options.file = open("/tmp/sefi-stdin", "r")
if options.d_backend is None:
pass
elif options.d_backend not in sefi.disassembler.backends:
print("invalid backend %r" % options.d_backend)
exit(1)
else:
#set rank of lib to arbitrary high number
sefi.disassembler.backend_set_rank(options.d_backend, 9999)
run_elf(options)
def run_elf(options):
run_search_elf(options)
run_dasm_elf(options)
def run_search_elf(options):
if not (options.ret or \
options.jmp_reg or \
options.call_reg or \
options.all or \
len(options.gadget) > 0):
return
result = set([])
def set_matcher_flow(m):
m.uncond_flow = options.uncond_flow
m.cond_flow = options.cond_flow
return m
if options.ret or options.all:
m = set_matcher_flow(sefi.matcher.Rets())
for gadget in sefi.search_elf_for_gadgets(options.file, options.n, m):
result.add(gadget)
if options.jmp_reg or options.all:
m = set_matcher_flow(sefi.matcher.JmpRegUncond())
for gadget in sefi.search_elf_for_gadgets(options.file, options.n, m):
result.add(gadget)
if options.call_reg or options.all:
m = set_matcher_flow(sefi.matcher.CallReg())
for gadget in sefi.search_elf_for_gadgets(options.file, options.n, m):
result.add(gadget)
if len(options.gadget) > 0:
for reg in options.gadget:
sefi.log.info("search for gadgets matching %r" % reg)
m = set_matcher_flow(sefi.matcher.REMatcher(reg))
for gadget in sefi.search_elf_for_gadgets(options.file, options.n, m):
result.add(gadget)
if len(result) < 1:
sys.stderr.write("no gadgets found\n")
return
cond_flow = []
uncond_flow = []
normal = []
for g in result:
#unconditional is the strongest condition
if g.has_uncond_ctrl_flow():
uncond_flow.append(g)
elif g.has_cond_ctrl_flow():
cond_flow.append(g)
else:
normal.append(g)
print("gadgets with unconditional control flow:")
display_gadgets(uncond_flow)
print("\n")
print("gadgets with conditional control flow:")
display_gadgets(cond_flow)
print("\n")
print("gadgets with no control flow:")
display_gadgets(normal)
print("\n")
def run_dasm_elf(options):
if not options.disassemble:
return
syms = set([])
syms_found = set([])
for sym in options.disassemble:
if isinstance(sym, str):
syms.add(sym)
elf_o, arch = sefi.elf.open(options.file)
dasm = sefi.disassembler.find(arch)
i = 0
for (name, addr, data) in sefi.elf.executable_data_by_symbol(elf_o):
if len(syms) < 1 or name in syms:
if i > 0:
print("")
disassemble_symbol(elf_o, name, addr, data, dasm)
i += 1
if name in syms:
syms_found.add(name)
not_found = syms - syms_found
if len(not_found) > 0:
for name in not_found:
print("failed to find symbol %r" % name)
def disassemble_symbol(elf_o, name, addr, data, dasm):
if not name:
sec = sefi.elf.section_at_addr(elf_o, addr)
if sec:
name = sec.name
name_str = ("<%s>" % name) if name else "(NO NAME)"
print '%s:' % name_str
print sefi.container.InstSeq(addr, data, dasm).display()
def display_gadgets(gadgets):
width = 60
for g in sorted(gadgets, lambda x,y: cmp(x.addr(), y.addr())):
print("-"*width)
print(g.display())
if __name__ == "__main__":
opt_p = opt_parser()
options = opt_p.parse_args()
try:
run(options)
except SefiCliErr as e:
print(e)
print("")
opt_p.print_help()
exit(1)
except IOError as e:
if e.args[0] != 32: #broken pipe
raise e