/
rest_svc.py
527 lines (467 loc) · 25.4 KB
/
rest_svc.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
import asyncio
import copy
import glob
import os
import pathlib
import uuid
from datetime import time
import yaml
from aiohttp import web
from app.objects.c_adversary import Adversary
from app.objects.c_objective import Objective
from app.objects.c_operation import Operation
from app.objects.c_source import Source
from app.objects.c_schedule import Schedule
from app.objects.secondclass.c_fact import Fact
from app.service.interfaces.i_rest_svc import RestServiceInterface
from app.utility.base_service import BaseService
class RestService(RestServiceInterface, BaseService):
def __init__(self):
self.log = self.add_service('rest_svc', self)
self.loop = asyncio.get_event_loop()
async def persist_adversary(self, access, data):
"""Persist adversaries. Accepts single adversary or bulk set of adversaries.
For bulk, supply dict of form {"bulk": [{<adversary>}, {<adversary>},...]}.
"""
if data.get('bulk', False):
data = data['bulk']
else:
data = [data]
r = []
for adv in data:
r.extend(await self._persist_adversary(access, adv))
return r
async def update_planner(self, data):
planner = (await self.get_service('data_svc').locate('planners', dict(name=data['name'])))[0]
planner_id = planner.planner_id
file_path = await self._get_file_path(planner_id)
planner_dict = await self._read_from_yaml(file_path)
planner_dict['stopping_conditions'] = self._get_stopping_conditions(data)
await self._write_to_yaml(file_path, planner_dict)
planner.stopping_conditions = [Fact.load(dict(trait=f.get('trait'), value=f.get('value')))
for f in data['stopping_conditions']]
await self.get_service('data_svc').store(planner)
async def persist_ability(self, access, data):
"""Persist abilities. Accepts single ability or bulk set of abilities.
For bulk, supply dict of form {"bulk": [{<ability>}, {<ability>},...]}.
"""
if data.get('bulk', False):
data = data['bulk']
else:
data = [data]
r = []
for ab in data:
r.extend(await self._persist_ability(access, ab))
return r
async def persist_source(self, access, data):
"""Persist sources. Accepts single source or bulk set of sources.
For bulk, supply dict of form {"bulk": [{<sourc>}, {<source>},...]}.
"""
if data.get('bulk', False):
data = data['bulk']
else:
data = [data]
r = []
for source in data:
r.extend(await self._persist_source(access, source))
return r
async def persist_objective(self, access, data):
"""Persist objectives. Accepts single objective or a bulk set of objectives.
For bulk, supply dict of form {"bulk": [{objective}, ...]}.
"""
if data.get('bulk', False):
data = data['bulk']
else:
data = [data]
r = []
for obj in data:
r.extend(await self._persist_objective(access, obj))
return r
async def delete_agent(self, data):
await self.get_service('data_svc').remove('agents', data)
return 'Delete action completed'
async def delete_ability(self, data):
return await self._delete_data_from_memory_and_disk(ram_key='abilities', identifier='ability_id', data=data)
async def delete_adversary(self, data):
return await self._delete_data_from_memory_and_disk(ram_key='adversaries', identifier='adversary_id', data=data)
async def delete_operation(self, data):
await self.get_service('data_svc').remove('operations', data)
await self.get_service('data_svc').remove('sources', dict(id=str(data.get('id'))))
for f in glob.glob('data/results/*'):
if '%s-' % data.get('id') in f:
os.remove(f)
for f in glob.glob('data/facts/*.yml'):
if '%s' % data.get('id') in f:
os.remove(f)
return 'Delete action completed'
async def display_objects(self, object_name, data):
results = [o.display for o in await self.get_service('data_svc').locate(object_name, match=data)]
return await self._explode_display_results(object_name, results)
async def display_result(self, data):
link_id = str(data.pop('link_id'))
link = await self.get_service('app_svc').find_link(link_id)
if link:
try:
content = self.get_service('file_svc').read_result_file('%s' % link_id)
return dict(link=link.display, output=content)
except FileNotFoundError:
return ''
return ''
async def display_operation_report(self, data):
op_id = data.pop('op_id')
op = (await self.get_service('data_svc').locate('operations', match=dict(id=int(op_id))))[0]
return await op.report(file_svc=self.get_service('file_svc'), data_svc=self.get_service('data_svc'),
output=data.get('agent_output'))
async def download_contact_report(self, contact):
return dict(contacts=self.get_service('contact_svc').report.get(contact.get('contact'), dict()))
async def update_agent_data(self, data):
paw = data.pop('paw', None)
if paw is None:
await self._update_global_props(**data)
for agent in await self.get_service('data_svc').locate('agents', match=dict(paw=paw)):
await agent.gui_modification(**data)
return agent.display
async def update_chain_data(self, data):
link = await self.get_service('app_svc').find_link(data.pop('link_id'))
link.status = data.get('status')
if data.get('command'):
link.command = data.get('command')
return ''
async def create_operation(self, access, data):
operation = await self._build_operation_object(access, data)
operation.set_start_details()
await self.get_service('data_svc').store(operation)
self.loop.create_task(operation.run(self.get_services()))
return [operation.display]
async def create_schedule(self, access, data):
operation = await self._build_operation_object(access, data['operation'])
schedules = await self.get_service('data_svc').locate('schedules', match=dict(name=operation.name))
if schedules:
self.log.debug('A scheduled operation with the name "%s" already exists, skipping' % operation.name)
else:
scheduled = await self.get_service('data_svc').store(
Schedule(name=operation.name,
schedule=time(data['schedule']['hour'], data['schedule']['minute'], 0),
task=operation)
)
self.log.debug('Scheduled new operation (%s) for %s' % (operation.name, scheduled.schedule))
async def list_payloads(self):
payload_dirs = [pathlib.Path.cwd() / 'data' / 'payloads']
payload_dirs.extend(pathlib.Path.cwd() / 'plugins' / plugin.name / 'payloads'
for plugin in await self.get_service('data_svc').locate('plugins') if plugin.enabled)
return set(p.name for p_dir in payload_dirs for p in p_dir.glob('*')
if p.is_file() and not p.name.startswith('.'))
async def find_abilities(self, paw):
data_svc = self.get_service('data_svc')
agent = (await data_svc.locate('agents', match=dict(paw=paw)))[0]
return await agent.capabilities(await self.get_service('data_svc').locate('abilities'))
async def get_potential_links(self, op_id, paw=None):
operation = (await self.get_service('data_svc').locate('operations', match=dict(id=op_id)))[0]
if operation.finish:
return []
agents = await self.get_service('data_svc').locate('agents', match=dict(paw=paw)) if paw else operation.agents
potential_abilities = await self._build_potential_abilities(operation)
operation.potential_links = await self._build_potential_links(operation, agents, potential_abilities)
return dict(links=[l.display for l in operation.potential_links])
async def apply_potential_link(self, link):
operation = await self.get_service('app_svc').find_op_with_link(link.id)
return await operation.apply(link)
async def task_agent_with_ability(self, paw, ability_id, obfuscator, facts=()):
new_links = []
for agent in await self.get_service('data_svc').locate('agents', dict(paw=paw)):
self.log.debug('Tasking %s with %s' % (paw, ability_id))
links = await agent.task(
abilities=await self.get_service('data_svc').locate('abilities', match=dict(ability_id=ability_id)),
obfuscator=obfuscator,
facts=facts
)
new_links.extend(links)
return new_links
async def get_link_pin(self, json_data):
link = await self.get_service('app_svc').find_link(json_data['link'])
if link and link.collect and not link.finish:
return link.pin
return 0
async def construct_agents_for_group(self, group):
if group:
return await self.get_service('data_svc').locate('agents', match=dict(group=group))
return await self.get_service('data_svc').locate('agents')
async def update_config(self, data):
if data.get('prop') == 'plugin':
enabled_plugins = self.get_config('plugins')
enabled_plugins.append(data.get('value'))
else:
self.set_config('main', data.get('prop'), data.get('value'))
return self.get_config()
async def update_operation(self, op_id, state=None, autonomous=None, obfuscator=None):
async def validate(op):
try:
if not len(op):
raise web.HTTPNotFound
elif await op[0].is_finished():
raise web.HTTPBadRequest(body='This operation has already finished.')
elif state not in op[0].states.values():
raise web.HTTPBadRequest(body='state must be one of {}'.format(op[0].states.values()))
except Exception as e:
self.log.error(repr(e))
operation = await self.get_service('data_svc').locate('operations', match=dict(id=op_id))
if state:
await validate(operation)
operation[0].state = state
if state == operation[0].states['FINISHED']:
operation[0].finish = self.get_current_timestamp()
self.log.debug('Changing operation=%s state to %s' % (op_id, state))
if autonomous:
operation[0].autonomous = 0 if operation[0].autonomous else 1
self.log.debug('Toggled operation=%s autonomous to %s' % (op_id, bool(operation[0].autonomous)))
if obfuscator:
operation[0].obfuscator = obfuscator
self.log.debug('Updated operation=%s obfuscator to %s' % (op_id, operation[0].obfuscator))
""" PRIVATE """
async def _build_operation_object(self, access, data):
name = data.pop('name')
group = data.pop('group', '')
planner = await self.get_service('data_svc').locate('planners', match=dict(name=data.get('planner', 'atomic')))
adversary = await self._construct_adversary_for_op(data.pop('adversary_id', ''))
agents = await self.construct_agents_for_group(group)
sources = await self.get_service('data_svc').locate('sources', match=dict(name=data.pop('source', 'basic')))
allowed = self._get_allowed_from_access(access)
return Operation(name=name, planner=planner[0], agents=agents, adversary=adversary,
group=group, jitter=data.pop('jitter', '2/8'), source=next(iter(sources), None),
state=data.pop('state', 'running'), autonomous=int(data.pop('autonomous', 1)), access=allowed,
obfuscator=data.pop('obfuscator', 'plain-text'),
auto_close=bool(int(data.pop('auto_close', 0))), visibility=int(data.pop('visibility', '50')))
def _get_allowed_from_access(self, access):
if self.Access.HIDDEN in access['access']:
return self.Access.HIDDEN
elif self.Access.BLUE in access['access']:
return self.Access.BLUE
else:
return self.Access.RED
@staticmethod
async def _read_from_yaml(file_path):
with open(file_path, 'r') as f:
return yaml.safe_load(f.read())
@staticmethod
async def _write_to_yaml(file_path, content):
with open(file_path, 'w') as f:
f.write(yaml.dump(content))
async def _get_file_path(self, planner_id):
_, file_path = await self.get_service('file_svc').find_file_path('%s.yml' % planner_id, location='data')
if not file_path:
file_path = 'data/planners/%s.yml' % planner_id
return file_path
@staticmethod
def _get_stopping_conditions(data):
new_stopping_conditions = data.get('stopping_conditions')
if new_stopping_conditions:
return [{s.get('trait'): s.get('value')} for s in new_stopping_conditions]
async def _build_potential_abilities(self, operation):
potential_abilities = []
for a in await self.get_service('data_svc').locate('abilities', match=dict(access=operation.access)):
if not operation.adversary.has_ability(a.ability_id):
potential_abilities.append(a)
return potential_abilities
async def _build_potential_links(self, operation, agents, abilities):
potential_links = []
for a in agents:
for pl in await self.get_service('planning_svc').generate_and_trim_links(a, operation, abilities):
potential_links.append(pl)
return await self.get_service('planning_svc').sort_links(potential_links)
async def _construct_adversary_for_op(self, adversary_id):
adv = await self.get_service('data_svc').locate('adversaries', match=dict(adversary_id=adversary_id))
if adv:
return copy.deepcopy(adv[0])
return Adversary.load(dict(adversary_id='ad-hoc', name='ad-hoc', description='an empty adversary profile', atomic_ordering=[]))
async def _update_global_props(self, sleep_min, sleep_max, watchdog, untrusted, implant_name, bootstrap_abilities):
if implant_name:
self.set_config(name='agents', prop='implant_name', value=implant_name)
if bootstrap_abilities:
abilities = self.get_config(name='agents', prop='bootstrap_abilities')
abilities.append(bootstrap_abilities)
self.set_config(name='agents', prop='sleep_min', value=sleep_min)
self.set_config(name='agents', prop='sleep_max', value=sleep_max)
self.set_config(name='agents', prop='untrusted_timer', value=untrusted)
self.set_config(name='agents', prop='watchdog', value=watchdog)
async def _explode_display_results(self, object_name, results):
if object_name == 'adversaries':
for adv in results:
adv['atomic_ordering'] = [ab.display for ab_id in adv['atomic_ordering'] for ab in
await self.get_service('data_svc').locate('abilities',
match=dict(ability_id=ab_id))]
if adv['objective']:
adv['objective'] = [ob.display for ob in
await self.get_service('data_svc').locate('objectives',
match=dict(id=adv['objective']))][0]
return results
async def _delete_data_from_memory_and_disk(self, ram_key, identifier, data):
await self.get_service('data_svc').remove(ram_key, data)
_, file_path = await self.get_service('file_svc').find_file_path('%s.yml' % data.get(identifier),
location='data')
if not file_path:
file_path = 'data/%s/%s.yml' % (ram_key, data.get(identifier))
if os.path.exists(file_path):
os.remove(file_path)
return 'Delete action completed'
async def _persist_adversary(self, access, adv):
"""Persist adversary.
Current policy for 'objective' field of adversary: If there isn't an
objective when an adversary is loaded from disk, it gets assigned a
default one, which will then get written out if the adversary is
explicitly saved. Newly created adversaries will also be given default
objective if created without one.
"""
if not adv.get('id') or not adv['id']:
adv['id'] = str(uuid.uuid4())
obj_default = (await self._services.get('data_svc').locate('objectives', match=dict(name='default')))[0]
adv['atomic_ordering'] = [list(ab_dict.values())[0] for ab_dict in adv['atomic_ordering']]
_, file_path = await self.get_service('file_svc').find_file_path('%s.yml' % adv['id'], location='data')
if file_path:
# exists
current_adv = dict(self.strip_yml(file_path)[0])
allowed = (await self.get_service('data_svc').locate('adversaries', dict(adversary_id=adv['id'])))[0].access
current_adv.update(adv)
final = current_adv
else:
# new
file_path = 'data/adversaries/%s.yml' % adv['id']
allowed = self._get_allowed_from_access(access)
adv['objective'] = adv.get('objective', obj_default)
final = adv
# verfiy objective is valid
if len(await self.get_service('data_svc').locate('objectives', match=dict(id=final['objective']))) == 0:
final['objective'] = obj_default.id
await self._save_and_refresh_item(file_path, Adversary, final, allowed)
return [a.display for a in await self._services.get('data_svc').locate('adversaries', dict(adversary_id=final["id"]))]
async def _persist_ability(self, access, ab):
"""Persist ability.
The model/format of the incoming ability (i.e. 'ab') is most similar to the ability
yaml file definition, with a few exceptions:
- 'platforms' sub-dict has sub executor keys split out versus a joined csv string
- 'platforms' executor sub-dicts dont have a 'parsers' field
- 'platforms' executor sub-dicts have a 'timeout' field
Update Strategy:
'new' ability is the ability dict that is supplied
'current' ability is the ability dict as read in directly from yaml file
------------
- on new ability, stash executor timeouts and then drop from new ability
- on new ability, combine executors that are the same under common platform
- on current ability, stash parsers and then drop from current ability
- update current ability with new ability
- add parsers back in to current ability
- save current ability to disk, then re-load ability from file
- check/set executor timeouts on loaded abilities
"""
if not ab.get('id') or not ab['id']:
ab['id'] = str(uuid.uuid4())
new_ability, new_ability_exec_timeouts = await self._prep_new_ability(ab)
_, file_path = await self.get_service('file_svc').find_file_path('%s.yml' % ab['id'], location='data')
if file_path:
# exists
current_ability = dict(self.strip_yml(file_path)[0][0])
allowed = (await self.get_service('data_svc').locate('abilities',
dict(ability_id=ab['id'])))[0].access
current_ability, current_parsers = await self._strip_parsers_from_ability(current_ability)
current_ability.update(new_ability)
final = await self._add_parsers_to_ability(current_ability, current_parsers)
else:
# new
d = 'data/abilities/%s' % new_ability.get('tactic')
if not os.path.exists(d):
os.makedirs(d)
file_path = '%s/%s.yml' % (d, new_ability['id'])
allowed = self._get_allowed_from_access(access)
final = new_ability
await self.get_service('file_svc').save_file(file_path, yaml.dump([final], encoding='utf-8'), '', encrypt=False)
await self.get_service('data_svc').remove('abilities', dict(ability_id=final['id']))
await self.get_service('data_svc').load_ability_file(file_path, allowed)
await self._restore_exec_timeouts(final['id'], new_ability_exec_timeouts)
return [a.display for a in
await self.get_service('data_svc').locate('abilities', dict(ability_id=final['id']))]
async def _persist_source(self, access, source):
return await self._persist_item(access, 'sources', Source, source)
async def _persist_objective(self, access, objective):
return await self._persist_item(access, 'objectives', Objective, objective)
async def _persist_item(self, access, object_class_name, object_class, item):
if not item.get('id') or not item['id']:
item['id'] = str(uuid.uuid4())
_, file_path = await self.get_service('file_svc').find_file_path('%s.yml' % item['id'], location='data')
if file_path:
current_item = dict(self.strip_yml(file_path)[0])
allowed = (await self.get_service('data_svc').locate(object_class_name, dict(id=item['id'])))[0].access
current_item.update(item)
final = item
else:
file_path = 'data/%s/%s.yml' % (object_class_name, item['id'])
allowed = self._get_allowed_from_access(access)
final = item
await self._save_and_refresh_item(file_path, object_class, final, allowed)
return [i.display for i in await self.get_service('data_svc').locate(object_class_name, dict(id=final['id']))]
async def _save_and_refresh_item(self, file_path, object_class, final, allowed):
await self.get_service('file_svc').save_file(file_path, yaml.dump(final, encoding='utf-8'), '', encrypt=False)
await self.get_service('data_svc').load_yaml_file(object_class, file_path, allowed)
async def _prep_new_ability(self, ab):
"""Take an ability dict, supplied by frontend, extract executor timeouts,
and combine executor sub-dicts that are equivalent under a single CSV
formed key under the parent platform.
Return modified ability dict, and a seperate dict of the executor timeouts.
"""
ability = copy.deepcopy(ab)
# remove and store executor timeouts
exec_timeouts = {}
for platform, executors in ability['platforms'].items():
exec_timeouts[platform] = {}
for executor, d in executors.items():
exec_timeouts[platform][executor] = d.get('timeout', 60)
if 'timeout' in ability['platforms'][platform][executor]:
del ability['platforms'][platform][executor]['timeout']
# Combine executors under common CSV keys if they are the same
platforms = {}
for platform, executors in ability['platforms'].items():
platforms[platform] = {}
for executor, d in executors.items():
match = False
for executor_1, d_1 in platforms[platform].items():
if d == d_1:
match = executor_1
break
if match:
combined_key = ','.join([match, executor])
platforms[platform][combined_key] = d
# and remove previous single key in set
del platforms[platform][match]
else:
platforms[platform][executor] = d
ability['platforms'] = platforms
return ability, exec_timeouts
async def _strip_parsers_from_ability(self, ability):
"""Remove the parsers sub-dict from the executors of an ability
(where the ability is not an ability object but just the loaded
dict from yaml ability file)
Return ability (minus parsers) and parsers as seperate dict
"""
parsers = {}
for platform, executors in ability['platforms'].items():
parsers[platform] = {}
for executor, d in executors.items():
if d.get('parsers', False):
parsers[platform][executor] = d['parsers']
del ability["platforms"][platform][executor]['parsers']
return ability, parsers
async def _add_parsers_to_ability(self, ability, parsers):
"""Add parsers back into an ability (where the ability is
not an ability object but just the loaded dict from yaml
ability file)
"""
for platform, executors in ability['platforms'].items():
if parsers.get(platform, False):
for executor, _ in executors.items():
if parsers[platform].get(executor, False):
ability['platforms'][platform][executor]['parsers'] = parsers[platform][executor]
return ability
async def _restore_exec_timeouts(self, ability_id, exec_timeouts):
"""For the supplied ability, set corresponding executor timeouts."""
abilities = await self.get_service('data_svc').locate('abilities', dict(ability_id=ability_id))
for ab in abilities:
ab.timeout = exec_timeouts[ab.platform][ab.executor]
await self.get_service('data_svc').store(ab)