-
Notifications
You must be signed in to change notification settings - Fork 3
/
MISPController.py
286 lines (221 loc) · 6.44 KB
/
MISPController.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
# Copyright (c) 2018 LAC Co.,Ltd.
# All rights reserved.
#
# This software is released under the BSD License.
# https://opensource.org/licenses/BSD-2-Clause
import time, datetime, traceback
from pymisp import ExpandedPyMISP, MISPEvent, MISPAttribute, MISPTag
import urllib3
from urllib3.exceptions import InsecureRequestWarning
urllib3.disable_warnings(InsecureRequestWarning)
class MISPController(object):
''' MISP Controller '''
def __init__(self, misp_param, debug = False):
self.misp_param = misp_param
self.debug = debug
if misp_param.get('connect_immediately', False):
self._connect()
else:
self.misp = None
def import_event(self, event_data):
''' Import event '''
# Check registered same event info
print('importing: {}'.format(event_data['title']))
events = self._search_event(eventinfo = event_data['title'])
if events != None:
for event in events:
if event_data['title'] == event['Event']['info']:
self._remove_event(event['Event']['id'])
event = self._add_event(event_data)
if event:
print('created event: {}'.format(event.id))
else:
print("Import failed.Please retry: {}".format(event_data['title']))
def _connect(self):
self.debug_print('URL: {}'.format(self.misp_param['url']))
self.debug_print('authkey: {}'.format(self.misp_param['authkey']))
self.misp = ExpandedPyMISP(self.misp_param['url'], self.misp_param['authkey'], ssl=False, debug=False)
self._registered_tags = self.misp.tags()
def _check_tag(self, target_tag):
if self.misp == None:
self._connect()
if self._registered_tags == None:
self._get_tags()
for tag_info in self._registered_tags:
if tag_info.get('name', '') == target_tag:
return True
self.debug_print('new tag: {}'.format(target_tag))
cnt = 0
while True:
try:
if self.misp == None:
self._connect()
tmp = MISPTag()
tmp.from_dict(name=target_tag)
self.misp.add_tag(tmp)
self._get_tags()
return True
except:
print(traceback.format_exc())
if cnt < int(self.misp_param.get('max_retry_count', '0')):
print('add new tag retry: {}'.format(cnt))
cnt = cnt + 1
time.sleep(10)
else:
return False
def _add_event(self, value):
for tag in value['event_tags']:
self._check_tag(tag)
for attribute in value['attributes']:
for tag in attribute['tags']:
self._check_tag(tag)
cnt = 0
while True:
try:
if self.misp == None:
self._connect()
tmp = MISPEvent()
tmp.from_dict(
distribution = self.misp_param['distribution']
, threat_level_id = self.misp_param['threat_level_id']
, analysis = self.misp_param['analysis']
, info = value['title']
, date = value['date']
, published = False
)
response = self.misp.add_event(tmp)
if response.get('errors'):
raise Exception(str(response['errors']))
event = MISPEvent()
event.load(response)
break
except:
print(traceback.format_exc())
if cnt < int(self.misp_param.get('max_retry_count', '0')):
print('add new event retry: {}'.format(cnt))
cnt = cnt + 1
time.sleep(10)
else:
return None
self.debug_print(event.id)
for tag in value['event_tags']:
event.add_tag(tag)
for attribute in value['attributes']:
attribute_tags = []
event.add_attribute(
type = attribute['type']
, value = attribute['value']
, category = attribute['category']
, comment = attribute.get('comment', '')
, distribution = self.misp_param['distribution']
, Tag = self._create_tags(attribute['tags'])
)
event.published = True
if self._update_event(event):
self.debug_print('completed')
return event
else:
self.debug_print('add failed')
return None
def _get_event(self, id):
cnt = 0
while True:
try:
if self.misp == None:
self._connect()
self.debug_print('get event start: {}'.format(id))
event=self.misp.get_event(id)
if event.get('errors'):
raise Exception(str(event['errors']))
self.debug_print('get event end: {}'.format(id))
return event
except:
print(traceback.format_exc())
if cnt < int(self.misp_param.get('max_retry_count', '0')):
print('get event retry: {}'.format(cnt))
cnt = cnt + 1
time.sleep(10)
else:
return None
def _remove_event(self, id):
if id:
print('delete event: {}'.format(id))
cnt = 0
while True:
try:
if self.misp == None:
self._connect()
response = self.misp.delete_event(id)
if response.get('errors'):
raise Exception(str(response['errors']))
return True
except:
print(traceback.format_exc())
if cnt < int(self.misp_param.get('max_retry_count', '0')):
print('remove event retry: {}'.format(cnt))
cnt = cnt + 1
time.sleep(10)
else:
return False
def _search_event(self, **cons):
cnt = 0
while True:
try:
if self.misp == None:
self._connect()
self.debug_print('search event start')
response = self.misp.search_index(**cons)
self.debug_print('search event end')
results = []
for json in response:
if json.get('id', ''):
results.append(self._get_event(json['id']))
else:
print('no event ID')
print(json)
return results
except:
print(traceback.format_exc())
if cnt < int(self.misp_param.get('max_retry_count', '0')):
print('search event retry: {}'.format(cnt))
cnt = cnt + 1
time.sleep(10)
else:
return None
def _update_event(self, event):
cnt = 0
while True:
try:
if self.misp == None:
self._connect()
self.debug_print('event update start: {}'.format(event.id))
response = self.misp.update_event(event)
if response.get('errors'):
raise Exception(str(response['errors']))
self.debug_print('{} updated'.format(event.id))
return True
except:
print(traceback.format_exc())
if cnt < int(self.misp_param.get('max_retry_count', '0')):
print('retry: {}'.format(cnt))
cnt = cnt + 1
time.sleep(10)
else:
print('event update failed: {}'.format(event.info))
try:
self._remove_event(event.id)
except:
pass
return False
def _create_tags(self, values):
tags=[]
for value in values:
if value:
tags.append({'name': value})
return tags
def debug_print(self, message):
if self.debug == False:
return
# nowstr = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
nowstr = datetime.datetime.now().strftime('%H:%M:%S')
print('{}\t{}'.format(nowstr, message))