-
-
Notifications
You must be signed in to change notification settings - Fork 133
/
ProtectMyToolingGUI.pyw
677 lines (555 loc) · 24.1 KB
/
ProtectMyToolingGUI.pyw
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
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Author:
# Mariusz Banach / mgeeky, '20-'23
# <mb [at] binary-offensive.com>
# https://mgeeky.tech
#
import time
import os
import sys
from turtle import title
import yaml
import random
import clipboard
from lib.utils import *
from lib.logger import Logger
from lib.packersloader import PackersLoader
from ProtectMyTooling import VERSION
from threading import Thread
import lib.optionsparser
import PySimpleGUI as sg
sg.theme("Dark")
font = ("Consolas", 8)
font2 = ("Consolas", 10)
phrases = (
'with great power, comes great responsibility.',
"don't detect tools, detect techniques",
'to be used in ethical offensive assessments only!',
'support hard-working open-source Offensive Security Tools developers :)',
'be responsible - watermark and track your implants',
'be responsible - collect your implants\'s IOCs'
)
packersChain = []
# https://stackoverflow.com/a/69064884
def runCommand(cmd, timeout=None, window=None):
cwd = os.getcwd()
try:
p = cmd[0]
if len(cmd) > 1:
p = cmd[1]
d = os.path.dirname(os.path.normpath(os.path.abspath(p)))
if os.path.isdir(d):
os.chdir(d)
p = subprocess.Popen(
cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = ''
for line in p.stdout:
line = line.decode(errors='replace' if (
sys.version_info) < (3, 5) else 'ignore').rstrip()
output += line
print(line)
if window:
window.Refresh()
window['-outputml-'].set_vscroll_position(1.0)
retval = p.wait(timeout)
window.set_title("Program completed.")
print(f'''
--------------------------------------------------------------------------------------------------------
Program completed.
''')
return (retval, output)
finally:
os.chdir(cwd)
#
# https://stackoverflow.com/a/67860031
#
right_click_menu_ro = ['', ['Copy', 'Select All']]
right_click_menu = ['', ['Copy', 'Paste', 'Select All', 'Cut']]
def multilineRightClick(window, event, multilineKey, readOnly = False):
mline: sg.Multiline = window[multilineKey]
if event == 'Select All':
mline.Widget.selection_clear()
mline.Widget.tag_add('sel', '1.0', 'end')
elif event == 'Copy':
try:
text = mline.Widget.selection_get()
window.TKroot.clipboard_clear()
window.TKroot.clipboard_append(text)
except:
pass
elif event == 'Paste':
if not readOnly:
try:
mline.Widget.delete("sel.first", "sel.last")
except:
pass
mline.Widget.insert("insert", clipboard.paste())
elif event == 'Cut':
if not readOnly:
try:
text = mline.Widget.selection_get()
window.TKroot.clipboard_clear()
window.TKroot.clipboard_append(text)
mline.Widget.delete("sel.first", "sel.last")
except Exception as e:
print(e)
pass
def run(command, width=120):
layout = [
[
sg.Multiline(
size=(width, 40),
key='-outputml-',
font=font,
echo_stdout_stderr=False,
reroute_stdout=True,
reroute_stderr=True,
no_scrollbar=False,
horizontal_scroll=True,
right_click_menu=right_click_menu_ro,
expand_x=True,
expand_y=True,
)
],
[
sg.Button("Close", key="-Exit-", font=font),
],
]
window = sg.Window("Protection in progress...",
layout, modal=True, finalize=True, resizable=True, return_keyboard_events=True)
window.bind("<Escape>", "-Exit-")
print(f'PS> {" ".join(command)}\n')
runCommand(cmd=command, window=window)
while True:
event, values = window.read()
if event == "-Exit-" or event == sg.WIN_CLOSED or event == 'Escape:27':
break
multilineRightClick(window, event, '-outputml-', True)
window.close()
def editConfig(config):
layout = [
[
sg.Text(config, font=font),
],
[
sg.Multiline(
size=(120, 40),
font=font,
echo_stdout_stderr=False,
reroute_stdout=True,
reroute_stderr=True,
key='-yaml-',
right_click_menu=right_click_menu,
expand_x=True,
expand_y=True,)
],
[
sg.Button("Save", key="-Save-", font=font),
sg.Button("Close", key="-Exit-", font=font),
],
]
window = sg.Window("Protection in progres...", layout,
modal=True, finalize=True, return_keyboard_events=True, resizable=True)
window.bind("<Escape>", "-Exit-")
with open(config) as f:
print(f.read())
while True:
event, values = window.read()
if event == "-Exit-" or event == sg.WIN_CLOSED or event == 'Escape:27':
break
if event == "-Save-":
with open(config, 'w') as f:
f.write(values['-yaml-'])
sg.Popup('Saved.', 'YAML saved.')
multilineRightClick(window, event, '-yaml-', False)
window.close()
def createWindow(packersList):
global packersChain
tooltip1 = 'Inject watermark to generated artifact. Syntax: where=value, e.g.: "dos-stub=Foobar".\nAvailable watermarks: dos-stub,checksum,overlay,section\nSection requires NAME,STR syntax where NAME denotes PE section name\ne.g. "section=.foo,bar" creates PE section named ".foo" with contents "bar".\nMay be repeated'
tooltip2 = 'Specify a custom IOC value that is to be written into output IOCs csv file in column "comment"'
params_column = [
[
sg.Text("Input File" + ' ' * 1, font=font,
tooltip='Input implant file to be obfuscated/protected'),
sg.Input(size=(60, 1), enable_events=True, key="-infile-", font=font,
tooltip='Input implant file to be obfuscated/protected', expand_x=True,),
sg.FileBrowse(font=font),
],
[
sg.Text("Output File", font=font,
tooltip='Output obfuscated/protected file.'),
sg.Input(size=(60, 1), enable_events=True, key="-outfile-",
font=font, tooltip='Output obfuscated/protected file.', expand_x=True,),
sg.FileSaveAs(font=font),
],
[
sg.Text("File Architecture" + ' ' * 1, font=font,
tooltip='Specify input file architecture, or leave "Auto" to make script auto detect it.'),
sg.Combo(size=(10, 1), values=["Auto", "x86", "x64"], readonly=True,
default_value="Auto", enable_events=True, key="-arch-", font=font,),
sg.Text("Detected file type: ", font=font),
sg.Text("", font=font, key='-detected-', text_color='cyan'),
],
[
sg.Column([
[
sg.Listbox(values=packersChain, enable_events=True, size=(
25, 15), pad=(5, 5), key="-packers chain-", font=font2, expand_x=True, expand_y=True,),
]
], expand_x=True, expand_y=True,),
sg.Column([
[sg.Text("", font=font2)],
[sg.Text("<-- Packers chain", font=font2)],
[sg.Text("", font=font2)],
[sg.Button("Move Up", font=font), ],
[sg.Button("Move Down", font=font), ],
[sg.Button("Remove", font=font), ],
[sg.Button("Clear", font=font), ],
], expand_x=True, expand_y=True,),
],
[
sg.Text("Config path" + ' ' * 3, font=font),
sg.Input(size=(61, 1), default_text=os.path.abspath(os.path.join(os.path.dirname(
__file__), "config/ProtectMyTooling.yaml")), enable_events=True, key="-config-", font=font, expand_x=True,),
sg.FileBrowse(font=font),
],
[
sg.Text("Watermark" + ' ' * 5, font=font, tooltip=tooltip1),
sg.Input(size=(70, 1), default_text="section=.foo,1234567890abcdef123456", pad=(
5, 5), enable_events=True, key="-watermark-", font=font, tooltip=tooltip1, expand_x=True,),
],
[
sg.Text("Custom IOC" + ' ' * 4, font=font, tooltip=tooltip2),
sg.Input(size=(70, 1), default_text="", pad=(
5, 5), enable_events=True, key="-customioc-", font=font, tooltip=tooltip2, expand_x=True,),
],
[
sg.Text("Custom Options" + ' ' * 0, font=font,
tooltip='Specify your own custom ProtectMyTooling options to be added to command line.'),
sg.Input(size=(70, 1), default_text="", pad=(5, 5), enable_events=True, key="-customopts-", font=font,
tooltip='Specify your own custom ProtectMyTooling options to be added to command line.', expand_x=True,),
],
[
sg.Text("File to backdoor" + ' ' * 0, font=font,
tooltip='You can backdoor specific EXE/DLL file by providing path to it here AND choosing BACKDOORER packer in the chain'),
sg.Input(size=(70, 1), default_text="", pad=(5, 5), enable_events=True, key="-backdoor-", font=font,
tooltip='You can backdoor specific EXE/DLL file by providing path to it here AND choosing BACKDOORER packer in the chain', expand_x=True,),
],
[
sg.Checkbox('Collect IOCs', key='-Collect IOCs-', text_color='cyan', default=False,
tooltip="Collect IOCs and save them to .csv file side by side to <outfile>", font=font),
sg.Checkbox('Hide Console', key='-Hide Console-', default=False,
tooltip="If output artifact is PE EXE, use this option to hide Console window by switching PE Subsystem from WINDOWS_GUI", font=font),
sg.Checkbox("Don't disable AV", key='-dont-disable-av-', default=False, font=font),
sg.Checkbox('Verbose', key='-Verbose-', default=True, font=font),
sg.Checkbox('Debug', key='-Debug-', default=False, font=font)
]
]
packers_column = [
[
sg.Text("Choose packers to work with:", font=font),
],
[
sg.Listbox(values=packersList, enable_events=True, size=(
20, 30), pad=(5, 5), key="-packers available-", font=font, expand_x=True, expand_y=True),
],
[
sg.Button("Add to chain", font=font, expand_x=True,),
]
]
layout = [
[
sg.Column(params_column, expand_x=True, expand_y=True,),
sg.VSeparator(),
sg.Column(packers_column, expand_x=True, expand_y=True,),
],
[
sg.HSeparator(),
],
[
sg.Text("", key='-current chain-', font=font2),
],
[
sg.Text("", font=font),
],
[
sg.Button(
"Protect", tooltip="Runs ProtectMyTooling.py with provided arguments.", font=font),
sg.Button(
"Protect & Run", tooltip="Protects input payload and runs protected file without parameters.", font=font),
sg.Button("List Packers & Details",
tooltip="List all packers details.", font=font),
sg.Button("Edit Config",
tooltip="Edit configuration YAML contents.", font=font),
sg.Button("Full Help", font=font),
sg.Button("About", font=font),
]
]
phrase = random.choice(phrases)
window = sg.Window(f"ProtectMyTooling v{VERSION} | {phrase} ",
layout, return_keyboard_events=True, resizable=True, finalize=True)
window.bind("<Escape>", "-Exit-")
return window
def detectFileType(p, window, values):
global packersChain
ftype = 'unkown'
if os.path.isfile(p):
if isDotNetExecutable(p):
window['-detected-'].update('.NET Assembly')
ftype = 'dotnet'
elif isValidPE(p):
window['-detected-'].update('PE Executable')
ftype = 'pe'
elif isShellcode(p):
window['-detected-'].update('Shellcode')
ftype = 'shellcode'
else:
window['-detected-'].update('Unknown')
if len(values['-config-']) > 0 and os.path.isfile(values['-config-']):
try:
with open(values['-config-']) as f:
parsed = yaml.load(f, Loader=yaml.FullLoader)
if ftype == 'pe':
packersChain = [
[x] for x in parsed['gui_default_chain_pe'].replace(' ', '').split(',')]
if ftype == 'dotnet':
packersChain = [
[x] for x in parsed['gui_default_chain_dotnet'].replace(' ', '').split(',')]
if ftype == 'shellcode':
packersChain = [
[x] for x in parsed['gui_default_chain_shellcode'].replace(' ', '').split(',')]
index = 0
window["-packers chain-"].update(packersChain, set_to_index=[
index + 1], scroll_to_index=index + 1)
chain = f'"{os.path.basename(values["-infile-"])}"'
for p in packersChain:
chain = f"{p[0].capitalize()}({chain})"
window['-current chain-'].update(chain)
except:
pass
def main():
global packersChain
packersList = []
files = os.listdir(os.path.join(os.path.dirname('__file__'), 'packers'))
for f in files:
if f.lower().endswith('.py'):
name = os.path.basename(f).replace('.py', '')
if name.lower() not in ['__init__', 'ipacker']:
if name in RenamePackerNameToPackerFile.values():
name = list(RenamePackerNameToPackerFile.keys())[list(RenamePackerNameToPackerFile.values()).index(name)]
packersList.append(name)
window = createWindow(packersList)
while True:
event, values = window.read()
if event == "Exit" or event == sg.WIN_CLOSED:
break
elif event == "Add to chain":
packersChain.append(values['-packers available-'])
chain = f'"{os.path.basename(values["-infile-"])}"'
for p in packersChain:
chain = f"{p[0].capitalize()}({chain})"
window['-current chain-'].update(chain)
window["-packers chain-"].update(packersChain)
chain = f'"{os.path.basename(values["-infile-"])}"'
for p in packersChain:
chain = f"{p[0].capitalize()}({chain})"
window['-current chain-'].update(chain)
elif event == "Remove":
index = int(
''.join(map(str, window["-packers chain-"].get_indexes())))
packersChain.pop(index)
chain = f'"{os.path.basename(values["-infile-"])}"'
for p in packersChain:
chain = f"{p[0].capitalize()}({chain})"
window['-current chain-'].update(chain)
window["-packers chain-"].update(packersChain, set_to_index=[
index - 1], scroll_to_index=index - 1)
elif event == "Clear":
packersChain.clear()
window['-current chain-'].update("")
window["-packers chain-"].update(packersChain)
elif event == "List Packers & Details":
script = os.path.abspath(os.path.join(
os.path.dirname(__file__), 'ProtectMyTooling.py'))
with tempfile.NamedTemporaryFile() as temp:
logpath = temp.name + ".log"
command = [
sys.executable,
script,
'-L',
'--widest-packers-list'
]
run(command, width=150)
elif event == "Move Up":
index = int(
''.join(map(str, window["-packers chain-"].get_indexes())))
if index > 0:
packersChain.insert(index - 1, packersChain.pop(index))
window["-packers chain-"].update(packersChain, set_to_index=[
index - 1], scroll_to_index=index - 1)
chain = f'"{os.path.basename(values["-infile-"])}"'
for p in packersChain:
chain = f"{p[0].capitalize()}({chain})"
window['-current chain-'].update(chain)
elif event == "Move Down":
index = int(
''.join(map(str, window["-packers chain-"].get_indexes())))
if index + 1 < len(packersChain):
packersChain.insert(index + 1, packersChain.pop(index))
window["-packers chain-"].update(packersChain, set_to_index=[
index + 1], scroll_to_index=index + 1)
chain = f'"{os.path.basename(values["-infile-"])}"'
for p in packersChain:
chain = f"{p[0].capitalize()}({chain})"
window['-current chain-'].update(chain)
elif event == "About":
sg.Popup("About ProtectMyTooling", f'''
Mariusz Banach / mgeeky, '20-'23
<mb [at] binary-offensive.com>
(https://mgeeky.tech)
------------------------------------------------------------
This and other projects are outcome of sleepless nights and
plenty of hard work. If you like what I do and appreciate
that I always give back to the community, Consider buying
me a coffee (or better a beer) just to say thank you! :-)
https://github.com/sponsors/mgeeky
------------------------------------------------------------
Use only for legitimate, ethical engagements.
Enjoy!
''', font=font)
elif event == "-infile-":
p = os.path.normpath(os.path.abspath(values["-infile-"]))
path, ext = os.path.splitext(p)
newname = os.path.basename(path) + '-obf' + ext
window["-infile-"].update(p)
if len(values["-outfile-"]) == 0:
outpath = os.path.normpath(os.path.abspath(
os.path.join(os.path.dirname(p), newname)))
window["-outfile-"].update(outpath)
#thread = Thread(target = detectFileType, args = (p, window, values))
# thread.start()
detectFileType(p, window, values)
elif event == "Edit Config":
if len(values["-config-"]) > 0:
editConfig(values["-config-"])
elif 'Up' in event or '16777235' in event:
element = window.find_element_with_focus().Key
if element in ['-packers chain-', '-packers available-']:
cur_index = window.Element(element).Widget.curselection()
cur_index = (
cur_index[0] - 1) % window.Element(element).Widget.size()
window.Element(element).Update(set_to_index=cur_index)
window.Element(element).Update(scroll_to_index=cur_index)
window.write_event_value(
element, [window.Element(element).GetListValues()[cur_index]])
elif 'Down' in event or '16777237' in event:
element = window.find_element_with_focus().Key
if element in ['-packers chain-', '-packers available-']:
cur_index = window.Element(element).Widget.curselection()
cur_index = (
cur_index[0] + 1) % window.Element(element).Widget.size()
window.Element(element).Update(set_to_index=cur_index)
window.Element(element).Update(scroll_to_index=cur_index)
window.write_event_value(
element, [window.Element(element).GetListValues()[cur_index]])
elif event == "Full Help":
script = os.path.abspath(os.path.join(
os.path.dirname(__file__), 'ProtectMyTooling.py'))
command = [
sys.executable,
script,
'-h',
'-v',
'-C',
]
run(command)
elif event == "Protect" or event == "Protect & Run":
infile = os.path.normpath(os.path.abspath(values["-infile-"]))
arch = values["-arch-"]
watermark = values["-watermark-"]
config = values["-config-"]
customioc = values["-customioc-"]
outfile = os.path.normpath(os.path.abspath(values["-outfile-"]))
packers = ','.join([x[0] for x in packersChain])
with tempfile.NamedTemporaryFile() as temp:
logpath = temp.name + ".log"
script = os.path.abspath(os.path.join(
os.path.dirname(__file__), 'ProtectMyTooling.py'))
command = [
sys.executable,
script,
'-c',
config,
packers,
'-l',
logpath,
'-C',
infile,
outfile
]
if arch.lower() != 'auto':
command.extend(['--arch', arch, ])
if len(watermark) > 0:
command.extend(['-w', watermark])
if len(customioc) > 0:
command.extend(['-I', customioc])
if values['-Collect IOCs-']:
command.append('-i')
if values['-Hide Console-']:
command.append('-g')
if values['-Verbose-']:
command.append('-v')
if values['-Debug-']:
command.append('-d')
if values['-dont-disable-av-']:
command.extend([
'--check-av-command',
'false'
])
if len(values["-backdoor-"]) > 0:
backdoor = values["-backdoor-"]
fname, ext = os.path.splitext(backdoor.lower())
if ext not in ('.exe', '.dll', '.cpl', '.xll', '.wll', '.ocx', '.sys'):
sg.Popup("File to be backdoored must be a valid PE executable: EXE/DLL/CPL/XLL/WLL/OCX/SYS and input file must be shellcode.")
continue
command.append(f'-B')
command.append(backdoor.strip())
if 'backdoor' not in [x[0].lower() for x in window["-packers chain-"].get_list_values()]:
sg.Popup("You did not select \"backdoor\" packer in your packers chain!")
continue
if len(values["-customopts-"]) > 0:
opts = values["-customopts-"]
pos = 0
failed = False
while pos < len(opts):
if opts[pos] == '"':
pos2 = opts.find('"', pos + 1)
if pos2 == 0:
sg.Popup("Missing \" (quote) character in custom options!")
failed = True
break
c = opts[pos + 1:pos2]
command.append(c.strip())
pos = pos2 + 1
else:
pos2 = opts.find(' ', pos + 1)
if pos2 > 0:
c = opts[pos:pos2]
command.append(c.strip())
pos = pos2 + 1
else:
c = opts[pos:]
command.append(c.strip())
break
if failed:
continue
if event == "Protect & Run":
command.append('-r')
if os.path.isfile(outfile):
os.remove(outfile)
run(command)
window.close()
if __name__ == '__main__':
main()