-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathReversingLabsRansomwareAndRelatedToolsFeed.py
355 lines (247 loc) · 10.1 KB
/
ReversingLabsRansomwareAndRelatedToolsFeed.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
from CommonServerPython import *
VERSION = "v1.0.0"
USER_AGENT = f"ReversingLabs XSOAR Ransomware Feed {VERSION}"
MAX_HOURS_HISTORICAL = 4
ALLOWED_INDICATOR_TYPES = ("ipv4", "domain", "hash", "uri")
INDICATOR_TYPE_MAP = {
"ipv4": FeedIndicatorType.IP,
"domain": FeedIndicatorType.Domain,
"hash": FeedIndicatorType.File,
"uri": FeedIndicatorType.URL
}
class Client(BaseClient):
RANSOMWARE_INDICATORS_ENDPOINT = "/api/public/v1/ransomware/indicators?hours={hours}&" \
"indicatorTypes={indicator_types}&tagFormat=dict"
def __init__(self, base_url, auth, headers, verify):
super(Client, self).__init__(base_url=base_url, auth=auth, headers=headers, verify=verify)
def query_indicators(self, hours, indicator_types, timeout, retries):
endpoint = self.RANSOMWARE_INDICATORS_ENDPOINT.format(
hours=hours,
indicator_types=indicator_types,
)
try:
response = self._http_request(
method="GET",
url_suffix=endpoint,
timeout=timeout,
auth=self._auth,
retries=retries,
resp_type="json"
)
except Exception as e:
return_error(f"Request towards the defined endpoint {endpoint} did not succeed. {str(e)}")
return response
def confidence_to_score(confidence):
if confidence >= 70:
return 3
elif 69 >= confidence >= 2:
return 2
else:
return None
def calculate_hours_historical(hours_param):
last_run = get_feed_last_run()
if not last_run:
return hours_param
try:
time_delta = datetime.now() - datetime.strptime(last_run.get("last_run"), "%Y-%m-%dT%H:%M:%S.%f")
time_delta_hours_rounded = round((time_delta.seconds / 3600) + 1)
return time_delta_hours_rounded
except Exception:
return 2
def return_validated_params(params):
hours_param = params.get("hours")
try:
hours_param = int(hours_param)
except ValueError:
return_error("The First fetch time parameter must be integer.")
hours_historical = calculate_hours_historical(hours_param)
if hours_historical > MAX_HOURS_HISTORICAL:
hours_historical = MAX_HOURS_HISTORICAL
indicator_types_param = params.get("indicatorTypes")
for indicator_type in indicator_types_param:
if indicator_type not in ALLOWED_INDICATOR_TYPES:
return_error(f"Selected indicator type '{indicator_type}' is not supported.")
indicator_types_param = ",".join(indicator_types_param)
return hours_historical, indicator_types_param
def fetch_indicators_command(client, params):
hours_historical, indicator_types_param = return_validated_params(params)
new_last_run = datetime.now().isoformat()
response = client.query_indicators(
hours=hours_historical,
indicator_types=indicator_types_param,
timeout=(30, 300),
retries=3
)
tlp_color_param = params.get("tlp_color", None)
user_tag_list = []
user_tags_param = params.get("feedTags", None)
if user_tags_param:
user_tags_param = user_tags_param.split(",")
for user_tag in user_tags_param:
user_tag_list.append(user_tag.strip())
data = response.get("data", [])
indicators = []
for rl_indicator in data:
indicator = create_indicator_object(rl_indicator, user_tag_list, tlp_color_param)
indicators.append(indicator)
return indicators, new_last_run
def map_file_info(indicator, tag_list, file_info):
if file_info:
if isinstance(file_info, list):
tag_list.extend(file_info)
elif isinstance(file_info, dict):
file_name = file_info.get("fileName")
file_info_fields = assign_params(
size=file_info.get("fileSize"),
filetype=file_info.get("fileType"),
associatedfilenames=[file_name]
)
indicator["fields"].update(file_info_fields)
if file_name and isinstance(file_name, str):
file_name_parts = file_name.split(".")
if len(file_name_parts) > 1:
file_extension = file_name_parts[-1]
indicator["fields"]["fileextension"] = file_extension
def create_indicator_object(rl_indicator, user_tag_list, tlp_color_param):
last_update = rl_indicator.get("lastUpdate", None)
last_seen = datetime.strptime(last_update, "%Y-%m-%dT%H:%M:%SZ") if last_update else datetime.now()
last_seen = last_seen.strftime("%Y-%m-%dT%H:%M:%S+00:00")
indicator_type = rl_indicator.get("indicatorType").lower()
indicator = {
"value": rl_indicator.get("indicatorValue"),
"type": INDICATOR_TYPE_MAP.get(indicator_type),
"rawJSON": rl_indicator,
"fields": {
"lastseenbysource": last_seen
},
"score": confidence_to_score(rl_indicator.get("confidence", 0)),
}
indicator_tags = rl_indicator.get("indicatorTags")
if not indicator_tags:
return indicator
tag_list = []
mitre = indicator_tags.get("mitre")
if mitre:
tag_list.extend(mitre)
lifecycle_stage = indicator_tags.get("lifecycleStage")
if lifecycle_stage:
tag_list.append(lifecycle_stage)
source = indicator_tags.get("source")
if source:
tag_list.append(source)
additional_fields = assign_params(
malwaretypes=indicator_tags.get("malwareType"),
malwarefamily=indicator_tags.get("malwareFamilyName"),
trafficlightprotocol=tlp_color_param
)
indicator["fields"].update(additional_fields)
if indicator_type == "hash":
hashes = rl_indicator.get("hash")
if hashes:
hash_fields = assign_params(
sha1=hashes.get("sha1"),
sha256=hashes.get("sha256"),
md5=hashes.get("md5")
)
indicator["fields"].update(hash_fields)
map_file_info(indicator, tag_list, indicator_tags.get("fileInfo"))
elif indicator_type in ("ipv4", "uri", "domain"):
port = indicator_tags.get("port")
if port:
indicator["fields"]["port"] = port
protocol = indicator_tags.get("Protocol")
if protocol:
tag_list.extend(protocol)
if indicator_type == "ipv4":
asn = indicator_tags.get("asn")
if asn:
indicator["fields"]["asn"] = asn
tag_list.extend(user_tag_list)
if len(tag_list) > 0:
indicator["fields"]["tags"] = tag_list
return indicator
def get_indicators_command(client):
hours_arg = demisto.args().get("hours_back", 2)
try:
hours_arg = int(hours_arg)
except ValueError:
return_error("The hours_back argument must be a whole number.")
if hours_arg > MAX_HOURS_HISTORICAL:
hours_arg = MAX_HOURS_HISTORICAL
indicator_types_arg = demisto.args().get("indicator_types", "ipv4,domain,hash,uri").replace(" ", "")
for indicator_type in indicator_types_arg.split(","):
if indicator_type not in ALLOWED_INDICATOR_TYPES:
return_error(f"Selected indicator type '{indicator_type}' is not supported.")
limit = int(demisto.args().get("limit", 50))
response = client.query_indicators(
hours=hours_arg,
indicator_types=indicator_types_arg,
timeout=(30, 300),
retries=3
)
indicator_list = response.get("data", [])[:limit]
readable_output = format_readable_output(response, indicator_list)
command_result = CommandResults(
readable_output=readable_output,
raw_response=response,
outputs_prefix='ReversingLabs',
outputs={"indicators": indicator_list}
)
return command_result
def format_readable_output(response, indicator_list):
indicator_types = response.get("request").get("indicatorTypes", [])
hours = response.get("request").get("hours", "")
markdown = f"""## ReversingLabs Ransomware and Related Tools Feed\n **Indicator types**: {', '.join(indicator_types)}
**Hours**: {hours}
"""
indicator_table = tableToMarkdown(
name="Indicators",
t=indicator_list,
headers=["indicatorValue", "indicatorType", "daysValid", "confidence",
"rating", "indicatorTags", "lastUpdate", "deleted", "hash"],
headerTransform=pascalToSpace
)
markdown = f"{markdown}\n{indicator_table}"
return markdown
def test_module_command(client, params):
hours_param, indicator_types_param = return_validated_params(params)
client.query_indicators(
hours=hours_param,
indicator_types=indicator_types_param,
timeout=(30, 300),
retries=1
)
return "ok"
def main():
params = demisto.params()
host = params.get("host")
username = params.get("credentials", {}).get("identifier")
password = params.get("credentials", {}).get("password")
verify = params.get("insecure")
command = demisto.command()
demisto.debug(f"Command being called is {command}")
try:
client = Client(
base_url=host,
verify=verify,
auth=(username, password),
headers={"User-Agent": USER_AGENT}
)
if command == "test-module":
result = test_module_command(client, params)
return_results(result)
elif command == "reversinglabs-get-indicators":
command_result = get_indicators_command(client)
return_results(command_result)
elif command == "fetch-indicators":
indicators, new_last_run = fetch_indicators_command(client, params)
for indicator_batch in batch(indicators, 200):
demisto.createIndicators(indicator_batch)
set_feed_last_run({"last_run": new_last_run})
else:
raise NotImplementedError(f"Command {command} is not implemented.")
except Exception as e:
demisto.error(traceback.format_exc())
return_error(f"Failed to execute {command} command.\nError:\n{str(e)}")
if __name__ in ["__main__", "builtin", "builtins"]:
main()