-
Notifications
You must be signed in to change notification settings - Fork 129
Expand file tree
/
Copy pathfeatherduster.py
More file actions
454 lines (371 loc) · 15.7 KB
/
Copy pathfeatherduster.py
File metadata and controls
454 lines (371 loc) · 15.7 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
'''
FeatherDuster - A wizard-like interface to cryptanalib
Author: Daniel Crowley
FeatherDuster is a tool for brushing away magical crypto fairy dust.
'''
import sys
import os
import readline
import completer #readline completion
import advice #advice text
from ishell.console import Console
from ishell.command import Command
try:
from IPython import embed
except ImportError:
import code
def embed():
vars = globals()
vars.update(locals())
shell = code.InteractiveConsole(vars)
shell.interact()
import feathermodules
feathermodules.samples = []
feathermodules.results = False
feathermodules.analysis_results = False
feathermodules.selected_attack_name = ''
feathermodules.current_options = {}
from feathermodules.stream import *
from feathermodules.block import *
from feathermodules.classical import *
from feathermodules.auxiliary import *
from feathermodules.custom import *
from feathermodules.pubkey import *
import cryptanalib as ca
# import
class ImportMultiFileCommand(Command):
def run(self, line):
ishellCompleter = readline.get_completer()
readline.set_completer_delims(' \t\n;')
readline.parse_and_bind("tab: complete")
readline.set_completer(completer.complete)
sample_file = raw_input('Please enter the filename you want to open: ')
try:
sample_fh = open(sample_file,'r')
feathermodules.samples.extend([sample.strip() for sample in sample_fh.readlines()])
sample_fh.close()
feathermodules.samples = filter(lambda x: x != '' and x != None, feathermodules.samples)
except:
print 'Something went wrong. Sorry! Please try again.'
finally:
readline.set_completer(ishellCompleter)
class ImportSingleFileCommand(Command):
def run(self, line):
ishellCompleter = readline.get_completer()
readline.set_completer_delims(' \t\n;')
readline.parse_and_bind("tab: complete")
readline.set_completer(completer.complete)
sample_file = raw_input('Please enter the filename you want to open: ')
try:
sample_fh = open(sample_file,'r')
feathermodules.samples.append(sample_fh.read())
sample_fh.close()
feathermodules.samples = filter(lambda x: x != '' and x != None, feathermodules.samples)
except:
print 'Something went wrong. Sorry! Please try again.'
finally:
readline.set_completer(ishellCompleter)
class ImportManualEntryCommand(Command):
def run(self, line):
feathermodules.samples.append(raw_input('Please enter your sample: ').strip())
feathermodules.samples = filter(lambda x: x != '' and x != None, feathermodules.samples)
class ImportResultsCommand(Command):
def run(self, line):
if not feathermodules.results:
print 'Last module failed to produce results.'
elif feathermodules.results == True:
print 'Last module succeeded, but did not return results.'
else:
print 'Last results (long values may be truncated):'
print '-'*80
for i in range(len(feathermodules.results)):
print '{0:d}: {1:60s}'.format(i, repr(feathermodules.results[i]))
selection = raw_input('\nPlease enter your selection by number, or \'all\' for all: ')
try:
if selection == 'all':
feathermodules.samples.extend(feathermodules.results)
elif int(selection) < len(feathermodules.results):
feathermodules.samples.append(feathermodules.results[int(selection)])
else:
print 'Invalid entry, please try again.'
feathermodules.samples = filter(lambda x: x != '' and x != None, feathermodules.samples)
except ValueError:
print 'Invalid entry, please try again.'
class ImportClearCommand(Command):
def run(self, line):
feathermodules.samples = []
class ImportCommand(Command):
def args(self):
return ['multifile', 'singlefile', 'manualentry', 'results', 'clear']
import_sample = ImportCommand('import', help='Import samples for analysis', dynamic_args=True)
import_multifile = ImportMultiFileCommand(
'multifile',
help='Import multiple newline-separated samples from one file',
dynamic_args=True)
import_singlefile = ImportSingleFileCommand(
'singlefile',
help='Import a single file as a raw sample',
dynamic_args=True)
import_manualentry = ImportManualEntryCommand(
'manualentry',
help='Manually enter a single sample',
dynamic_args=True)
import_results = ImportResultsCommand(
'results',
help='Import last module\'s results as samples',
dynamic_args=True)
import_clear = ImportClearCommand(
'clear',
help='Clear current sample set',
dynamic_args=True)
import_sample.addChild(import_multifile)
import_sample.addChild(import_singlefile)
import_sample.addChild(import_manualentry)
import_sample.addChild(import_results)
import_sample.addChild(import_clear)
# advice
class AdviceCommand(Command):
def run(self, line):
advice.give_advice()
advice_command = AdviceCommand('advice', help='Provides advice on next steps and research based on current state')
# console
class ConsoleCommand(Command):
def run(self, line):
ishellCompleter = readline.get_completer()
embed()
readline.set_completer(ishellCompleter)
console = ConsoleCommand('console', help='Opens an interactive prompt', dynamic_args=True)
# export to file
class ExportCommand(Command):
def run(self, line):
def _formatOutput(res):
if isinstance(res, str):
return res
else:
try:
return "\n".join(_formatOutput(r) for r in res)
except TypeError:
return str(res)
ishellCompleter = readline.get_completer()
readline.set_completer_delims(' \t\n;')
readline.parse_and_bind("tab: complete")
readline.set_completer(completer.complete)
filePath = raw_input("Please specify a path to the output file: ").strip()
readline.set_completer(ishellCompleter)
if os.path.isfile(filePath):
confirm = raw_input("File already exists and will be overwritten, confirm? [y/N] ")
if confirm is "" or confirm[0] not in ("y", "Y"):
print "Canceled."
return
with open(filePath, "w+") as handle:
handle.write(_formatOutput(feathermodules.results))
export = ExportCommand('export', help='Export current results to file', dynamic_args=True)
# use
class UseCommand(Command):
def args(self):
return feathermodules.module_list.keys()
def run(self, line):
if line.split()[-1] not in feathermodules.module_list.keys():
print 'Invalid module selection. Please try again.'
else:
feathermodules.selected_attack = feathermodules.module_list[ line.split()[-1] ]
feathermodules.selected_attack_name = line.split()[-1]
feathermodules.current_options = feathermodules.selected_attack['options']
use = UseCommand('use', help='Select the module to use', dynamic_args=True)
# analyze
class AnalyzeCommand(Command):
def run(self, line):
if len(feathermodules.samples) == 0:
print 'No loaded samples. Please use the \'import\' command.'
return False
print '[+] Analyzing samples...'
feathermodules.analysis_results = ca.analyze_ciphertext(feathermodules.samples, verbose=True)
if feathermodules.analysis_results['decoded_ciphertexts'] != feathermodules.samples:
decode = raw_input('[+] Analysis suggests encoded samples. Decode before continuing (Y/n)? ')
if decode.lower() not in ('n','no','nope','nah','no thank you'):
feathermodules.samples = feathermodules.analysis_results['decoded_ciphertexts']
print ''
print '[+] Suggested modules:'
for attack in feathermodules.module_list.keys():
if len(set(feathermodules.module_list[attack]['keywords']) & set(feathermodules.analysis_results['keywords'])) > 0:
print ' {0:<20} - {1:<57}'.format(attack, feathermodules.module_list[attack]['description'])
analyze = AnalyzeCommand('analyze', help='Analyze/decode samples', dynamic_args=True)
# autopwn
class AutopwnCommand(Command):
def run(self, line):
if len(feathermodules.samples) == 0:
print 'No loaded samples. Please use the \'import\' command.'
return False
print '[+] Analyzing samples...'
feathermodules.analysis_results = ca.analyze_ciphertext(feathermodules.samples, verbose=True)
if feathermodules.analysis_results['decoded_ciphertexts'] != feathermodules.samples:
feathermodules.samples = feathermodules.analysis_results['decoded_ciphertexts']
for attack in feathermodules.module_list.keys():
if len(set(feathermodules.module_list[attack]['keywords']) & set(feathermodules.analysis_results['keywords'])) > 0:
print 'Running module: %s' % attack
feathermodules.current_options = feathermodules.module_list[attack]['options']
if debug:
print feathermodules.module_list[attack]['attack_function'](feathermodules.samples)
else:
try:
print feathermodules.module_list[attack]['attack_function'](feathermodules.samples)
except:
print '[*] Module execution failed, please report this issue at https://github.com/nccgroup/featherduster/issues'
autopwn = AutopwnCommand('autopwn', help='Analyze samples and run all attacks', dynamic_args=True)
# search
class SearchCommand(Command):
def run(self, line):
matching_modules = []
search_param = line.split()[-1].lower()
for attack in feathermodules.module_list.keys():
if attack.lower().find(search_param) != -1:
matching_modules.append(attack)
elif feathermodules.module_list[attack]['description'].lower().find(search_param) != -1:
matching_modules.append(attack)
elif search_param in feathermodules.module_list[attack]['keywords']:
matching_modules.append(attack)
for module in matching_modules:
print "%s - %s" % (module, feathermodules.module_list[module]['description'])
search = SearchCommand('search', help='Search module names and descriptions by keyword')
# samples
class SamplesCommand(Command):
def run(self, line):
print '-' * 60
for sample in feathermodules.samples:
print repr(sample)
print '-' * 60
samples = SamplesCommand('samples', help='Show samples')
# modules
class ModulesCommand(Command):
def run(self, line):
for attack in feathermodules.module_list.keys():
print "%s - %s" % (attack, feathermodules.module_list[attack]['description'])
modules = ModulesCommand('modules', help='Show all available modules')
# run
class RunCommand(Command):
def run(self, line):
if len(feathermodules.samples) == 0:
print 'No loaded samples. Please use the \'import\' command.'
return False
elif feathermodules.selected_attack_name not in feathermodules.module_list.keys():
print 'Invalid module selection. Please use the \'use\' command.'
return False
if debug:
feathermodules.results = feathermodules.selected_attack['attack_function'](feathermodules.samples)
else:
try:
feathermodules.results = feathermodules.selected_attack['attack_function'](feathermodules.samples)
except:
print '[*] Module execution failed, please report this issue at https://github.com/nccgroup/featherduster/issues'
run = RunCommand('run', help='Run the currently selected module')
# options
class OptionsCommand(Command):
def run(self, line):
if feathermodules.selected_attack_name not in feathermodules.module_list.keys():
print 'Please select a valid module first.'
return False
else:
print ''
print '{0:^60}'.format('Currently selected module: ' + feathermodules.selected_attack_name)
print '-' * 60
if len(feathermodules.selected_attack['options'].items()) == 0:
print 'No options to configure.'
else:
for option, default in feathermodules.selected_attack['options'].items():
try:
print '{0:<20}{1:>40}'.format(option, feathermodules.current_options[option])
except:
print '{0:<20}{1:>40}'.format(option, default)
# set
class SetCommand(Command):
def run(self, line):
line_split = line.split()
# set option_name value
if not (len(line_split) == 2 and '=' in line_split[1]):
print 'Usage: set <option>=<value>'
return False
option = line_split[1].split('=')[0]
first_eq = line_split[1].find('=')
value = line_split[1][first_eq+1:]
feathermodules.current_options[option] = value
def args(self):
return feathermodules.selected_attack['options'].keys()
# unset
class UnsetCommand(Command):
def run(self, line):
line_split = line.split()
# unset option_name
if len(line_split) != 2:
print 'Usage: unset <option>'
return False
option = line_split[1]
try:
feathermodules.current_options[option] = feathermodules.selected_attack['options'][option]
except KeyError:
print '[*] That option doesn\'t exist, sorry!'
except AttributeError:
print '[*] Please select an attack first!'
def args(self):
return feathermodules.selected_attack['options'].keys()
# results
class ResultsCommand(Command):
def run(self, line):
if not feathermodules.results:
print 'Last module failed to produce results.'
elif feathermodules.results == True:
print 'Last module succeeded, but did not return results.'
else:
print 'Last results (long values may be truncated):'
print '-'*80
for i in range(len(feathermodules.results)):
print '{0:d}: {1:60s}'.format(i, repr(feathermodules.results[i]))
set_command = SetCommand('set', help='Set an option (i.e., "set num_answers=3"', dynamic_args=True)
unset = UnsetCommand('unset', help='Revert an option to its default value', dynamic_args=True)
options = OptionsCommand('options', help='Show the current option values', dynamic_args=True)
results = ResultsCommand('results', help='Show the results from the last module run')
# Build the console
fd_console = Console(prompt='\nFeatherDuster', prompt_delim='>')
fd_console.addChild(import_sample)
fd_console.addChild(console)
fd_console.addChild(export)
fd_console.addChild(use)
fd_console.addChild(analyze)
fd_console.addChild(autopwn)
fd_console.addChild(search)
fd_console.addChild(samples)
fd_console.addChild(modules)
fd_console.addChild(run)
fd_console.addChild(options)
fd_console.addChild(set_command)
fd_console.addChild(unset)
fd_console.addChild(results)
fd_console.addChild(advice_command)
#--------
# Main menu
#
debug = False
for filename in sys.argv[1:]:
if filename in ['-h', '--help']:
print 'Usage: python featherduster.py [ciphertext file 1] ... [ciphertext file n]'
exit()
if filename in ['-d', '--debug']:
debug = True
print 'Debug mode enabled.'
try:
sample_fh = open(filename,'r')
feathermodules.samples.append(sample_fh.read())
sample_fh.close()
except:
continue
print """Welcome to FeatherDuster!
To get started, use 'import' to load samples.
Then, use 'analyze' to analyze/decode samples and get attack recommendations.
Next, run the 'use' command to select an attack module.
Finally, use 'run' to run the attack and see its output.
For a command reference, press Enter on a blank line.
"""
fd_console.loop()
print '\nThank you for using FeatherDuster!'
def main():
# blank function so I don't have to restructure this whole file to address an annoying error
return 0