/
Exporter.py
1889 lines (1586 loc) · 68.7 KB
/
Exporter.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
"""
__ ___ __ __ ___ __
/\ |__) | /__` /__` |__ / `
/~~\ | \ | .__/ .__/ |___ \__,
Security without imagination is a vulnerability.
Author: ArtsSEC
Site: https://artssec.com
Title: Burp Suite exporter extension
About: Exporter is a Burp Suite extension to copy a request to a file or the clipboard as multiple programming languages functions.
Version: 1.0
Changelog:
1.0: Added a tab called Exporter, where you can search and filter URLs, also export from there to a file or copy to the clipboard.
0.5: Added more snippets.
0.2: Add python-readable exceptions. Thanks @securityMB
0.1: First public version
"""
from burp import IBurpExtender, IContextMenuFactory, ITab
from burp import IMessageEditorController
from burp import IHttpListener
from java.awt.event import ActionListener
from java.io import PrintWriter
from java.util import ArrayList
from javax.swing.event import ChangeListener
from javax.swing import JScrollPane
from javax.swing import JSplitPane
from javax.swing import JTabbedPane
from javax.swing import JTable
from javax.swing import JButton
from javax.swing import JTextArea
from javax.swing import JTextField
from javax.swing import JLabel
from javax.swing import JComboBox
from javax.swing.table import AbstractTableModel
from threading import Lock
from javax.swing import JMenuItem, JMenu, JFileChooser, JPanel
from java.awt.datatransfer import StringSelection
from java.lang import UnsupportedOperationException
from java.awt import Toolkit
from java.awt import Color
import json
# python-readable exceptions
# Original code: https://raw.githubusercontent.com/securityMB/burp-exceptions/master/exceptions_fix.py
# Burp Exceptions Fix magic code
import sys
import functools
import inspect
import traceback
def decorate_function(original_function):
@functools.wraps(original_function)
def decorated_function(*args, **kwargs):
try:
return original_function(*args, **kwargs)
except Exception:
sys.stdout.write('\n\n*** PYTHON EXCEPTION\n')
traceback.print_exc(file=sys.stdout)
raise
return decorated_function
def FixBurpExceptionsForClass(cls):
for name, method in inspect.getmembers(cls, inspect.ismethod):
setattr(cls, name, decorate_function(method))
return cls
def FixBurpExceptions():
for name, cls in inspect.getmembers(sys.modules['__main__'], predicate=inspect.isclass):
FixBurpExceptionsForClass(cls)
class BurpExtender(IBurpExtender, IContextMenuFactory, ITab, AbstractTableModel, IMessageEditorController, IHttpListener):
def registerExtenderCallbacks(self, callbacks):
self._stdout = PrintWriter(callbacks.getStdout(), True)
self._callbacks = callbacks
self._helpers = callbacks.getHelpers()
self._callbacks.setExtensionName("Exporter")
self._callbacks.registerContextMenuFactory(self)
self.mainpanel = JPanel()
self.mainpanel.setLayout(None)
self._log = ArrayList()
self._lock = Lock()
self._splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT)
toCopyPaneBtns = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
clipboardBtn = JButton("Exporter to clipboard", actionPerformed=self.snippetToClipboard)
fileBtn = JButton("Exporter to file", actionPerformed=self.snippetToFile)
clipboardBtn.setEnabled(False)
fileBtn.setEnabled(False)
self.clipboardBtn = clipboardBtn
self.fileBtn = fileBtn
toCopyPaneBtns.setRightComponent(clipboardBtn)
toCopyPaneBtns.setLeftComponent(fileBtn)
toCopyPane = JSplitPane(JSplitPane.VERTICAL_SPLIT)
snippetCode = JTextArea()
self.snippetCode = snippetCode
snippetCodeScrollable = JScrollPane(snippetCode)
toCopyPane.setRightComponent(toCopyPaneBtns)
toCopyPane.setLeftComponent(snippetCodeScrollable)
toCopyPaneCombo = JSplitPane(JSplitPane.VERTICAL_SPLIT)
snippetLanCombo = JComboBox()
snippetLanCombo.addItem(self.ComboboxItem('0', 'Code snippets'))
snippetLanCombo.addItem(self.ComboboxItem('1', 'cURL'))
snippetLanCombo.addItem(self.ComboboxItem('2', 'Wget'))
snippetLanCombo.addItem(self.ComboboxItem('3', 'Python Request'))
snippetLanCombo.addItem(self.ComboboxItem('4', 'Perl LWP'))
snippetLanCombo.addItem(self.ComboboxItem('5', 'PHP HTTP_Request2'))
snippetLanCombo.addItem(self.ComboboxItem('6', 'GO Native'))
snippetLanCombo.addItem(self.ComboboxItem('7', 'NodeJS Request'))
snippetLanCombo.addItem(self.ComboboxItem('8', 'jQuery AJAX'))
snippetLanCombo.addItem(self.ComboboxItem('9', 'PowerShell'))
snippetLanCombo.addItem(self.ComboboxItem('10', 'HTML Forms'))
snippetLanCombo.addItem(self.ComboboxItem('11', 'Ruby Net::HTTP'))
snippetLanCombo.addItem(self.ComboboxItem('12', 'Javascript XHR'))
snippetLanCombo.addActionListener(self.ComboboxListener(self, "snippet"))
snippetLanCombo.setEnabled(False)
self.snippetLanCombo = snippetLanCombo
toCopyPaneCombo.setRightComponent(toCopyPane)
toCopyPaneCombo.setLeftComponent(snippetLanCombo)
toCopyPane.setResizeWeight(0.99)
search = JLabel('Filter:')
text = JTextField()
self.filterText = text
self.filterText.addActionListener(self.FilterTextListener(self, "enter"))
searchText = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
searchText.setLeftComponent(search)
searchText.setRightComponent(text)
searchButtons = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
searchBtn = JButton("Search!", actionPerformed=self.searchLogs)
resetBtn = JButton("Reset", actionPerformed=self.resetSearchLogs)
searchButtons.setRightComponent(resetBtn)
searchButtons.setLeftComponent(searchBtn)
searchButtons.setResizeWeight(0.5)
searchPane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
searchPane.setLeftComponent(searchText)
searchPane.setRightComponent(searchButtons)
searchPane.setResizeWeight(0.9)
logTable = Table(self)
logTablePane = JScrollPane(logTable)
logTableSearch = JSplitPane(JSplitPane.VERTICAL_SPLIT)
logTableSearch.setLeftComponent(searchPane)
logTableSearch.setRightComponent(logTablePane)
scrollPane = JScrollPane(logTableSearch)
self.logTable = logTable
splitpaneMain = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
splitpaneMain.setLeftComponent(scrollPane)
splitpaneMain.setRightComponent(toCopyPaneCombo)
splitpaneMain.setResizeWeight(0.5)
tabs = JTabbedPane()
self._requestViewer = callbacks.createMessageEditor(self, False)
self._responseViewer = callbacks.createMessageEditor(self, False)
tabs.addTab("Request", self._requestViewer.getComponent())
tabs.addTab("Response", self._responseViewer.getComponent())
self._splitpane.setLeftComponent(splitpaneMain)
self._splitpane.setRightComponent(tabs)
self._splitpane.setResizeWeight(0.7)
callbacks.customizeUiComponent(self._splitpane)
callbacks.customizeUiComponent(logTable)
callbacks.customizeUiComponent(scrollPane)
callbacks.customizeUiComponent(tabs)
callbacks.addSuiteTab(self)
return
def filterResults(self, text):
if text == None: # noqa
self._log = self._partialLog if len(self._partialLog) > 0 else self._log
else:
self._partialLog = self._log.clone()
self._lock.acquire()
self._log.clear()
self._lock.release()
for log in self._partialLog:
if text in log._requestResponse.request.tostring().decode('utf-8', 'replace'):
self._lock.acquire()
row = self._log.size()
self._log.add(log)
self.fireTableRowsInserted(row, row)
self._lock.release()
self.logTable.updateUI()
def searchLogs(self, event):
text = self.filterText.getText()
self.filterResults(text)
def resetSearchLogs(self, event):
self.filterResults(None)
self.filterText.setText('')
def snippetToClipboard(self, event):
to_copy = self.snippetCode.getText()
self.saveToClipboard(to_copy)
def snippetToFile(self, event):
to_copy = self.snippetCode.getText()
self.saveToFile(to_copy)
class ComboboxItem:
def __init__(self, key, val):
self._key = key
self._val = val
def get_key(self):
return self._key
# Set label inside ComboBox
def __repr__(self):
return self._val
class TabListener(ChangeListener):
def __init__(self, extender, name):
self.extender = extender
self.name = name
def stateChanged(self, action_event):
try:
self.extender.setFocus(False)
except Exception:
pass
class FilterTextListener(ActionListener):
def __init__(self, extender, name):
self.extender = extender
self.name = name
def actionPerformed(self, action_event):
self.extender.searchLogs(action_event)
class ComboboxListener(ActionListener):
def __init__(self, extender, name):
self.extender = extender
self.name = name
def possibleActions(self, code):
actions = {
'1': self.extender.asCURL,
'2': self.extender.asWget,
'3': self.extender.asPythonRequest,
'4': self.extender.asPerl,
'5': self.extender.asPHPRequest,
'6': self.extender.asGO,
'7': self.extender.asNodeJSRequest,
'8': self.extender.asJQueryAjax,
'9': self.extender.asPowerShell,
'10': self.extender.asHTMLForm,
'11': self.extender.asRuby,
'12': self.extender.asXHR
}
return actions.get(code)
def clearSnippetCode(self):
self.extender.snippetCode.setText('')
self.extender.clipboardBtn.setEnabled(False)
self.extender.fileBtn.setEnabled(False)
def actionPerformed(self, action_event):
selected = self.extender.snippetLanCombo.getSelectedItem().get_key()
self.extender.clipboardBtn.setEnabled(True)
self.extender.fileBtn.setEnabled(True)
snippet = self.possibleActions(selected)
if snippet:
self.extender.snippetCode.setText(snippet('n/a'))
else:
self.clearSnippetCode()
def getTabCaption(self):
return "Exporter"
def getUiComponent(self):
return self._splitpane
def getRowCount(self):
try:
return self._log.size()
except Exception:
return 0
def getColumnCount(self):
return 4
def getColumnName(self, columnIndex):
if columnIndex == 0:
return "#"
if columnIndex == 1:
return "URL"
if columnIndex == 2:
return "Method"
if columnIndex == 3:
return "Status"
return ""
def getValueAt(self, rowIndex, columnIndex):
logEntry = self._log.get(rowIndex)
if columnIndex == 0:
return rowIndex
if columnIndex == 1:
return logEntry._url.toString()
if columnIndex == 2:
return str(logEntry._method)
if columnIndex == 3:
return str(logEntry._status)
return ""
def setFocus(self, enabled):
'''
:param Boolean enabled: True if focus else False
'''
pane = self.getUiComponent().getParent()
if enabled:
color = Color.decode('0xff6633')
pane.addChangeListener(self.TabListener(self, "tab"))
else:
color = Color.BLACK
pane.removeChangeListener(pane.getChangeListeners()[0])
exporter_pane_idx = [i for i in range(0, pane.getTabCount()) if pane.getTitleAt(i) == self.getTabCaption()]
exporter_pane_idx = exporter_pane_idx[0] if exporter_pane_idx else None
pane.setBackgroundAt(exporter_pane_idx, color)
def sendToExporter(self, event):
self.setFocus(True)
if self._context.getSelectedMessages()[0].getRequest():
messageInfo = self._context.getSelectedMessages()[0]
self._lock.acquire()
row = self._log.size()
self._log.add(LogEntry(1, self._callbacks.saveBuffersToTempFiles(messageInfo), self._helpers.analyzeRequest(messageInfo).getUrl(), self._helpers.analyzeRequest(messageInfo).method, messageInfo.getStatusCode()))
self.fireTableRowsInserted(row, row)
self._lock.release()
return
def getHttpService(self):
return self._currentlyDisplayedItem.getHttpService()
def getRequest(self):
return self._currentlyDisplayedItem.getRequest()
def getResponse(self):
return self._currentlyDisplayedItem.getResponse()
def createMenuItems(self, invocation):
self._context = invocation
menuList = ArrayList()
invocation_allowed = [invocation.CONTEXT_MESSAGE_EDITOR_REQUEST, invocation.CONTEXT_PROXY_HISTORY,
invocation.CONTEXT_TARGET_SITE_MAP_TABLE, invocation.CONTEXT_TARGET_SITE_MAP_TREE,
invocation.CONTEXT_MESSAGE_VIEWER_REQUEST, invocation.CONTEXT_INTRUDER_ATTACK_RESULTS,
invocation.CONTEXT_INTRUDER_PAYLOAD_POSITIONS, invocation.CONTEXT_SCANNER_RESULTS,
invocation.CONTEXT_SEARCH_RESULTS]
if self._context.getInvocationContext() in invocation_allowed and len(self._context.selectedMessages) == 1:
parentMenu = JMenu('Exporter to')
menuItemClipboard = JMenu("To clipboard")
menuItemFile = JMenu("To file")
menuItemPythonRequest = JMenuItem("Python Request", actionPerformed=self.asPythonRequest, actionCommand="file")
menuItemCURL = JMenuItem("cURL", actionPerformed=self.asCURL, actionCommand="file")
menuItemWget = JMenuItem("Wget", actionPerformed=self.asWget, actionCommand="file")
menuItemPhpRequest = JMenuItem("PHP HTTP_Request2", actionPerformed=self.asPHPRequest, actionCommand="file")
menuItemGo = JMenuItem("GO Native", actionPerformed=self.asGO, actionCommand="file")
menuItemNodeRequest = JMenuItem("NodeJS Request", actionPerformed=self.asNodeJSRequest, actionCommand="file")
menuItemJQueryAjax = JMenuItem("jQuery AJAX", actionPerformed=self.asJQueryAjax, actionCommand="file")
menuItemPowerShell = JMenuItem("PowerShell", actionPerformed=self.asPowerShell, actionCommand="file")
menuItemPerl = JMenuItem("Perl LWP", actionPerformed=self.asPerl, actionCommand="file")
menuItemHTML = JMenuItem("HTML Forms", actionPerformed=self.asHTMLForm, actionCommand="file")
menuItemRuby = JMenuItem("Ruby - Net::HTTP", actionPerformed=self.asRuby, actionCommand="file")
menuItemXHR = JMenuItem("Javascript - XHR", actionPerformed=self.asXHR, actionCommand="file")
parentMenu.add(menuItemFile)
parentMenu.add(menuItemClipboard)
menuItemFile.add(menuItemCURL)
menuItemFile.add(menuItemWget)
menuItemFile.add(menuItemPythonRequest)
menuItemFile.add(menuItemPerl)
menuItemFile.add(menuItemPhpRequest)
menuItemFile.add(menuItemGo)
menuItemFile.add(menuItemNodeRequest)
menuItemFile.add(menuItemJQueryAjax)
menuItemFile.add(menuItemPowerShell)
menuItemFile.add(menuItemHTML)
menuItemFile.add(menuItemRuby)
menuItemFile.add(menuItemXHR)
menuItemPythonRequest = JMenuItem("Python Request", actionPerformed=self.asPythonRequest, actionCommand="clipboard")
menuItemCURL = JMenuItem("cURL", actionPerformed=self.asCURL, actionCommand="clipboard")
menuItemWget = JMenuItem("Wget", actionPerformed=self.asWget, actionCommand="clipboard")
menuItemPhpRequest = JMenuItem("PHP HTTP_Request2", actionPerformed=self.asPHPRequest, actionCommand="clipboard")
menuItemGo = JMenuItem("GO Native", actionPerformed=self.asGO, actionCommand="clipboard")
menuItemNodeRequest = JMenuItem("NodeJS Request", actionPerformed=self.asNodeJSRequest, actionCommand="clipboard")
menuItemJQueryAjax = JMenuItem("jQuery AJAX", actionPerformed=self.asJQueryAjax, actionCommand="clipboard")
menuItemPowerShell = JMenuItem("PowerShell", actionPerformed=self.asPowerShell, actionCommand="clipboard")
menuItemPerl = JMenuItem("Perl LWP", actionPerformed=self.asPerl, actionCommand="clipboard")
menuItemHTML = JMenuItem("HTML Forms", actionPerformed=self.asHTMLForm, actionCommand="clipboard")
menuItemRuby = JMenuItem("Ruby - Net::HTTP", actionPerformed=self.asRuby, actionCommand="clipboard")
menuItemXHR= JMenuItem("Javascript - XHR", actionPerformed=self.asXHR, actionCommand="clipboard")
menuItemClipboard.add(menuItemCURL)
menuItemClipboard.add(menuItemWget)
menuItemClipboard.add(menuItemPythonRequest)
menuItemClipboard.add(menuItemPerl)
menuItemClipboard.add(menuItemPhpRequest)
menuItemClipboard.add(menuItemGo)
menuItemClipboard.add(menuItemNodeRequest)
menuItemClipboard.add(menuItemJQueryAjax)
menuItemClipboard.add(menuItemPowerShell)
menuItemClipboard.add(menuItemHTML)
menuItemClipboard.add(menuItemRuby)
menuItemClipboard.add(menuItemXHR)
menuList.add(parentMenu)
menuItemSendToExporter = JMenuItem("Send to Exporter", actionPerformed=self.sendToExporter)
menuList.add(menuItemSendToExporter)
# Request info
iRequestInfo = self._helpers.analyzeRequest(self._context.getSelectedMessages()[0])
self.setData(iRequestInfo)
return menuList
def setPayload(self, iRequestInfo):
params_type = {
0: 'url',
1: 'body',
2: 'cookie',
3: 'xml',
4: 'xml_attr',
5: 'multipart_attr',
6: 'json'
}
if self.contentType == iRequestInfo.CONTENT_TYPE_MULTIPART:
params = {i.name: i.value for i in iRequestInfo.getParameters() if params_type[i.getType()] == "body"}
self.payload = params
elif self.contentType == iRequestInfo.CONTENT_TYPE_JSON:
self.payload = str({str(i.name): str(i.value) for i in self.parameters})
elif self.contentType == iRequestInfo.CONTENT_TYPE_XML:
self.payload = "<?" + str(self._context.getSelectedMessages()[0].request.tostring().split("<?")[1])
else:
pass
def setData(self, iRequestInfo):
self.headers = iRequestInfo.getHeaders()
self.parameters = iRequestInfo.getParameters()
self.method = iRequestInfo.getMethod()
self.contentType = iRequestInfo.getContentType()
try:
self.url = iRequestInfo.getUrl().toString()
except UnsupportedOperationException:
host = [i for i in self.headers if 'Host' in i][0].split(" ")[1]
uri = [i for i in self.headers if self.method in i][0].split(' ')[1]
self.url = host + uri
self.url = 'http://' + self.url if '://' not in self.url else self.url
self.setPayload(iRequestInfo)
def headersDict(self):
return dict(item.split(': ',1) for item in self.headers[1:])
def asPythonRequest_multipart(self, headers):
payload = self.payload
payload_list = list(payload.items())
payload.clear()
headers.pop(u'Content-Type')
for key, val in payload_list:
new_key = '"{}"'.format(key)
if len(val.split("\x00")) > 1:
payload[new_key] = 'open("<yourAwesomeFileHere>", "rb")'
else:
new_val = '"{}"'.format(val)
payload[new_key] = new_val
to_copy = '''# -*- coding: UTF-8 -*-
import requests
requests.packages.urllib3.disable_warnings()
url = "{url}"
payload = {payload}
headers = {headers}
response = requests.request("{method}", url, files=payload, headers=headers, verify=False)
print(response.text)'''.format(url=self.url, payload=payload, method=self.method, headers=json.dumps(headers, indent=4)) # noqa
return to_copy.replace("'", "")
def asPythonRequest_json(self, headers):
payload = self.payload.replace("\n", "").replace("\t", "").replace('"', '\\"')
to_copy = '''# -*- coding: UTF-8 -*-
import requests
requests.packages.urllib3.disable_warnings()
url = "{url}"
payload = '''"{payload}"'''
headers = {headers}
response = requests.request("{method}", url, data=payload, headers=headers, verify=False)
print(response.text)'''.format(url=self.url, payload=payload, method=self.method, headers=json.dumps(headers, indent=4)) # noqa
return to_copy
def asPythonRequest_none(self, headers):
to_copy = '''# -*- coding: UTF-8 -*-
import requests
requests.packages.urllib3.disable_warnings()
url = "{url}"
headers = {headers}
response = requests.request("{method}", url, headers=headers, verify=False)
print(response.text)'''.format(url=self.url, method=self.method, headers=json.dumps(headers, indent=4)) # noqa
return to_copy
def asPythonRequest_xml(self, headers):
payload = self.payload.replace("\n", "").replace("\t", "").replace('"', '\\"')
to_copy = '''# -*- coding: UTF-8 -*-
import requests
requests.packages.urllib3.disable_warnings()
url = "{url}"
payload = "{payload}"
headers = {headers}
response = requests.request("{method}", url, data=payload, headers=headers, verify=False)
print(response.text)'''.format(url=self.url, payload=payload, method=self.method, headers=json.dumps(headers, indent=4)) # noqa
return to_copy
def asPythonRequest(self, event):
if event == 'n/a':
iRequestInfo = self._helpers.analyzeRequest(self._exporter)
self.setData(iRequestInfo)
else:
iRequestInfo = self._helpers.analyzeRequest(self._context.getSelectedMessages()[0])
headers = self.headersDict()
if self.contentType == iRequestInfo.CONTENT_TYPE_MULTIPART:
to_copy = self.asPythonRequest_multipart(headers)
elif self.contentType == iRequestInfo.CONTENT_TYPE_JSON:
to_copy = self.asPythonRequest_json(headers)
elif self.contentType == iRequestInfo.CONTENT_TYPE_NONE:
to_copy = self.asPythonRequest_none(headers)
elif self.contentType == iRequestInfo.CONTENT_TYPE_XML:
to_copy = self.asPythonRequest_xml(headers)
else:
to_copy = "Not supported yet!"
if event == 'n/a':
return to_copy
elif event.getActionCommand() == 'clipboard':
# Copy to clipboard
self.saveToClipboard(to_copy)
else:
# Save file
self.saveToFile(to_copy)
def asCURL_multipart(self, headers, iRequestInfo):
headers.pop('Content-Length')
formatted_headers = ' \\\n'.join(["--header '" + i + ": " + headers.get(i) + "'" for i in headers])
formatted_data = []
for param in iRequestInfo.getParameters():
if len(param.value.split("\x00")) > 1:
data = '''--form "{name}=@myAwesomeFile"'''.format(name=param.name)
else:
data = '''--form "{name}='{value}'"'''.format(name=param.name, value=param.value)
formatted_data.append(data)
raw_binary = ' \\\n'.join(formatted_data)
to_copy = "curl -i -s -k --location --request {method} '{url}' \\\n{headers} \\\n{payload}".format(method=self.method, url=self.url, headers=formatted_headers, payload=raw_binary) # noqa
return to_copy
def asCURL(self, event):
if event == 'n/a':
iRequestInfo = self._helpers.analyzeRequest(self._exporter)
self.setData(iRequestInfo)
else:
iRequestInfo = self._helpers.analyzeRequest(self._context.getSelectedMessages()[0])
headers = self.headersDict()
formatted_headers = ' \\\n'.join(["--header '" + i + ": " + headers.get(i) + "'" for i in headers])
if self.contentType == iRequestInfo.CONTENT_TYPE_MULTIPART:
to_copy = self.asCURL_multipart(headers, iRequestInfo)
elif self.contentType == iRequestInfo.CONTENT_TYPE_JSON:
to_copy = "curl -i -s -k --location --request {method} '{url}' \\\n{headers} \\\n--data-raw '{payload}'".format(method=self.method, url=self.url, headers=formatted_headers, payload=self.payload) # noqa
elif self.contentType == iRequestInfo.CONTENT_TYPE_NONE:
to_copy = "curl -i -s -k --location --request {method} '{url}' \\\n{headers} \\\n".format(method=self.method, url=self.url, headers=formatted_headers) # noqa
elif self.contentType == iRequestInfo.CONTENT_TYPE_XML:
to_copy = "curl -i -s -k --location --request {method} '{url}' \\\n{headers} \\\n--data-raw '{payload}'".format(method=self.method, url=self.url, headers=formatted_headers, payload=self.payload) # noqa
else:
to_copy = "Not supported yet!"
if event == 'n/a':
return to_copy
elif event.getActionCommand() == 'clipboard':
# Copy to clipboard
self.saveToClipboard(to_copy)
else:
# Save file
self.saveToFile(to_copy)
def asWget_multipart(self, formatted_headers, iRequestInfo):
formatted_data = []
for param in iRequestInfo.getParameters():
if len(param.value.split("\x00")) > 1:
data = '''--post-data "{name}=@myAwesomeFile"'''.format(name=param.name)
else:
data = '''--post-data "{name}='{value}'"'''.format(name=param.name, value=param.value)
formatted_data.append(data)
raw_binary = ' \\\n'.join(formatted_data)
to_copy = '''wget --no-check-certificate --quiet -S \\\n--method {method} --timeout=0 \\\n{payload} \\\n{headers} \\\n{url}'''.format(url=self.url, payload=raw_binary, method=self.method, headers=formatted_headers) # noqa
return to_copy
def asWget_json(self, formatted_headers):
payload = self.payload.replace('"', '\\"')
to_copy = '''wget --no-check-certificate --quiet -S \\\n--method {method} --timeout=0 \\\n--body-data '{payload}' \\\n{headers} \\\n{url}'''.format(url=self.url,
payload=payload,
method=self.method,
headers=formatted_headers) # noqa
return to_copy
def asWget_none(self, formatted_headers):
to_copy = '''wget --no-check-certificate --quiet -S \\\n--method {method} --timeout=0 \\\n{headers} \\\n{url}'''.format(url=self.url,
method=self.method,
headers=formatted_headers) # noqa
return to_copy
def asWget_xml(self, formatted_headers):
payload = self.payload.replace('"', '\\"')
to_copy = '''wget --no-check-certificate --quiet -S \\\n--method {method} --timeout=0 \\\n--body-data '{payload}' \\\n{headers} \\\n{url}'''.format(url=self.url,
payload=payload,
method=self.method,
headers=formatted_headers) # noqa
return to_copy
def asWget(self, event):
if event == 'n/a':
iRequestInfo = self._helpers.analyzeRequest(self._exporter)
self.setData(iRequestInfo)
else:
iRequestInfo = self._helpers.analyzeRequest(self._context.getSelectedMessages()[0])
headers = self.headersDict()
formatted_headers = ' \\\n'.join(["--header '" + i + ": " + headers.get(i) + "'" for i in headers])
if self.contentType == iRequestInfo.CONTENT_TYPE_MULTIPART:
to_copy = self.asWget_multipart(formatted_headers, iRequestInfo)
elif self.contentType == iRequestInfo.CONTENT_TYPE_JSON:
to_copy = self.asWget_json(formatted_headers)
elif self.contentType == iRequestInfo.CONTENT_TYPE_NONE:
to_copy = self.asWget_none(formatted_headers)
elif self.contentType == iRequestInfo.CONTENT_TYPE_XML:
to_copy = self.asWget_xml(formatted_headers)
else:
to_copy = "Not supported yet!"
if event == 'n/a':
return to_copy
elif event.getActionCommand() == 'clipboard':
# Copy to clipboard
self.saveToClipboard(to_copy)
else:
# Save file
self.saveToFile(to_copy)
def asPHPRequest_multipart(self, headers, formatted_headers, method):
payload = self.payload
payload_list = list(payload.items())
payload.clear()
headers.pop(u'Content-Type')
headers.pop(u'Content-Length')
for key, val in payload_list:
new_key = "'{}'".format(key)
if len(val.split("\x00")) > 1:
payload[new_key] = '$myAwesomeFileR'
else:
new_val = "'{}'".format(val)
payload[new_key] = new_val
payload = json.dumps(payload)
to_copy = '''<?php
require_once 'HTTP/Request2.php';
$request = new HTTP_Request2();
$request->setUrl('{url}');
$request->setMethod({method});
$request->setConfig(array(
'follow_redirects' => TRUE,
'ssl_verify_peer' => FALSE,
'ssl_verify_host' => FALSE
));
$request->setHeader(array(
{headers}
));
$nameF = '<myAwesomeFile>';
$myAwesomeFile = fopen($nameF, 'r');
$myAwesomeFileR = fread($myAwesomeFile, filesize($nameF));
$request->setBody(&dquote{payload}&dquote);
try {{
$response = $request->send();
if ($response->getStatus() == 200) {{
echo $response->getBody();
}}
else {{
echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
$response->getReasonPhrase();
}}
}}
catch(HTTP_Request2_Exception $e) {{
echo 'Error: ' . $e->getMessage();
}}'''.format(url=self.url, payload=str(payload), method=method, headers=formatted_headers) # noqa
to_copy = to_copy.replace('"', '')
to_copy = to_copy.replace('&dquote', '"')
return to_copy
def asPHPRequest_json(self, formatted_headers, method):
payload = self.payload.replace("\n", "").replace("\t", "")
to_copy = '''<?php
require_once 'HTTP/Request2.php';
$request = new HTTP_Request2();
$request->setUrl('{url}');
$request->setMethod({method});
$request->setConfig(array(
'follow_redirects' => TRUE,
'ssl_verify_peer' => FALSE,
'ssl_verify_host' => FALSE
));
$request->setHeader(array(
{headers}
));
$request->setBody('{payload}');
try {{
$response = $request->send();
if ($response->getStatus() == 200) {{
echo $response->getBody();
}}
else {{
echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
$response->getReasonPhrase();
}}
}}
catch(HTTP_Request2_Exception $e) {{
echo 'Error: ' . $e->getMessage();
}}'''.format(url=self.url, payload=payload, method=method, headers=formatted_headers) # noqa
return to_copy
def asPHPRequest_none(self, formatted_headers, method):
to_copy = '''<?php
require_once 'HTTP/Request2.php';
$request = new HTTP_Request2();
$request->setUrl('{url}');
$request->setMethod({method});
$request->setConfig(array(
'follow_redirects' => TRUE,
'ssl_verify_peer' => FALSE,
'ssl_verify_host' => FALSE
));
$request->setHeader(array(
{headers}
));
try {{
$response = $request->send();
if ($response->getStatus() == 200) {{
echo $response->getBody();
}}
else {{
echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
$response->getReasonPhrase();
}}
}}
catch(HTTP_Request2_Exception $e) {{
echo 'Error: ' . $e->getMessage();
}}'''.format(url=self.url, method=method, headers=formatted_headers) # noqa
return to_copy
def asPHPRequest_xml(self, formatted_headers, method):
payload = self.payload.replace("\n", "").replace("\t", "")
to_copy = '''<?php
require_once 'HTTP/Request2.php';
$request = new HTTP_Request2();
$request->setUrl('{url}');
$request->setMethod({method});
$request->setConfig(array(
'follow_redirects' => TRUE,
'ssl_verify_peer' => FALSE,
'ssl_verify_host' => FALSE
));
$request->setHeader(array(
{headers}
));
$request->setBody('{payload}');
try {{
$response = $request->send();
if ($response->getStatus() == 200) {{
echo $response->getBody();
}}
else {{
echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
$response->getReasonPhrase();
}}
}}
catch(HTTP_Request2_Exception $e) {{
echo 'Error: ' . $e->getMessage();
}}'''.format(url=self.url, payload=payload, method=method, headers=formatted_headers) # noqa
return to_copy
def asPHPRequest(self, event):
def formatPhpMethod(method):
common_methods = ['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS']
return 'HTTP_Request2::METHOD_' + method if method in common_methods else method
if event == 'n/a':
iRequestInfo = self._helpers.analyzeRequest(self._exporter)
self.setData(iRequestInfo)
else:
iRequestInfo = self._helpers.analyzeRequest(self._context.getSelectedMessages()[0])
headers = self.headersDict()
formatted_headers = ',\n'.join([" '" + i + "' => '" + headers.get(i) + "'" for i in headers])
method = formatPhpMethod(self.method)
if self.contentType == iRequestInfo.CONTENT_TYPE_MULTIPART:
to_copy = self.asPHPRequest_multipart(headers, formatted_headers, method)
elif self.contentType == iRequestInfo.CONTENT_TYPE_JSON:
to_copy = self.asPHPRequest_json(formatted_headers, method)
elif self.contentType == iRequestInfo.CONTENT_TYPE_NONE:
to_copy = self.asPHPRequest_none(formatted_headers, method)
elif self.contentType == iRequestInfo.CONTENT_TYPE_XML:
to_copy = self.asPHPRequest_xml(formatted_headers, method)
else:
to_copy = "Not supported yet!"
if event == 'n/a':
return to_copy
elif event.getActionCommand() == 'clipboard':
# Copy to clipboard
self.saveToClipboard(to_copy)
else:
# Save file
self.saveToFile(to_copy)
def asGO_multipart(self, formatted_headers):
payload = self.payload
payload_list = list(payload.items())
payload.clear()
for key, val in payload_list:
new_key = "'{}'".format(key)
if len(val.split("\x00")) > 1:
payload[new_key] = '%s'
else:
new_val = "'{}'".format(val)
payload[new_key] = new_val
payload = json.dumps(payload)
to_copy = '''package main
import (
"fmt"
"strings"
"net/http"
"io/ioutil"
"os"
"crypto/tls"
)
func main() {{
url := "{url}"
method := "{method}"
myFile := os.Open("<YourAwesomeFile>")
payload := strings.NewReader("{payload}", myFile)
tr := &http.Transport{{
TLSClientConfig: &tls.Config{{InsecureSkipVerify: true}},
}}
client := &http.Client {{ Transport: tr }}
req, err := http.NewRequest(method, url, payload)
if err != nil {{
fmt.Println(err)
}}
{headers}
res2, err := client.Do(req)
res := *res2
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
fmt.Println(string(body))
}}'''.format(url=self.url, payload=payload, method=self.method, headers=formatted_headers) # noqa
return to_copy
def asGO_json(self, formatted_headers):
payload = self.payload.replace("\n", "").replace("\t", "").replace('"', '\\"') if self.payload.__class__ == str else self.payload
to_copy = '''package main
import (
"fmt"
"strings"
"net/http"
"io/ioutil"
"crypto/tls"
)
func main() {{
url := "{url}"
method := "{method}"
payload := strings.NewReader("{payload}")
tr := &http.Transport{{
TLSClientConfig: &tls.Config{{InsecureSkipVerify: true}},
}}
client := &http.Client {{ Transport: tr }}
req, err := http.NewRequest(method, url, payload)
if err != nil {{
fmt.Println(err)
}}
{headers}
res2, err := client.Do(req)
res := *res2
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
fmt.Println(string(body))
}}'''.format(url=self.url, payload=payload, method=self.method, headers=formatted_headers) # noqa
return to_copy
def asGO_none(self, formatted_headers):
to_copy = '''package main
import (
"fmt"
"strings"
"net/http"
"io/ioutil"
"crypto/tls"
)
func main() {{
url := "{url}"
method := "{method}"
payload := strings.NewReader("")
tr := &http.Transport{{
TLSClientConfig: &tls.Config{{InsecureSkipVerify: true}},
}}
client := &http.Client {{ Transport: tr }}
req, err := http.NewRequest(method, url, payload)
if err != nil {{
fmt.Println(err)
}}
{headers}
res2, err := client.Do(req)
res := *res2