-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathzf2th.py
executable file
·431 lines (366 loc) · 13.9 KB
/
zf2th.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
#!/usr/bin/env python3
# coding: utf-8
import sys
import os
import json
import logging
import getpass
import argparse
import base64
from PIL import Image
from io import BytesIO
from Zerofox.api import ZerofoxApi
from config import Zerofox, TheHive
from thehive4py.api import TheHiveApi
from thehive4py.models import Alert, AlertArtifact
from zf2markdown import th_title, th_case_description
class monitoring():
def __init__(self, file):
self.monitoring_file = file
def touch(self):
"""
touch status file when successfully terminated
"""
if os.path.exists(self.monitoring_file):
os.remove(self.monitoring_file)
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("ZF:{}".format(newtag))
return t
def th_severity(sev):
"""
convert ZeroFOX severity in TH severity
:param sev: ZF severity
:type sev: string
:return TH severity
:rtype: int
"""
severities = {
'NONE': 1,
1: 1,
2: 1,
3: 2,
4: 3,
5: 3
}
return severities[sev]
def add_alert_artifact(artifacts, data_type, data, tags, tlp):
"""
:param artifacts: array
:param data_type: string
:param data: string
:param tags: array
:param tlp: int
:return: array
:rtype: array
"""
if data is not None:
return artifacts.append(AlertArtifact(tags=tags,
dataType=data_type,
data=str(data),
message="From Zerofox",
tlp=tlp)
)
def init_artifact_tags(content):
"""
param content:
type content:
return: list of tags
rtype: array
"""
return ["src:ZEROFOX",
"ZF:Perpetrator",
"Network:{}".format(content.get('network', 'None'))
]
def prepare_artifacts(content):
"""
param content: Zerofox alert
type content: dict
return: list AlertArtifact
rtype: array
"""
artifacts = []
if content.get('perpetrator'):
perpetrator = content.get('perpetrator')
add_alert_artifact(artifacts,
'other',
perpetrator.get('display_name', None),
add_tags(init_artifact_tags(content),
['{}=\"Display Name\"'.format(perpetrator.get('network', None))]
),
2)
add_alert_artifact(artifacts,
'url', perpetrator.get('url', None),
init_artifact_tags(content),
2)
add_alert_artifact(artifacts,
'other',
perpetrator.get('account_number', None),
add_tags(init_artifact_tags(content),
['{}=\"Account Number\"'.format(perpetrator.get('network', 'None'))]
),
2)
add_alert_artifact(artifacts,
'other',
perpetrator.get('id', None),
add_tags(init_artifact_tags(content),
['{}=\"id\"'.format(perpetrator.get('network'))]
),
2)
if perpetrator.get('username') != '':
add_alert_artifact(artifacts,
'other',
perpetrator.get('username', None),
add_tags(init_artifact_tags(content),
['{}=\"Username\"'.format(perpetrator.get('network', 'None'))]
),
2)
try:
if json.loads(content.get('metadata')).get('occurrences'):
add_alert_artifact(artifacts, 'other', '{}'.format(
json.loads(content.get('metadata')).get(
'occurrences', 'None')[0].get(
'text', 'None')),
add_tags(init_artifact_tags(content),
['type=\"{}\"'.format(perpetrator.get('type'))]),
2)
except json.decoder.JSONDecodeError:
pass
return artifacts
def prepare_alert(content, thumbnails):
"""
convert a ZeroFOX alert into a TheHive alert
:param incident: Zerofox Alert
:type incident: dict
:type thumbnails: dict
:return: Thehive alert
:rtype: thehive4py.models Alerts
"""
case_tags = ["src:ZEROFOX"]
case_tags = add_tags(case_tags, [
"Type={}".format(content.get("alert_type")),
"Network={}".format(content.get("network")),
"Entity={}".format(content.get("entity", {}).get("name", "-")),
"Id={}".format(content.get('id'))
])
alert = Alert(title=th_title(content),
tlp=2,
tags=case_tags,
severity=th_severity(content.get('severity', "3")),
description=th_case_description(content, thumbnails),
type='{}'.format(content.get('alert_type')),
source='Zerofox',
caseTemplate=TheHive['template'],
sourceRef=str(content.get('id')),
artifacts=prepare_artifacts(content))
logging.debug("prepare_alert: alert built for \
ZF id #{}".format(content.get('id')))
return alert
def create_th_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:
response = thapi.create_alert(a)
logging.debug('API TheHive - status code: {}'.format(
response.status_code))
if response.status_code > 299:
logging.debug('API TheHive - raw error output: {}'.format(
response.raw.read()))
def get_alerts(zfapi, id_list):
"""
:type zfapi: Zerofox.api.ZerofoxApi
:param id_list: list of alert id
:type id_list: array
:return: TheHive alert
:rtype: thehive4py.models Alert
"""
while id_list:
id = id_list.pop()
response = zfapi.get_alerts(id)
if response.get('status') == "success":
data = response.get('data').get('alert')
logging.debug('get_alerts(): {} ZF alert(s)\
downloaded'.format(data.get('id')))
entity_image_url = data.get('entity', None).get('image', None)
perpetrator_image_url = data.get('perpetrator', None).get(
'image', None)
thumbnails = build_thumbnails(zfapi, entity_image_url,
perpetrator_image_url)
yield prepare_alert(data, thumbnails)
else:
logging.debug("get_alerts(): Error while \
fetching alert #{}: {}".format(id, response.get('data')))
sys.exit("get_alerts(): Error while \
fetching alert #{}: {}".format(id, response.get('data')))
def find_alerts(zfapi, last):
"""
:type zfapi: Zerofox.api.ZerofoxApi
:param id_list: list of alert id
:type id_list: array
:return: TheHive alert
:rtype: thehive4py.models Alert
"""
response = zfapi.find_alerts(last)
if response.get('status') == "success":
data = response.get('data').get('alerts')
logging.debug('find_alerts(): {} ZF alert(s)\
downloaded'.format(response.get('data').get('count')))
for a in data:
logging.debug('find_alerts(): building alert {}\
downloaded'.format(a.get('id')))
entity_image_url = a.get("entity", None).get("image", None)
perpetrator_image_url = a.get('perpetrator', None).get(
'image', None)
thumbnails = build_thumbnails(zfapi, entity_image_url,
perpetrator_image_url)
yield prepare_alert(a, thumbnails)
def base64_image(content, width):
"""
:param content: raw image
:type content: raw
:param width: size of the return image
:type width: int
:return: base64 encoded image
:rtype: string
"""
try:
fd = BytesIO(content)
image = Image.open(fd)
ft = image.format
# basewidth = width
wpercent = (width / float(image.size[0]))
if image.size[0] > width:
hsize = int(float(image.size[1]) * float(wpercent))
image = image.resize((width, hsize), Image.ANTIALIAS)
ImgByteArr = BytesIO()
image.save(ImgByteArr, format=ft)
ImgByteArr = ImgByteArr.getvalue()
with BytesIO(ImgByteArr) as bytes:
encoded = base64.b64encode(bytes.read())
base64_image = encoded.decode()
return base64_image
except Exception as e:
return "No image"
def build_thumbnails(zfapi, entity_image_url, perpetrator_image_url):
"""
:param zfapi:
:type zfapi:
:param entity_image_url:
:type entity_image_url: string
:param perpetrator_image_url:
:type perpetrator_image_url: string
:return: base64 encoded images ready to be added in markdown
:rtype: dict
"""
if entity_image_url is not None:
resp_entity_image = zfapi.get_image(entity_image_url)
entity_image = "data:{};base64,{}".format(
resp_entity_image.headers['Content-Type'],
base64_image(resp_entity_image.content, 400))
else:
entity_image = "no image"
perpetrator_image = "no image"
if perpetrator_image_url is not None:
resp_perpetrator_image = zfapi.get_image(perpetrator_image_url)
if resp_perpetrator_image is not None:
perpetrator_image = "data:{};base64,{}".format(
resp_perpetrator_image.headers['Content-Type'],
base64_image(resp_perpetrator_image.content, 400))
return {
"entity_image": entity_image,
"perpetrator_image": perpetrator_image
}
def run():
"""
Download ZeroFOX alerts and create a new alert in TheHive
"""
def get_api(args):
if "password" not in Zerofox:
Zerofox['username'] = input("ZeroFOX username"
"[%s]: " % getpass.getuser())
Zerofox['password'] = getpass.getpass("ZeroFOX password: ")
zfapi = ZerofoxApi(Zerofox)
t = zfapi.getApiKey()
if t.get("status") == "success":
print("Key = {}\n"
"Add this to your config.py file to "
"start fetching alerts".format(t.get("data")['token']))
sys.exit(0)
else:
print(t.get("content"))
sys.exit(1)
def alerts(args):
zfapi = ZerofoxApi(Zerofox)
alerts = get_alerts(zfapi, args.id)
create_th_alerts(TheHive, alerts)
def find(args):
last = args.last.pop()
zfapi = ZerofoxApi(Zerofox)
alerts = find_alerts(zfapi, last)
create_th_alerts(TheHive, alerts)
if args.monitor:
mon = monitoring("{}/zf2th.status".format(
os.path.dirname(os.path.realpath(__file__))))
mon.touch()
parser = argparse.ArgumentParser(description="Retrieve ZeroFOX \
alerts and feed them to 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_api = subparsers.add_parser("api", help="get your API key")
parser_api.set_defaults(func=get_api)
parser_alert = subparsers.add_parser('alerts', help="fetch alerts by ID")
parser_alert.add_argument("id",
metavar="ID",
action='store',
type=int,
nargs='+',
help="get ZF alerts by ID")
parser_alert.set_defaults(func=alerts)
parser_find = subparsers.add_parser('find',
help="find open alerts")
parser_find.add_argument("-l", "--last",
metavar="M",
nargs=1,
type=int,
required=True,
help="get all alerts published during the last [M] minutes")
parser_find.add_argument("-m", "--monitor",
action='store_true',
default=False,
help="active monitoring")
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='{}/zf2th.log'.format(
os.path.dirname(os.path.realpath(__file__))),
level='DEBUG', format='%(asctime)s\
%(levelname)s\
%(message)s')
args.func(args)
if __name__ == '__main__':
run()