-
Notifications
You must be signed in to change notification settings - Fork 1
/
set_log_only.py
executable file
·270 lines (206 loc) · 8.31 KB
/
set_log_only.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
#!/usr/bin/env python3
# coding=utf-8
"""
Version 1.1
Script to activate log-only mode on a Deny Rule on a set of mappings.
All actions operate on the newest saved or active configuration and
will save a new configuration.
The new configuration will NOT be activated. You have to load and activate
it in the Configuration Center ("Configuration" - "Configuration Files").
We suggest to use the config diff function in the GUI before activation.
Script may require about 3 minutes to patch 150 mappings.
Example usage:
Activate log-only mode for rule TI_001a on all mappings containing one of the
strings cust0, cust1,..., cust9 on system aldea
./set_log_only.py -k api_key -n aldea -r -2170 -m 'cust[0-9]'
To find out the rule id use the following shell comand on Airlock Gateway
NAME=TI_001c; grep -P -B1 "\.Name=.*$NAME" /opt/airlock/mgt-agent/conf/default-patterns/denyRuleFactoryDefaults.properties | awk -F= '/Id=/ { print $2 }'
Tested with Airlock Gateway: 7.7.1, 7.6.2, 7.5.3
"""
from cgitb import enable
from urllib import request
import ssl
import json
import os
import sys
import re
from argparse import ArgumentParser
from http.cookiejar import CookieJar
import signal
from zipfile import ZipFile
from io import BytesIO
import xml.etree.ElementTree as ET
DEFAULT_API_KEY_FILE = "./api_key"
parser = ArgumentParser()
parser.add_argument("-n", dest="host", metavar="hostname",
required=True,
help="Airlock Gateway hostname")
parser.add_argument("-r", dest="rule_id", metavar="rule_id",
required=True,
help="Deny Rule ID")
group_sel = parser.add_mutually_exclusive_group(required=True)
group_sel.add_argument("-m", dest="mapping_selector_pattern",
metavar="pattern",
help="Pattern matching mapping name, e.g. ^mapping_a$")
group_sel.add_argument("-l", dest="mapping_selector_label", metavar="label",
help="Label for mapping selection")
parser.add_argument("-f", dest="confirm", action="store_false",
help="Force, no confirmation needed")
parser.add_argument("-d", dest="activate", action="store_false",
help="disabled log-only")
parser.add_argument("-k", dest="api_key_file", metavar="api_key_file",
default=DEFAULT_API_KEY_FILE,
help="Path to API key file "
f"(default {DEFAULT_API_KEY_FILE})")
args = parser.parse_args()
sys.tracebacklimit = 0
TARGET_GATEWAY = f'https://{args.host}'
CONFIG_XML_NAME = "alec_table.xml"
try:
api_key = open(args.api_key_file, 'r').read().strip()
except (IOError, FileNotFoundError) as error:
print(f'Can not read API key from {args.api_key_file}')
sys.exit(-1)
DEFAULT_HEADERS = {"Authorization": f'Bearer {api_key}'}
# we need a cookie store
opener = request.build_opener(request.HTTPCookieProcessor(CookieJar()))
# ignore invalid SSL cert on the management interface
if (not os.environ.get('PYTHONHTTPSVERIFY', '') and
getattr(ssl, '_create_unverified_context', None)):
ssl._create_default_https_context = ssl._create_unverified_context
# method to send REST calls
def send_request(
method,
path,
body="",
accept_header="application/json",
content_type="application/json"):
DEFAULT_HEADERS['Accept'] = accept_header
DEFAULT_HEADERS['Content-Type'] = content_type
if content_type == "application/json":
body = body.encode('utf-8')
req = request.Request(TARGET_GATEWAY + "/airlock/rest/" + path,
body, DEFAULT_HEADERS)
req.get_method = lambda: method
r = opener.open(req)
return r.read()
def terminate_and_exit(text):
send_request("POST", "session/terminate")
sys.exit(text)
# signal handler
def register_cleanup_handler():
def cleanup(signum, frame):
terminate_and_exit("Terminate session")
for sig in (signal.SIGABRT, signal.SIGILL, signal.SIGINT, signal.SIGSEGV,
signal.SIGTERM):
signal.signal(sig, cleanup)
def load_last_config():
resp = json.loads(send_request("GET", "configuration/configurations"))
send_request("POST", 'configuration/configurations/'
f"{resp['data'][0]['id']}/load")
def get_all_mappings():
resp = json.loads(send_request("GET", "configuration/mappings"))['data']
return sorted(resp, key=lambda x: x['attributes']['name'])
def get_mappings():
# filter mappings
return ([
{'id': x['id'],
'name': x['attributes']['name'],
'ip_rules': x['attributes']['ipRules']}
for x in get_all_mappings() if (
args.mapping_selector_pattern and
re.search(args.mapping_selector_pattern,
x['attributes']['name']) or
args.mapping_selector_label in x['attributes']['labels']
)
])
def create_change_info(affected_mapping_names):
if args.activate:
change_info = 'Log-only for rule {} enabled'.format(args.rule_id)
else:
change_info = 'Log-only for rule {} removed'.format(args.rule_id)
change_info += ' for the following mapping(s): \n\t{}'\
.format('\n\t'.join(affected_mapping_names))
return change_info
def export_mappings(mappings):
mapping_xmls = []
for mapping in mappings:
resp = send_request(method="GET",
path="configuration/mappings/{}/export".format(
mapping['id']),
accept_header="application/zip")
z = ZipFile(BytesIO(resp))
mapping_xml = z.open(CONFIG_XML_NAME).read()
mapping_xmls.append(mapping_xml)
return mapping_xmls
def modify_mappings(mapping_xmls):
new_mapping_xmls = []
for mapping_xml in mapping_xmls:
doc = ET.fromstring(mapping_xml)
mapping_name = doc.find('./Mappings/Mapping/Name').text
rules = doc.findall('.//DenyRuleUsage')
rule = None
for r in rules:
if r.findtext('DenyRuleId') == args.rule_id:
rule = r
if rule == None:
print ("No deny Rule found with Id: {}".format(args.rule_id))
terminate_and_exit()
enabled = rule.find('.//Enabled')
log_only = rule.find('.//LogOnly')
if args.activate:
enabled.text = 'true'
log_only.text = 'true'
else:
enabled.text = 'false'
log_only.text = 'false'
new_mapping_xmls.append(ET.tostring(doc))
return new_mapping_xmls
def upload_mappings(mapping_xmls):
for mapping_xml in mapping_xmls:
mapping_zip = BytesIO()
with ZipFile(mapping_zip, mode="w") as zf:
zf.writestr(CONFIG_XML_NAME, mapping_xml)
mapping_zip.seek(0)
send_request(method="PUT",
path="configuration/mappings/import",
body=mapping_zip.read(),
content_type="application/zip")
def get_mapping_names(mapping_xmls):
mapping_names = []
for mapping_xml in mapping_xmls:
doc = ET.fromstring(mapping_xml)
mapping_name = doc.find('./Mappings/Mapping/Name').text
mapping_names.append(mapping_name)
return sorted(mapping_names)
def confirm(change_info):
if not args.confirm:
return True
print(change_info)
if input('\nContinue to save the config? [y/n] ') == 'y':
return True
print("Nothing changed")
return False
def save_config(change_info):
data = {"comment": "REST: " + change_info.replace('\n\t', ', ')
.replace(': ,', ':')}
# save config
send_request("POST", "configuration/configurations/save", json.dumps(data))
print(f"\nConfig saved with comment: {data['comment']}")
# create session
send_request("POST", "session/create")
register_cleanup_handler()
# load last config (active or saved)
load_last_config()
# filter mappings
mappings = get_mappings()
if not mappings:
terminate_and_exit("No mapping found - exit")
mapping_xmls = export_mappings(mappings)
modified_mapping_xmls = modify_mappings(mapping_xmls)
upload_mappings(modified_mapping_xmls)
affected_mapping_names = get_mapping_names(modified_mapping_xmls)
change_info = create_change_info(affected_mapping_names)
confirm(change_info) or terminate_and_exit(0)
save_config(change_info)
terminate_and_exit(0)