-
Notifications
You must be signed in to change notification settings - Fork 10
/
ds2th.py
executable file
·531 lines (440 loc) · 17.5 KB
/
ds2th.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import re
import argparse
import datetime
from io import BytesIO
import base64
import logging
from DigitalShadows.api import DigitalShadowsApi
from thehive4py.api import TheHiveApi
from thehive4py.models import Alert, AlertArtifact
from config import DigitalShadows,TheHive
from ds2markdown import ds2markdown, databreach_message
class monitoring():
def __init__(self, file):
self.monitoring_file = file
def touch(self):
"""
//touch status file when successfully terminated
"""
try:
os.utime(self.monitoring_file, None)
except FileNotFoundError:
open(self.monitoring_file, 'a').close()
def add_tags(tags, content):
"""
add tag to tags
:param tags: existing tags
:type tags: list
:param content: string, mainly like taxonomy
:type content: string
"""
t = tags
for newtag in content:
t.append("DS:{}".format(newtag))
return t
def th_alert_tags(incident):
"""
Convert DS incident tags into TH tags
:param incident: DS incident
:type incident: dict
:return: TH tags
:rtype: list
"""
tags = []
add_tags(tags, ["id={}".format(incident.get('id')), "type={}".format(incident.get('type'))])
for t in incident.get('tags'):
add_tags(tags, ["{}={}".format(t.get('type'),t.get('name'))])
return tags
def th_severity(sev):
"""
convert DigitalShadows severity in TH severity
:param sev: DS severity
:type sev: string
:return TH severity
:rtype: int
"""
severities = {
'NONE':1,
'VERY_LOW':1,
'LOW':1,
'MEDIUM':2,
'HIGH':3,
'VERY_HIGH':3
}
return severities[sev]
def th_dataType(type):
"""
convert DigitalShadows IOC type to TH dataType
:param type: DS type
:type type: str
:return: TH dataType
:rtype: str
"""
types = {
'IP':'ip',
'HOST': 'domain',
'URL':'url',
'SHA256':'hash',
'SHA1':'hash',
'MD5':'hash',
'FILENAME':'filename',
'FILEPATH':'filename',
'EMAIL': 'mail'
}
if type in types:
return types[type]
else:
return "other"
def add_alert_artefact(artefacts, dataType, data, tags, tlp):
"""
:type artefacts: array
:type dataType: string
:type data: string
:type tags: array
:type tlp: int
:rtype: array
"""
return artefacts.append(AlertArtifact(tags=tags,
dataType=dataType,
data=data,
message="From DigitalShadows",
tlp=tlp)
)
def build_observables(observables):
"""
Convert DS observables into TheHive observables
:param observables: observables from DS
:type observables: dict
:return: AlertArtifact
:rtype: thehive4py.models AlertArtifact
"""
artefacts = []
if observables.get('total', 0) > 0:
for ioc in observables.get('content'):
a = AlertArtifact(
data=ioc.get('value'),
dataType=th_dataType(ioc.get('type')),
message="Observable from DigitalShadows. \
Source: {}".format(ioc.get('source')),
tlp=2,
tags=["src:DigitalShadows"]
)
artefacts.append(a)
return artefacts
def databreach_list(iocs):
"""
Return str content for csv file
:param iocs:
:return:
"""
csv = ''
index=[]
if len(iocs) > 0 and type(iocs[0] is dict):
for k, v in iocs[0].items():
if type(v) is str:
csv += f"{k};"
index.append(k)
for ioc in iocs:
csv += "\n"
for i in index:
csv += f"{ioc.get(i, '')};"
return csv
def build_observables_from_databreach(observables):
"""
Convert DS observables into TheHive observables
:param observables: observables from DS
:type observables: dict
:return: AlertArtifact
:rtype: thehive4py.models AlertArtifact
"""
artefacts = []
if observables.get('total', 0) > 0:
for ioc in observables.get('content'):
a = AlertArtifact(
data=ioc.get('username'),
dataType="mail" if bool(re.search(r"^[A-Za-z0-9\.\+\-\_]+\@[\w\d\-\_\.]+\.[a-zA-Z]{2,3}$", ioc.get('username'))) else "other",
message=databreach_message(ioc),
tlp=2,
tags=["src:DigitalShadows", "databreach"]
)
artefacts.append(a)
leakfile = '/tmp/leak.csv'
leakfd = open( leakfile, 'w')
leakfd.write(databreach_list(observables.get('content')))
leakfd.close()
artefacts.append(AlertArtifact(dataType="file",
data=leakfile,
message="List of records from DigitalShadows",
tlp=2,
tags=["src:DigitalShadows", "databreach"])
)
return artefacts
def build_alert(incident, type, observables, thumbnail):
"""
Convert DigitalShadows alert into a TheHive Alert
:param incident: Incident from DS
:type incident: dict
:param observables: observables from DS
:type observables: dict
:type thumbnail: str
:return: Thehive alert
:rtype: thehive4py.models Alerts
"""
template = TheHive.get('templates').get(incident.get('type'), 'default')
if type in ['incident', 'intel-incident']:
obs=build_observables(observables)
elif type in ['databreach']:
obs = build_observables_from_databreach(observables.get('data'))
a = Alert(title="{}".format(incident.get('title')),
tlp=2,
severity=th_severity(incident.get('severity')),
description=ds2markdown(incident, thumbnail).thdescription,
type=incident.get('type'),
tags=th_alert_tags(incident),
caseTemplate=template,
source="DigitalShadows",
sourceRef=str(incident.get('id')),
artifacts=obs
)
logging.debug("build_alert: alert built for DS id #{}".format(incident.get('id')))
return a
def find_incidents(dsapi, since):
"""
:param dsapi: DigitalShadows.api.DigitalShadowsApi
:param since: number of minutes
:type since: int
:return: list of thehive4py.models Alerts
:rtype: array
"""
inc_type = "incident"
s = "{}/{}".format((datetime.datetime.utcnow() - datetime.timedelta(minutes=int(since))).isoformat(),
datetime.datetime.utcnow().isoformat())
response = dsapi.find_incidents(s)
if response.get('status') == "success":
data = response.get('data')
logging.debug('find_incidents(): {} DS incident(s) downloaded'.format(data.get('total')))
for i in data.get('content'):
iocs = {}
# add records for databreaches
if i.get('entitySummary') and i.get('entitySummary').get('screenshotThumbnailId'):
thumbnail = build_thumbnail(dsapi, i.get('entitySummary').get('screenshotThumbnailId'))
else:
thumbnail = {'thumbnail':""}
# add records for databreaches
if data.get('entitySummary') and data.get('entitySummary').get('dataBreach'):
inc_type = "databreach"
iocs = dsapi.get_databreach_records(data.get('entitySummary') and data.get('entitySummary').get('dataBreach').get('id'))
yield build_alert(i, inc_type, iocs, thumbnail)
else:
logging.debug("find_incidents(): Error while fetching incident #{}: {}".format(id, response.get('data')))
sys.exit("find_incidents(): Error while fetching incident #{}: {}".format(id, response.get('data')))
def get_incidents(dsapi, id_list):
"""
:type dsapi: DigitalShadows.api.DigitalShadowsApi
:param id_list: list of incident id
:type id_list: array
:return: TheHive alert
:rtype: thehive4py.models Alert
"""
inc_type = "incident"
while id_list:
iocs = {}
id = id_list.pop()
response = dsapi.get_incident(id)
if response.get('status') == 'success':
data = response.get('data')
logging.debug('get_incidents(): DS incident {} fetched'.format(data.get('id')))
# Add Thumbnail or screenshot if exist
if data.get('entitySummary') and data.get('entitySummary').get('screenshotThumbnailId'):
thumbnail = build_thumbnail(dsapi, data.get('entitySummary').get('screenshotThumbnailId'))
else:
thumbnail = {'thumbnail': ""}
# add records for databreaches
if data.get('entitySummary') and data.get('entitySummary').get('dataBreach'):
inc_type = "databreach"
iocs = dsapi.get_databreach_records(data.get('entitySummary') and data.get('entitySummary').get('dataBreach').get('id'))
yield build_alert(data, inc_type, iocs, thumbnail)
else:
logging.debug("get_incidents(): Error while fetching incident #{}: {}".format(id, response.get('data')))
sys.exit("get_incidents: Error while fetching incident #{}: {}".format(id, response.get('data')))
def find_intel_incidents(dsapi, since):
"""
:type dsapi: DigitalShadows.api.DigitalShadowsApi
:param since: number of minutes, period of time
:type since: int
:return: alert
:rtype: thehive4py.models Alert
"""
inc_type = "intel-incident"
s = "{}/{}".format((datetime.datetime.utcnow() - datetime.timedelta(minutes=int(since))).isoformat(),
datetime.datetime.utcnow().isoformat())
response = dsapi.find_intel_incidents(s)
if response.get('status') == "success":
data = response.get('data')
logging.debug('find_intel_incidents(): {} DS intel-incident(s) downloaded'.format(data.get('total')))
for i in data.get('content'):
iocs = {}
if i.get('entitySummary') and i.get('entitySummary').get('screenshotThumbnailId'):
thumbnail = build_thumbnail(dsapi, i.get('entitySummary').get('screenshotThumbnailId'))
else:
thumbnail = {'thumbnail':''}
iocs = dsapi.get_intel_incident_iocs(i.get('id')).json()
yield build_alert(i, inc_type, iocs, thumbnail)
else:
logging.debug("find_intel_incidents(): Error while searching intel-incidents since {} min: {}".format(s, response.get('data')))
sys.exit("find_intel_incidents(): Error while searching intel-incidents since {} min: {}".format(s, response.get('data')))
def get_intel_incidents(dsapi, id_list):
"""
:param dsapi: DigitalShadows api init
:type dsapi:
:param id: intel-incident id
:type id: list
:return: Thehive alert
:rtype: thehive4py.models Alert
"""
inc_type = "intel-incident"
while id_list:
iocs = {}
id = id_list.pop()
response = dsapi.get_intel_incident(id)
if response.get('status') == "success":
data = response.get('data')
logging.debug('get_incidents(): DS intel-incident {} fetched'.format(data.get('id')))
if data.get('entitySummary') and data.get('entitySummary').get('screenshotThumbnailId'):
thumbnail = build_thumbnail(dsapi, data.get('entitySummary').get('screenshotThumbnailId'))
else:
thumbnail = {'thumbnail': ""}
iocs = dsapi.get_intel_incident_iocs(data.get('id')).json()
yield build_alert(data, inc_type, iocs, thumbnail)
else:
logging.debug("Error while fetching intel-incident #{}: {}".format(id, response.get('data')))
sys.exit("Error while fetching intel-incident #{}: {}".format(id, response.get('data')))
def build_thumbnail(dsapi, thumbnail_id):
"""
Get DigitalShadows intel-incident screenshot thumbnail
:param dsapi:
:type dsapi: DigitalShadows.api.DigitalShadowsApi
:param thumbnail_id:
:type thumbnail_id: string
:return: dict with base64 pict ready to be added in markdown
"""
response = dsapi.get_thumbnail(thumbnail_id)
if response.status_code == 200:
with BytesIO(response.content) as bytes:
encoded = base64.b64encode(bytes.read())
b64_thumbnail = encoded.decode()
return {"thumbnail":"data:{};base64,{}".format(response.headers['Content-Type'], b64_thumbnail)}
else:
return {"thumbnail": ""}
def databreach_records(dsapi, databreach_id):
"""
Return list of interesting records in the databreach
:param dsapi:
:param databreach_id:
:return:
"""
return dsapi.get_databreach_records(databreach_id)
def create_thehive_alerts(config, alerts):
"""
:param config: TheHive config
:type config: dict
:param alerts: List of alerts
:type alerts: list
:return: create TH alert
"""
thapi = TheHiveApi(config.get('url', None), config.get('key'), config.get('password', None),
config.get('proxies'))
for a in alerts:
if config.get('templates').get(a.type):
a.caseTemplate = config.get('templates').get(a.type)
thapi.create_alert(a)
def run():
"""
Download DigitalShadows incident and create a new alert in TheHive
"""
try:
logfile = DigitalShadows.get('log_file')
monitoringfile = DigitalShadows.get('monitoring_file')
print(monitoringfile)
except ModuleNotFoundError as e:
logging.debug("Error while importing config, check config.py file in config folder: \n{}".format(e))
sys.exit("Error while importing config, check config.py file in config/ folder or debug logs")
def find(args):
if 'last' in args and args.last is not None:
last = args.last.pop()
if (not args.i ^ args.I) or args.I:
intel = find_intel_incidents(dsapi, last)
create_thehive_alerts(TheHive, intel)
if (not args.i ^ args.I) or args.i:
incidents = find_incidents(dsapi, last)
create_thehive_alerts(TheHive, incidents)
if args.monitor:
mon = monitoring(monitoringfile)
mon.touch()
def inc(args):
if 'intel_incidents' in args and args.intel_incidents is not None:
intel_incidents = get_intel_incidents(dsapi, args.intel_incidents)
create_thehive_alerts(TheHive, intel_incidents)
if 'incidents' in args and args.incidents is not None:
incidents = get_incidents(dsapi, args.incidents)
create_thehive_alerts(TheHive, incidents)
parser = argparse.ArgumentParser(
description="Get DS incidents and intel-incidents and create alerts in TheHive")
parser.add_argument("-d", "--debug",
action='store_true',
default=False,
help="generate a log file and active debug logging")
subparsers = parser.add_subparsers(help="subcommand help")
parser_incident = subparsers.add_parser('inc',
help="fetch incidents or \
intel-incidents by ID")
parser_incident.add_argument("-i", "--incidents",
metavar="ID",
action='store',
type=int,
nargs='+',
help="Get DS incidents by ID")
parser_incident.add_argument("-I", "--intel-incidents",
metavar="ID",
action='store',
type=int, nargs='+',
help="Get DS intel-incidents by ID")
parser_incident.set_defaults(func=inc)
parser_find = subparsers.add_parser('find',
help="find incidents and \
intel-incidents in time")
parser_find.add_argument("-l", "--last",
metavar="M",
nargs=1,
type=int,required=True,
help="Get all incidents published during\
the last [M] minutes")
parser_find.add_argument("-m", "--monitor",
action='store_true',
default=False,
help="active monitoring")
parser_find.add_argument("-i",
action='store_true',
default=False,
help="Get Digital Shadows incidents only")
parser_find.add_argument("-I",
action='store_true',
default=False,
help="Get Digital Shadows intel-incidents only")
parser_find.set_defaults(func=find)
if len(sys.argv[1:]) == 0:
parser.print_help()
parser.exit()
args = parser.parse_args()
if args.debug:
logging.basicConfig(filename=logfile,
level='DEBUG',
format='%(asctime)s %(levelname)s %(message)s')
dsapi = DigitalShadowsApi(DigitalShadows)
args.func(args)
if __name__ == '__main__':
run()