-
Notifications
You must be signed in to change notification settings - Fork 153
/
Copy pathrun_simulation_yaml.py
286 lines (235 loc) · 11.1 KB
/
run_simulation_yaml.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
# author Chris Gates - Uber
# additions Maus - Uber
# additions author Russ Nolen - Riot Games
# adversarial simulation engine
from __future__ import print_function
import datetime
import json
import logging
import os
import subprocess
import sys
import time
from argparse import ArgumentParser
from random import randint
import requests
import yaml
from reporting.log_to_file import *
from workers.vagranttasks import *
try:
import configparser as ConfigParser # Python 3
except ImportError:
import ConfigParser # Python 2
# slack hook URL
hook = ""
# vagrant variables that get populated below
windows = " "
osx = " "
linux = " "
kali = " "
# banners for metta
banner = '''
_____ __ __
/ \ _____/ |__/ |______
/ \ / \_/ __ \ __\ __\__ \
/ Y \ ___/| | | | / __ \_
\____|__ /\___ >__| |__| (____ /
\/ \/ \/
'''
banner2 = '''
__ __ _______ _______ _______ _______
| |_| || || || || _ |
| || ___||_ _||_ _|| |_| |
| || |___ | | | | | |
| || ___| | | | | | |
| ||_|| || |___ | | | | | _ |
|_| |_||_______| |___| |___| |__| |__|
'''
# module to post to slack if you set the webhook in config.ini
def post_to_slack(hook, json):
try:
r = requests.post(hook, json=json)
except Exception as e:
print(e)
def run_scenario(ioc_filename):
try:
print("### Running the Scenario ###")
raw_iocs = yaml.load_all(open(ioc_filename, 'r').read())
timenow = datetime.datetime.utcnow()
for raw_ioc in raw_iocs:
scenario = raw_ioc.get('meta').get('scenario_actions')
rule_name = raw_ioc.get('name')
print("### {} ###".format(rule_name))
scenario_actions = []
# read the steps from purple_actions in yaml and load them into purple_actions
for x in range(1, len(scenario)+1):
scenario_actions.append(raw_ioc.get('meta').get('scenario_actions').get(x))
for uuid_file in scenario_actions:
run_uuid(uuid_file)
except Exception as e:
print(e)
def run_uuid(ioc_filename):
try:
print("\nRunning UUID actions inside:{}".format(ioc_filename))
raw_iocs = yaml.load_all(open(ioc_filename, 'r').read())
for raw_ioc in raw_iocs:
rule_name = raw_ioc.get('name')
rule_uuid = raw_ioc.get('uuid')
rule_os = raw_ioc.get('os')
mitre_phase = raw_ioc.get('meta').get('mitre_attack_phase')
mitre_tech = raw_ioc.get('meta').get('mitre_attack_technique')
purple = raw_ioc.get('meta').get('purple_actions')
if not purple:
print("No Purple Actions detected you've probably messed up your scenario.yml...")
sys.exit(0)
purple_actions = []
# read the steps from purple_actions in yaml and load them into purple_actions
for x in range(1, len(purple)+1):
purple_actions.append(raw_ioc.get('meta').get('purple_actions').get(x))
if rule_os == "windows":
print("OS matched Windows...sending to the windows vagrant")
for action in purple_actions:
print("Running: {}".format(action))
timenow = datetime.datetime.utcnow()
date = timenow.strftime('%Y-%m-%d')
hourminsec = timenow.strftime('%H:%M:%S')
time_to_log = date+" "+hourminsec
try:
vagrant = runcmd_nodb_win.delay(action, rule_name, rule_uuid, windows)
data = json.dumps({'time': time_to_log, 'rule_name': rule_name, 'action': action, 'mitre_attack_phase': mitre_phase, 'mitre_attack_technique': mitre_tech, 'host': windows})
logging.info(data)
write_row(time_to_log, rule_name, action, mitre_phase, mitre_tech, windows)
'''
# if you want to post to slack uncomment this and set the slack hook above
json = {'text': "Automated Purple Team --> Simulation: {} | Action: {} | Host: {} | Execution Time: {} UTC".format(rule_name,action,windows,datetime.datetime.utcnow())}
post_to_slack(hook,json)
'''
time.sleep(randint(2, 30))
except Exception as e:
print(e)
elif rule_os == "osx":
print("OS matched OSX...sending to the OSX vagrant")
for action in purple_actions:
print("Running: {}".format(action))
timenow = datetime.datetime.utcnow()
date = timenow.strftime('%Y-%m-%d')
hourminsec = timenow.strftime('%H:%M:%S')
time_to_log = date+" "+hourminsec
try:
vagrant = runcmd_nodb_osx.delay(action, rule_name, rule_uuid, osx)
data = json.dumps({'time': time_to_log, 'rule_name': rule_name, 'action': action, 'mitre_attack_phase': mitre_phase, 'mitre_attack_technique': mitre_tech, 'host': osx})
logging.info(data)
write_row(time_to_log, rule_name, action, mitre_phase, mitre_tech, osx)
'''
# if you want to post to slack uncomment this and set the slack hook above
json = {'text': "Automated Purple Team --> Simulation: {} | Action: {} | Host: {} | Execution Time: {} UTC".format(rule_name,action,osx,datetime.datetime.utcnow())}
post_to_slack(hook,json)
'''
time.sleep(randint(2, 30))
except Exception as e:
print(e)
elif rule_os == "linux":
print("OS matched Linux...sending to the Linux vagrant")
for action in purple_actions:
print("Running: {}".format(action))
timenow = datetime.datetime.utcnow()
date = timenow.strftime('%Y-%m-%d')
hourminsec = timenow.strftime('%H:%M:%S')
time_to_log = date+" "+hourminsec
try:
vagrant = runcmd_nodb_linux.delay(action, rule_name, rule_uuid, linux)
data = json.dumps({'time': time_to_log, 'rule_name': rule_name, 'action': action, 'mitre_attack_phase': mitre_phase, 'mitre_attack_technique': mitre_tech, 'host': linux})
logging.info(data)
write_row(time_to_log, rule_name, action, mitre_phase, mitre_tech, linux)
'''
# if you want to post to slack uncomment this and set the slack hook above
json = {'text': "Automated Purple Team --> Simulation: {} | Action: {} | Host: {} | Execution Time: {} UTC".format(rule_name,action,osx,datetime.datetime.utcnow())}
post_to_slack(hook,json)
'''
time.sleep(randint(2, 30))
except Exception as e:
print(e)
elif rule_os == "kali":
print("OS matched Kali...sending to the Kali Linux vagrant")
for action in purple_actions:
print("Running: {}".format(action))
timenow = datetime.datetime.utcnow()
date = timenow.strftime('%Y-%m-%d')
hourminsec = timenow.strftime('%H:%M:%S')
time_to_log = date+" "+hourminsec
try:
vagrant = runcmd_nodb_kali.delay(action, rule_name, rule_uuid, kali)
data = json.dumps({'time': time_to_log, 'rule_name': rule_name, 'action': action, 'mitre_attack_phase': mitre_phase, 'mitre_attack_technique': mitre_tech, 'host': kali})
logging.info(data)
write_row(time_to_log, rule_name, action, mitre_phase, mitre_tech, kali)
'''
#if you want to post to slack uncomment this and set the slack hook above
#json = {'text': "Automated Purple Team --> Simulation: {} | Action: {} | Host: {} | Execution Time: {} UTC".format(rule_name,action,osx,datetime.datetime.utcnow())}
#post_to_slack(hook,json)
'''
time.sleep(randint(2, 30))
except Exception as e:
print(e)
else:
print("I received an unknown OS")
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
except Exception as e:
print(e)
def parse_yaml(ioc_filename):
print(banner2)
print("YAML FILE: {}".format(ioc_filename))
try:
raw_iocs = yaml.load_all(open(ioc_filename, 'r').read())
start_log("Adversarial Simulation", "1.0")
for raw_ioc in raw_iocs:
scenario = raw_ioc.get('meta').get('scenario')
purple = raw_ioc.get('meta').get('purple_actions')
# if we cant find the scenario tag, default to run_uuid
if not scenario:
run_uuid(ioc_filename)
# if the scenario field is found and if it's true run the run_scenario function
if scenario is True:
run_scenario(ioc_filename)
close_log()
except KeyboardInterrupt:
print("CTRL-C received, exiting...")
except Exception as e:
print(e)
def main():
parser = ArgumentParser(description="adversarial-simulation ")
parser.add_argument("-f", "--simfile", action="store", default=None, required=True, dest="simfile", help="Path to simulation file you want to run")
args = parser.parse_args()
config = ConfigParser.RawConfigParser()
try:
config.read('config.ini')
except Exception as e:
print(e)
sys.exit(0)
global windows
windows = config.get('vms', 'windows')
global osx
osx = config.get('vms', 'osx')
global linux
linux = config.get('vms', 'linux')
global kali
kali = config.get('vms', 'kali')
global console_output
console_log_output = config.get('console_log_output', 'enabled')
# logging function to log json to a file
logging.basicConfig(level=logging.DEBUG, format='%(message)s', filename='simulation.log', filemode='w')
if console_log_output == 'True' or console_log_output == 'true':
# logging function to give info to the console
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# set a format which is simpler for console use
formatter = logging.Formatter('%(levelname)-4s : %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)
else:
''
parse_yaml(args.simfile)
if __name__ == '__main__':
main()