-
Notifications
You must be signed in to change notification settings - Fork 1
/
policy_updater.py
425 lines (334 loc) · 18 KB
/
policy_updater.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
__author__ = "Simon Melotte"
import os
import json
import csv
import requests
import argparse
import logging
from dotenv import load_dotenv
# Create a logger object
logger = logging.getLogger()
def update_policy_from_csv(base_url, token, csv_file_path):
# Fetch the existing policies
policies = get_policies(base_url, token)
# Define the policy types that are allowed to update compliance metadata
allowed_policy_types = ["config", "anomaly", "audit_event"]
# Read the CSV file and update policies accordingly
with open(csv_file_path, mode='r') as file:
csv_reader = csv.DictReader(file)
for row in csv_reader:
policy_name = row['policy_name']
csv_labels = row['labels'].split('|') # Split labels using "|" delimiter
framework = row['compliance_framework']
requirement_name = row['compliance_requirement']
section_id = row['compliance_section']
status = row['status'].lower() == "true" # Convert status to boolean
# Find the policy by name in the existing policies
matching_policy = None
for policy in policies:
if policy['name'] == policy_name:
matching_policy = policy
break
if matching_policy:
policy_id = matching_policy['policyId']
# Combine existing labels with new labels from CSV
existing_labels = matching_policy.get('labels', [])
updated_labels = list(set(existing_labels + csv_labels)) # Ensure no duplicates
# Prepare the updated policy data (without compliance metadata yet)
updated_policy = {
"cloudType": matching_policy['cloudType'],
"description": matching_policy['description'],
"enabled": status, # Update policy status from CSV
"findingTypes": matching_policy['findingTypes'],
"labels": updated_labels, # Updated labels array
"name": matching_policy['name'],
"policyType": matching_policy['policyType'],
"recommendation": matching_policy['recommendation'],
"severity": matching_policy['severity'],
"rule": matching_policy['rule'],
}
# Only update compliance metadata for allowed policy types
if matching_policy['policyType'] in allowed_policy_types:
# Step 1: Ensure compliance framework exists
compliance = create_if_not_exists_compliance_framework(base_url, token, framework, framework)
if not compliance:
logger.error(f"Failed to create or find compliance framework '{framework}' for policy '{policy_name}'.")
continue # Skip to the next row
# Step 2: Ensure compliance requirement exists
requirement = create_if_not_exists_compliance_requirement(base_url, token, compliance['id'], requirement_name, "Requirement description", section_id)
if not requirement:
logger.error(f"Failed to create or find compliance requirement '{requirement_name}' for policy '{policy_name}'.")
continue # Skip to the next row
# Step 3: Ensure compliance section exists
section = create_if_not_exists_compliance_section(base_url, token, requirement['id'], section_id, "Section description")
if not section:
logger.error(f"Failed to create or find compliance section '{section_id}' for policy '{policy_name}'.")
continue # Skip to the next row
# Get existing compliance metadata
compliance_metadata = matching_policy.get('complianceMetadata', [])
# Check if the section['id'] already exists in compliance metadata
section_exists = False
for metadata in compliance_metadata:
if metadata['sectionId'] == section['sectionId']:
section_exists = True
break
# Add new compliance metadata only if section does not exist
if not section_exists:
compliance_metadata.append({
"complianceId": section['id'],
"customAssigned": True,
"policyId": policy_id,
"requirementDescription": requirement['description'],
"requirementId": requirement['requirementId'],
"requirementName": requirement['name'],
"sectionDescription": section['description'],
"sectionId": section['sectionId'],
"sectionLabel": section['sectionId'],
"standardDescription": compliance['description'],
"standardId": compliance['id'],
"standardName": compliance['name']
})
else:
logger.info(f"Section '{section['sectionId']}' already exists in compliance metadata for policy '{policy_name}', skipping append.")
# Add compliance metadata to the policy if the policyType supports it
updated_policy["complianceMetadata"] = compliance_metadata
# Send the PUT request to update the policy
update_url = f"https://{base_url}/policy/{policy_id}"
headers = {
"Content-Type": "application/json; charset=UTF-8",
"Accept": "application/json; charset=UTF-8",
"x-redlock-auth": token
}
try:
response = requests.put(update_url, headers=headers, json=updated_policy)
response.raise_for_status()
logger.info(f"Policy '{policy_name}' updated successfully.")
except requests.exceptions.RequestException as err:
logger.error(f"Failed to update policy '{policy_name}': {err}")
else:
logger.error(f"Policy '{policy_name}' not found in existing policies.")
def create_if_not_exists_compliance_section(base_url, token, requirement_id, section_id, section_description):
# URL to get the list of compliance sections for a requirement
get_url = f"https://{base_url}/compliance/{requirement_id}/section"
headers = {
"Accept": "application/json; charset=UTF-8",
"x-redlock-auth": token
}
# Check if the section exists
try:
response = requests.get(get_url, headers=headers)
response.raise_for_status() # Raise error for bad status codes
except requests.exceptions.RequestException as err:
logger.error(f"Exception in checking compliance sections for requirement ID {requirement_id}: {err}")
return None
section_list = response.json()
# Check if the compliance section already exists
for section in section_list:
if section['sectionId'].lower() == section_id.lower():
logger.info(f"Compliance section '{section_id}' already exists for requirement ID {requirement_id}.")
return section # If it exists, return the section (including its ID)
# If the section does not exist, create it
post_url = f"https://{base_url}/compliance/{requirement_id}/section"
payload = {
"description": section_description,
"sectionId": section_id
}
headers["Content-Type"] = "application/json"
try:
post_response = requests.post(post_url, headers=headers, json=payload)
post_response.raise_for_status() # Raise error for bad status codes
except requests.exceptions.RequestException as err:
logger.error(f"Exception in creating compliance section: {err}")
return None
logger.info(f"Compliance section '{section_id}' created successfully.")
# Fetch the list of sections again to retrieve the new section's details
try:
response = requests.get(get_url, headers=headers)
response.raise_for_status() # Raise error for bad status codes
except requests.exceptions.RequestException as err:
logger.error(f"Exception in fetching compliance sections after creation for requirement ID {requirement_id}: {err}")
return None
section_list = response.json()
# Look for the newly created section in the updated list
for section in section_list:
if section['sectionId'].lower() == section_id.lower():
logger.info(f"Found newly created compliance section '{section_id}' with ID: {section['id']}")
return section # Return the section details including its ID
logger.error(f"Failed to find the newly created compliance section '{section_id}'")
return None
def create_if_not_exists_compliance_requirement(base_url, token, compliance_id, requirement_name, requirement_description, requirement_id):
# URL to get the list of compliance requirements
get_url = f"https://{base_url}/compliance/{compliance_id}/requirement"
headers = {
"Accept": "application/json; charset=UTF-8",
"x-redlock-auth": token
}
# Check if the requirement exists
try:
response = requests.get(get_url, headers=headers)
response.raise_for_status() # Raise error for bad status codes
except requests.exceptions.RequestException as err:
logger.error(f"Exception in checking compliance requirements for compliance ID {compliance_id}: {err}")
return None
requirement_list = response.json()
# Check if the compliance requirement already exists
for requirement in requirement_list:
if requirement['name'].lower() == requirement_name.lower():
logger.info(f"Compliance requirement '{requirement_name}' already exists for compliance ID {compliance_id}.")
return requirement # If it exists, return the requirement (including its ID)
# If the requirement does not exist, create it
post_url = f"https://{base_url}/compliance/{compliance_id}/requirement"
payload = {
"description": requirement_description,
"name": requirement_name,
"requirementId": requirement_id
}
headers["Content-Type"] = "application/json"
try:
post_response = requests.post(post_url, headers=headers, json=payload)
post_response.raise_for_status() # Raise error for bad status codes
except requests.exceptions.RequestException as err:
logger.error(f"Exception in creating compliance requirement: {err}")
return None
logger.info(f"Compliance requirement '{requirement_name}' created successfully.")
# Fetch the list of requirements again to retrieve the new requirement's ID
try:
response = requests.get(get_url, headers=headers)
response.raise_for_status() # Raise error for bad status codes
except requests.exceptions.RequestException as err:
logger.error(f"Exception in fetching compliance requirements after creation for compliance ID {compliance_id}: {err}")
return None
requirement_list = response.json()
# Look for the newly created requirement in the updated list
for requirement in requirement_list:
if requirement['name'].lower() == requirement_name.lower():
logger.info(f"Found newly created compliance requirement '{requirement_name}' with ID: {requirement['id']}")
return requirement # Return the requirement details including its ID
logger.error(f"Failed to find the newly created compliance requirement '{requirement_name}'")
return None
def create_if_not_exists_compliance_framework(base_url, token, framework_name, framework_description):
# URL to get the list of compliance frameworks
get_url = f"https://{base_url}/compliance"
headers = {
"Accept": "application/json; charset=UTF-8",
"x-redlock-auth": token
}
# Check if the framework exists
try:
response = requests.get(get_url, headers=headers)
response.raise_for_status() # Raise error for bad status codes
except requests.exceptions.RequestException as err:
logger.error(f"Exception in checking compliance frameworks: {err}")
return None
compliance_list = response.json()
# Check if the compliance framework already exists
for framework in compliance_list:
if framework['name'].lower() == framework_name.lower():
logger.info(f"Compliance framework '{framework_name}' already exists.")
return framework # If it exists, return the framework (with the ID)
# If the framework does not exist, create it
post_url = f"https://{base_url}/compliance"
payload = {
"description": framework_description,
"name": framework_name
}
headers["Content-Type"] = "application/json"
try:
post_response = requests.post(post_url, headers=headers, json=payload)
post_response.raise_for_status() # Raise error for bad status codes
except requests.exceptions.RequestException as err:
logger.error(f"Exception in creating compliance framework: {err}")
return None
logger.info(f"Compliance framework '{framework_name}' created successfully.")
# Fetch the list of frameworks again to retrieve the new framework's ID
try:
response = requests.get(get_url, headers=headers)
response.raise_for_status() # Raise error for bad status codes
except requests.exceptions.RequestException as err:
logger.error(f"Exception in fetching compliance frameworks after creation: {err}")
return None
compliance_list = response.json()
# Look for the newly created framework in the updated list
for framework in compliance_list:
if framework['name'].lower() == framework_name.lower():
logger.info(f"Found newly created compliance framework '{framework_name}' with ID: {framework['id']}")
return framework # Return the framework details including its ID
logger.error(f"Failed to find the newly created compliance framework '{framework_name}'")
return None
def get_policies(base_url, token):
url = f"https://{base_url}/v2/policy"
headers = {"content-type": "application/json; charset=UTF-8", "x-redlock-auth": token}
try:
response = requests.get(url, headers=headers)
response.raise_for_status() # Raises a HTTPError if the status is 4xx, 5xx
except requests.exceptions.RequestException as err:
logger.error(f"Exception in get_policies: {err}")
return None
response_json = response.json()
logger.debug(f"Response status code: {response.status_code}")
logger.debug(f"Response headers: {response.headers}")
return response_json
def get_compute_url(base_url, token):
url = f"https://{base_url}/meta_info"
headers = {"content-type": "application/json; charset=UTF-8", "Authorization": "Bearer " + token}
try:
response = requests.get(url, headers=headers)
response.raise_for_status() # Raises a HTTPError if the status is 4xx, 5xx
except requests.exceptions.RequestException as err:
logger.error("Oops! An exception occurred in get_compute_url, ", err)
return None
response_json = response.json()
return response_json.get("twistlockUrl", None)
def login_saas(base_url, access_key, secret_key):
url = f"https://{base_url}/login"
payload = json.dumps({"username": access_key, "password": secret_key})
headers = {"content-type": "application/json; charset=UTF-8"}
try:
response = requests.post(url, headers=headers, data=payload)
response.raise_for_status() # Raises a HTTPError if the status is 4xx, 5xx
except Exception as e:
logger.info(f"Error in login_saas: {e}")
return None
return response.json().get("token")
def login_compute(base_url, access_key, secret_key):
url = f"{base_url}/api/v1/authenticate"
payload = json.dumps({"username": access_key, "password": secret_key})
headers = {"content-type": "application/json; charset=UTF-8"}
response = requests.post(url, headers=headers, data=payload)
return response.json()["token"]
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--debug", action="store_true", help="Enable debug logging.")
args = parser.parse_args()
input_csv_file = 'matched_policies.csv'
if args.debug:
logging_level = logging.DEBUG
else:
logging_level = logging.INFO
logging.basicConfig(
level=logging_level, format="%(asctime)s - %(levelname)s - %(message)s", filename="app.log", filemode="a"
)
# Create a console handler
console_handler = logging.StreamHandler()
# Add the console handler to the logger
logger.addHandler(console_handler)
logger.info("======================= START =======================")
logger.debug("======================= DEBUG MODE =======================")
load_dotenv()
url = os.environ.get("PRISMA_API_URL")
identity = os.environ.get("PRISMA_ACCESS_KEY")
secret = os.environ.get("PRISMA_SECRET_KEY")
if not url or not identity or not secret:
logger.error("PRISMA_API_URL, PRISMA_ACCESS_KEY, PRISMA_SECRET_KEY variables are not set.")
return
token = login_saas(url, identity, secret)
# compute_url = get_compute_url(url, token)
# compute_token = login_compute(compute_url, identity, secret)
# logger.debug(f"Compute url: {compute_url}")
if token is None:
logger.error("Unable to authenticate.")
return
update_policy_from_csv(url, token, input_csv_file)
logger.info("======================= END =======================")
if __name__ == "__main__":
main()