-
Notifications
You must be signed in to change notification settings - Fork 115
/
AuthMatrix.py
3254 lines (2688 loc) · 133 KB
/
AuthMatrix.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
# Copyright (c) 2016 Mick Ayzenberg - Security Innovation
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from burp import IBurpExtender
from burp import ITab
from burp import IMessageEditorController
from burp import IContextMenuFactory
from burp import IHttpRequestResponse
from java.awt import Component;
from java.awt import GridBagLayout;
from java.awt import GridBagConstraints;
from java.awt import Dimension;
from java.util import ArrayList;
from java.lang import Boolean;
from javax.swing import JScrollPane;
from javax.swing import JSplitPane;
from javax.swing import JTabbedPane;
from javax.swing import JPanel;
from javax.swing import JButton;
from javax.swing import JTable;
from javax.swing import JOptionPane;
from javax.swing import JMenuItem;
from javax.swing import JCheckBox;
from javax.swing import JComboBox;
from javax.swing import DefaultCellEditor;
from javax.swing import JLabel;
from javax.swing import JFileChooser;
from javax.swing import JPopupMenu;
from javax.swing import JTextField;
from javax.swing import TransferHandler;
from javax.swing import DropMode;
from javax.swing import JSeparator;
from javax.swing import SwingConstants;
from javax.swing import JList
from javax.swing import AbstractCellEditor
from javax.swing import Timer
from java.awt.datatransfer import StringSelection;
from java.awt.datatransfer import DataFlavor;
from javax.swing.table import AbstractTableModel;
from javax.swing.table import TableCellRenderer;
from javax.swing.table import JTableHeader;
from javax.swing.table import TableCellEditor
from java.awt import Color;
from java.awt import Font;
from java.awt.event import MouseAdapter;
from java.awt.event import ActionListener;
from java.awt.event import ItemListener;
from java.awt.event import ItemEvent;
from javax.swing.event import DocumentListener;
from javax.swing.event import ChangeListener;
import java.lang;
from org.python.core.util import StringUtil
from threading import Lock
from threading import Thread
import traceback
import re
import urllib
import hashlib
import json
import base64
import random
import string
AUTHMATRIX_VERSION = "0.8.2"
class BurpExtender(IBurpExtender, ITab, IMessageEditorController, IContextMenuFactory):
#
# implement IBurpExtender
#
def registerExtenderCallbacks(self, callbacks):
# keep a reference to our Burp callbacks object
self._callbacks = callbacks
# obtain an Burp extension helpers object
self._helpers = callbacks.getHelpers()
# set our extension name
callbacks.setExtensionName("AuthMatrix - v"+AUTHMATRIX_VERSION)
# DB that holds everything users, roles, and messages
self._db = MatrixDB()
# For saving/loading config
self._fc = JFileChooser()
# Used by inner classes
selfExtender = self
self._selectedColumn = -1
self._selectedRow = -1
# Table of Chain entries (NOTE: must be instantiated before userTable since its referenced)
self._chainTable = ChainTable(model = ChainTableModel(self))
chainScrollPane = JScrollPane(self._chainTable)
self._chainTable.redrawTable()
# Table of User entries
self._userTable = UserTable(model = UserTableModel(self))
roleScrollPane = JScrollPane(self._userTable)
self._userTable.redrawTable()
# Table of Request (AKA Message) entries
self._messageTable = MessageTable(model = MessageTableModel(self))
messageScrollPane = JScrollPane(self._messageTable)
self._messageTable.redrawTable()
# Set Messages to reorderable
self._messageTable.setDragEnabled(True)
self._messageTable.setDropMode(DropMode.INSERT_ROWS)
self._messageTable.setTransferHandler(RowTransferHandler(self._messageTable))
# Set Users to reorderable
self._userTable.setDragEnabled(True)
self._userTable.setDropMode(DropMode.INSERT_ROWS)
self._userTable.setTransferHandler(RowTransferHandler(self._userTable))
# Semi-Generic Popup stuff
def addPopup(component, popup):
class genericMouseListener(MouseAdapter):
def mousePressed(self, e):
if e.isPopupTrigger():
self.showMenu(e)
def mouseReleased(self, e):
if e.isPopupTrigger():
self.showMenu(e)
def showMenu(self, e):
# NOTE: testing if .locked is ok here since its a manual operation
if selfExtender._db.lock.locked():
return
if type(component) is JTableHeader:
table = component.getTable()
column = component.columnAtPoint(e.getPoint())
if (type(table) is MessageTable
and column >= selfExtender._db.STATIC_MESSAGE_TABLE_COLUMN_COUNT
or type(table) is UserTable
and column >= selfExtender._db.STATIC_USER_TABLE_COLUMN_COUNT):
selfExtender._selectedColumn = column
else:
return
else:
selfExtender._selectedRow = component.rowAtPoint(e.getPoint())
popup.show(e.getComponent(), e.getX(), e.getY())
component.addMouseListener(genericMouseListener())
class actionRunMessage(ActionListener):
def actionPerformed(self,e):
if selfExtender._selectedRow >= 0:
if selfExtender._selectedRow not in selfExtender._messageTable.getSelectedRows():
indexes = [selfExtender._db.getMessageByRow(selfExtender._selectedRow)._index]
else:
indexes = [selfExtender._db.getMessageByRow(rowNum)._index for rowNum in selfExtender._messageTable.getSelectedRows()]
t = Thread(target=selfExtender.runMessagesThread, args = [indexes])
t.start()
selfExtender._selectedColumn = -1
# Redrawing the table happens in colorcode within the thread
class actionToggleEnableUser(ActionListener):
def actionPerformed(self,e):
if selfExtender._selectedRow >= 0:
if selfExtender._selectedRow not in selfExtender._userTable.getSelectedRows():
usersArray = [selfExtender._db.getUserByRow(selfExtender._selectedRow)]
else:
usersArray = [selfExtender._db.getUserByRow(rowNum) for rowNum in selfExtender._userTable.getSelectedRows()]
for userEntry in usersArray:
userEntry.toggleEnabled()
selfExtender._selectedColumn = -1
selfExtender._userTable.redrawTable()
class actionToggleEnableMessage(ActionListener):
def actionPerformed(self,e):
if selfExtender._selectedRow >= 0:
if selfExtender._selectedRow not in selfExtender._messageTable.getSelectedRows():
messagesArray = [selfExtender._db.getMessageByRow(selfExtender._selectedRow)]
else:
messagesArray = [selfExtender._db.getMessageByRow(rowNum) for rowNum in selfExtender._messageTable.getSelectedRows()]
for messageEntry in messagesArray:
messageEntry.toggleEnabled()
selfExtender._selectedColumn = -1
selfExtender._messageTable.redrawTable()
class actionToggleEnableChain(ActionListener):
def actionPerformed(self,e):
if selfExtender._selectedRow >= 0:
if selfExtender._selectedRow not in selfExtender._chainTable.getSelectedRows():
chainArray = [selfExtender._db.getChainByRow(selfExtender._selectedRow)]
else:
chainArray = [selfExtender._db.getChainByRow(rowNum) for rowNum in selfExtender._chainTable.getSelectedRows()]
for chainEntry in chainArray:
chainEntry.toggleEnabled()
selfExtender._selectedColumn = -1
selfExtender._chainTable.redrawTable()
class actionRemoveMessage(ActionListener):
def actionPerformed(self,e):
if selfExtender._selectedRow >= 0:
if selfExtender._selectedRow not in selfExtender._messageTable.getSelectedRows():
indexes = [selfExtender._db.getMessageByRow(selfExtender._selectedRow)._index]
else:
indexes = [selfExtender._db.getMessageByRow(rowNum)._index for rowNum in selfExtender._messageTable.getSelectedRows()]
for i in indexes:
selfExtender._db.deleteMessage(i)
selfExtender._selectedColumn = -1
selfExtender._messageTable.redrawTable()
selfExtender._chainTable.redrawTable()
class actionRemoveUser(ActionListener):
def actionPerformed(self,e):
if selfExtender._selectedRow >= 0:
if selfExtender._selectedRow not in selfExtender._userTable.getSelectedRows():
indexes = [selfExtender._db.getUserByRow(selfExtender._selectedRow)._index]
else:
indexes = [selfExtender._db.getUserByRow(rowNum)._index for rowNum in selfExtender._userTable.getSelectedRows()]
for i in indexes:
selfExtender._db.deleteUser(i)
selfExtender._selectedColumn = -1
selfExtender._userTable.redrawTable()
selfExtender._chainTable.redrawTable()
class actionRemoveChain(ActionListener):
def actionPerformed(self,e):
if selfExtender._selectedRow >= 0:
if selfExtender._selectedRow not in selfExtender._chainTable.getSelectedRows():
indexes = [selfExtender._db.getChainByRow(selfExtender._selectedRow)._index]
else:
indexes = [selfExtender._db.getChainByRow(rowNum)._index for rowNum in selfExtender._chainTable.getSelectedRows()]
for i in indexes:
selfExtender._db.deleteChain(i)
selfExtender._selectedColumn = -1
selfExtender._chainTable.redrawTable()
class actionRemoveColumn(ActionListener):
def __init__(self, table):
self._table = table
def actionPerformed(self,e):
if selfExtender._selectedColumn >= 0:
if self._table == "u":
# Delete Role
if selfExtender._selectedColumn >= selfExtender._db.STATIC_USER_TABLE_COLUMN_COUNT + selfExtender._db.headerCount + selfExtender._db.arrayOfSVs.size():
selfExtender._db.deleteRole(selfExtender._db.getRoleByColumn(
selfExtender._selectedColumn, self._table)._index)
# Delete SV
elif selfExtender._selectedColumn >= selfExtender._db.STATIC_USER_TABLE_COLUMN_COUNT + selfExtender._db.headerCount:
selfExtender._db.deleteSV(selfExtender._selectedColumn-(selfExtender._db.STATIC_USER_TABLE_COLUMN_COUNT+selfExtender._db.headerCount))
# Delete Header
elif selfExtender._selectedColumn >= selfExtender._db.STATIC_USER_TABLE_COLUMN_COUNT:
selfExtender._db.deleteHeader(selfExtender._selectedColumn-selfExtender._db.STATIC_USER_TABLE_COLUMN_COUNT)
elif self._table == "m":
# Delete Role
selfExtender._db.deleteRole(selfExtender._db.getRoleByColumn(
selfExtender._selectedColumn, self._table)._index)
selfExtender._selectedColumn = -1
selfExtender._userTable.redrawTable()
selfExtender._messageTable.redrawTable()
selfExtender._chainTable.redrawTable()
class actionToggleRegex(ActionListener):
def actionPerformed(self,e):
if selfExtender._selectedRow >= 0:
if selfExtender._selectedRow not in selfExtender._messageTable.getSelectedRows():
messages = [selfExtender._db.getMessageByRow(selfExtender._selectedRow)]
else:
messages = [selfExtender._db.getMessageByRow(rowNum) for rowNum in selfExtender._messageTable.getSelectedRows()]
for m in messages:
m.setFailureRegex(not m.isFailureRegex())
m.clearResults()
selfExtender._selectedColumn = -1
selfExtender._messageTable.redrawTable()
class actionChangeRegexes(ActionListener):
def actionPerformed(self,e):
if selfExtender._selectedRow >= 0:
if selfExtender._selectedRow not in selfExtender._messageTable.getSelectedRows():
messages = [selfExtender._db.getMessageByRow(selfExtender._selectedRow)]
else:
messages = [selfExtender._db.getMessageByRow(rowNum) for rowNum in selfExtender._messageTable.getSelectedRows()]
newRegex,failureRegex = selfExtender.changeRegexPopup()
if newRegex:
for message in messages:
message._regex = newRegex
message.setFailureRegex(failureRegex)
# Add to list of regexes if its not already there
if newRegex not in selfExtender._db.arrayOfRegexes:
selfExtender._db.arrayOfRegexes.append(newRegex)
selfExtender._selectedColumn = -1
selfExtender._messageTable.redrawTable()
class actionChangeDomain(ActionListener):
def replaceDomain(self, requestResponse, newDomain):
requestInfo = selfExtender._helpers.analyzeRequest(requestResponse)
reqBody = requestResponse.getRequest()[requestInfo.getBodyOffset():]
newHeaders = ModifyMessage.getNewHeaders(requestInfo, None, ["Host: "+newDomain])
newreq = selfExtender._helpers.buildHttpMessage(newHeaders, reqBody)
return newreq
def actionPerformed(self,e):
if selfExtender._selectedRow >= 0:
if selfExtender._selectedRow not in selfExtender._messageTable.getSelectedRows():
messages = [selfExtender._db.getMessageByRow(selfExtender._selectedRow)]
else:
messages = [selfExtender._db.getMessageByRow(rowNum) for rowNum in selfExtender._messageTable.getSelectedRows()]
# Autofill the service values if they are all the same
uniqueServices = [(message._requestResponse.getHttpService().getHost(),
message._requestResponse.getHttpService().getPort(),
message._requestResponse.getHttpService().getProtocol()) for message in messages]
service = None if len(set(uniqueServices)) != 1 else messages[0]._requestResponse.getHttpService()
ok, host, port, tls, replaceHost = selfExtender.changeDomainPopup(service)
if ok and host:
if not port or not port.isdigit():
port = 443 if tls else 80
for m in messages:
if replaceHost:
request = self.replaceDomain(m._requestResponse, host)
else:
request = m._requestResponse.getRequest()
# TODO save the Response?
m._requestResponse = RequestResponseStored(selfExtender, host, int(port), "https" if tls else "http", request)
m.clearResults()
selfExtender._selectedColumn = -1
selfExtender._messageTable.redrawTable()
class actionSetToggleForRole(ActionListener):
def __init__(self, enabled):
self._enabled = enabled
def actionPerformed(self, e):
if selfExtender._selectedColumn >= 0:
messageIndexes = [selfExtender._db.getMessageByRow(rowNum)._index for rowNum in selfExtender._messageTable.getSelectedRows()]
for messageIndex in messageIndexes:
roleIndex = selfExtender._db.getRoleByColumn(selfExtender._selectedColumn, "m")._index
selfExtender._db.setToggleForRole(messageIndex, roleIndex, self._enabled)
selfExtender._selectedColumn = -1
selfExtender._messageTable.redrawTable()
# Message Table popups
messagePopup = JPopupMenu()
addPopup(self._messageTable,messagePopup)
toggleEnabled = JMenuItem("Disable/Enable Request(s)")
toggleEnabled.addActionListener(actionToggleEnableMessage())
messagePopup.add(toggleEnabled)
messageRun = JMenuItem("Run Request(s)")
messageRun.addActionListener(actionRunMessage())
messagePopup.add(messageRun)
toggleRegex = JMenuItem("Toggle Regex Mode (Success/Failure)")
toggleRegex.addActionListener(actionToggleRegex())
messagePopup.add(toggleRegex)
changeRegex = JMenuItem("Change Regexes")
changeRegex.addActionListener(actionChangeRegexes())
messagePopup.add(changeRegex)
changeDomain = JMenuItem("Change Target Domain")
changeDomain.addActionListener(actionChangeDomain())
messagePopup.add(changeDomain)
messageRemove = JMenuItem("Remove Request(s)")
messageRemove.addActionListener(actionRemoveMessage())
messagePopup.add(messageRemove)
messageHeaderPopup = JPopupMenu()
addPopup(self._messageTable.getTableHeader(),messageHeaderPopup)
roleRemoveFromMessageTable = JMenuItem("Remove Role")
roleRemoveFromMessageTable.addActionListener(actionRemoveColumn("m"))
messageHeaderPopup.add(roleRemoveFromMessageTable)
enableToggle = JMenuItem("Bulk Select Checkboxes")
enableToggle.addActionListener(actionSetToggleForRole(True))
messageHeaderPopup.add(enableToggle)
disableToggle = JMenuItem("Bulk Unselect Checkboxes")
disableToggle.addActionListener(actionSetToggleForRole(False))
messageHeaderPopup.add(disableToggle)
# User Table popup
userPopup = JPopupMenu()
addPopup(self._userTable,userPopup)
toggleEnabled = JMenuItem("Disable/Enable User(s)")
toggleEnabled.addActionListener(actionToggleEnableUser())
userPopup.add(toggleEnabled)
userRemove = JMenuItem("Remove Users(s)")
userRemove.addActionListener(actionRemoveUser())
userPopup.add(userRemove)
userHeaderPopup = JPopupMenu()
addPopup(self._userTable.getTableHeader(),userHeaderPopup)
removeColumnFromUserTable = JMenuItem("Remove")
removeColumnFromUserTable.addActionListener(actionRemoveColumn("u"))
userHeaderPopup.add(removeColumnFromUserTable)
# Chain Table popup
chainPopup = JPopupMenu()
addPopup(self._chainTable,chainPopup)
toggleEnabled = JMenuItem("Disable/Enable Chain(s)")
toggleEnabled.addActionListener(actionToggleEnableChain())
chainPopup.add(toggleEnabled)
chainRemove = JMenuItem("Remove Chain(s)")
chainRemove.addActionListener(actionRemoveChain())
chainPopup.add(chainRemove)
# request tabs added to this tab on click in message table
self._tabs = JTabbedPane()
# Add change listener to set currentDisplayedItem
class TabChangeListener(ChangeListener):
def stateChanged(self, e):
if type(e.getSource()) == JTabbedPane and e.getSource().getSelectedIndex()>=0:
selfExtender._currentlyDisplayedItem = e.getSource().getSelectedComponent()._requestResponse
self._tabs.addChangeListener(TabChangeListener())
# Button pannel
buttons = JPanel()
self._runButton = JButton("Run", actionPerformed=self.runClick)
self._cancelButton = JButton("Cancel", actionPerformed=self.cancelClick)
self._newUserButton = JButton("New User", actionPerformed=self.getInputUserClick)
self._newRoleButton = JButton("New Role", actionPerformed=self.getInputRoleClick)
self._newHeaderButton = JButton("New Header", actionPerformed=self.newHeaderClick)
self._newChainButton = JButton("New Chain", actionPerformed=self.newChainClick)
self._newStaticValueButton = JButton("New Chain Source", actionPerformed=self.newStaticValueClick)
self._saveButton = JButton("Save", actionPerformed=self.saveClick)
self._loadButton = JButton("Load", actionPerformed=self.loadClick)
self._clearButton = JButton("Clear", actionPerformed=self.clearClick)
buttons.add(self._runButton)
buttons.add(self._cancelButton)
self._cancelButton.setEnabled(False)
separator1 = JSeparator(SwingConstants.VERTICAL)
separator1.setPreferredSize(Dimension(25,0))
buttons.add(separator1)
buttons.add(self._newUserButton)
buttons.add(self._newRoleButton)
buttons.add(self._newHeaderButton)
separator2 = JSeparator(SwingConstants.VERTICAL)
separator2.setPreferredSize(Dimension(25,0))
buttons.add(separator2)
buttons.add(self._newChainButton)
buttons.add(self._newStaticValueButton)
separator3 = JSeparator(SwingConstants.VERTICAL)
separator3.setPreferredSize(Dimension(25,0))
buttons.add(separator3)
buttons.add(self._saveButton)
buttons.add(self._loadButton)
buttons.add(self._clearButton)
# Top pane
firstPane = JSplitPane(JSplitPane.VERTICAL_SPLIT,roleScrollPane,messageScrollPane)
self._topPane = JSplitPane(JSplitPane.VERTICAL_SPLIT, firstPane, chainScrollPane)
bottomPane = JSplitPane(JSplitPane.VERTICAL_SPLIT, self._tabs, buttons)
# Main Pane
self._splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT, self._topPane, bottomPane)
# customize our UI components
callbacks.customizeUiComponent(self._splitpane)
callbacks.customizeUiComponent(firstPane)
callbacks.customizeUiComponent(self._topPane)
callbacks.customizeUiComponent(bottomPane)
callbacks.customizeUiComponent(messageScrollPane)
callbacks.customizeUiComponent(roleScrollPane)
callbacks.customizeUiComponent(chainScrollPane)
callbacks.customizeUiComponent(self._messageTable)
callbacks.customizeUiComponent(self._userTable)
callbacks.customizeUiComponent(self._chainTable)
callbacks.customizeUiComponent(self._tabs)
callbacks.customizeUiComponent(buttons)
self._splitpane.setResizeWeight(0.5)
firstPane.setResizeWeight(0.35)
self._topPane.setResizeWeight(0.85)
bottomPane.setResizeWeight(0.95)
# Handles checkbox, regex, and enabled coloring
# Must be bellow the customizeUiComponent calls
self._messageTable.setDefaultRenderer(Boolean, SuccessBooleanRenderer(self._messageTable.getDefaultRenderer(Boolean), self._db))
self._messageTable.setDefaultRenderer(str, RegexRenderer(self._messageTable.getDefaultRenderer(str), self._db))
self._userTable.setDefaultRenderer(str, UserEnabledRenderer(self._userTable.getDefaultRenderer(str), self._db))
self._userTable.setDefaultRenderer(Boolean, UserEnabledRenderer(self._userTable.getDefaultRenderer(Boolean), self._db))
self._chainTable.setDefaultRenderer(str, ChainEnabledRenderer(self._chainTable.getDefaultRenderer(str), self._db))
# add the custom tab to Burp's UI
callbacks.addSuiteTab(self)
# register SendTo option
callbacks.registerContextMenuFactory(self)
return
##
## implement ITab
##
def getTabCaption(self):
return "AuthMatrix"
def getUiComponent(self):
return self._splitpane
def highlightTab(self):
currentPane = self._splitpane
previousPane = currentPane
while currentPane and not isinstance(currentPane, JTabbedPane):
previousPane = currentPane
currentPane = currentPane.getParent()
if currentPane:
index = currentPane.indexOfComponent(previousPane)
# TODO use old background instead of black (currently doesnt work)
#oldBackground = currentPane.getBackgroundAt(index)
currentPane.setBackgroundAt(index,self._db.BURP_ORANGE)
class setColorBackActionListener(ActionListener):
def actionPerformed(self, e):
currentPane.setBackgroundAt(index,Color.BLACK)
timer = Timer(5000, setColorBackActionListener())
timer.setRepeats(False)
timer.start()
##
## Creates the sendto tab in other areas of Burp
##
def createMenuItems(self, invocation):
def addRequestsToTab(e):
for messageInfo in messages:
requestInfo = self._helpers.analyzeRequest(messageInfo)
name = str(requestInfo.getMethod()).ljust(8) + requestInfo.getUrl().getPath()
# Grab regex from response
regex = "^HTTP/1\\.1 200 OK"
response = messageInfo.getResponse()
if response:
responseInfo=self._helpers.analyzeResponse(response)
if len(responseInfo.getHeaders()):
responseCodeHeader = responseInfo.getHeaders()[0]
regex = "^"+re.escape(responseCodeHeader)
# Must create a new RequestResponseStored object since modifying the original messageInfo
# from its source (such as Repeater) changes this saved object. MessageInfo is a reference, not a copy
messageIndex = self._db.createNewMessage(RequestResponseStored(self,requestResponse=messageInfo), name, regex)
self._messageTable.redrawTable()
self._chainTable.redrawTable()
self.highlightTab()
class UserCookiesActionListener(ActionListener):
def __init__(self, currentUser, extender):
self.currentUser=currentUser
self.extender = extender
def actionPerformed(self, e):
for messageInfo in messages:
cookieVal = ""
requestInfo = self.extender._helpers.analyzeRequest(messageInfo)
for header in requestInfo.getHeaders():
cookieStr = "Cookie: "
if header.startswith(cookieStr):
cookieVal = header[len(cookieStr):]
# Grab Set-Cookie headers from the responses as well
response = messageInfo.getResponse()
if response:
responseInfo = self.extender._helpers.analyzeResponse(response)
responseCookies = responseInfo.getCookies()
newCookies = "; ".join([x.getName()+"="+x.getValue() for x in responseCookies])
cookieVal = ModifyMessage.cookieReplace(cookieVal,newCookies)
self.currentUser._cookies = cookieVal
self.extender._userTable.redrawTable()
self.extender.highlightTab()
ret = []
messages = invocation.getSelectedMessages()
# Check if the messages in the target tree have a response
valid = True
if invocation.getInvocationContext() == invocation.CONTEXT_TARGET_SITE_MAP_TREE:
for selected in messages:
if not selected.getResponse():
valid = False
if valid:
menuItem = JMenuItem("Send request(s) to AuthMatrix");
menuItem.addActionListener(addRequestsToTab)
ret.append(menuItem)
if len(messages)==1:
# Send cookies to user:
for user in self._db.getUsersInOrderByRow():
menuItem = JMenuItem("Send cookies to AuthMatrix user: "+user._name);
menuItem.addActionListener(UserCookiesActionListener(user, self))
ret.append(menuItem)
return ret
##
## implement IMessageEditorController
## this allows our request/response viewers to obtain details about the messages being displayed
##
def getHttpService(self):
return self._currentlyDisplayedItem.getHttpService()
def getRequest(self):
return self._currentlyDisplayedItem.getRequest()
def getResponse(self):
return self._currentlyDisplayedItem.getResponse()
##
## Actions on Bottom Row Button Clicks
##
def getInputUserClick(self, e):
newUser = JOptionPane.showInputDialog(self._splitpane,"Enter New User:")
if newUser:
self._db.getOrCreateUser(newUser)
self._userTable.redrawTable()
# redraw Message Table since it adds a new SingleUser Role
self._messageTable.redrawTable()
self._chainTable.redrawTable()
def getInputRoleClick(self, e):
newRole = JOptionPane.showInputDialog(self._splitpane,"Enter New Role:")
if newRole:
self._db.getOrCreateRole(newRole)
self._userTable.redrawTable()
self._messageTable.redrawTable()
def newChainClick(self,e):
self._db.createNewChain()
self._chainTable.redrawTable()
def newHeaderClick(self, e):
self._db.addNewHeader()
self._userTable.redrawTable()
def newStaticValueClick(self, e):
newSV = JOptionPane.showInputDialog(self._splitpane,"Enter a label for the new Chain Source:")
if newSV:
self._db.addNewSV(newSV)
self._userTable.redrawTable()
self._chainTable.redrawTable()
def cancelClick(self,e):
self._runCancelled = True
self._cancelButton.setEnabled(False)
def saveClick(self, e):
# Update original requests with any user changes
self._messageTable.updateMessages()
returnVal = self._fc.showSaveDialog(self._splitpane)
if returnVal == JFileChooser.APPROVE_OPTION:
f = self._fc.getSelectedFile()
if f.exists():
result = JOptionPane.showConfirmDialog(self._splitpane, "The file exists, overwrite?", "Existing File", JOptionPane.YES_NO_OPTION)
if result != JOptionPane.YES_OPTION:
return
fileName = f.getPath()
# TODO Potential bug here. Check if the value being written is 0 before opening
# TODO add a try catch here?
jsonValue = self._db.getSaveableJson()
if jsonValue:
fileout = open(fileName,'w')
fileout.write(jsonValue)
fileout.close()
else:
# TODO popup errors instead of prints
print "Error: Save Failed. JSON empty."
# TODO currently this will save the config to burp, but not to a specific project
# Will also need an export and loadFromFile feature if this is ever implemented
# self._callbacks.saveExtensionSetting("AUTHMATRIX", self._db.getSaveableJson())
def loadClick(self,e):
returnVal = self._fc.showOpenDialog(self._splitpane)
if returnVal == JFileChooser.APPROVE_OPTION:
f = self._fc.getSelectedFile()
fileName = f.getPath()
filein = open(fileName,'r')
jsonText = filein.read()
filein.close()
# Check if using on older state file compatible with v0.5.2 or greater
if not jsonText or jsonText[0] !="{":
warning = """
CAUTION:
Loading a saved configuration prior to v0.6.3 deserializes data into Jython objects.
This action may pose a security threat to the application.
Only proceed when the source and contents of this file is trusted.
Load Selected File?
"""
result = JOptionPane.showOptionDialog(self._splitpane,
warning, "Caution",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE,
None,
["OK", "Cancel"],
"OK")
if result != JOptionPane.YES_OPTION:
return
self._db.loadLegacy(fileName,self)
else:
self._db.loadJson(jsonText,self)
# TODO currently can load exention settings, but this is saved for Burp and not for the Project specifically
# self._db.loadJson(self._callbacks.loadExtensionSetting("AUTHMATRIX"),self)
self._userTable.redrawTable()
self._messageTable.redrawTable()
self._chainTable.redrawTable()
def clearClick(self,e):
result = JOptionPane.showConfirmDialog(self._splitpane, "Clear AuthMatrix Configuration?", "Clear Config", JOptionPane.YES_NO_OPTION)
if result == JOptionPane.YES_OPTION:
self._db.clear()
self._tabs.removeAll()
self._userTable.redrawTable()
self._messageTable.redrawTable()
self._chainTable.redrawTable()
def runClick(self,e):
t = Thread(target=self.runMessagesThread)
self._tabs.removeAll()
t.start()
def changeRegexPopup(self):
regexComboBox = JComboBox(self._db.arrayOfRegexes)
regexComboBox.setEditable(True)
failureModeCheckbox = JCheckBox()
panel = JPanel(GridBagLayout())
gbc = GridBagConstraints()
gbc.anchor = GridBagConstraints.WEST
firstline = JPanel()
firstline.add(JLabel("Select a Regex for all selected Requests:"))
secondline = JPanel()
secondline.add(regexComboBox)
thirdline = JPanel()
thirdline.add(failureModeCheckbox)
thirdline.add(JLabel("Regex Detects Unauthorized Requests (Failure Mode)"))
gbc.gridy = 0
panel.add(firstline,gbc)
gbc.gridy = 1
panel.add(secondline, gbc)
gbc.gridy = 2
panel.add(thirdline, gbc)
result = JOptionPane.showConfirmDialog(self._splitpane, panel, "Select Response Regex", JOptionPane.OK_CANCEL_OPTION)
value = regexComboBox.getSelectedItem()
if result == JOptionPane.CANCEL_OPTION or not value:
return None, None
return value, failureModeCheckbox.isSelected()
def changeDomainPopup(self, service):
hostField = JTextField(25)
portField = JTextField(25)
checkbox = JCheckBox()
replaceHostCheckbox = JCheckBox()
replaceHostCheckbox.setSelected(True)
errorField = JLabel("\n")
errorField.setForeground(Color.orange);
errorField.setFont
def isValidDomain(domain):
return re.match(r'^[a-zA-Z0-9-\.]+$', domain)
if service:
hostField.setText(service.getHost())
portField.setText(str(service.getPort()))
if service.getProtocol()=="https":
checkbox.setSelected(True)
class HttpsItemListener(ItemListener):
def itemStateChanged(self, e):
if e.getStateChange() == ItemEvent.SELECTED and portField.getText() == "80":
portField.setText("443")
elif e.getStateChange() == ItemEvent.DESELECTED and portField.getText() == "443":
portField.setText("80")
checkbox.addItemListener(HttpsItemListener())
class HostDocumentListener(DocumentListener):
def changeUpdate(self, e):
self.testHost()
def removeUpdate(self, e):
self.testHost()
def insertUpdate(self, e):
self.testHost()
def testHost(self):
domain = hostField.getText()
matches = isValidDomain(domain)
if not matches:
# NOTE Hacky way to fix layout when host is long
if len(domain)>40:
domain = domain[:40]+"..."
errorField.setText("Invalid host: "+domain)
else:
errorField.setText("\n")
hostField.getDocument().addDocumentListener(HostDocumentListener())
domainPanel = JPanel(GridBagLayout())
gbc = GridBagConstraints()
gbc.anchor = GridBagConstraints.WEST
firstline = JPanel()
firstline.add(JLabel("Specify the details of the server to which the request will be sent."))
secondline = JPanel()
secondline.add(JLabel("Host: "))
secondline.add(hostField)
thirdline = JPanel()
thirdline.add(JLabel("Port: "))
thirdline.add(portField)
fourthline = JPanel()
fourthline.add(checkbox)
fourthline.add(JLabel("Use HTTPS"))
fifthline = JPanel()
fifthline.add(replaceHostCheckbox)
fifthline.add(JLabel("Replace Host in HTTP header"))
sixthline = JPanel()
sixthline.add(errorField)
gbc.gridy = 0
domainPanel.add(firstline,gbc)
gbc.gridy = 1
domainPanel.add(secondline, gbc)
gbc.gridy = 2
domainPanel.add(thirdline, gbc)
gbc.gridy = 3
domainPanel.add(fourthline, gbc)
gbc.gridy = 4
domainPanel.add(fifthline, gbc)
gbc.gridy = 5
domainPanel.add(sixthline, gbc)
result = JOptionPane.showConfirmDialog(
self._splitpane,domainPanel, "Configure target details", JOptionPane.OK_CANCEL_OPTION)
cancelled = (result == JOptionPane.CANCEL_OPTION)
if cancelled or not isValidDomain(hostField.getText()):
return (False, None, None, False, False)
return (True, hostField.getText(), portField.getText(), checkbox.isSelected(), replaceHostCheckbox.isSelected())
##
## Methods for running messages and analyzing results
##
def lockButtons(self, running=True):
# Disable run button, enable cancel button
self._runButton.setEnabled(not running)
self._newUserButton.setEnabled(not running)
self._newRoleButton.setEnabled(not running)
self._newHeaderButton.setEnabled(not running)
self._newChainButton.setEnabled(not running)
self._newStaticValueButton.setEnabled(not running)
self._saveButton.setEnabled(not running)
self._loadButton.setEnabled(not running)
self._clearButton.setEnabled(not running)
self._cancelButton.setEnabled(running)
def runMessagesThread(self, messageIndexes=None):
self._db.lock.acquire()
try:
self.lockButtons()
self._runCancelled=False
# Update original requests with any user changes
self._messageTable.updateMessages()
self._db.clearAllChainResults()
indexes = messageIndexes
if not indexes:
indexes = self._db.getActiveMessageIndexes()
self.clearColorResults(indexes)
# Run in order of row, not by index
messagesThatHaveRun = []
for message in self._db.getMessagesInOrderByRow():
# Only run if message is in the selected indexes (NOTE: dependencies will be run even if not selected)
if message._index in indexes:
messagesThatHaveRun = self.runMessageAndDependencies(message._index, messagesThatHaveRun, [])
except:
traceback.print_exc(file=self._callbacks.getStderr())
finally:
self.lockButtons(False)
self._db.lock.release()
self._messageTable.redrawTable()
def runMessageAndDependencies(self, messageIndex, messagesThatHaveRun, recursionCheckArray):
messageEntry = self._db.arrayOfMessages[messageIndex]
updatedMessagesThatHaveRun = messagesThatHaveRun[:]
updatedRecursionCheckArray = recursionCheckArray[:]
if messageIndex in updatedRecursionCheckArray:
print "Error: Recursion detected in message chains: "+"->".join([str(i) for i in updatedRecursionCheckArray])+"->"+str(messageIndex)
elif (messageIndex not in updatedMessagesThatHaveRun
and messageEntry.isEnabled()
and messageIndex in self._db.getActiveMessageIndexes()):
updatedRecursionCheckArray.append(messageIndex)
for chainIndex in self._db.getActiveChainIndexes():
# Run any dependencies first
chainEntry = self._db.arrayOfChains[chainIndex]
if (messageIndex in chainEntry.getToIDRange()
and chainEntry.isEnabled()
and str(chainEntry._fromID).isdigit()
and int(chainEntry._fromID) >= 0):
updatedMessagesThatHaveRun = self.runMessageAndDependencies(int(chainEntry._fromID), updatedMessagesThatHaveRun, updatedRecursionCheckArray)
self.runMessage(messageIndex)
# print messageIndex
updatedMessagesThatHaveRun.append(messageIndex)
return updatedMessagesThatHaveRun
def runMessage(self, messageIndex):
# NOTE: this uses hacky threading tricks for handling timeouts
tempRequestResponse = []
index = 0
def loadRequestResponse(index, service, message):
# NOTE: tempRequestResponse is an array because of a threading issue,
# where if this thread times out, it will still update temprequestresponse later on..
try:
tempRequestResponse[index] = self._callbacks.makeHttpRequest(service,message)
except java.lang.RuntimeException:
# Catches if there is a bad host
# TODO there may sometimes be an unhandled exception thrown in the stack trace here?
print "Runtime Exception"
return
except:
traceback.print_exc(file=callbacks.getStderr())
messageEntry = self._db.arrayOfMessages[messageIndex]
messageEntry.clearResults()
messageInfo = messageEntry._requestResponse
requestInfo = self._helpers.analyzeRequest(messageInfo)
reqBody = messageInfo.getRequest()[requestInfo.getBodyOffset():]
for userIndex in [userEntry._index for userEntry in self._db.getUsersInOrderByRow()]:
# Handle cancel button early exit here
if self._runCancelled:
return
userEntry = self._db.arrayOfUsers[userIndex]
# Only run if the user is enabled