-
Notifications
You must be signed in to change notification settings - Fork 3
/
headers_window.py
2776 lines (2250 loc) · 124 KB
/
headers_window.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
from burp import IBurpExtender, ITab
from burp import IContextMenuFactory
import threading
#import java
import shutil, glob, re, sys, os, subprocess
#from time import sleep
from javax.swing import JFrame, JProgressBar, JSplitPane, JTable, JScrollPane, JPanel, BoxLayout, WindowConstants, JLabel, JMenuItem, JTabbedPane, JButton, JTextField, JTextArea, SwingConstants, JEditorPane, JComboBox, DefaultComboBoxModel, JFileChooser, ImageIcon, JCheckBox, JRadioButton, ButtonGroup, KeyStroke
from javax.swing.table import DefaultTableModel, DefaultTableCellRenderer, TableCellRenderer
from java.awt import BorderLayout, Dimension, FlowLayout, GridLayout, GridBagLayout, GridBagConstraints, Point, Component, Color # quitar los layout que no utilice
from java.util import List, ArrayList
from java.lang import Boolean, String, Integer
#from java.awt.event.MouseEvent import getPoint
from java.awt.event import MouseListener, FocusListener
burp_extender_instance = "" # variable global que sera el instance de bupr extender, para acceder a los valores de la instancia de IBurpExtender que burp crea, pero desde fuera, sobre todo para cambiar con clicks la tabla de endpoints
history1 = []
host_endpoint = [] #se rellena al darle a filter en la tab, pero habra que arreglar que no haya duplicados cuando cambian los valores de los query string rameters (o puedo dejar que se repitan y ponerlos todos.) lo bueno seria poner tambien el index del history y en el text area poner los headers de la req los de la resp, separados por una =========, etc
endpoint_table = []
endpoint_table_meta = []
selected_header_name = ""
class RawHtmlRenderer(DefaultTableCellRenderer):
def __init__(self):
self.result = JLabel()
self.DTCR = DefaultTableCellRenderer()
def getTableCellRendererComponent(
self,
table, # JTable - table containing value
value, # Object - value being rendered
isSelected, # boolean - Is value selected?
hasFocus, # boolean - Does this cell have focus?
row, # int - Row # (0..N)
col # int - Col # (0..N)
) :
comp = self.DTCR.getTableCellRendererComponent(
table, value, isSelected, hasFocus, row, col
)
result = self.result
############################################################################
###### something is not right, clicking on cells doesn't change selected background
result.setBorder( comp.getBorder() )
if (isSelected):
result.setBackground(table.getSelectionBackground())
#result.setBackground(Color.blue))
result.setForeground(table.getSelectionForeground())
else:
result.setBackground(table.getBackground())
result.setForeground(table.getForeground())
################################################################################
result.setText(value)
result.putClientProperty("html.disable", None)
return result
class ConfigTableModel(DefaultTableModel):
def __init__(self, data, headings):
DefaultTableModel.__init__(self, data, headings)
def getColumnClass(self, col):
return [Boolean, String][col]
class IssueTableModel(DefaultTableModel):
"""Extends the DefaultTableModel to make it readonly."""
def __init__(self, data, headings):
# call the DefaultTableModel constructor to populate the table
DefaultTableModel.__init__(self, data, headings)
def isCellEditable(self, row, column):
"""Returns True if cells are editable."""
canEdit = [False, False, False]
return canEdit[column]
class IssueTableMouseListener(MouseListener):
"""Some necessary entries that must be present on all mouse listeners, so this is a parent class that is inherited by the other specific mouse listener clases below."""
def getClickedIndex(self, event):
"""Returns the value of the first column of the table row that was
clicked. This is not the same as the row index because the table
can be sorted."""
# get the event source, the table in this case.
tbl = event.getSource()
# get the clicked row
row = tbl.getSelectedRow()
# get the first value of clicked row
return tbl.getValueAt(row, 0)
# return event.getSource.getValueAt(event.getSource().getSelectedRow(), 0)
def getClickedRow(self, event):
"""Returns the complete clicked row."""
tbl = event.getSource()
return [tbl.getModel().getDataVector().elementAt(tbl.getSelectedRow()), tbl.getSelectedRow()]
def mousePressed(self, event):
pass
def mouseReleased(self, event):
pass
# the following two are necessary, although they are empty, otherwise the extension crashes when the mouse cursor enters or exits the table
def mouseEntered(self, event):
pass
def mouseExited(self, event):
pass
class IssueTableMouseListener_Window(IssueTableMouseListener):
"""Adds values to the extra information panel when an entry in the floating window is double clicked. The extra info panel is always there, double clicking elements of the floating window only makes it visible."""
def mouseClicked(self, event):
if event.getClickCount() == 1: # single click on table elements
header = self.getClickedRow(event)[0]
header = header[0].split('<font color="{}">'.format(burp_extender_instance.color1))[1].split('</b></font>')[0] #debe haber mas abajo al reves el orden de las closing tabs b y font
burp_extender_instance.extra_info_textarea1.setText(header)
if header in list(burp_extender_instance.dict_req_headers.keys()) and header not in list(burp_extender_instance.dict_resp_headers.keys()):
burp_extender_instance.extra_info_textarea2.setText(burp_extender_instance.dict_req_headers[header][0])
burp_extender_instance.extra_info_textarea3.setText(burp_extender_instance.dict_req_headers[header][1])
burp_extender_instance.extra_info_textarea4.setText(burp_extender_instance.dict_req_headers[header][2])
burp_extender_instance.extra_info_textarea5.setText(burp_extender_instance.dict_req_headers[header][3])
if header not in (list(burp_extender_instance.dict_req_headers.keys())) and header not in list(burp_extender_instance.dict_resp_headers.keys()):
burp_extender_instance.extra_info_textarea2.setText('Description unavailable for header: ' + header)
burp_extender_instance.extra_info_textarea3.setText('Example unavailable for header: ' + header)
burp_extender_instance.extra_info_textarea4.setText('URL unavailable for header: ' + header)
burp_extender_instance.extra_info_textarea5.setText('Potential risks unavailable for header: ' + header)
if header in list(burp_extender_instance.dict_resp_headers.keys()):
burp_extender_instance.extra_info_textarea2.setText(burp_extender_instance.dict_resp_headers[header][0])
burp_extender_instance.extra_info_textarea3.setText(burp_extender_instance.dict_resp_headers[header][1])
burp_extender_instance.extra_info_textarea4.setText(burp_extender_instance.dict_resp_headers[header][2])
burp_extender_instance.extra_info_textarea5.setText(burp_extender_instance.dict_resp_headers[header][3])
if event.getClickCount() == 2: # double click to make extra info panel visible
burp_extender_instance.extra_info.setVisible(True)
class IssueTableMouseListener_Meta(IssueTableMouseListener):
"""Adds functionality to the Header-host table (to the <meta> tab) when its elements are clicked."""
def mouseClicked(self, event):
burp_extender_instance.is_meta = True
if event.getClickCount() == 1:
tbl = event.getSource()
val = tbl.getModel().getDataVector().elementAt(tbl.getSelectedRow())
identifier = val[0]
clicked_host = val[1]
k = tbl.getSelectedRow()
if identifier == '':
while identifier == '':
k -= 1
identifier = tbl.getModel().getDataVector().elementAt(k)[0]
global endpoint_table_meta # igual no tiene que ser gobal
endpoint_table_meta = []
# meta_table tiene columnas: host | url | meta tag, una para cada tag, repitiendo host y url si hay mas de una tag en una url
for (host, endpoint, meta) in burp_extender_instance.meta_table:
#if identifier not in meta and clicked_host != host:
if clicked_host == host:
spl = endpoint.split(' ')
line = spl[0] + " :: " + host + " :: " + " ".join(spl[1:])
endpoint_table_meta.append([endpoint]) #poner el host antes de la url pero despues del method
#endpoint_table_meta.append([line]) #poner el host antes de la url pero despues del method
#ESTA COGIENDO ENPOINTS QUE NO CORRESPONDEN, VER SI ES QUE COINCIDEN CON UN HOST DIFERENTE. TAMBIEN TENGO QUE APLICAR REGEX EN LOS UNIQUE ENDPOINTS
burp_extender_instance.selected_meta_header = identifier#header # este lo settea ok para la de endpoints
burp_extender_instance.selected_host = clicked_host
burp_extender_instance.update_meta_endpoints(endpoint_table_meta)
class IssueTableMouseListener_Tab(IssueTableMouseListener):
"""Adds functionality to the Header-host table when its elements are clicked."""
def mouseClicked(self, event):
burp_extender_instance.is_meta = False
if event.getClickCount() == 1:
tbl = event.getSource()
val = tbl.getModel().getDataVector().elementAt(tbl.getSelectedRow())
header = val[0]
clicked_host = val[1]
k = tbl.getSelectedRow()
if header == '':
while header == '':
k -= 1
header = tbl.getModel().getDataVector().elementAt(k)[0]
header_value = header.split('<font color="{}">'.format(burp_extender_instance.color1))[1].split('</font>')[0]
#hasta aqui ok, header_value es el header que se ha marcado (primera columna), creo que este solo lo uso para subrayado en el textarea
global host_endpoint
global endpoint_table
endpoint_table = []
for (host, endpoint) in host_endpoint:
if clicked_host == host:# and endpoint not in endpoint_table:
endpoint_table.append([endpoint])
###global burp_extender_instance #variable global que representa la instancia de IBurpExtender que se crea al cargar la extension. se usa para acceder desde fuera (especialmente desde el mouse event handler para actualizar la endpoint_table) a propiedades y metodos de la instancia "principal" de la extension. el valor se lo doy dentro de la intancia, igualando esta variable a self
global selected_header_name
selected_header_name = header_value
burp_extender_instance.selected_host = clicked_host
burp_extender_instance.selected_header = header_value#header # este lo settea ok para la de endpoints
burp_extender_instance.endpoint_table1 = endpoint_table
burp_extender_instance.update_endpoints(endpoint_table)
class IssueTableMouseListener_Endpoints(IssueTableMouseListener):
"""Adds functionality to the click actions on rows of the "Unique endpoints" and "All endpoints" tables."""
def extra_symbol(self, head):
if head.split(": ")[0].lower() in self.security_headers:
extra_symbol = '<b><font color="#00FF00"> [ + ] </font><b>'
elif head.split(": ")[0].lower() in self.dangerous_headers:
extra_symbol = '<b><font color="#FF0000"> [ X ] </font><b>'
elif head.split(": ")[0].lower() in self.potentially_dangerous_headers:
extra_symbol = '<b><font color="#4FC3F7"> [ ? ] </font><b>'
else:
extra_symbol = ""
return extra_symbol
def mouseClicked(self, event):
if event.getClickCount() == 1:
tbl = event.getSource()
burp_extender_instance.clicked_endpoint(tbl, True)
class summary_unique_mouse_listener(IssueTableMouseListener):
def mouseClicked(self, event):
print('summary table clicked')
class summary_all_mouse_listener(IssueTableMouseListener):
def mouseClicked(self, event):
print('summary all clicked, go to history and show request/response')
class SummaryTableModel_left(DefaultTableModel):
def __init__(self, data, headings):
DefaultTableModel.__init__(self, data, headings)
def getColumnClass(self, col):
# columnas: add to report?, Host
return [Boolean, String][col]
def isCellEditable(self, row, column):
"""Returns True if cells are editable."""
canEdit = [True, False]
return canEdit[column]
class SummaryTableModel_right(DefaultTableModel):
def __init__(self, data, headings):
DefaultTableModel.__init__(self, data, headings)
def getColumnClass(self, col):
# columnas: history index, add to report?, issue type, host, unique endpoint
# issue types:
# - missing security headers
# - dangerous
# - potentially dangerous
# - http verbs
# - cookies without flags
return [Boolean, String, String, String][col]
#return [Integer, Boolean, String, String, String][col]
def isCellEditable(self, row, column):
"""Returns True if cells are editable."""
canEdit = [True, False, False, False, False]
return canEdit[column]
class IssueTable(JTable):
"""Table class for the tables used in the extension. Needed to give the capacity to tables to perform actions when their rows are clicked."""
def __init__(self, model, table_type):
self.setModel(model)
self.getTableHeader().setReorderingAllowed(False)
if table_type == "tab":
self.addMouseListener(IssueTableMouseListener_Tab())
elif table_type == "meta":
self.addMouseListener(IssueTableMouseListener_Meta())
elif table_type == "window":
self.addMouseListener(IssueTableMouseListener_Window())
elif table_type == "endpoints":
self.addMouseListener(IssueTableMouseListener_Endpoints())
elif table_type == "config_headers":
pass
elif table_type == "summary_unique_endpoints":
self.addMouseListener(summary_unique_mouse_listener())
elif table_type == "summary_all_endpoints":
self.addMouseListener(summary_all_mouse_listener())
'''def getTableCellRendererComponent(
self,
table, # JTable - table containing value
value, # Object - value being rendered
isSelected, # boolean - Is value selected?
hasFocus, # boolean - Does this cell have focus?
row, # int - Row # (0..N)
col # int - Col # (0..N)
) :
comp = self.DTCR.getTableCellRendererComponent(
table, value, isSelected, hasFocus, row, col
)
result = self.result
result.setText(value)
result.putClientProperty("html.disable", None)
return result'''
class BurpExtender(IBurpExtender, IContextMenuFactory, ITab):
"""Main class of the Headers extension, instantiated by Burp."""
def apply_config(self):
"""Read the configuration file and load the configurations. It is run when the extension loads."""
print("Applying config...")
f = open("config.txt","r")
for line in f.readlines():
feature = line.split(' -- ')[0]
value = line.split(' -- ')[1].strip('\n')
if feature == "last_save_type":
self.save_format.setSelectedItem(value)
self.config_dict[feature] = value
elif feature == "last_output_file":
self.save_path.setText(value)
self.config_dict[feature] = value
elif feature == "last_filter_type":
self.preset_filters.setSelectedItem(value)
self.config_dict[feature] = value
elif feature == "UI_theme":
self.UI_theme = value
self.config_dict[feature] = value
f.close()
f = open('security_headers.txt','r')
self.total_security_headers = len(f.readlines())
f.close()
f = open('potentially_dangerous_headers.txt','r')
self.total_potential_headers = len(f.readlines())
f.close()
f = open('dangerous_headers.txt','r')
self.total_dangerous_headers = len(f.readlines())
f.close()
f = open('cookie_flags.txt','r')
self.total_cookie_flags = len(f.readlines())
f.close()
# UI colors
if self.UI_theme == "dark":
f = open('UI_theme_dark.txt', 'r')
elif self.UI_theme == "light":
f = open('UI_theme_light.txt', 'r')
for k, line in enumerate(f.readlines()):
if k == 0:
self.color1 = line.strip('\n') # for titles and dashed lines
elif k == 1:
self.color2 = line.strip('\n') # for security headers
elif k == 2:
self.color3 = line.strip('\n') # for potentially dangerous headers
elif k == 3:
self.color4 = line.strip('\n') # for dangerous or verbose headers
elif k == 4:
self.color5 = line.strip('\n') # for the rest of headers
elif k == 5:
self.color6 = line.strip('\n') # for the wildcards in the unique endpoints URL
f.close()
def update_config(self):#, feature, value):
"""Update the configuration file with values supplied in the configuration panel of the extension"""
f = open("config.txt", "w")
for key in list(self.config_dict.keys()):
f.write(key + " -- " + self.config_dict[key] + "\n") #comprobar
f.close()
def read_headers(self):
""" Read the values currently checked in the advanced config tables and use them in the future """
self.table_config_security = []
self.table_config_dangerous = []
self.table_config_potentially_dangerous = []
self.table_config_cookie_flags = []
for i in range(self.initial_count_security_headers):
if self.model_tab_config_security.getValueAt(i,0):
self.table_config_security.append([True, self.model_tab_config_security.getValueAt(i,1)])
for i in range(self.initial_count_dangerous_headers):
if self.model_tab_config_dangerous.getValueAt(i,0):
self.table_config_dangerous.append([True, self.model_tab_config_dangerous.getValueAt(i,1)])
for i in range(self.initial_count_potentially_dangerous_headers):
if self.model_tab_config_potentially_dangerous.getValueAt(i,0):
self.table_config_potentially_dangerous.append([True, self.model_tab_config_potentially_dangerous.getValueAt(i,1)])
for i in range(self.initial_count_cookie_flags):
if self.model_tab_config_cookie_flags.getValueAt(i,0):
self.table_config_cookie_flags.append([True, self.model_tab_config_cookie_flags.getValueAt(i,1)])
self.dangerous_headers = []
self.security_headers = []
self.potentially_dangerous_headers = []
self.cookie_flags = []
for line in self.table_config_security:
self.security_headers.append(line[1].strip('\n').lower())
for line in self.table_config_dangerous:
self.dangerous_headers.append(line[1].strip('\n'))
for line in self.table_config_potentially_dangerous:
self.potentially_dangerous_headers.append(line[1].strip('\n'))
for line in self.table_config_cookie_flags:
self.cookie_flags.append(line[1].strip('\n'))
def make_chosen_headers_permanent(self, event):
self.security_headers = []
f = open("security_headers.txt","w")
for i in range(self.initial_count_security_headers):
#print(str(i) + '/' + str(self.initial_count_security_headers))
if i < self.initial_count_security_headers - 1:
if self.model_tab_config_security.getValueAt(i,0):
f.write("1 " + self.model_tab_config_security.getValueAt(i,1) + '\n')
self.security_headers.append(self.model_tab_config_security.getValueAt(i,1))
else:
f.write("0 " + self.model_tab_config_security.getValueAt(i,1) + '\n')
else:
if self.model_tab_config_security.getValueAt(i,0):
f.write("1 " + self.model_tab_config_security.getValueAt(i,1))
self.security_headers.append(self.model_tab_config_security.getValueAt(i,1))
else:
f.write("0 " + self.model_tab_config_security.getValueAt(i,1))
f.close()
f = open("dangerous_headers.txt","w")
self.dangerous_headers = []
for i in range(self.initial_count_dangerous_headers):
if i < self.initial_count_dangerous_headers - 1:
if self.model_tab_config_dangerous.getValueAt(i,0):
f.write("1 " + self.model_tab_config_dangerous.getValueAt(i,1) + '\n')
self.dangerous_headers.append(self.model_tab_config_dangerous.getValueAt(i,1))
else:
f.write("0 " + self.model_tab_config_dangerous.getValueAt(i,1) + '\n')
else:
if self.model_tab_config_dangerous.getValueAt(i,0):
f.write("1 " + self.model_tab_config_dangerous.getValueAt(i,1))
self.dangerous_headers.append(self.model_tab_config_dangerous.getValueAt(i,1))
else:
f.write("0 " + self.model_tab_config_dangerous.getValueAt(i,1))
f.close()
f = open("potentially_dangerous_headers.txt","w")
self.potentially_dangerous_headers = []
for i in range(self.initial_count_potentially_dangerous_headers):
if i < self.initial_count_potentially_dangerous_headers - 1:
if self.model_tab_config_potentially_dangerous.getValueAt(i,0):
f.write("1 " + self.model_tab_config_potentially_dangerous.getValueAt(i,1) + '\n')
self.potentially_dangerous_headers.append(self.model_tab_config_potentially_dangerous.getValueAt(i,1))
else:
f.write("0 " + self.model_tab_config_potentially_dangerous.getValueAt(i,1) + '\n')
else:
if self.model_tab_config_potentially_dangerous.getValueAt(i,0):
f.write("1 " + self.model_tab_config_potentially_dangerous.getValueAt(i,1))
self.potentially_dangerous_headers.append(self.model_tab_config_potentially_dangerous.getValueAt(i,1))
else:
f.write("0 " + self.model_tab_config_potentially_dangerous.getValueAt(i,1))
f.close()
f = open("cookie_flags.txt","w")
self.cookie_flags = []
for i in range(self.initial_count_cookie_flags):
if i < self.initial_count_cookie_flags - 1:
if self.model_tab_config_cookie_flags.getValueAt(i,0):
f.write("1 " + self.model_tab_config_cookie_flags.getValueAt(i,1) + '\n')
self.cookie_flags.append(self.model_tab_config_cookie_flags.getValueAt(i,1))
else:
f.write("0 " + self.model_tab_config_cookie_flags.getValueAt(i,1) + '\n')
else:
if self.model_tab_config_cookie_flags.getValueAt(i,0):
f.write("1 " + self.model_tab_config_cookie_flags.getValueAt(i,1))
self.cookie_flags.append(self.model_tab_config_cookie_flags.getValueAt(i,1))
else:
f.write("0 " + self.model_tab_config_cookie_flags.getValueAt(i,1))
f.close()
def create_extra_info_window(self):
# el extra info window lo defino aqui fuera para que exista desde un principio y al hacer doble click en las tablas solamente se haga visible, pero no se ee un nuevo frame por cada doble click
self.extra_info = JFrame("Extended header info")
self.extra_info_panel = JPanel()
self.extra_info_panel.setLayout(BoxLayout(self.extra_info_panel, BoxLayout.Y_AXIS ) )
self.extra_info.setSize(400, 350)
self.extra_info.setLocation(840, 0)
self.extra_info.toFront()
self.extra_info.setAlwaysOnTop(True)
self.extra_info_label1 = JLabel("<html><b><font color='orange'>Header Name:</font></b></html>")
self.extra_info_label1.putClientProperty("html.disable", None)
#extra_info_label1 = JLabel("<html><b><font color='{}'>Header Name:</font></b></html>".format(self.color1))
self.extra_info_label1.setAlignmentX(JLabel.LEFT_ALIGNMENT)
self.extra_info_textarea1 = JTextArea("Header Name", rows=1, editable=False)
self.extra_info_textarea1.setLineWrap(True)
self.scrollPane_1 = JScrollPane(self.extra_info_textarea1)
self.scrollPane_1.setAlignmentX(JScrollPane.LEFT_ALIGNMENT)
self.extra_info_label2 = JLabel("<html><b><font color='orange'>Header Description:</font></b></html>")
self.extra_info_label2.putClientProperty("html.disable", None)
#extra_info_label2 = JLabel("<html><b><font color='{}'>Header Description:</font></b></html>".format(self.color1))
self.extra_info_label2.setAlignmentX(JLabel.LEFT_ALIGNMENT)
self.extra_info_textarea2 = JTextArea("Description",rows=5, editable=False)
self.extra_info_textarea2.setLineWrap(True)
self.scrollPane_2 = JScrollPane(self.extra_info_textarea2)
self.scrollPane_2.setAlignmentX(JScrollPane.LEFT_ALIGNMENT)
self.extra_info_label3 = JLabel("<html><b><font color='orange'>Usage example:</font></b></html>")
self.extra_info_label3.putClientProperty("html.disable", None)
#extra_info_label3 = JLabel("<html><b><font color='{}'>Usage example:</font></b></html>".format(self.color1))
self.extra_info_label3.setAlignmentX(JLabel.LEFT_ALIGNMENT)
self.extra_info_textarea3 = JTextArea("Example",rows=3, editable=False)
self.extra_info_textarea3.setLineWrap(True)
self.scrollPane_3 = JScrollPane(self.extra_info_textarea3)
self.scrollPane_3.setAlignmentX(JScrollPane.LEFT_ALIGNMENT)
self.extra_info_label4 = JLabel("<html><b><font color='orange'>URL describing header:</font></b></html>")
self.extra_info_label4.putClientProperty("html.disable", None)
#extra_info_label4 = JLabel("<html><b><font color='{}'>URL describing header:</font></b></html>".format(self.color1))
self.extra_info_label4.setAlignmentX(JLabel.LEFT_ALIGNMENT)
self.extra_info_textarea4 = JTextArea("URL2",rows=2, editable=False)
self.extra_info_textarea4.setLineWrap(True)
self.scrollPane_4 = JScrollPane(self.extra_info_textarea4)
self.scrollPane_4.setAlignmentX(JScrollPane.LEFT_ALIGNMENT)
self.extra_info_label5 = JLabel("<html><b><font color='orange'>Potential risks associated with header:</font></b></html>")
self.extra_info_label5.putClientProperty("html.disable", None)
#extra_info_label5 = JLabel("<html><b><font color='{}'>Potential risks associated with header:</font></b></html>".format(self.color1))
self.extra_info_label5.setAlignmentX(JLabel.LEFT_ALIGNMENT)
self.extra_info_textarea5 = JTextArea("There are no potential risks associated with this header",rows=3, editable=False)
self.extra_info_textarea5.setLineWrap(True)
self.scrollPane_5 = JScrollPane(self.extra_info_textarea5)
self.scrollPane_5.setAlignmentX(JScrollPane.LEFT_ALIGNMENT)
for element in [self.extra_info_label1, self.scrollPane_1, self.extra_info_label2, self.scrollPane_2, self.extra_info_label3, self.scrollPane_3, self.extra_info_label4, self.scrollPane_4, self.extra_info_label5, self.scrollPane_5]:
self.extra_info_panel.add(element)
self.extra_info.add(self.extra_info_panel)
self.dict_req_headers = {}
self.req_headers_description = open('request_headers.txt','r')
for line in self.req_headers_description.readlines():
line_split = line.split('&&')
header_name = line_split[0]
header_description = line_split[1]
if header_description.rstrip() == '':
header_description = 'Description unavailable for header: ' + header_name
header_example = line_split[2]
if header_example.rstrip() == '':
header_example = 'Example unavailable for header: ' + header_name
header_url = line_split[3]
if header_url.rstrip() == '':
header_url = 'URL unavailable for header ' + header_name
header_risk = line_split[4]
if header_risk.rstrip() == '':
header_risk = 'Potential risks information unavailable for header ' + header_name
self.dict_req_headers[header_name] = (header_description, header_example, header_url, header_risk)
self.req_headers_description.close()
self.dict_resp_headers = {}
self.resp_headers_description = open('response_headers.txt','r')
for line in self.resp_headers_description.readlines():
line_split = line.split('&&')
header_name = line_split[0]
header_description = line_split[1]
if header_description.rstrip() == '':
header_description = 'Description unavailable for header: ' + header_name
header_example = line_split[2]
if header_example.rstrip() == '':
header_example = 'Example unavailable for header: ' + header_name
header_url = line_split[3]
if header_url.rstrip() == '':
header_url = 'URL unavailable for header ' + header_name
header_risk = line_split[4]
if header_risk.rstrip() == '':
header_risk = 'Potential risks information unavailable for header ' + header_name
self.dict_resp_headers[header_name] = (header_description, header_example, header_url, header_risk)
self.resp_headers_description.close()
def compile_regex(self):
"""Compile regular expressions that will be used later by the extension to match URL parameters"""
#matchea lo que haya entre = y & o entre = y ' ', para el ultimo parametro de la linea
self.query_params = re.compile('=.*?&|=.*? ')
# matchea numeros en la url tipo /asdf/1234/qwe/1234, matchearia los dos 1234 y secuencias de letras, numeros y guiones o puntos. igual algun caso raro se cuela, pero por lo que he visto pilla todo
self.number_between_forwardslash = re.compile('\/[a-zA-Z]*\d+[a-zA-Z0-9-_\.]*')
# match de <meta> headers
self.meta = re.compile('<meta .*?>')
def find_host(self, req_headers):
"""Given a request-response object, find the Host to which it was requested"""
for req_head in req_headers[1:]:
if 'Host: ' in req_head:
host = req_head.split(': ')[1]
break
return host
def restore_save_thresholds_func(self, event):
f = open('thresholds.txt', 'r')
thresholds = f.readlines()
f.close()
check_box_security_value = thresholds[0].split(' ')[0]
check_box_potentially_dangerous_value = thresholds[1].split(' ')[0]
check_box_dangerous_value = thresholds[2].split(' ')[0]
threshold_security_value = thresholds[0].split(' ')[1]
threshold_potentially_dangerous_value = thresholds[1].split(' ')[1]
threshold_dangerous_value = thresholds[2].split(' ')[1]
security_checkbox_state = True if check_box_security_value == '1' else False
potentially_dangerous_checkbox_state = True if check_box_potentially_dangerous_value == '1' else False
dangerous_checkbox_state = True if check_box_dangerous_value == '1' else False
self.check_box_security.setSelected(security_checkbox_state)
self.check_box_potentially_dangerous.setSelected(potentially_dangerous_checkbox_state)
self.check_box_dangerous.setSelected(dangerous_checkbox_state)
self.threshold_count_security.setText(threshold_security_value)
self.threshold_count_potentially_dangerous.setText(threshold_potentially_dangerous_value)
self.threshold_count_dangerous.setText(threshold_dangerous_value)
def save_threshold_config_func(self, event):
f = open('thresholds.txt', 'w')
selected_security = '1' if self.check_box_security.isSelected() == True else '0'
selected_potentially_dangerous = '1' if self.check_box_potentially_dangerous.isSelected() == True else '0'
selected_dangerous = '1' if self.check_box_dangerous.isSelected() == True else '0'
f.write(selected_security + ' ' + self.threshold_count_security.getText() + '\n')
f.write(selected_potentially_dangerous + ' ' + self.threshold_count_potentially_dangerous.getText() + '\n')
f.write(selected_dangerous + ' ' + self.threshold_count_dangerous.getText())
f.close()
return
def reset_threshold_config_func(self, event):
self.threshold_count_security.setText(str(self.initial_count_security_headers))
self.threshold_count_potentially_dangerous.setText("{}".format(self.initial_count_potentially_dangerous_headers))
self.threshold_count_dangerous.setText("{}".format(self.initial_count_dangerous_headers))
self.check_box_security.setSelected(False)
self.check_box_dangerous.setSelected(False)
self.check_box_potentially_dangerous.setSelected(False)
return
def create_advanced_config_frame(self):
self.advanced_config_panel = JFrame("Advanced configuration")
self.advanced_config_panel.setLayout(BorderLayout())
self.advanced_config_panel.toFront()
self.advanced_config_panel.setAlwaysOnTop(True)
self.advanced_config_panel.setSize(800, 600)
self.advanced_config_panel.setLocationRelativeTo(None)
# --------------------- Theme selection ------------------------#
self.theme_model = DefaultComboBoxModel()
self.theme_model.addElement("Dark")
self.theme_model.addElement("Light")
theme_selector = JComboBox(self.theme_model)
# ----------------------------------------------------------------#
# --------------------- Headers selection ------------------------#
self.table_config_security = []
self.table_config_potentially_dangerous = []
self.table_config_dangerous = []
self.table_config_cookie_flags = []
f = open('security_headers.txt','r')
for line in f.readlines():
active = line.split(' ')[0]
if active == '1':
self.table_config_security.append([True, line.split(' ')[1].strip('\n')])
else:
self.table_config_security.append([False, line.split(' ')[1].strip('\n')])
f.close()
f = open('potentially_dangerous_headers.txt','r')
for line in f.readlines():
active = line.split(' ')[0]
if active == '1':
self.table_config_potentially_dangerous.append([True, line.split(' ')[1].strip('\n')])
else:
self.table_config_potentially_dangerous.append([False, line.split(' ')[1].strip('\n')])
f.close()
f = open('dangerous_headers.txt','r')
for line in f.readlines():
active = line.split(' ')[0]
if active == '1':
self.table_config_dangerous.append([True, line.split(' ')[1].strip('\n')])
else:
self.table_config_dangerous.append([False, line.split(' ')[1].strip('\n')])
f.close()
f = open('cookie_flags.txt','r')
for line in f.readlines():
active = line.split(' ')[0]
if active == '1':
self.table_config_cookie_flags.append([True, line.split(' ')[1].strip('\n')])
else:
self.table_config_cookie_flags.append([False, line.split(' ')[1].strip('\n')])
f.close()
self.config_column_names = ("Use?", "Header name")
self.config_column_names_flags = ("Use?", "Flag name")
self.model_tab_config_security = ConfigTableModel(self.table_config_security, self.config_column_names)
self.table_tab_config_security = JTable(self.model_tab_config_security)
self.model_tab_config_potentially_dangerous = ConfigTableModel(self.table_config_potentially_dangerous, self.config_column_names)
self.table_tab_config_potentially_dangerous = JTable(self.model_tab_config_potentially_dangerous)
self.model_tab_config_dangerous = ConfigTableModel(self.table_config_dangerous, self.config_column_names)
self.table_tab_config_dangerous = JTable(self.model_tab_config_dangerous)
self.model_tab_config_cookie_flags = ConfigTableModel(self.table_config_cookie_flags, self.config_column_names_flags)
self.table_tab_config_cookie_flags = JTable(self.model_tab_config_cookie_flags)
self.table_tab_config_security.getColumnModel().getColumn(0).setMaxWidth(50)
self.table_tab_config_security.getColumnModel().getColumn(1).setPreferredWidth(400)
self.table_tab_config_potentially_dangerous.getColumnModel().getColumn(0).setMaxWidth(50)
self.table_tab_config_potentially_dangerous.getColumnModel().getColumn(1).setPreferredWidth(400)
self.table_tab_config_dangerous.getColumnModel().getColumn(0).setMaxWidth(50)
self.table_tab_config_dangerous.getColumnModel().getColumn(1).setPreferredWidth(400)
self.table_tab_config_cookie_flags.getColumnModel().getColumn(0).setMaxWidth(50)
self.table_tab_config_cookie_flags.getColumnModel().getColumn(1).setPreferredWidth(400)
c = GridBagConstraints()
c.fill = GridBagConstraints.HORIZONTAL
security_headers_tab = JPanel(GridBagLayout())
security_headers_tab.add(JScrollPane(self.table_tab_config_security), c)
dangerous_headers_tab = JPanel(GridBagLayout())
dangerous_headers_tab.add(JScrollPane(self.table_tab_config_dangerous), c)
dangerous_headers_tab = JPanel(GridBagLayout())
dangerous_headers_tab.add(JScrollPane(self.table_tab_config_cookie_flags), c)
potentially_dangerous_headers_tab = JPanel(GridBagLayout())
potentially_dangerous_headers_tab.add(JScrollPane(self.table_tab_config_potentially_dangerous), c)
# ----------------------------------------------------------------#
# ------------------ Add contents to main tabs -------------------#
aux_panel = JPanel(BorderLayout())
theme_panel = JPanel(GridBagLayout())
# Add buttons at the bottom inside a panel
add_header_to_category_button = JButton("<html><b>Add header to category</b></html>", actionPerformed = self.add_headers_to_categories)
add_header_to_category_button.putClientProperty("html.disable", None)
add_header_to_category_button.setForeground(Color.WHITE)
add_header_to_category_button.setBackground(Color(10,101,247))
remove_header_from_category_button = JButton("<html><b>Remove header from category</b></html>", actionPerformed = self.remove_headers_from_categories)
remove_header_from_category_button.putClientProperty("html.disable", None)
remove_header_from_category_button.setForeground(Color.WHITE)
remove_header_from_category_button.setBackground(Color(210,101,47))#Color(10,101,247)) Color(210,101,47)
make_curr_selection_permanent_button = JButton("<html><b>Apply changes</b></html>", actionPerformed = self.make_chosen_headers_permanent)
make_curr_selection_permanent_button.putClientProperty("html.disable", None)
make_curr_selection_permanent_button.setForeground(Color.WHITE)
make_curr_selection_permanent_button.setBackground(Color(10,101,247))
button_panel = JPanel(GridBagLayout())
e = GridBagConstraints()
e.fill = GridBagConstraints.HORIZONTAL
e.gridx = 0
e.weightx = 1
e.gridy = 0
button_panel.add(add_header_to_category_button, e)
e.gridx += 1
button_panel.add(remove_header_from_category_button, e)
e.gridx += 1
button_panel.add(make_curr_selection_permanent_button, e)
# Fill the tables for each category
self.categories_tabs = JTabbedPane()
self.categories_tabs.add("Security headers", JScrollPane(self.table_tab_config_security))
self.categories_tabs.add("Potentially dangerous headers", JScrollPane(self.table_tab_config_potentially_dangerous))
self.categories_tabs.add("Dangerous headers", JScrollPane(self.table_tab_config_dangerous))
self.categories_tabs.add("Cookie Flags", JScrollPane(self.table_tab_config_cookie_flags))
aux_panel.add(self.categories_tabs, BorderLayout.CENTER)
aux_panel.add(button_panel, BorderLayout.SOUTH)
#--------------- threshold panel ---------------------
threshold_panel = JPanel(GridBagLayout())
c = GridBagConstraints()
c.anchor = GridBagConstraints.WEST
c.gridx = 0
c.gridy = 0
c.weightx = 1
c.fill = GridBagConstraints.HORIZONTAL
threshold_panel.add(JLabel("Use threshold for Security headers?"), c)
c.gridy += 1
threshold_panel.add(JLabel("Use threshold for Potentially Dangerous headers?"), c)
c.gridy += 1
threshold_panel.add(JLabel("Use threshold for Dangerous headers?"), c)
c.gridx = 1
c.gridy = 0
self.check_box_security = JCheckBox()
threshold_panel.add(self.check_box_security, c)
c.gridy += 1
self.check_box_potentially_dangerous = JCheckBox()
threshold_panel.add(self.check_box_potentially_dangerous, c)
c.gridy += 1
self.check_box_dangerous = JCheckBox()
threshold_panel.add(self.check_box_dangerous, c)
c.gridx = 2
c.gridy = 0
self.threshold_count_security = JTextField("{}".format(len(self.table_config_security)))
threshold_panel.add(self.threshold_count_security, c)
c.gridy += 1
self.threshold_count_potentially_dangerous = JTextField("{}".format(len(self.table_config_potentially_dangerous)))
threshold_panel.add(self.threshold_count_potentially_dangerous, c)
c.gridy += 1
self.threshold_count_dangerous = JTextField("{}".format(len(self.table_config_dangerous)))
threshold_panel.add(self.threshold_count_dangerous, c)
c.gridx = 0
c.gridy += 1
save_threshold_config = JButton("Save thresholds", actionPerformed = self.save_threshold_config_func)
threshold_panel.add(save_threshold_config, c)
c.gridx += 1
restore_threshold_config = JButton("Restore saved thresholds", actionPerformed = self.restore_save_thresholds_func)
threshold_panel.add(restore_threshold_config, c)
c.gridx += 1
reset_threshold_config = JButton("Reset to default", actionPerformed = self.reset_threshold_config_func)
threshold_panel.add(reset_threshold_config, c)
# Theme panel contents
d = GridBagConstraints()
d.fill = GridBagConstraints.HORIZONTAL
d.gridx = 0
d.gridy = 0
theme_panel.add(JLabel("If you use Burp's dark theme, you will probably see better this extension by selecting 'dark', and vice versa."), d)
d.gridy += 1
theme_panel.add(theme_selector, d)
# add the main tabs
self.main_tabs = JTabbedPane()
self.main_tabs.addTab('Configure headers criteria', aux_panel)
self.main_tabs.addTab('Configure thresholds', threshold_panel)
self.main_tabs.addTab('Theme', theme_panel)
self.advanced_config_panel.add(self.main_tabs, BorderLayout.CENTER)
# ----------------------------------------------------------------#
return
def show_advanced_config(self, event):
"""Show the advanced configuration window when clicking the gear button"""
self.advanced_config_panel.setVisible(True)
def get_categories_headers_length(self):
""" Get how many headers are in each category when the extension is loaded. Used in read_headers()
to tell it how many times it must loop to generate arrays of each category of headers"""
f = open('security_headers.txt','r')
# the filter in the next line removes all occurences of '', i.e. doesnt consider empty lines for counting the number of headers
self.initial_count_security_headers = len(list(filter(('').__ne__, f.readlines())))
#self.initial_count_security_headers = len(f.readlines())
f.close()
f = open('dangerous_headers.txt','r')
self.initial_count_dangerous_headers= len(list(filter(('').__ne__, f.readlines())))
#self.initial_count_dangerous_headers= len(f.readlines())
f.close()
f = open('potentially_dangerous_headers.txt','r')
self.initial_count_potentially_dangerous_headers = len(list(filter(('').__ne__, f.readlines())))
#self.initial_count_potentially_dangerous_headers = len(f.readlines())
f.close()
f = open('cookie_flags.txt','r')
self.initial_count_cookie_flags = len(list(filter(('').__ne__, f.readlines())))
#self.initial_count_dangerous_headers= len(f.readlines())
f.close()
def check_python_modules(self, event):
# subprocess que guarde en una variable output de python -c import ...
python_path = self.python_path_textfield.getText()
os_type = sys.platform.getshadow()
win_python_command = "py --version"
linux_python_command = 'python3 --version'
win_python_command = 'py docx.py'
if 'win' in os_type:
#proc = subprocess.Popen(win_python_command, stdout=subprocess.PIPE)
if python_path != '':
proc = subprocess.Popen("{} --version".format(python_path), stdout=subprocess.PIPE)
else:
proc = subprocess.Popen(["py","--version"], stdout=subprocess.PIPE)
elif 'linux' in os_type:
#proc = subprocess.Popen(linux_python_command, stdout=subprocess.PIPE)
if python_path != '':
proc = subprocess.Popen(["{}".format(python_path),"--version"], stdout=subprocess.PIPE)
else:
proc = subprocess.Popen(["python3","--version"], stdout=subprocess.PIPE)
else:
raise("Error identifying operating system type. Provide path to Python3 binary.")
if 'docxtpl' not in sys.modules.keys():
os.system('pip install docxtpl')
if python_path != '':
docxtpl_version = subprocess.Popen(["{}".format(python_path),"-c","import docxtpl; print('Docxtpl version:',docxtpl.__version__)"],stdout=subprocess.PIPE)
else:
docxtpl_version = subprocess.Popen(["python3","-c","import docxtpl; print('Docxtpl version:',docxtpl.__version__)"],stdout=subprocess.PIPE)
print(python_path)
output = proc.stdout.read()
self.python_msg.setText(output.strip('\r\n') + '; ' + docxtpl_version.stdout.read())
def create_docx_frame(self):
self.docx_frame = JFrame("Configure .docx report")
self.docx_frame.setLayout(GridBagLayout())
self.docx_frame.setAlwaysOnTop(True)
self.docx_frame.setSize(800, 600)
self.docx_frame.setLocationRelativeTo(None)
self.docx_frame.toFront()
self.docx_frame.setAlwaysOnTop(True)
c = GridBagConstraints()
c.gridx = 0
c.weightx = 0
c.gridy = 0
self.docx_frame.add(JLabel('Make sure your Python3 installation runs on windows by typing "py" on Powershell or python3 or bash\n'), c)
c.gridy += 1
self.docx_frame.add(JLabel('If your python executable is in a custom path, please write it in the next textbox'), c)
c.gridy += 1
c.weightx = 1
c.fill = GridBagConstraints.HORIZONTAL
self.python_path_textfield = JTextField()
self.docx_frame.add(self.python_path_textfield, c)
c.gridy += 1
self.docx_frame.add(JLabel(' '))
self.check_python_docx_modules = JButton("Check docx modules", actionPerformed = self.check_python_modules)
self.docx_frame.add(self.check_python_docx_modules, c)
c.gridy += 1
self.export_docx = JButton("Export docx", actionPerformed = self.output_selected_summary)
self.docx_frame.add(self.check_python_docx_modules, c)
c.gridy += 1
self.python_msg = JTextArea()
self.docx_frame.add(self.python_msg, c)
def registerExtenderCallbacks(self, callbacks):
"""Import Burp Extender callbacks and execute some preliminary functions for setting up the extension when it's loaded with proper configurations"""
self._callbacks = callbacks
self._helpers = callbacks.helpers
callbacks.setExtensionName("Headers")
callbacks.registerContextMenuFactory(self)
callbacks.addSuiteTab(self)
self.req_header_dict = {}
self.resp_header_dict = {}
self.for_table = [] # Items in this table will be shown in the Header-Host table (left side of the screen) for Requests and Responses headers
self.header_host_table = [] # This holds data in three columns with Headers, Unique headers and Hosts and it's used for saving data to a file
self.for_req_table = []