-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathparse_callbacks.py
414 lines (333 loc) · 13.7 KB
/
parse_callbacks.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
# File: parse_callbacks.py
#
# Copyright (c) 2018-2025 Splunk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under
# the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied. See the License for the specific language governing permissions
# and limitations under the License.
#
#
# A list of methods to parse output
# The first few are generic methods, mainly for actions that don't have any output that needs to be parsed
# in any specific manner
import base64
import json
from builtins import str
from collections import OrderedDict
import phantom.app as phantom
import six
import xmltodict
from phantom.vault import Vault
def clean_str(input_str):
return input_str.replace("\r", "").replace("\n", "")
def basic(action_result, response):
# Default one, just add the data to the action result
data = {}
data["status_code"] = response.status_code
data["std_out"] = response.std_out
data["std_err"] = response.std_err
action_result.add_data(data)
return phantom.APP_SUCCESS
def check_exit(action_result, response):
if response.std_err:
return action_result.set_status(phantom.APP_ERROR, "Error running command: {}".format(clean_str(response.std_err)))
data = {}
data["status_code"] = response.status_code
data["std_out"] = response.std_out
data["std_err"] = response.std_err
action_result.add_data(data)
def check_exit_no_data(action_result, response):
if response.status_code:
if isinstance(response.std_err, bytes):
try:
response.std_err = response.std_err.decode("UTF-8")
except:
pass
return action_result.set_status(phantom.APP_ERROR, "Error running command: {}".format(clean_str(response.std_err)))
return phantom.APP_SUCCESS
def check_exit_no_data2(action_result, response):
if response.std_err:
return action_result.set_status(phantom.APP_ERROR, "Error running command: {}".format(clean_str(response.std_err)))
return phantom.APP_SUCCESS
def check_exit_no_data_stdout(action_result, response):
# Same as above, but for when the error message appears in std_out instead of std_err
if response.status_code:
return action_result.set_status(phantom.APP_ERROR, "Error running command: {}".format(clean_str(response.std_out)))
return phantom.APP_SUCCESS
def ensure_no_errors(action_result, response):
if response.status_code and response.std_err:
return action_result.set_status(phantom.APP_ERROR, "Error running command: {}{}".format(response.std_out, response.std_err))
return phantom.APP_SUCCESS
def list_processes(action_result, response):
if response.status_code != 0:
return action_result.set_status(
phantom.APP_ERROR, "Error: Returned non-zero status code. stderr: {}".format(clean_str(response.std_err))
)
output = response.std_out
processes = json.loads(output)
if not processes:
summary = action_result.update_summary({})
summary["num_processes"] = 0
return action_result.set_status(phantom.APP_ERROR, "No processes found")
column_mapping = {
"Handles": "handles",
"NPM": "non_paged_memory",
"PM": "paged_memory",
"WS": "working_set",
"VM": "virtual_memory",
"CPU": "processor_time_(s)",
"Id": "pid",
"SessionId": "session_id",
"Name": "name",
}
for process in processes:
data = {"raw": process}
for key, value in process.items():
key = column_mapping.get(key)
if key:
data[key] = value
action_result.add_data(data)
size = action_result.get_data_size()
if size == 0:
return action_result.set_status(phantom.APP_ERROR, "Unable to parse process list")
summary = action_result.update_summary({})
summary["num_processes"] = size
return phantom.APP_SUCCESS
def terminate_process(action_result, response):
if response.std_err:
return action_result.set_status(phantom.APP_ERROR, "Error terminating process: {}".format(clean_str(response.std_err)))
return phantom.APP_SUCCESS
def list_connections(action_result, response):
if response.status_code != 0:
return action_result.set_status(
phantom.APP_ERROR, "Error: Returned non-zero status code. stderr: {}".format(clean_str(response.std_err))
)
lines = response.std_out.splitlines()
for line in lines[4:]:
connection = {}
columns = line.split()
try:
connection["protocol"] = columns[0]
try:
local_address = columns[1].rsplit(":", 1)
except TypeError: # py3
local_address = (columns[1].decode("UTF-8")).rsplit(":", 1)
connection["local_address_ip"] = local_address[0]
connection["local_address_port"] = local_address[1]
try:
foreign_address = columns[2].rsplit(":", 1)
except TypeError: # py3
foreign_address = (columns[2].decode("UTF-8")).rsplit(":", 1)
connection["foreign_address_ip"] = foreign_address[0]
connection["foreign_address_port"] = foreign_address[1]
connection["state"] = columns[3]
connection["pid"] = int(columns[4])
except:
continue
action_result.add_data(connection)
size = action_result.get_data_size()
if size == 0:
return action_result.set_status(phantom.APP_ERROR, "Unable to parse connection list")
summary = action_result.update_summary({})
summary["num_connections"] = size
return phantom.APP_SUCCESS
def parse_rule(action_result, rule_lines):
name_map = {"localip": "local_ip", "remoteip": "remote_ip", "localport": "local_port", "remoteport": "remote_port"}
rule = {}
for line in rule_lines:
columns = line.split(":", 1)
if columns[0].startswith("--"):
continue
key_name = columns[0].lower().replace(" ", "_")
key_name = name_map.get(key_name, key_name)
try:
rule[key_name] = columns[1].lower().strip()
except IndexError:
pass
return rule
def filtered_rule(action_result, rule, filter_port=None, filter_ip=None, **kwargs):
if filter_port:
if rule.get("remote_port") == filter_port:
pass
elif rule.get("local_port") == filter_port:
pass
else:
return False
if filter_ip:
if rule.get("remote_ip") == filter_ip:
pass
elif rule.get("local_ip") == filter_ip:
pass
else:
return False
for k, v in six.iteritems(kwargs):
if rule.get(k, "").lower() != v.lower():
return False
return True
# Unfortunately, the actual command for running this doesn't allow you to filter
# (or at least, not with every field), so we need to do most of it here
def list_firewall_rules(action_result, response, **kwargs):
if response.status_code != 0:
# The only reason this should fail is if there are no firewall rules
action_result.update_summary({"num_rules": 0})
return action_result.set_status(phantom.APP_SUCCESS, "No firewall rules were found")
lines = list()
if isinstance(response.std_out, str):
lines = response.std_out.splitlines()
else:
lines = response.std_out.decode("UTF-8").splitlines()
rule_lines = None
for line in lines:
# start of a new rule
if line.startswith("Rule Name:"):
rule_lines = []
rule_lines.append(line)
elif not rule_lines:
continue
elif line.strip() == "" and rule_lines:
rule = parse_rule(action_result, rule_lines)
if filtered_rule(action_result, rule, **kwargs):
action_result.add_data(rule)
rule_lines = []
else:
rule_lines.append(line)
size = action_result.get_data_size()
summary = action_result.update_summary({})
summary["num_rules"] = size
if size == 0:
return action_result.set_status(phantom.APP_SUCCESS, "No firewall rule found for given parameters")
return action_result.set_status(phantom.APP_SUCCESS, "Successfully retrieved firewall rules")
def create_firewall_rule(action_result, response):
if response.status_code:
try:
message = response.std_out.splitlines()[1]
except:
message = response.std_out
return action_result.set_status(phantom.APP_ERROR, "Error running command: {}".format(message))
return phantom.APP_SUCCESS
def delete_firewall_rule(action_result, response):
if response.status_code:
return action_result.set_status(phantom.APP_ERROR, "Error running command: {}".format(clean_str(response.std_out)))
# action_result.add_data({'message': response.std_out})
summary = action_result.update_summary({})
try:
summary["rules_deleted"] = int(response.std_out.split()[1])
except:
pass
return phantom.APP_SUCCESS
def list_sessions(action_result, response):
if isinstance(response.std_out, bytes):
lines = (response.std_out.decode("UTF-8")).splitlines()
else:
lines = response.std_out.splitlines()
username_index = lines[0].find("USERNAME")
type_index = lines[0].find("TYPE")
device_index = lines[0].find("DEVICE")
for line in lines[1:]:
i = 0
session = {}
columns = line.split()
if line.startswith(">"):
session["name"] = columns[i][1:]
session["this"] = True
else:
session["name"] = columns[i]
session["this"] = False
if not line[username_index].isspace():
i += 1
username = columns[i]
else:
username = ""
i += 1
session["username"] = username
session["id"] = columns[i]
if not line[type_index].isspace():
i += 1
type_ = columns[i]
else:
type_ = ""
i += 1
session["type"] = type_
if not line[device_index].isspace():
i += 1
device = columns[i]
else:
device = ""
i += 1
session["type"] = device
action_result.add_data(session)
size = action_result.get_data_size()
summary = action_result.update_summary({})
summary["num_sessions"] = size
return phantom.APP_SUCCESS
def _parse_rule(rule):
d = {}
d["description"] = rule.pop("@Description", "")
d["name"] = rule.pop("@Name", "")
d["user_or_group_sid"] = rule.pop("@UserOrGroupSid", None)
d["action"] = rule.pop("@Action", None)
d["id"] = rule.pop("@Id", None)
file_path_condition = rule.get("Conditions", {}).get("FilePathCondition", {}).get("@Path")
if file_path_condition:
d["file_path_condition"] = file_path_condition
rule.get("Conditions", {}).pop("FilePathCondition", None)
if len(rule.get("Conditions", {})) == 0:
rule.pop("Conditions", None)
for k, v in six.iteritems(rule):
# Add anything left over
d[k] = v
return d
def list_applocker_policies(action_result, response):
if response.status_code:
return action_result.set_status(phantom.APP_ERROR, "Error running command: {}".format(clean_str(response.std_err)))
try:
# Get rid of all the linebreaks to prevent errors during reading
data = xmltodict.parse("".join(response.std_out.splitlines()))
except TypeError:
data = xmltodict.parse("".join((response.std_out.decode("utf-8")).splitlines()))
except Exception as e:
return action_result.set_status(phantom.APP_ERROR, "Error parsing XML response: {}".format(str(e)))
try:
rule_collection = data["AppLockerPolicy"]["RuleCollection"]
except KeyError:
return action_result.set_status(phantom.APP_SUCCESS, "No AppLocker Policies were found")
if type(rule_collection) in (dict, OrderedDict):
rule_collection = [rule_collection]
for rule in rule_collection:
r_type = rule["@Type"]
enforcement_mode = rule["@EnforcementMode"]
for rule_condition in ["FilePublisherRule", "FilePathRule", "FileHashRule"]:
condition = rule.get(rule_condition)
if condition is None:
continue
if type(condition) in (dict, OrderedDict):
d = _parse_rule(condition)
d["type"] = r_type
d["enforcement_mode"] = enforcement_mode
action_result.add_data(d)
elif type(condition) is list:
for c in condition:
d = _parse_rule(c)
d["type"] = r_type
d["enforcement_mode"] = enforcement_mode
action_result.add_data(d)
return phantom.APP_SUCCESS
def decodeb64_add_to_vault(action_result, response, container_id, file_name):
if response.status_code:
if isinstance(response.std_err, bytes):
response.std_err = response.std_err.decode("UTF-8")
return action_result.set_status(phantom.APP_ERROR, "Error running command: {}".format(clean_str(response.std_err)))
b64string = response.std_out
try:
resp = Vault.create_attachment(base64.b64decode(b64string), container_id, file_name=file_name)
except Exception as e:
return action_result.set_status(phantom.APP_ERROR, "Error adding file to vault", e)
action_result.update_summary({"vault_id": resp["vault_id"]})
return phantom.APP_SUCCESS