forked from wirasecure/pentest-notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
scythe.py
executable file
·1429 lines (1259 loc) · 57.3 KB
/
scythe.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
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
"""
scythe: account enumerator
Account Enumerator is designed to make it simple to perform account
enumeration as part of security testing. The framework offers the ability
to easily create new modules (XML files) and speed up the process of testing.
This tool was created with 2 main use cases in mind:
- The ability to test a range of email addresses across a range of sites (e.g.
social media, blogging platforms, etc...) to find where those targets have
active accounts. This can be useful in a social engineering test where you
have email accounts for a company and want to list where these users have
used their work email for 3rd party web based services.
- The ability to quickly create a custom testcase module and use it to enumerate
for a list of active accounts. Using either a list of know usernames, email
addresses, or a dictionary of common account names.
This program is released as is and is not designed to be used to test again sites
where you do not have permission. Any modules provided are for demonstration purposes
and may breach end user license agreements if used against a site. Your mileage may
vary... be responsible!
External module depenancies:
colorama (Windows only, optional)
"""
import os
import re
import signal
import urllib
import urllib2
import string
import textwrap
import sys
import traceback
import time
import Queue
import random
from Cookie import BaseCookie
from threading import Thread, activeCount, Lock, current_thread
from random import Random
from optparse import OptionParser, OptionGroup, SUPPRESS_HELP
from array import *
from xml.dom.minidom import parse
__author__ = 'Chris John Riley'
__license__ = 'BSD (3-Clause)'
__version__ = '0.2.81'
__codename__ = 'Lazy Lizard'
__date__ = '24 May 2013'
__maintainer__ = 'ChrisJohnRiley'
__email__ = '[email protected]'
__status__ = 'Beta'
modules = []
accounts = []
success = []
color = {}
queue = Queue.Queue()
startTime = time.clock()
sigint = False
def logo():
# because ASCII-art is the future!
logo = '''
,,
mm `7MM
MM MM
,pP"Ybd ,p6"bo `7M' `MF'mmMMmm MMpMMMb. .gP"Ya
8I `" 6M' OO VA ,V MM MM MM ,M' Yb
`YMMMa. 8M VA ,V MM MM MM 8M""""""
L. I8 YM. , VVV MM MM MM YM. ,
M9mmmP' YMbmd' ,V `Mbmo.JMML JMML.`Mbmmd'
,V
OOb" ::: account harvester :::'''
# add version, codename and maintainer to logo
print logo
print string.rjust('ver ' + __version__ + ' (' + __codename__ + ')', 74)
print string.rjust(__maintainer__, 73)
def extract_module_data(file, module_dom):
# extract module information from the provided dom
for each in module_dom:
try:
xmlData = {}
# try/except blocks to handle badly formed XML modules
try:
xmlData['name'] = each.getElementsByTagName('name')[0].firstChild.nodeValue
except (IndexError, AttributeError):
xmlData['name'] = 'unspecified'
# set URL - prepend http:// if not present in string
if not each.getElementsByTagName('url')[0].firstChild.nodeValue.startswith('http'):
xmlData['url'] = 'http://' + each.getElementsByTagName('url')[0].firstChild.nodeValue
else:
xmlData['url'] = each.getElementsByTagName('url')[0].firstChild.nodeValue
# set Method
try:
xmlData['method'] = each.getElementsByTagName('method')[0].firstChild.nodeValue
except (IndexError, AttributeError):
# default to GET if not specified
xmlData['method'] = 'GET'
# set POST Parameters if set in the module XML
try:
if each.getElementsByTagName('postParameters')[0].firstChild.nodeValue.lower() == 'false':
# handle instances where people enter False insterad of leaving this field blank
xmlData['postParameters'] = ''
else:
xmlData['postParameters'] = \
each.getElementsByTagName('postParameters')[0].firstChild.nodeValue
except (IndexError, AttributeError):
xmlData['postParameters'] = ''
# set headers if set in the module XML
try:
if each.getElementsByTagName('headers')[0].firstChild.nodeValue.lower() == 'false':
# handle instances where people enter False insterad of leaving this field blank
xmlData['headers'] = ''
else:
xmlData['headers'] = \
each.getElementsByTagName('headers')[0].firstChild.nodeValue.split(",")
except (IndexError, AttributeError):
xmlData['headers'] = ''
# set request cookie if set in the module XML
try:
if each.getElementsByTagName('requestCookie')[0].firstChild.nodeValue.lower() == 'true':
xmlData['requestCookie'] = True
else:
xmlData['requestCookie'] = False
except (IndexError, AttributeError):
xmlData['requestCookie'] = False
# set csrf mode if set in the module XML
# Extract csrf_url and csrf_regex if present
# if not default to False
try:
if each.getElementsByTagName('requestCSRF')[0].firstChild.nodeValue.lower() == 'false':
xmlData['requestCSRF'] = False
# set csrf_url and csrf_regex to False by default
xmlData['csrf_url'] = False
xmlData['csrf_regex'] = False
else:
xmlData['requestCSRF'] = True
if each.getElementsByTagName('csrf_url')[0].firstChild:
xmlData['csrf_url'] = \
each.getElementsByTagName('csrf_url')[0].firstChild.nodeValue
else:
# if no specific csrf_url is set, default to xmlData['url']'
xmlData['csrf_url'] = xmlData['url']
if each.getElementsByTagName('csrf_regex')[0].firstChild:
xmlData['csrf_regex'] = \
each.getElementsByTagName('csrf_regex')[0].firstChild.nodeValue
else:
xmlData['csrf_regex'] = 'unspecified'
except (IndexError, AttributeError):
# if requestCSRF not present or noneType
xmlData['requestCSRF'] = False
xmlData['csrf_url'] = False
xmlData['csrf_regex'] = False
# set success match if specified in the module XML
try:
xmlData['successmatch'] = \
each.getElementsByTagName('successmatch')[0].firstChild.nodeValue
except (IndexError, AttributeError):
xmlData['successmatch'] = ''
# set negative match if specified in the module XML
try:
# handle instances where people enter False insterad of leaving this field blank
if each.getElementsByTagName('negativematch')[0].firstChild.nodeValue.lower() == 'false':
xmlData['negativematch'] = ''
else:
xmlData['negativematch'] = \
each.getElementsByTagName('negativematch')[0].firstChild.nodeValue
except (IndexError, AttributeError):
xmlData['negativematch'] = ''
# set error match if specified in the module XML
try:
# handle instances where people enter False insterad of leaving this field blank
if each.getElementsByTagName('errormatch')[0].firstChild.nodeValue.lower() == 'false':
xmlData['errormatch'] = ''
else:
xmlData['errormatch'] = \
each.getElementsByTagName('errormatch')[0].firstChild.nodeValue
except (IndexError, AttributeError):
xmlData['errormatch'] = ''
# set message if specified in the module XML
try:
# handle instances where people enter False insterad of leaving this field blank
if each.getElementsByTagName('message')[0].firstChild.nodeValue.lower() == 'false':
xmlData['message'] = ''
else:
xmlData['message'] = \
each.getElementsByTagName('message')[0].firstChild.nodeValue
except (IndexError, AttributeError):
xmlData['message'] = ''
# set module date
try:
xmlData['date'] = each.getElementsByTagName('date')[0].firstChild.nodeValue
except (IndexError, AttributeError):
xmlData['date'] = 'unspecified'
# set module version if specified in the module XML
try:
xmlData['version'] = each.getElementsByTagName('version')[0].firstChild.nodeValue
except (IndexError, AttributeError):
xmlData['version'] = 'unspecified'
# set module author
try:
xmlData['author'] = each.getElementsByTagName('author')[0].firstChild.nodeValue
except (IndexError, AttributeError):
xmlData['author'] = 'unlisted'
# set category
try:
xmlData['category'] = each.getElementsByTagName('category')[0].firstChild.nodeValue
except (IndexError, AttributeError):
xmlData['category'] = 'unspecified'
# filter modules based on selected categories
if xmlData['category'].lower() in (cat.lower() for cat in opts.category) or \
"all" in (cat.lower() for cat in opts.category) or \
(opts.single.lower() and opts.single.lower() in xmlData['name'].lower()) or \
(file.lower() in opts.single.lower()):
if xmlData['category'].lower() == "example" and \
("example" not in (cat.lower() for cat in opts.category) \
and not opts.single):
# skip example module when running with all or default settings
if opts.verbose:
print "\t[" + color['red'] + "!" + color['end'] \
+ "] Skipping example module : %s" % xmlData['name']
else:
print "\t[" + color['yellow'] + "+" + color['end'] \
+"] Extracted module information from %s" \
% xmlData['name']
modules.append(xmlData)
# print module message if present
if xmlData['message']:
print textwrap.fill(("\t[" + color['yellow'] + "!" + color['end'] \
+"] "+ color['red'] + "Note" + color['end'] +" [%s]:" \
% xmlData['name']),
initial_indent='', subsequent_indent='\t -> ', width=100)
print textwrap.fill(("\t -> %s" % xmlData['message']),
initial_indent='', subsequent_indent='\t -> ', width=80)
else:
if opts.debug and not opts.category == "single":
print "\t[" + color['red'] + "!" + color['end'] \
+ "] Skipping module %s. Not in category (%s)" \
% (xmlData['name'], opts.category)
except Exception, ex:
print "\t[" + color['red'] + "!" + color['end'] \
+ "] Failed to extracted module information\n\t\tError: %s" % ex
if opts.debug:
print "\n\t[" + color['red'] + "!" + color['end'] + "] ",
traceback.print_exc()
continue
def output_modules():
# print information about the loaded module(s)
print "\n ------------------------------------------------------------------------------"
print string.center(color['yellow'] + ">>>>>" + color['end'] + " Module Information " + \
color['yellow'] + "<<<<<" + color['end'], 100)
print " ------------------------------------------------------------------------------"
if opts.verbose and not opts.listmodules:
for mod in modules:
print textwrap.fill((" NAME: %s" % mod['name']),
initial_indent='', subsequent_indent=' -> ', width=80)
print textwrap.fill((" URL: %s" % mod['url']),
initial_indent='', subsequent_indent=' -> ', width=80)
print textwrap.fill((" METHOD: %s" % mod['method']),
initial_indent='', subsequent_indent=' -> ', width=80)
print textwrap.fill((" HEADERS: %s" % mod['headers']),
initial_indent='', subsequent_indent=' -> ', width=80)
print textwrap.fill((" POST PARAMETERS: %s" % mod['postParameters']),
initial_indent='', subsequent_indent=' -> ', width=80)
print textwrap.fill((" REQUEST COOKIE: %s" % mod['requestCookie']),
initial_indent='', subsequent_indent=' -> ', width=80)
print textwrap.fill((" REQUEST CSRF TOKEN: %s" % mod['requestCSRF']),
initial_indent='', subsequent_indent=' -> ', width=80)
print textwrap.fill((" SUCCESS MATCH: %s" % mod['successmatch']),
initial_indent='', subsequent_indent=' -> ', width=80)
print textwrap.fill((" NEGATIVE MATCH: %s" % mod['negativematch']),
initial_indent='', subsequent_indent=' -> ', width=80)
print textwrap.fill((" ERROR MATCH: %s" % mod['errormatch']),
initial_indent='', subsequent_indent=' -> ', width=80)
print textwrap.fill((" MODULE NOTE: %s" % mod['message']),
initial_indent='', subsequent_indent=' -> ', width=80)
print textwrap.fill((" DATE: %s" % mod['date']),
initial_indent='', subsequent_indent=' -> ', width=80)
print textwrap.fill((" VERSION: %s" % mod['version']),
initial_indent='', subsequent_indent=' -> ', width=80)
print textwrap.fill((" AUTHOR: %s" % mod['author']),
initial_indent='', subsequent_indent=' -> ', width=80)
print textwrap.fill((" CATEGORY: %s" % mod['category']),
initial_indent='', subsequent_indent=' -> ', width=80)
print " ------------------------------------------------------------------------------"
else:
print " ", "| Name |".ljust(35), "| Category |".ljust(26), "| Version |".ljust(8)
print " ------------------------------------------------------------------------------"
for mod in modules:
print " " + mod['name'].ljust(37) + mod['category'].ljust(30) + mod['version'].ljust(10)
print " ------------------------------------------------------------------------------\n"
# exit after providing module list
sys.exit(0)
def output_accounts():
# print information about the accounts loaded from accountfile
print "\n ------------------------------------------------------------------------------"
print string.center(color['yellow'] + ">>>>>" + color['end'] + " Accounts Loaded " + \
color['yellow'] + "<<<<<" + color['end'], 100)
print " ------------------------------------------------------------------------------"
for a in accounts:
print textwrap.fill((" Account name: %s" % a),
initial_indent='', subsequent_indent=' -> ', width=80)
print " ------------------------------------------------------------------------------\n"
def output_success():
# print information about success matches
if opts.summary or (opts.verbose and opts.summary):
print "\n ------------------------------------------------------------------------------"
print string.center(color['yellow'] + ">>>>>" + color['end'] + " Successful Matches " + \
color['yellow'] + "<<<<<" + color['end'], 100)
print " ------------------------------------------------------------------------------"
s_success = sorted(success, key=lambda k: k['name']) # group by site name
# print normal summary table on request (--summary)
if not opts.verbose and opts.summary:
print "\n ------------------------------------------------------------------------------"
print " ", "| Module |".ljust(35), " | Account |".ljust(28)
print " ------------------------------------------------------------------------------"
for s in s_success:
print " " + s['name'].ljust(37) + s['account'].ljust(30)
print " ------------------------------------------------------------------------------\n"
# print verbose summary on request (-v --summary)
elif opts.verbose and opts.summary:
for s in s_success:
print textwrap.fill((" NAME: \t\t\t%s" % s['name']),
initial_indent='', subsequent_indent='\t -> ', width=80)
print textwrap.fill((" ACCOUNT: \t\t%s" % s['account']),
initial_indent='', subsequent_indent='\t -> ', width=80)
print textwrap.fill((" URL: \t\t\t%s" % s['url']),
initial_indent='', subsequent_indent='\t -> ', width=80)
print textwrap.fill((" METHOD: \t\t%s" % s['method']),
initial_indent='', subsequent_indent='\t -> ', width=80)
print textwrap.fill((" POST PARAMETERS: \t%s" % s['postParameters']),
initial_indent='', subsequent_indent='\t -> ', width=80)
print " ------------------------------------------------------------------------------"
else:
print " ------------------------------------------------------------------------------\n"
def load_modules():
# load the modules from moduledir
# only XML files are permitted
if not "all" in (cat.lower() for cat in opts.category):
# using options from command line
if opts.verbose:
print " [" + color['yellow'] + "-" + color['end'] \
+ "] using command line supplied category : %s" \
% ", ".join(opts.category)
for (path, dirs, files) in os.walk(opts.moduledir):
for d in dirs:
if d.startswith("."): # ignore hidden . dirctories
dirs.remove(d)
print " [" + color['yellow'] + "-" + color['end'] \
+"] Starting to load modules from %s" % path
for file in files:
if not path.endswith('/'):
path = path + '/'
# read in modules
if file.endswith('.xml') and not file.startswith('.'):
if opts.verbose:
print "\t[ ] Checking module : %s" % file
try:
module_dom = parse(path + file)
module_dom = module_dom.getElementsByTagName('site')
extract_module_data(file, module_dom)
except:
print "\t[" + color['red'] + "!" + color['end'] \
+"] Error parsing %s module, check XML" % file
elif opts.debug:
print "\t[" + color['red'] + "!" + color['end'] \
+ "] Skipping non-XML file : %s" % file
if opts.verbose or opts.listmodules:
output_modules() #debug and module output
def load_accounts():
# if account is passed in we use that, otherwise
# load accounts from accountfile
# one account per line
if opts.account:
# load account from command line
if opts.verbose:
print " [" + color['yellow'] + "-" + color['end'] \
+ "] using command line supplied user(s) : %s" \
% ", ".join(opts.account)
for a in opts.account:
# add all command line accounts to array for testcases
if a: # ignore empty fields
accounts.append(a)
else:
# load accounts from file if it exists
if not os.path.exists(opts.accountfile):
print "\n [" + color['red'] + "!" + color['end'] \
+ "] The supplied file (%s) does not exist!" \
% opts.accountfile
sys.exit(0)
account_file = open(opts.accountfile, 'r')
account_read = account_file.readlines()
account_read = [item.rstrip() for item in account_read]
for a in account_read:
if not a.startswith("#"): # ignore comment lines in accountfile
accounts.append(a)
if opts.verbose:
output_accounts() # debug output
def create_testcases():
# create a list of testcases from accounts and modules
#
# replace functions are in place to replace <ACCOUNT>
# with the account names presented
# the script will also replace any instances of <RANDOM>
# with a random string (8) to avoid detection
testcases = []
tempcase = {}
for a in accounts:
for m in modules:
rand = ''.join( Random().sample(string.letters+string.digits, 8) ) # 8 random chars
tempcase['url'] = m['url'].replace("<ACCOUNT>", a).replace("<RANDOM>", rand)
tempcase['account'] = a
tempcase['name'] = m['name']
tempcase['method'] = m['method']
tempcase['postParameters'] = m['postParameters'].replace("<ACCOUNT>", a).replace("<RANDOM>", rand)
tempcase['headers'] = m['headers']
tempcase['requestCookie'] = m['requestCookie']
tempcase['requestCSRF'] = m['requestCSRF']
tempcase['csrf_url'] = m['csrf_url']
tempcase['csrf_regex'] = m['csrf_regex']
tempcase['successmatch'] = m['successmatch']
tempcase['negativematch'] = m['negativematch']
tempcase['errormatch'] = m['errormatch']
testcases.append(tempcase)
tempcase = {}
if testcases:
return testcases
else:
print " [" + color['red'] + "!" + color['end'] + \
"] No testcases created, check your accounts and module settings"
print
sys.exit(0)
def request_handler(testcases):
# handle requests present in testcases
print "\n ------------------------------------------------------------------------------"
print string.center(color['yellow'] + ">>>>>" + color['end'] + " Testcases " + \
color['yellow'] + "<<<<<" + color['end'], 100)
print " ------------------------------------------------------------------------------"
print " [" + color['yellow'] + "-" + color['end'] \
+"] Starting testcases (%d in total)" % len(testcases)
if opts.wait:
print " [" + color['yellow'] + "-" + color['end'] \
+"] Throttling in place (%.2f seconds)\n" % opts.wait
elif opts.threads:
print " [" + color['yellow'] + "-" + color['end'] \
+"] Threading in use (%d threads max)\n" % opts.threads
else:
print
progress = 0 # initiate progress count
if opts.threads > 1:
threads = []
for test in testcases:
# add testcases to queue
queue.put(test)
# create progress update lock
progress_lock = Lock()
while not queue.empty() and not sigint:
# only allow a limited number of threads
if opts.threads >= activeCount() and not sigint:
# get next test from queue
test = queue.get()
try:
# setup thread to perform test
t = Thread(target=make_request, args=(test,))
t.daemon=True
threads.append(t)
t.start()
finally:
# iterate progress value for the progress bar
progress = len(testcases) - queue.qsize()
# call progressbar
progress_lock.acquire()
try:
progressbar(progress, len(testcases))
finally:
progress_lock.release()
# mark task as done
queue.task_done()
# wait for queue and threads to end before continuing
while activeCount() > 1:
# keep main program active to catch keyboard interrupts
time.sleep(0.1)
for thread in threads:
thread.join()
# no more active threads. resolve queue
queue.join()
else:
for test in testcases:
# make request without using threading
make_request(test)
# iterate progress value for the progress bar
progress = progress +1
# call progressbar
progressbar(progress, len(testcases))
if opts.wait: # wait X seconds as per wait setting
time.sleep(opts.wait)
return
def progressbar(progress, total):
# progressbar
if total > 50: # only show progress on tests of > 50
if not progress == 0:
# set percentage
progress_percentage = int(100 / (float(total) / float(progress)))
# display progress at set points
total = float(total)
# calculate progress for 25, 50, 75, and 99%
vals = [int(total/100*25), int(total/100*50), int(total/100*75), int(total-1)]
if progress in vals:
print " [" + color['yellow'] + "-" + color['end'] +"] [%s] %s%% complete\n" \
% ((color['yellow'] + ("#"*(progress_percentage / 10)) + \
color['end']).ljust(10, "."),progress_percentage),
def make_request(test, retry=0, wait_time=False):
# make request and add output to array
# set threadname
if not current_thread().name == 'MainThread':
threadname = "[" + current_thread().name +"] >"
else:
# return blank string when not using threading
threadname = '>'
# GET method worker
if test['method'] == 'GET':
test, resp, r_info, req = get_request(test)
# success match
if resp and test['successmatch']:
matched = success_check(resp, test['successmatch'])
if matched:
print " [" + color['green'] + "X" + color['end'] + "] Account %s exists on %s" \
% (test['account'], test['name'])
success.append(test)
if opts.debug:
print # spacing forverbose output
if opts.outputfile:
# log to outputfile
opts.outputfile.write("Account " + test['account'] + " exists on " \
+ test['name'] +"\n")
# error match
if resp and test['errormatch']:
error = error_check(resp, test['errormatch'])
if error and retry >= opts.retries:
print " [" + color['red'] + "!" + color['end'] + \
"] %s Retries exceeded when testing account %s on %s" \
% (threadname, test['account'], test['name'])
elif error:
print " [" + color['yellow'] + "!" + color['end'] + \
"] %s Error detected when testing account %s on %s" \
% (threadname, test['account'], test['name'])
# wait X seconds and retry
if wait_time:
# double existing wait_time
wait_time = wait_time * 2
else:
# set starting point for wait_time
wait_time = opts.retrytime
if opts.verbose:
print " [ ] %s Waiting %d seconds before retry" \
% (threadname, wait_time)
time.sleep(wait_time)
# increment retry counter
retry = retry + 1
if opts.verbose:
print " [ ] %s Attempting retry (%d of %d)" \
% (threadname, retry, opts.retries)
make_request(test, retry, wait_time)
return
# negative match
if resp and test['negativematch']:
matched = negative_check(resp, test['negativematch'])
if matched and opts.verbose:
print " [" + color['red'] + "X" + color['end'] + "] Negative matched %s on %s" \
% (test['account'], test['name'])
# advance debug output
if resp and opts.debugoutput:
debug_save_response(test, resp, r_info, req)
return
# POST method worker
elif test['method'] == 'POST':
test, resp, r_info, req = post_request(test)
# success match
if resp and test['successmatch']:
matched = success_check(resp, test['successmatch'])
if matched:
print " [" + color['green'] + "X" + color['end'] + "] Account %s exists on %s" \
% (test['account'], test['name'])
success.append(test)
if opts.debug:
print # spacing forverbose output
if opts.outputfile:
# log to outputfile
opts.outputfile.write("Account " + test['account'] + " exists on " \
+ test['name'] +"\n")
# error match
if resp and test['errormatch']:
error = error_check(resp, test['errormatch'])
if error and retry >= opts.retries:
print " [" + color['red'] + "!" + color['end'] + \
"] %s Retries exceeded when testing account %s on %s" \
% (threadname, test['account'], test['name'])
elif error:
print " [" + color['yellow'] + "!" + color['end'] + \
"] %s Error detected when testing account %s on %s" \
% (threadname, test['account'], test['name'])
# wait X seconds and retry
if wait_time:
# double existing wait_time
wait_time = wait_time * 2
else:
# set starting point for wait_time
wait_time = opts.retrytime
if opts.verbose:
print " [ ] %s Waiting %d seconds before retry" \
% (threadname, wait_time)
time.sleep(wait_time)
# increment retry counter
retry = retry + 1
if opts.verbose:
print " [ ] %s Attempting retry (%d of %d)" \
% (threadname, retry, opts.retries)
make_request(test, retry, wait_time)
# negative match
if resp and test['negativematch']:
matched = negative_check(resp, test['negativematch'])
if matched and opts.verbose:
print " [" + color['red'] + "X" + color['end'] + "] Negative matched %s on %s" \
% (test['account'], test['name'])
if resp and opts.debugoutput:
debug_save_response(test, resp, r_info, req)
return
else:
print " [" + color['red'] + "!" + color['end'] + "] Unknown Method %s : %s" \
% test['method'], test['url']
return
def get_request(test):
# perform GET request
urllib.urlcleanup() # clear cache
try:
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
req_headers = { 'User-Agent' : user_agent }
for each in test['headers']:
key, val = each.split(":", 1)
key = key.lstrip()
val = val.lstrip()
req_headers[key] = val
if test['requestCookie'] or test['requestCSRF']:
# request cookie and csrf token if set in module XML
cookie_val, csrf_val = request_value(test)
if cookie_val:
req_headers['cookie'] = cookie_val
if csrf_val:
# replace <CSRFTOKEN> with the collected token
test['url'] = test['url'].replace("<CSRFTOKEN>", csrf_val)
test['postParameters'] = test['postParameters'].replace("<CSRFTOKEN>", csrf_val)
test['headers'] = [h.replace('<CSRFTOKEN>', csrf_val) for h in test['headers']]
if opts.debug:
# print debug output
print textwrap.fill((" [ ] URL (GET): %s" % test['url']),
initial_indent='', subsequent_indent=' -> ', width=80)
print
# assign NullHTTPErrorProcessor as default opener
opener = urllib2.build_opener(NullHTTPErrorProcessor())
urllib2.install_opener(opener)
req = urllib2.Request(test['url'], headers=req_headers)
f = urllib2.urlopen(req)
r_body = f.read()
r_info = f.info()
f.close()
# handle instances where the response body is 0 bytes in length
if not r_body:
print " [" + color['red'] + "!" + color['end'] + "] Zero byte response received from %s" \
% test['name']
r_body = "<Scythe Message: Empty response from server>"
# returned updated test and response data
return test, r_body, r_info, req
except Exception:
print textwrap.fill((" [" + color['red'] + "!" + color['end'] + "] Error contacting %s" \
% test['url']), initial_indent='', subsequent_indent='\t', width=80)
if opts.debug:
for ex in traceback.format_exc().splitlines():
print textwrap.fill((" %s" \
% str(ex)), initial_indent='', subsequent_indent='\t', width=80)
print
return test, False, False, req
def post_request(test):
# perform POST request
urllib.urlcleanup() # clear cache
try:
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
req_headers = { 'User-Agent' : user_agent }
if test['requestCookie'] or test['requestCSRF']:
# request cookie and csrf token if set in module XML
cookie_val, csrf_val = request_value(test)
if cookie_val:
req_headers['cookie'] = cookie_val
if csrf_val:
# replace <CSRFTOKEN> with the collected token
test['url'] = test['url'].replace("<CSRFTOKEN>", csrf_val)
test['postParameters'] = test['postParameters'].replace("<CSRFTOKEN>", csrf_val)
test['headers'] = [h.replace('<CSRFTOKEN>', csrf_val) for h in test['headers']]
if test['headers']:
for each in test['headers']:
key, val = each.split(":", 1)
key = key.lstrip()
val = val.lstrip()
req_headers[key] = val
if opts.debug:
# print debug output
print textwrap.fill((" [ ] URL (POST): %s" % test['url']),
initial_indent='', subsequent_indent=' -> ', width=80)
print textwrap.fill((" [ ] POST PARAMETERS: %s" % test['postParameters']),
initial_indent='', subsequent_indent=' -> ', width=80)
print
# assign NullHTTPErrorProcessor as default opener
opener = urllib2.build_opener(NullHTTPErrorProcessor())
urllib2.install_opener(opener)
req = urllib2.Request(test['url'], test['postParameters'], req_headers)
f = urllib2.urlopen(req)
r_body = f.read()
r_info = f.info()
f.close()
# handle instances where the response body is 0 bytes in length
if not r_body:
print " [" + color['red'] + "!" + color['end'] + "] Zero byte response received from %s" \
% test['name']
r_body = "<Scythe Message: Empty response from server>"
# returned updated test and response data
return test, r_body, r_info, req
except Exception:
print textwrap.fill((" [" + color['red'] + "!" + color['end'] + "] Error contacting %s" \
% test['url']), initial_indent='', subsequent_indent='\t', width=80)
if opts.debug:
for ex in traceback.format_exc().splitlines():
print textwrap.fill((" %s" \
% str(ex)), initial_indent='', subsequent_indent='\t', width=80)
print
return test, False, False, req
def request_value(test):
# request a cookie or CSRF token from the target site for use during the logon attempt
urllib.urlcleanup() # clear cache
# assign NullHTTPErrorProcessor as default opener
opener = urllib2.build_opener(NullHTTPErrorProcessor())
urllib2.install_opener(opener)
# capture cookie first for use with the CSRF token request
# capture Set-Cookie
if test['requestCookie']:
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
req_headers = { 'User-Agent' : user_agent }
if test['csrf_url']:
# if csrf_url is set, use the same page to collect cookies
url = test['csrf_url']
else:
url = test['url'].split("?", 1)[0] # strip parameters from url where present
req_val = urllib2.Request(url, headers=req_headers)
response = urllib2.urlopen(req_val)
resp_body = response.read()
if response.info().getheader('Set-Cookie'):
set_cookie = response.info().getheader('Set-Cookie') # grab Set-cookie
# work Set-cookie into valid cookies to set
bcookie = BaseCookie(set_cookie)
# strip off unneeded attributes (e.g. expires, path, HTTPOnly etc...
cookie_val = bcookie.output(attrs=[], header="").lstrip()
else:
cookie_val = False
print " [" + color['red'] + "!" + color['end'] \
+ "] Set-Cookie Error: No valid Set-Cookie response received"
else:
cookie_val = False
# capture CSRF token (using regex from module XML)
if test['requestCSRF']:
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
req_headers = { 'User-Agent' : user_agent }
if cookie_val:
# if a cookie value exists, use the existing response
if opts.debug:
print " [" + color['yellow'] + "-" + color['end'] \
+ "] Using existing response to gather CSRF token"
else:
# get new response to work with
url = test['csrf_url']
req_val = urllib2.Request(url, headers=req_headers)
response = urllib2.urlopen(req_val)
try:
csrf_regex = re.compile(test['csrf_regex'])
match = re.search(csrf_regex, resp_body)
if match:
csrf_val = match.group(1)
else:
csrf_val = False
print " [" + color['red'] + "!" + color['end'] \
+ "] Invalid CSRF regex. Please check parameters"
except:
print " [" + color['red'] + "!" + color['end'] \
+ "] Invalid CSRF regex. Please check parameters"
if opts.debug:
print "\n\t[" + color['red'] + "!" + color['end'] + "] ",
traceback.print_exc()
else:
csrf_val = False
return cookie_val, csrf_val
def error_check(data, errormatch):
# checks response data against errormatch regex
try:
regex = re.compile(errormatch)
if regex.search(data):
return True
else:
return False
except:
print " [" + color['red'] + "!" + color['end'] \
+ "] Invalid in error check. Please check parameter"
if opts.debug:
print "\n\t[" + color['red'] + "!" + color['end'] + "] ",
traceback.print_exc()
def success_check(data, successmatch):
# checks response data against successmatch regex
try:
regex = re.compile(successmatch)
if regex.search(data):
return True
else:
return False
except:
print " [" + color['red'] + "!" + color['end'] \
+ "] Invalid in success check. Please check parameter"
if opts.debug:
print "\n\t[" + color['red'] + "!" + color['end'] + "] ",
traceback.print_exc()
def negative_check(data, negativematch):
# checks response data against negativematch regex
try:
regex = re.compile(negativematch)
if regex.search(data):
return True
else:
return False
except:
print " [" + color['red'] + "!" + color['end'] \
+ "] Invalid in negative check. Please check parameter"
if opts.debug:
print "\n\t[" + color['red'] + "!" + color['end'] + "] ",
traceback.print_exc()
def debug_save_response(test, resp, r_info, req):
# save advanced deug responses to ./debug/
# get time to attach to filename
timenow = int(time.time())
# set testname, remove spaces
testname = re.sub(r'[^\w]', '_', test['name']) + "_"
# check debug directory exists, if not create it
if not os.path.exists('./debug/'):
os.makedirs('./debug/')
# filename for html and headers, strip unusable chars from filenames
htmlfile = testname + str(timenow)
htmlfile = './debug/' + re.sub(r'[^\w]', '_', htmlfile) + '.html' # strip unsuitable chars
hdrfile = testname + str(timenow)
hdrfile = './debug/' + re.sub(r'[^\w]', '_', hdrfile) + '.headers' # strip unsuitable chars
# format headers
header_output = []
header_output.append('---------------------\nrequest headers\n---------------------\n')
for key in req.headers:
header_output.append(key + ': ' + req.headers[key])
header_output.append('\n---------------------\nresponse headers\n---------------------\n')
for each in r_info.headers:
header_output.append(each.rstrip())
header_output.append('\n')
# check if file exists, if so add random number to filename
if os.path.isfile(htmlfile):
rand_addition = str(random.randint(0000, 9999)).zfill(4)
htmlfile = htmlfile[:-5] + '_' + rand_addition + '.html'
hdrfile = hdrfile[:-8] + '_' + rand_addition + '.headers'
# open file for writing
f_html = open(htmlfile, 'w')
f_headers = open(hdrfile, 'w')
# write response and close
f_html.write(resp)
f_html.close()
# write headers and close
f_headers.write("\n".join(header_output))