-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathappNovi.py
426 lines (333 loc) · 12 KB
/
appNovi.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
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
import json
from typing import Any, Dict, List, Union
import urllib3
# Disable insecure warnings
urllib3.disable_warnings()
""" CONSTANTS """
API_PREFIX = "/api/v1"
""" CLIENT CLASS """
class Client(BaseClient):
"""Client class to interact with the service API
Interaction with the appNovi API
"""
def get_search_results(
self, search_term: str, max_results: int = 25
) -> Dict[str, Any]:
"""Gets the IP reputation using the '/ip' API endpoint
:type search_term: ``str``
:param search_term: Search for anything in appNovi
:return: dict containing the results as returned from the API
:rtype: ``Dict[str, Any]``
"""
return self._http_request(
method="GET",
url_suffix="/components/search",
params={
"string": search_term,
"include_properties": True,
"max_results": max_results,
},
)
def get_connected_results(
self,
search_identity: Union[str, Dict],
connect_type: Optional[List] = None,
connect_category: Optional[List] = None,
max_results: int = 25,
) -> List[Dict[str, Any]]:
# Can't use json= since it's already in use by xsoar
return self._http_request(
method="POST",
url_suffix="/components/connected",
data=json.dumps([search_identity]),
params={
"max_results": max_results,
"type": connect_type,
"category": connect_category,
},
)
def get_types(self):
return self._http_request(
method="GET",
url_suffix="/components/types",
)
def get_prop_search_results(
self, prop: str, value: str, max_results: int = 25
) -> Dict:
return self._http_request(
method="GET",
url_suffix="/components/propsearch",
params={
"prop": prop,
"value": value,
"include_properties": True,
"max_results": max_results,
},
)
""" HELPER FUNCTIONS """
def dict_by_path(full_dict: dict, dict_path: str) -> Any:
"""Get values from dictionary by path
just some code
"""
paths = dict_path.split(".")
return_value = full_dict
for path in paths:
try:
return_value = return_value[path]
except (KeyError, TypeError):
return None
return return_value
def process_sources(source_dict: dict) -> str:
"""Parse source dict into something readable"""
source = source_dict.keys()
return ",".join([s for s in source if len(s)])
""" COMMAND FUNCTIONS """
def test_module(client: Client) -> str:
"""Test Integration
:type client: ``Client``
:return:
A ``str`` representing if authentication was successful
:rtype: ``str``
"""
# Call the Client function and get the raw response
try:
client.get_types()
except DemistoException as e:
if "Forbidden" in str(e):
return "Authorization Error: make sure API Key is correctly set"
else:
raise e
return "ok"
def search_appnovi_command(client: Client, args: Dict[str, Any]) -> CommandResults:
search_term = args.get("search_term", None)
if not search_term:
raise ValueError("Search term not specified")
results = client.get_search_results(search_term, args.get("max_results", 25))
table_layout = {
"name": "name",
"appnoviid": "u._id",
"type": "u.identity.type",
"value": "u.identity.value",
"lastSeen": "u.lastSeen",
"connections": "connections",
}
readable_output = (
"### Search Results\n" + " | ".join(table_layout.keys()) + " | sources" + "\n"
)
readable_output += (
"|".join(["-----" for th in table_layout.keys()]) + "|----" + "\n"
)
for result in results["components"]:
readable_output += (
" | ".join([str(dict_by_path(result, f)) for f in table_layout.values()])
+ " | "
+ process_sources(result["u"].get("source", {}))
+ "\n"
)
return CommandResults(
readable_output=readable_output,
outputs_prefix="appnovi.search",
outputs_key_field=table_layout["appnoviid"],
outputs=results,
)
def search_appnovi_prop_command(client: Client, args: Dict[str, Any]) -> CommandResults:
search_prop = args.get("property", None)
search_value = args.get("value", None)
if not search_prop or not search_value:
raise ValueError("Search terms not specified")
results = client.get_prop_search_results(
search_prop, search_value, args.get("max_results", 25)
)
table_layout = {
"name": "name",
"appnoviid": "u._id",
"type": "u.identity.type",
"value": "u.identity.value",
"lastSeen": "u.lastSeen",
"connections": "connections",
}
readable_output = (
"### Search Results\n" + " | ".join(table_layout.keys()) + " | sources" + "\n"
)
readable_output += (
"|".join(["-----" for th in table_layout.keys()]) + "|----" + "\n"
)
for result in results["components"]:
readable_output += (
" | ".join([str(dict_by_path(result, f)) for f in table_layout.values()])
+ " | "
+ process_sources(result["u"].get("source", {}))
+ "\n"
)
return CommandResults(
readable_output=readable_output,
outputs_prefix="appnovi.searchProp",
outputs_key_field=table_layout["appnoviid"],
outputs=results,
)
def search_appnovi_connected_command(
client: Client, args: Dict[str, Any]
) -> CommandResults:
"""Search for components connected to other components.
Can be limited in the types of things returned"""
identity = args.get("identity", None)
if not identity:
raise ValueError("Identity not specified")
if appnovi_id := identity.get("_id", None):
identity = appnovi_id
# Check for arguments
cats = argToList(args.get("category", "")) or None
types = argToList(args.get("type", "")) or None
# Process identity
results = client.get_connected_results(identity, types, cats)
table_layout = {
"name": "name",
"appnoviid": "_id",
"category": "category",
"type": "identity.type",
"value": "identity.value",
}
readable_output = "### Search Results\n" + " | ".join(table_layout.keys()) + "\n"
readable_output += "|".join(["-----" for th in table_layout.keys()]) + "\n"
for result in results:
readable_output += (
" | ".join([str(dict_by_path(result, f)) for f in table_layout.values()])
+ "\n"
)
return CommandResults(
readable_output=readable_output,
outputs_prefix="appnovi.connected",
outputs_key_field=table_layout["appnoviid"],
outputs=results,
)
def search_appnovi_cve_servers_command(
client: Client, args: Dict[str, Any]
) -> CommandResults:
"""Find Servers with CVE
This is a convenience command using the connected search"""
cve = args.get("cve", None)
if not cve:
raise ValueError("CVE not specified")
results = client.get_connected_results(
{"type": "cve", "value": cve.upper()}, None, ["Server"]
)
table_layout = {
"name": "name",
"appnoviid": "_id",
"category": "category",
"type": "identity.type",
"value": "identity.value",
}
readable_output = "### Search Results\n" + " | ".join(table_layout.keys()) + "\n"
readable_output += "|".join(["-----" for th in table_layout.keys()]) + "\n"
for result in results:
readable_output += (
" | ".join([str(dict_by_path(result, f)) for f in table_layout.values()])
+ "\n"
)
return CommandResults(
readable_output=readable_output,
outputs_prefix="appnovi.cveServers",
outputs_key_field=table_layout["appnoviid"],
outputs=results,
)
def find_server_by_ip_command(client: Client, args: Dict[str, Any]) -> CommandResults:
"""Use the connected function to return servers owning a given IP
Good example of how you an chain requests to walk the graph via command or playbook
"""
ip = args.get("ip", None)
if not ip:
raise ValueError("IP not specified")
# Keep track of things
servers = {}
interfaces: List[str] = []
# Let's get any servers or interfaces connected to the IP
first_walk = client.get_connected_results(
{"type": "ip", "value": ip}, None, ["Server", "Interface"]
)
# Examine first walk
for thing in first_walk:
category = thing.get("category", None)
# Collect interfaces for next walk
if category == "Interface":
# Make mypy happy by checking thing.get("_id") for str type.
_id = thing.get("_id")
if isinstance(_id, str):
interfaces.append(_id)
# Servers are usually not directly connected to IP, but in case...
if category == "Server":
servers[thing.get("_id")] = thing
# Walk each interface. Serching by _id is /very/ fast
for interface in interfaces:
possible_server = client.get_connected_results(interface, None, ["Server"])
for server in possible_server:
servers[server.get("_id")] = server
# Walk finished, output some results
readable_output = f"### Servers with IP {ip}\n"
if len(servers.keys()):
table_layout = {
"name": "name",
"appnoviid": "_id",
"type": "identity.type",
"value": "identity.value",
}
readable_output = (
"### Search Results\n" + " | ".join(table_layout.keys()) + "\n"
)
readable_output += "|".join(["-----" for th in table_layout.keys()]) + "\n"
for result in servers.values():
readable_output += (
" | ".join(
[str(dict_by_path(result, f)) for f in table_layout.values()]
)
+ "\n"
)
else:
readable_output += "No Results \n"
return CommandResults(
readable_output=readable_output,
outputs_prefix="appnovi.server",
outputs_key_field="",
outputs=[v for k, v in servers.items()],
)
""" MAIN FUNCTION """
def main() -> None: # pragma: no cover
"""main function, parses params and runs command functions
:return:
:rtype:
"""
params = demisto.params()
command = demisto.command()
api_key = params.get("appnovi_token")
base_url = urljoin(params["appnovi_url"], API_PREFIX)
verify_certificate = not params.get("insecure", False)
proxy = params.get("proxy", False)
demisto.debug(f"Command being called is {command}")
try:
headers = {"Authorization": f"Bearer {api_key}"}
client = Client(
base_url=base_url, verify=verify_certificate, headers=headers, proxy=proxy
)
command = demisto.command()
if command == "test-module":
return_results(test_module(client))
return
commands = {
"search-appnovi-components": search_appnovi_command,
"search-appnovi-component-property": search_appnovi_prop_command,
"search-appnovi-connected": search_appnovi_connected_command,
"search-appnovi-cve": search_appnovi_cve_servers_command,
"search-appnovi-server-by-ip": find_server_by_ip_command,
}
fn = commands.get(command, None)
if fn:
return_results(fn(client, demisto.args()))
# Log exceptions and return errors
except Exception as e:
return_error(f"Failed to execute {command} command.\nError:\n{str(e)}")
""" ENTRY POINT """
if __name__ in ("__main__", "__builtin__", "builtins"):
main()