-
Notifications
You must be signed in to change notification settings - Fork 0
/
amnesia.py
465 lines (400 loc) · 15.2 KB
/
amnesia.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
# ////////////////////////////////////////////////////////////////////////////
# ----------------------------------------------------------------------------
#
# Amnesia - Layer 1 binary analysis system.
# Copyright (c) 2013 Tristan Strathearn (r3oath@gmail.com)
# Website: www.r3oath.com
#
# ----------------------------------------------------------------------------
# ////////////////////////////////////////////////////////////////////////////
import sys
import re
import pefile
import peutils
import pydasm
import struct
# ----------------------------------------------------------------------------
print """
_____ __ __ __ __ _____ ______ __ _____
/\___/\ /_/\ /\_\ /_/\ /\_\ /\_____\/ ____/\ /\_\ /\___/\\
/ / _ \ \ ) ) \/ ( ( ) ) \ ( (( (_____/) ) __\/ \/_/ / / _ \ \\
\ \(_)/ //_/ \ / \_\/_/ \ \_\\\\ \__\ \ \ \ /\_\\\\ \(_)/ /
/ / _ \ \\\\ \ \\\\// / /\ \ \ / // /__/_ _\ \ \ / / // / _ \ \\
( (_( )_) ))_) )( (_( )_) \ (_(( (_____\)____) )( (_(( (_( )_) )
\/_/ \_\/ \_\/ \/_/ \_\/ \/_/ \/_____/\____\/ \/_/ \/_/ \_\/
Layer 1 binary analysis system.
Created by Tristan Strathearn (www.r3oath.com)
"""
# ----------------------------------------------------------------------------
def getInput(question, default_answer='', override=False):
required = True if default_answer == '' else False
if default_answer == '':
formatted_string = '%s: ' % question
else:
formatted_string = '%s [%s]: ' % (question, default_answer)
if override is True:
formatted_string = '%s ' % question
required = False
while True:
input_ = raw_input(formatted_string).strip()
len_ = len(input_)
if len_ > 0: return input_
elif len_ == 0 and not required: return default_answer
def print_(message):
print '%s' % message
def reportError(message):
print_('ERROR: %s!' % message)
def spacer():
print_('')
def drawLine():
sys.stdout.write('>' * 80)
def getDataDump(file_):
f = open(file_, 'rb')
data = f.read()
f.close()
return data
# ----------------------------------------------------------------------------
# Hehe.
class ChocolateLog:
log = []
def __init__(self):
self.log = []
def add(self, message):
self.log.append(message)
def writeToFile(self):
file_ = getInput('Please specify a file name')
try:
f = open(file_, 'w')
for entry in self.log:
f.write('%s\n' % entry)
f.close()
except:
reportError('ChocolateLog failed to write to "%s"' % file_)
def interactiveOutput(self):
choice = getInput('Save to file instead of viewing?', 'N').upper()
if choice.count('Y') > 0:
self.writeToFile()
return
print_('Press Enter to scroll down, (S)ave or (Q)uit.')
spacer()
base = 0
step_size = 20
while True:
index = 0
for entry in self.log[base:]:
print_(entry)
index += 1
if index >= step_size:
break
base += index
index = 0
if base >= len(self.log):
break
choice = getInput('...',
override=True).upper()
if choice.count('Q') > 0:
return
elif choice.count('S') > 0:
self.writeToFile()
return
else:
continue
# ----------------------------------------------------------------------------
SUBJECT = None
ORIG_FILE = None
def loadSubject():
global SUBJECT
global ORIG_FILE
ORIG_FILE = getInput('Please enter the file to process')
try:
SUBJECT = pefile.PE(ORIG_FILE)
print_('Loaded the binary "%s"' % ORIG_FILE)
except:
reportError('Cannot open the file "%s"' % ORIG_FILE)
loadSubject()
loadSubject()
# ----------------------------------------------------------------------------
def strings_display_all():
try:
min_ = int(getInput('Minimum string length', '5'))
max_ = int(getInput('Maximum string length', '999'))
except ValueError:
reportError('Please specify only numeric values')
return
clog = ChocolateLog()
clog.add('Strings:')
data = getDataDump(ORIG_FILE)
search_str = '[\x20-\x7F]{%i,%i}' % (min_, max_)
for string_ in re.findall(search_str, data):
string_ = string_.strip()
if len(string_) > 0:
clog.add('\t%s' % string_)
clog.interactiveOutput()
def strings_search():
try:
min_ = int(getInput('Minimum string length', '5'))
max_ = int(getInput('Maximum string length', '999'))
except ValueError:
reportError('Please specify only numeric values')
return
keyword = getInput('Keyword to search for').lower()
clog = ChocolateLog()
clog.add('Strings containing the keyword "%s":' % keyword)
data = getDataDump(ORIG_FILE)
search_str = '[\x20-\x7F]{%i,%i}' % (min_, max_)
for string_ in re.findall(search_str, data):
string_ = string_.strip()
if string_.lower().count(keyword) > 0:
clog.add('\t%s' % string_)
clog.interactiveOutput()
def misc_verify_checksum():
verified = SUBJECT.verify_checksum()
if verified: print_('Checksum is valid.')
else: print_('Checksum is invalid.')
def misc_generate_checksum():
print_('Checksum: 0x%08X' % SUBJECT.generate_checksum())
def imports_dump_all():
clog = ChocolateLog()
clog.add('Imports:')
for desc in SUBJECT.DIRECTORY_ENTRY_IMPORT:
clog.add('\t%s' % desc.dll)
for import_ in desc.imports:
if import_.import_by_ordinal is not True:
clog.add('\t\t%s' % import_.name)
else:
clog.add('\t\tOrdinal: %i' % import_.ordinal)
clog.add('Delayed Imports:')
for desc in SUBJECT.DIRECTORY_ENTRY_DELAY_IMPORT:
clog.add('\t%s' % desc.dll)
for import_ in desc.imports:
if import_.import_by_ordinal is not True:
clog.add('\t\t%s' % import_.name)
else:
clog.add('\t\tOrdinal: %i' % import_.ordinal)
clog.interactiveOutput()
def imports_search():
keyword = getInput('Keyword to search for').lower()
clog = ChocolateLog()
clog.add('Imports containing the keyword "%s":' % keyword)
for desc in SUBJECT.DIRECTORY_ENTRY_IMPORT:
for import_ in desc.imports:
if import_.import_by_ordinal is not True:
if import_.name.lower().count(keyword) > 0:
clog.add('\t%s (%s)' % (import_.name, desc.dll))
for desc in SUBJECT.DIRECTORY_ENTRY_DELAY_IMPORT:
for import_ in desc.imports:
if import_.import_by_ordinal is not True:
if import_.name.lower().count(keyword) > 0:
clog.add('\t%s (%s)' % (import_.name, desc.dll))
clog.interactiveOutput()
def exports_dump_all():
try:
clog = ChocolateLog()
clog.add('Exports:')
for symbol in SUBJECT.DIRECTORY_ENTRY_EXPORT.symbols:
if symbol.name is not None:
if symbol.forwarder is None:
clog.add('\tOrdinal: %i / %s' %
(symbol.ordinal, symbol.name))
else:
clog.add('\t%s -> %s' %
(symbol.name, symbol.forwarder))
else:
if symbol.forwarder is None:
clog.add('\tOrdinal: %i / %s' %
(symbol.ordinal, '<Exported by ordinal>'))
else:
clog.add('\tOrdinal %i -> %s' %
(symbol.ordinal, symbol.forwarder))
clog.interactiveOutput()
except:
print_('Could not be processed (binary may not export anything)')
def exports_search():
try:
keyword = getInput('Keyword to search for').lower()
clog = ChocolateLog()
clog.add('Exports containing the keyword "%s":' % keyword)
for symbol in SUBJECT.DIRECTORY_ENTRY_EXPORT.symbols:
if symbol.name is None:
continue
if symbol.name.lower().count(keyword) == 0:
continue
if symbol.name is not None:
if symbol.forwarder is None:
clog.add('\tOrdinal: %i / %s' %
(symbol.ordinal, symbol.name))
else:
clog.add('\t%s -> %s' %
(symbol.name, symbol.forwarder))
else:
if symbol.forwarder is None:
clog.add('\tOrdinal: %i / %s' %
(symbol.ordinal, '<Exported by ordinal>'))
else:
clog.add('\tOrdinal %i -> %s' %
(symbol.ordinal, symbol.forwarder))
clog.interactiveOutput()
except:
print_('Could not be processed (binary may not export anything)')
def exports_build_vs_pragma_forwards():
s_by_name = '#pragma comment(linker, "/export:%s=%s.%s")\n'
s_by_ord = '#pragma comment(linker, "/export:ord%i=%s.#%i,@%i,NONAME")\n'
try:
new_dll = getInput('DLL name to forward too').lower().strip('.dll')
clog = ChocolateLog()
for symbol in SUBJECT.DIRECTORY_ENTRY_EXPORT.symbols:
if symbol.name is not None:
clog.add(s_by_name % (symbol.name, new_dll, symbol.name))
else:
clog.add(s_by_ord %
(symbol.ordinal, new_dll, symbol.ordinal, symbol.ordinal))
clog.interactiveOutput()
except:
print_('Could not be processed (binary may not export anything)')
def __assembly_offset(offset):
return '%08X' % offset
def assembly_disassemble():
try:
max_bytes = int(getInput('Number of bytes to disassemble'))
except ValueError:
reportError('Please specify only numeric values')
return
clog = ChocolateLog()
OEP = SUBJECT.OPTIONAL_HEADER.AddressOfEntryPoint
OEP_base = OEP + SUBJECT.OPTIONAL_HEADER.ImageBase
data = SUBJECT.get_memory_mapped_image()[OEP:]
offset = 0
while offset < max_bytes:
ins = pydasm.get_instruction(data[offset:], pydasm.MODE_32)
if ins is None:
asm = 'db %02x' % ord(data[offset])
clog.add('%s\t%s' % (__assembly_offset(offset), asm))
offset += 1
continue
asm = pydasm.get_instruction_string(ins, pydasm.FORMAT_INTEL,
OEP_base + offset)
clog.add('%s\t%s' % (__assembly_offset(offset), asm))
offset += ins.length
clog.interactiveOutput()
def metadata_subject_overview():
if SUBJECT.is_exe() is True:
print_('Binary "%s" is an EXE' % ORIG_FILE)
if SUBJECT.is_dll() is True:
print_('Binary "%s" is a DLL' % ORIG_FILE)
flagged = False
if peutils.is_probably_packed(SUBJECT) is True:
print_('Binary is possibly packed!')
flagged = True
if peutils.is_suspicious(SUBJECT) is True:
print_('Binary is suspicious!')
flagged = True
if flagged is False:
print_('Binary appears to be normal')
print_('Address of Entry Point: 0x%08x' %
SUBJECT.OPTIONAL_HEADER.AddressOfEntryPoint)
misc_generate_checksum()
misc_verify_checksum()
print_('Sections:')
for section in SUBJECT.sections:
print_('\tRVA: 0x%08x - Name: %s - %i bytes' %
(section.VirtualAddress, section.Name.strip('\x00'),
section.SizeOfRawData))
print_('Imports from:')
for entry in SUBJECT.DIRECTORY_ENTRY_IMPORT:
count = 0
for i in entry.imports:
count += 1
print_('\t%s -> %i functions' % (entry.dll, count))
def callback():
reportError('Callback not yet implemented')
# ----------------------------------------------------------------------------
menu_tree = [
{'Section': 'Strings', 'Contents': [
{'Option': 'Dump All', 'Callback': strings_display_all},
{'Option': 'Search by keyword', 'Callback': strings_search},
]},
{'Section': 'Imports', 'Contents': [
{'Option': 'Dump All', 'Callback': imports_dump_all},
{'Option': 'Search by keyword', 'Callback': imports_search},
]},
{'Section': 'Exports', 'Contents': [
{'Option': 'Dump All', 'Callback': exports_dump_all},
{'Option': 'Search by keyword', 'Callback': exports_search},
{'Option': 'Build VS #Pragma forwards',
'Callback': exports_build_vs_pragma_forwards},
]},
{'Section': 'Assembly', 'Contents': [
{'Option': 'Disassemble at OEP', 'Callback': assembly_disassemble},
]},
{'Section': 'Metadata', 'Contents': [
{'Option': 'Binary Overview', 'Callback': metadata_subject_overview},
]},
{'Section': 'Misc', 'Contents': [
{'Option': 'Verify Checksum', 'Callback': misc_verify_checksum},
{'Option': 'Generate Checksum', 'Callback': misc_generate_checksum},
{'Option': 'Load new binary', 'Callback': loadSubject}
]},
]
# ----------------------------------------------------------------------------
class Menu:
cur_section = None
def __init__(self, menu_tree=None):
self.tree = menu_tree
def display(self):
spacer()
if self.cur_section is None:
self.display_root()
else:
self.display_section()
def display_root(self):
index = 0
for e in self.tree:
print_('....[%i] %s' % (index, e['Section']))
index += 1
user_choice = None
try:
user_choice = int(getInput('Menu selection'))
except ValueError:
user_choice = None
if user_choice >= index or user_choice < 0 or user_choice == None:
reportError('Invalid menu selection')
self.display()
else:
self.cur_section = user_choice
self.display()
def display_section(self):
index = 0
print_('....[+] %s' % self.tree[self.cur_section]['Section'])
for e in self.tree[self.cur_section]['Contents']:
print_('........[%i] %s' % (index, e['Option']))
index += 1
print_('........[%i] %s' % (index, 'Main menu'))
user_choice = None
try:
user_choice = int(getInput('Menu selection'))
except ValueError:
user_choice = None
if user_choice > index or user_choice < 0 or user_choice == None:
reportError('Invalid menu selection')
self.display()
elif user_choice == index:
self.cur_section = None
self.display()
else:
# Bit of visual formatting happening here before the callback.
spacer()
drawLine()
spacer()
self.tree[self.cur_section]['Contents'][user_choice]['Callback']()
spacer()
drawLine()
self.display()
# ----------------------------------------------------------------------------
AmnesiaMenu = Menu(menu_tree)
try:
AmnesiaMenu.display()
except KeyboardInterrupt:
print_('\n\nGoodbye.')
except Exception as e:
reportError('Unhandled exception caught')
reportError('%s' % e)