-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
NetskopeV2.py
274 lines (203 loc) · 6.8 KB
/
NetskopeV2.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
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
import traceback
from typing import Any, Dict
import urllib3
# Disable insecure warnings
urllib3.disable_warnings()
''' CONSTANTS '''
''' CLIENT CLASS '''
class Client(BaseClient):
"""Client class to interact with the service API"""
def get_lists(self):
return self._http_request(
method='GET'
)
def get_list(self, list_id):
return self._http_request(
method='GET',
url_suffix=list_id
)
def patch_list(self, list_id, url_list_object, action):
return self._http_request(
method='PATCH',
url_suffix=f'{list_id}/{action}',
json_data=url_list_object
)
def replace_url_list(self, list_id, url_list_object):
return self._http_request(
method='PUT',
url_suffix=list_id,
json_data=url_list_object
)
def deploy_lists(self):
return self._http_request(
method='POST',
url_suffix='deploy'
)
''' HELPER FUNCTIONS '''
def create_url_list_object(urls, type_='exact'):
return {
'data': {
'urls': urls,
'type': type_
}
}
def get_list_id_from_name(client, list_name):
# get list ID from lists, filtered by list name
lists = client.get_lists()
list_id = [listt.get('id') for listt in lists if listt.get('name') == list_name]
if len(list_id) == 0:
raise Exception(f'A Netskope URL List with the name "{list_name}" does not exist')
elif len(list_id) == 1:
return str(list_id[0])
else:
raise Exception(f'Found multiple Netskope URL Lists with the name "{list_name}"')
''' COMMAND FUNCTIONS '''
def test_module(client: Client) -> str:
"""Tests API connectivity and authentication'
Returning 'ok' indicates that the integration works like it is supposed to.
Connection to the service is successful.
Raises exceptions if something goes wrong.
:type Client: ``client``
:param client: Netskope client to use
:return: 'ok' if test passed, anything else will fail the test.
:rtype: ``str``
"""
try:
client._http_request(
method='GET'
)
except DemistoException as e:
if 'Unauthorized' in str(e):
return 'Authorization Error: make sure API Key is correctly set'
else:
raise e
return 'ok'
def get_lists(client: Client, args: Dict[str, Any]) -> CommandResults:
r = client.get_lists()
markdown = tableToMarkdown('Retrieved all applied and pending lists', r)
return CommandResults(
readable_output=markdown,
outputs_prefix='Netskope',
outputs_key_field='',
outputs={
'URLList': r
}
)
def get_list(client: Client, args: Dict[str, Any]) -> CommandResults:
list_name = args.get('list_name')
list_id = get_list_id_from_name(client, list_name)
r = client.get_list(list_id)
markdown = tableToMarkdown(f'Retrieved "{list_name}" list', r)
return CommandResults(
readable_output=markdown,
outputs_prefix='Netskope',
outputs_key_field='',
outputs={
'URLList': r
}
)
def add_url(client: Client, args: Dict[str, Any]) -> CommandResults:
list_name = args.get('list_name')
url = argToList(args.get('url'))
if len(url) == 0:
raise Exception('received an empty list of URLs')
list_id = get_list_id_from_name(client, list_name)
# create 'urls' list
urls = []
for u in url:
urls.append(u)
# append urls to list
url_list_object = create_url_list_object(urls)
r = client.patch_list(list_id, url_list_object, 'append')
# apply pending changes
client.deploy_lists()
markdown = tableToMarkdown(f'Added "{url}" to "{r.get("name")}" list', r)
return CommandResults(
readable_output=markdown,
outputs_prefix='Netskope',
outputs_key_field='',
outputs={
'URLList': r
}
)
def remove_url(client: Client, args: Dict[str, Any]) -> CommandResults:
list_name = args.get('list_name')
url = argToList(args.get('url'))
if len(url) == 0:
raise Exception('received an empty list of URLs')
list_id = get_list_id_from_name(client, list_name)
# get urls from list
r = client.get_list(list_id)
urls = r.get('data').get('urls')
# remove urls
urls_found = []
urls_not_found = []
for u in url:
if u in urls:
urls_found.append(u)
else:
urls_not_found.append(u)
for u in urls_found:
urls.remove(u)
# write urls to list
url_list_object = create_url_list_object(urls, r.get('data').get('type'))
r = client.patch_list(list_id, url_list_object, 'replace')
# apply pending changes
client.deploy_lists()
message = f'Remove URLs from "{r.get("name")}" list'
if urls_found:
message += f'\nRemoved: {urls_found}'
if urls_not_found:
message += f"\nNot found: {urls_not_found}"
markdown = tableToMarkdown(message, r)
return CommandResults(
readable_output=markdown,
outputs_prefix='Netskope',
outputs_key_field='',
outputs={
'URLList': r
}
)
''' MAIN FUNCTION '''
def main() -> None:
"""main function, parses params and runs command functions
:return:
:rtype:
"""
api_key = demisto.params().get("api_key_credentials", {}).get("password") or demisto.params().get("api_key")
if not api_key:
return_error('Please provide a valid API Key')
base_url = urljoin(demisto.params()['url'], '/api/v2/policy/urllist/')
verify_certificate = not demisto.params().get('insecure', False)
proxy = demisto.params().get('proxy', False)
headers = {
'Netskope-Api-Token': api_key
}
commands = {
'netskopev2-get-lists': get_lists,
'netskopev2-get-list': get_list,
'netskopev2-add-url': add_url,
'netskopev2-remove-url': remove_url
}
command = demisto.command()
demisto.debug(f'Command being called is {command}')
try:
client = Client(
base_url=base_url,
verify=verify_certificate,
proxy=proxy,
headers=headers
)
if command == 'test-module':
return_results(test_module(client))
if command in commands:
return_results(commands[command](client, demisto.args()))
# Log exceptions and return errors
except Exception as e:
demisto.error(traceback.format_exc()) # print the traceback
return_error(f'Failed to execute {command} command.\nError:\n{str(e)}')
''' ENTRY POINT '''
if __name__ in ('__main__', '__builtin__', 'builtins'):
main()