-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
ThreatQ.py
330 lines (270 loc) · 10.6 KB
/
ThreatQ.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
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
''' IMPORTS '''
import os
import datetime
import requests
import json
# disable insecure warnings
requests.packages.urllib3.disable_warnings()
''' GLOBAL VARS '''
API_URL = demisto.params()['apiUrl']
API_TOKEN_URL = API_URL + "/token"
CLIENT_ID = demisto.params()['client_id']
EMAIL = demisto.getParam('credentials').get('identifier')
PASSWORD = demisto.getParam('credentials').get('password')
USE_SSL = not demisto.params().get('insecure', False)
''' HELPER FUNCTIONS '''
def load_proxy():
# Load the system configured proxy if enabled in configuration
proxy = {}
if 'proxy' in demisto.params():
proxy["http"] = os.environ["http_proxy"]
proxy["https"] = os.environ["https_proxy"]
return proxy
PROXY = load_proxy()
def get_errors_string_from_bad_request(bad_request_results):
errors_list = bad_request_results.json().get("errors", [])
errors_string = ""
error_num = 1
if errors_list:
errors_string = "Errors from server: \n"
for error in errors_list:
errors_string += "Error #{0}: {1}\n".format(error_num, error)
error_num += 1
return errors_string
# ThreatQ auth based on OAuth 2.0 credential grand method
def tq_access():
data = {'grant_type': 'password','email': EMAIL, 'password': PASSWORD, 'client_id': CLIENT_ID}
access_token_response = requests.post(API_TOKEN_URL, data=data, verify=False, allow_redirects=False)
tokens = json.loads(access_token_response.text)
if int(access_token_response.status_code) >= 400:
errors_string = get_errors_string_from_bad_request(access_token_response)
error_message = "Authentication failed, unable to retrieve an access token.\n {}".format(errors_string)
return_error(error_message)
new_integration_context = {
"access_token": tokens['access_token'],
"access_token_creation_time": int(time.time()) -1, # decrementing one second to be on the safe side
"access_token_expires_in": tokens['expires_in']
}
demisto.setIntegrationContext(new_integration_context)
token = tokens['access_token']
return token
def access_token_not_expired():
epoch_time_now = time.time()
epoch_time_when_token_granted = demisto.getIntegrationContext().get("access_token_creation_time")
token_time_until_expiration = demisto.getIntegrationContext().get("access_token_expires_in")
return int(epoch_time_now) - int(epoch_time_when_token_granted) < int(token_time_until_expiration)
def get_access_token():
existing_access_token = demisto.getIntegrationContext().get("access_token")
if existing_access_token and access_token_not_expired():
return existing_access_token
else:
new_access_token = tq_access()
return new_access_token
# remove html tags from ThreatQ description field
def cleanhtml(raw_html):
cleanr = re.compile('<.*?>')
cleantext = re.sub(cleanr, '', raw_html)
return cleantext
''' Catch-all function for all command '''
def query_tq(keyword):
'''
This function handles all the querying of threatq
'''
tq_url = API_URL + "/search?query=" + keyword
access_token = get_access_token()
api_call_headers = {'Authorization': 'Bearer ' + access_token}
api_call_response = requests.get(tq_url, headers=api_call_headers, verify=False)
response = json.loads(api_call_response.text)
# Find ThreatQ object type and object id based on keyword search results
try:
object_type = str(response['data'][0]['object'])
object_id = str(response['data'][0]['id']) # get the object id from the query results
except Exception, e:
results = {'ContentsFormat': formats['markdown'], 'Type': entryTypes['note'], 'Contents': "No results from ThreatQ"}
return results
results = describe_by_id(object_type,object_id)
return results
''' FUNCTIONS '''
''' Get ThreatQ object details '''
def describe_by_id(tq_obj_type,tq_obj_id):
md = ''
# build the ThreatQ query url
if tq_obj_type == "indicator":
tq_url = API_URL + "/indicators" + "/" + tq_obj_id
elif tq_obj_type == "adversary":
tq_url = API_URL + "/adversaries" + "/" + tq_obj_id
elif tq_obj_type == "event":
tq_url = API_URL + "/events" + "/" + tq_obj_id
else:
tq_url = API_URL + "/" + tq_obj_type + "/" + tq_obj_id
# get ThreatQ response
access_token = get_access_token()
api_call_headers = {'Authorization': 'Bearer ' + access_token}
api_call_response = requests.get(tq_url, headers=api_call_headers, verify=False)
response = json.loads(api_call_response.text)
if not response or len(response['data']) == 0:
return "Found in ThreatQ, but no context"
description = response['data']['description']
name = response['data']['value']
tq_attributes = None
dbot_score = None
if tq_obj_type == "indicator":
result = tq_indicator(name)
tq_attributes = result['attributes']
dbot_score = result['dbotscore']
# Description in clear text will be sent to War Room
if description:
clean_desc = cleanhtml(description)
else:
clean_desc = "No description found in ThreatQ"
last_update = str(response['data']['updated_at'])
tq_desc = {
'name': name,
'last_update' : last_update,
'description' : clean_desc,
'is_indicator': str(tq_obj_type == "indicator")
}
md += "## TQ Object: " + tq_obj_type + " ID: " + tq_obj_id + "\n"
# Build a ThreatQ Response table
md += tableToMarkdown('ThreatQ Response',tq_desc)
if tq_obj_type == "indicator":
if not tq_attributes or len(tq_attributes) == 0:
md += "Found no attributs"
else:
md += tableToMarkdown("Attributes", tq_attributes)
tq_desc.update(tq_attributes)
entry2 = {
'Type': entryTypes['note'],
'Contents': tq_desc,
'ContentsFormat': formats['json'],
'ReadableContentsFormat': formats['markdown'],
'HumanReadable': md,
'EntryContext': {'ThreatQ(val.name && val.name == obj.name)': createContext(tq_desc, removeNull=True)},
}
if dbot_score:
entry2['EntryContext']['DBotScore(val.Vendor && val.Indicator && val.Vendor == obj.Vendor && val.Indicator == obj.Indicator)'] = createContext(dbot_score, removeNull=True)
return entry2
def create_dbot_score(ind_name, ind_score):
return dbot_score
''' Get ThreatQ indicator's score and attributes '''
def tq_indicator(indicator):
'''
This function parse all the attributes of an indicator
'''
tq_url = API_URL + "/indicators/?value=" + indicator + "&with=score,attributes,sources"
# get ThreatQ response on indicators attributes
access_token = get_access_token()
api_call_headers = {'Authorization': 'Bearer ' + access_token}
api_call_response = requests.get(tq_url, headers=api_call_headers, verify=False)
try:
response = json.loads(api_call_response.text)
except requests.exceptions.RequestException as e:
md += '## TQ cound not FIND this indicator\n'
exit(1)
# check if any attributes
attributes = response["data"][0]["attributes"]
score = response["data"][0]["score"]
sources = response["data"][0]["sources"][0]
gen_score = score["generated_score"]
manual_score = score["manual_score"]
source = sources["name"]
if not manual_score:
manual_score = 0
ind_score = max(float(gen_score),float(manual_score))
''' TBD - ThreatQ score to dbot_score conversion '''
if ind_score >= 8 :
dbot_score = 3
malicious = {
'Vendor' : 'ThreatQ',
'Detections' : 'high risk',
}
elif 4 < ind_score < 8:
dbot_score = 2
malicious = {
'Vendor' : 'ThreatQ',
'Detections' : 'mid risk',
}
elif ind_score <= 2:
dbot_score = 1
malicious = {
'Vendor' : 'ThreatQ',
'Detections' : 'low risk',
}
dbot_score = {
'Vendor' : 'ThreatQ',
'Indicator' : indicator,
'Type' : 'ip',
'Score' : dbot_score,
'Malicious' : malicious,
}
md = ''
try:
length = len(attributes)
if length > 0:
md += "## TQ found " + str(length) + " attributes\n"
else:
md += "## TQ found no attributes\n"
tq_attr = {
'name' : indicator,
'score' : ind_score
}
for x in range(length):
name = str(attributes[x]["name"])
value = str(attributes[x]["value"])
tq_attr[name] = value
md += "Attribute " + name + " is " + value + "\n"
tq_attr_context = dict(tq_attr)
except:
md += '## TQ could not EXTRACT attributes\n'
pass
entry3 = {
'Type': entryTypes['note'],
'Contents': tq_attr_context,
'ContentsFormat': formats['json'],
'ReadableContentsFormat': formats['markdown'],
'HumanReadable': md,
'EntryContext': {'ThreatQ(val.name && val.name == obj.name)': createContext(tq_attr_context, removeNull=True),
'DBotScore(val.Vendor && val.Indicator && val.Vendor == obj.Vendor && val.Indicator == obj.Indicator)' :
createContext(dbot_score, removeNull=True),
}
}
# demisto.results(entry3)
return {'attributes': tq_attr_context,
'dbotscore': dbot_score }
''' EXECUTION CODE '''
LOG('command is %s' % (demisto.command(), ))
try:
if demisto.command() == 'test-module':
token = tq_access()
if token:
demisto.results('ok')
else:
demisto.results('test failed')
elif demisto.command() == 'tq-search-by-name':
args = demisto.args()
keyword = demisto.get(args, 'keyword')
results = query_tq(keyword)
demisto.results(results)
elif demisto.command() == 'ip':
args = demisto.args()
ip = demisto.get(args, 'ip')
results = query_tq(ip)
demisto.results(results)
elif demisto.command() == 'url':
args = demisto.args()
url = demisto.get(args, 'url')
results = query_tq(url)
demisto.results(results)
elif demisto.command() == 'file':
args = demisto.args()
file = demisto.get(args, 'file')
results = query_tq(file)
demisto.results(results)
elif demisto.command() == 'fetch-incidents':
fetch_incidents()
except Exception, e:
raise
return_error(e)
# Params are of the type given in the integration page creation.