-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathappgate_heimdall_data_import.py
537 lines (504 loc) · 30.2 KB
/
appgate_heimdall_data_import.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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
import csv
import secrets
import json
from decouple import config
import requests
import sys
import random
import string
"""
The CSV file needs to be written in the following format starting from the top line:
service name, "list of servers separated by a comma ", ports(no spaces allow if there's more than one), "okta application ids (if applicable)",
a "Y" if an admin account is needed", a comma.
"""
# Function to transform csv file into a list.
def read_csv(file):
with open(file) as csv_file:
csv_data = csv.reader(csv_file, delimiter=',')
csv_data_list = []
csv_data_final_list = []
for row in csv_data:
csv_data_list.append(row)
for csv_final_list in csv_data_list:
del csv_final_list[-1]
csv_data_final_list.append(csv_final_list)
return csv_data_final_list
# Function to create the JSON entitlement skeleton structure
# The site points to AWS
def create_entitlement_structure():
false_str = "false"
empty_entitlement = {
"id": "",
"name": "object",
"notes": "Automatically Created.",
"tags": [],
"displayName": "",
"disabled": false_str,
"site": "",
"conditionLogic": "and",
"conditions": [],
"actions": [
{
"subtype": "tcp_up",
"action": "allow",
"hosts": [],
"ports": [],
"type": "IpAccess",
"monitor": {
"enabled": false_str,
"timeout": 30
}
}]
}
return empty_entitlement
# Function to create a new action for entitlements
def create_entitlement_action_structure():
false_str = "false"
empty_action = {
"subtype": "tcp_up",
"action": "allow",
"hosts": [],
"ports": [],
"type": "IpAccess",
"monitor": {
"enabled": false_str,
"timeout": 30
}
}
return empty_action
# Function to create the JSON policy structure, with an empty expression which will be filled in by the ICC team.
def create_policy_structure():
true_str = "true"
empty_policy = {
"id": "4c07bc67-57ea-42dd-b702-c2d6c45419fc",
"name": "object",
"notes": "Automatically Created.",
"tags": [
],
"expression": "//Generated by criteria builder, Operator: or\nvar result = false;\nreturn result;",
"entitlements": [
],
"entitlementLinks": [
],
"ringfenceRules": [
],
"ringfenceRuleLinks": [
],
"tamperProofing": true_str,
"administrativeRoles": [],
'administrativeRoleLinks': []
}
return empty_policy
# Function to create the JSON Assumed Roles structure
def create_assumed_roles_structure():
empty_assumed_roles = {
'accountId': '',
'roleName': 'SDP_NameResolver',
'externalId': config('AWS_KEY_ID'),
'regions': []
}
return empty_assumed_roles
# Function to create random entitlement and policies IDs.
# Note: Policies or Entitlements are not overwritten if they share the same name even if the IDs are different.
def create_random_id():
first_hex = secrets.token_hex(4)
second_hex = secrets.token_hex(2)
third_hex = secrets.token_hex(2)
fourth_hex = secrets.token_hex(2)
fifth_hex = secrets.token_hex(6)
rand_entitlement_id = first_hex + "-" + second_hex + "-" + third_hex + "-" + fourth_hex + "-" + fifth_hex
return rand_entitlement_id
# Functions to retrieve the bear tokens for the dev, stage, and prod environments
def get_token(passwd, device_id, url_var):
payload = {"providerName": "local", "username": config('USERNAME_VAR'),
"password": config(passwd), "deviceId": config(device_id)}
headers = {'Content-Type': 'application/json',
'Accept': 'application/vnd.appgate.peer-v11+json'}
url = config(url_var) + 'login'
token_post = requests.post(
url, headers=headers, json=payload, verify=False)
token_data = token_post.text
token_string = token_data
token_clean_string = token_string.replace("'", '"')
token_dict = json.loads(token_clean_string)
token = token_dict['token']
return token
# Function to perform a REST API call to retrieve data
def get_operations(bear_token, ops_type, url_var):
headers = {'Authorization': 'Bearer ' + bear_token, 'Content-Type': 'application/json',
'Accept': 'application/vnd.appgate.peer-v10+json'}
url = config(url_var) + ops_type
ops_get = requests.get(url, headers=headers, verify=False)
if ops_get.status_code == 200:
print("GET Request Successful!")
elif ops_get.status_code == 401:
print("Token error. Login again.")
elif ops_get.status_code == 403:
print("Insufficient permissions to access this resource.")
elif ops_get.status_code == 500:
print("Unexpected server side error.")
else:
print("GET Request Failed")
ops_data = ops_get.text
return ops_data
# Functions to create (POST) entitlements in dev, stage, and prod environments
def post_operations(bear_token, operations_data, ops_type, url_var):
headers = {'Authorization': 'Bearer ' + bear_token,
'Content-Type': 'application/json',
'Accept': 'application/vnd.appgate.peer-v11+json'}
payload = operations_data
url = config(url_var) + ops_type
ops_post = requests.post(url, headers=headers, json=payload, verify=False)
if ops_post.status_code == 200:
print("POST Request Successful! Feature Updated!")
elif ops_post.status_code == 400:
print("JSON error. Check the JSON format.")
elif ops_post.status_code == 401:
print("Token error. Login again.")
elif ops_post.status_code == 403:
print("Insufficient permissions to access this resource.")
elif ops_post.status_code == 409:
print("The submitted resource conflicts with another.")
elif ops_post.status_code == 422:
print('Request validation error. Check "errors" array for details.')
elif ops_post.status_code == 500:
print("Unexpected server side error.")
else:
print("POST Request Failed")
ops_data = ops_post.text
return ops_data
# Function to perform REST API PUT operations
def put_operations(bear_token, operations_data, ops_type, url_var):
headers = {'Authorization': 'Bearer ' + bear_token,
'Content-Type': 'application/json',
'Accept': 'application/vnd.appgate.peer-v11+json'}
payload = operations_data
url = config(url_var) + ops_type
ops_put = requests.put(url, headers=headers, json=payload, verify=False)
if ops_put.status_code == 200:
print("PUT Request Successful! Feature Updated!")
elif ops_put.status_code == 400:
print("JSON error. Check the JSON format.")
elif ops_put.status_code == 401:
print("Token error. Login again.")
elif ops_put.status_code == 403:
print("Insufficient permissions to access this resource.")
elif ops_put.status_code == 404:
print("The requested resource can not be found.")
elif ops_put.status_code == 422:
print('Request validation error. Check "errors" array for details.')
elif ops_put.status_code == 500:
print("Unexpected server side error.")
else:
print("PUT Request Failed")
ops_data = ops_put.text
return ops_data
def main():
# Initialize variables
heimdall_entitlements_list_dict = []
heimdall_entitlements_names_list = []
heimdall_entitlements_names_aws_list = []
heimdall_entitlements_aws_list_dict = []
repeated_names_list = []
heimdall_policies_list_dict = []
env_var = sys.argv[1].lower()
file_var = config('IMPORT_FILE')
true_str = "true"
aws_account_id_list = []
heimdall_master_list = read_csv(file_var)
###########################################################################################################################
# Data Fetching #
###########################################################################################################################
# Loop to read the arguments to know whether dev, stage, or prod will be modified
# To run the program, you need to enter the environment argument in the following form
# python data_import_1_gw.py dev for example
if env_var == 'dev' or env_var == 'stage' or env_var == 'prod':
ops_url_var = env_var.upper() + '_URL_VAR'
ops_pwd_var = env_var.upper() + '_PASSWORD_VAR'
ops_devid_var = env_var.upper() + '_DEVICE_ID_VAR'
else:
print("Invalid argument, enter DEV, STAGE, or PROD, exiting...")
quit()
"""
The next part of the script formats the data taken from the csv file and puts it
into the REST API entitlement structure, JSON format.
Starting with the entitlements and then policies.
Entitlements are linked to policies using a tag based on the okta application ID
"""
# Start of REST API call to get the Tokens
print("Getting Token")
token = get_token(ops_pwd_var, ops_devid_var, ops_url_var)
# Gets the Site ID for AWS and SWE EXT from the relevant environment
print("Getting Sites Data")
get_sites = json.loads(get_operations(token, 'sites', ops_url_var))
print("Getting Conditions Data")
get_conditions = json.loads(get_operations(token, 'conditions', ops_url_var))
print("Getting Identity Providers Data")
get_id_providers = json.loads(get_operations(token, 'identity-providers', ops_url_var))
# Loop to fetch AWS ID data
for site in get_sites['data']:
site_id = site['id']
site_name = site['name']
if site_name == "AWS":
aws_site_id = site_id
else:
pass
# Loop to fetch Heimdall condition ID
for condition in get_conditions['data']:
condition_id = condition['id']
condition_name = condition['name']
if condition_name == "COND_ALWAYS_HEIMDALL":
heimdall_condition_id = condition_id
# Fetch the data for the AWS site
get_aws_site = json.loads(get_operations(token, 'sites/' + aws_site_id , ops_url_var))
# Loop to fetch the Okta client ID
for okta_provider in get_id_providers['data']:
okta_provider_tag = okta_provider['tags']
if "okta_client" in okta_provider_tag:
okta_client_id = okta_provider['id']
else:
pass
###########################################################################################################################
# JSON Data Structure Creation #
###########################################################################################################################
# DNS Based Entitlements Data Structure Creation
print("Formatting and creating Entitlements structure - DNS Based...")
# Evaluates line by line of the CSV file
for heimdall_entitlements_line in heimdall_master_list:
if heimdall_entitlements_line[8].upper().replace(" ", "") == "Y" or heimdall_entitlements_line[8].lower().replace(" ", "") == 'manual':
# Creates a dictionary using the REST API entitlement structure
heimdall_entitlements_dict = create_entitlement_structure()
# The next lines of code format the csv data to prettify the JSON structures (tags, names, and okta id)
heimdall_ent_service_name = heimdall_entitlements_line[0].replace(
"-", "").replace(" ", " ").replace(" ", "_").upper().replace("(", "").replace(")", "").replace("/", "_").replace(".","_")
heimdall_ent_tag_name = heimdall_entitlements_line[0].replace(
"-", "").replace(" ", " ").replace(" ", "_").lower().replace("(", "").replace(")", "").replace("/", "_").replace(".","_")
heimdall_ent_oktaid_string = heimdall_entitlements_line[3]
heimdall_ent_oktaid_clean = heimdall_ent_oktaid_string.split(',')
# Check to see if there are multiple lines per service, if not, create a new entitlement
# If there are multiple lines, then create additional firewall rules.
if heimdall_ent_service_name not in heimdall_entitlements_names_list:
# The next lines of code begins to fill in the JSON structure with csv data (id, name, and display name)
# Below the okta application id loop, displayName is also filled.
heimdall_entitlements_names_list.append(heimdall_ent_service_name)
heimdall_entitlements_dict['id'] = create_random_id()
heimdall_entitlements_dict['name'] = "ENT_" + heimdall_ent_service_name
# Loops the csv field for application okta id to create a list of tags to follow the REST API JSON structure
heimdall_entitlements_dict['tags'].append('tag_heimdall')
heimdall_entitlements_dict['tags'].append('tag_heimdall_dns-resolver')
# Check if everyone has access to this entitlement
if heimdall_ent_oktaid_string.lower() == "everyone":
heimdall_entitlements_dict['tags'].append('all_okta_access-' + heimdall_ent_tag_name.replace("_",""))
else:
# Loops the csv field for application okta id to create a list of tags to follow the REST API JSON structure
for endpoints_ent_okta_id in heimdall_ent_oktaid_clean:
heimdall_entitlements_dict['tags'].append('oktaid-' + endpoints_ent_okta_id + "-" + heimdall_ent_tag_name.replace("_",""))
heimdall_entitlements_dict['disabled'] = true_str
heimdall_entitlements_dict['displayName'] = heimdall_entitlements_dict['name']
heimdall_entitlements_dict['site'] = aws_site_id
heimdall_entitlements_dict['conditions'].append(heimdall_condition_id)
heimdall_ent_endpoints_string = heimdall_entitlements_line[1]
heimdall_ent_ports_string = heimdall_entitlements_line[2]
# The split method is used to dissolve the ports and endpoints from a single string into list elements
heimdall_ent_endpoints_clean = heimdall_ent_endpoints_string.split(',')
heimdall_ent_ports_clean = heimdall_ent_ports_string.split(',')
# The below loops are used to fill in the hosts and ports in a list format as required by the REST API using
# the formatted data from the csv
for endpoints_ent_hosts in heimdall_ent_endpoints_clean:
heimdall_entitlements_dict['actions'][0]['hosts'].append(endpoints_ent_hosts)
for endpoints_ent_ports in heimdall_ent_ports_clean:
heimdall_entitlements_dict['actions'][0]['ports'].append(endpoints_ent_ports)
# Each entitlement will be a dictionary following the entitlement JSON data structure
# The next line appends each dictionary into a list, to save the values of each dictionary into a variable
heimdall_entitlements_list_dict.append(heimdall_entitlements_dict)
elif heimdall_ent_service_name in heimdall_entitlements_names_list:
# Checks what's the service name that has been repeated and saves the index number to perform
# a look out on the entitlement data structure
repeated_ent_name_list_index = heimdall_entitlements_names_list.index(heimdall_ent_service_name)
heimdall_add_action_structure = create_entitlement_action_structure()
heimdall_ent_endpoints_string = heimdall_entitlements_line[1]
heimdall_ent_ports_string = heimdall_entitlements_line[2]
# The split method is used to dissolve the ports and endpoints from a single string into list elements
heimdall_ent_endpoints_clean = heimdall_ent_endpoints_string.split(',')
heimdall_ent_ports_clean = heimdall_ent_ports_string.split(',')
# Adds a new firewall rule for the entitlement
for endpoints_ent_hosts in heimdall_ent_endpoints_clean:
heimdall_add_action_structure['hosts'].append(endpoints_ent_hosts)
for endpoints_ent_ports in heimdall_ent_ports_clean:
heimdall_add_action_structure['ports'].append(endpoints_ent_ports)
heimdall_entitlements_list_dict[repeated_ent_name_list_index]['actions'].append(heimdall_add_action_structure)
else:
pass
# AWS Based Entitlements Data Structure Creation
print("Formatting and creating Entitlements structure - AWS Resolver Based...")
# Evaluates line by line of the CSV file
for heimdall_entitlements_aws_line in heimdall_master_list:
if heimdall_entitlements_aws_line[8].upper().replace(" ", "") == "Y":
# Creates a dictionary using the REST API entitlement structure
heimdall_entitlements_aws_dict = create_entitlement_structure()
# The next lines of code format the csv data to prettify the JSON structures (tags, names, and okta id)
heimdall_ent_service_name = heimdall_entitlements_aws_line[0].replace(
"-", "").replace(" ", " ").replace(" ", "_").upper().replace("(", "").replace(")", "").replace("/", "_").replace(".","_") + "_AWS"
heimdall_ent_tag_name = heimdall_entitlements_aws_line[0].replace(
"-", "").replace(" ", " ").replace(" ", "_").lower().replace("(", "").replace(")", "").replace("/", "_").replace(".","_")
heimdall_ent_oktaid_string = heimdall_entitlements_aws_line[3]
heimdall_ent_oktaid_clean = heimdall_ent_oktaid_string.split(',')
heimdall_aws_tag_id = heimdall_entitlements_aws_line[6]
heimdall_aws_account_id = heimdall_entitlements_aws_line [4]
# Check to see if there are multiple lines per service, if not, create a new entitlement
# If there are multiple lines, then create additional firewall rules.
if heimdall_ent_service_name not in heimdall_entitlements_names_aws_list:
# The next lines of code begins to fill in the JSON structure with csv data (id, name, and display name)
# Below the okta application id loop, displayName is also filled.
heimdall_entitlements_names_aws_list.append(heimdall_ent_service_name)
repeated_names_list.append(heimdall_ent_service_name)
heimdall_entitlements_aws_dict['id'] = create_random_id()
heimdall_entitlements_aws_dict['name'] = "ENT_" + heimdall_ent_service_name
# Loops the csv field for application okta id to create a list of tags to follow the REST API JSON structure
heimdall_entitlements_aws_dict['tags'].append('tag_heimdall')
heimdall_entitlements_aws_dict['tags'].append('tag_heimdall_aws-resolver')
# Check if everyone has access to this entitlement
if heimdall_ent_oktaid_string.lower() == "everyone":
heimdall_entitlements_aws_dict['tags'].append("all_okta_access-" + heimdall_ent_tag_name.replace("_",""))
else:
# Loops the csv field for application okta id to create a list of tags to follow the REST API JSON structure
for endpoints_ent_okta_id in heimdall_ent_oktaid_clean:
heimdall_entitlements_aws_dict['tags'].append('oktaid-' + endpoints_ent_okta_id + "-" + heimdall_ent_tag_name.replace("_",""))
heimdall_entitlements_aws_dict['displayName'] = heimdall_entitlements_aws_dict['name']
heimdall_entitlements_aws_dict['site'] = aws_site_id
heimdall_entitlements_aws_dict['conditions'].append(heimdall_condition_id)
heimdall_ent_ports_string = heimdall_entitlements_aws_line[2]
# The split method is used to dissolve the ports and endpoints from a single string into list elements
heimdall_ent_ports_clean = heimdall_ent_ports_string.split(',')
# The below loops are used to fill in the hosts and ports in a list format as required by the REST API using
# the formatted data from the csv
aws_rule_ec2 = 'aws://tag:' + heimdall_aws_tag_id + '=sdp_' + heimdall_aws_account_id + '&publicIp&account=' + heimdall_aws_account_id
aws_rule_lb = 'aws://lb-tag:' + heimdall_aws_tag_id + '=sdp_' + heimdall_aws_account_id + '&publicIp&account=' + heimdall_aws_account_id
aws_rule_lbv2 = 'aws://lbv2-tag:' + heimdall_aws_tag_id + '=sdp_' + heimdall_aws_account_id + '&publicIp&account=' + heimdall_aws_account_id
heimdall_entitlements_aws_dict['actions'][0]['hosts'].append(aws_rule_ec2)
heimdall_entitlements_aws_dict['actions'][0]['hosts'].append(aws_rule_lb)
heimdall_entitlements_aws_dict['actions'][0]['hosts'].append(aws_rule_lbv2)
for endpoints_ent_ports in heimdall_ent_ports_clean:
heimdall_entitlements_aws_dict['actions'][0]['ports'].append(endpoints_ent_ports)
# Each entitlement will be a dictionary following the entitlement JSON data structure
# The next line appends each dictionary into a list, to save the values of each dictionary into a variable
heimdall_entitlements_aws_list_dict.append(heimdall_entitlements_aws_dict)
elif heimdall_ent_service_name in heimdall_entitlements_names_aws_list:
# Checks what's the service name that has been repeated and saves the index number to perform
# a look out on the entitlement data structure
repeated_ent_name_aws_list_index = heimdall_entitlements_names_aws_list.index(heimdall_ent_service_name)
heimdall_add_action_structure = create_entitlement_action_structure()
heimdall_ent_ports_string = heimdall_entitlements_aws_line[2]
# The split method is used to dissolve the ports and endpoints from a single string into list elements
heimdall_ent_ports_clean = heimdall_ent_ports_string.split(',')
# Adds a new firewall rule for the entitlement
aws_rule_ec2 = 'aws://tag:' + heimdall_aws_tag_id + '=sdp_' + heimdall_aws_account_id + ' &publicIp&account=' + heimdall_aws_account_id
aws_rule_lb = 'aws://lb-tag:' + heimdall_aws_tag_id + '=sdp_' + heimdall_aws_account_id + '&publicIp&account=' + heimdall_aws_account_id
aws_rule_lbv2 = 'aws://lbv2-tag:' + heimdall_aws_tag_id + '=sdp_' + heimdall_aws_account_id + '&publicIp&account=' + heimdall_aws_account_id
heimdall_add_action_structure['hosts'].append(aws_rule_ec2)
heimdall_add_action_structure['hosts'].append(aws_rule_lb)
heimdall_add_action_structure['hosts'].append(aws_rule_lbv2)
for endpoints_ent_ports in heimdall_ent_ports_clean:
heimdall_add_action_structure['ports'].append(endpoints_ent_ports)
heimdall_entitlements_aws_list_dict[repeated_ent_name_aws_list_index]['actions'].append(heimdall_add_action_structure)
else:
pass
# Policies Data Structure Creation
print("Formatting and creating Policies structure")
# Evaluates line by line of the CSV file
for heimdall_policies_line in heimdall_master_list:
if heimdall_policies_line[8].upper().replace(" ", "") == "Y" or heimdall_policies_line[8].lower().replace(" ", "") == 'manual':
# Creates a dictionary using the REST API policy structure
heimdall_policies_dict = create_policy_structure()
# The next lines of code format the csv data to prettify the JSON structures (tags, names, and okta id)
heimdall_pol_service_name = heimdall_policies_line[0].replace(
"-", "").replace(" ", " ").replace(" ", "_").upper().replace("(", "").replace(")", "").replace("/", "_").replace(".", "_")
heimdall_pol_tag_name = heimdall_policies_line[0].replace(
"-", "").replace(" ", " ").replace(" ", "_").lower().replace("(", "").replace(")", "").replace("/", "_").replace(".", "_")
# The next lines of code begins to fill in the JSON structure with csv data (id, name, and display name)
# Below the okta application id loop, displayName is also filled.
heimdall_policies_dict['id'] = create_random_id()
heimdall_policies_dict['name'] = "POL_" + heimdall_pol_service_name
heimdall_policies_dict['tags'].append("tag_heimdall")
heimdall_pol_oktaid_string = heimdall_policies_line[3]
# The split method is used to dissolve the ports and endpoints from a single string into list elements
heimdall_pol_oktaid_clean = heimdall_pol_oktaid_string.split(',')
# Check to see if policy should be allowed for Everyone...
if heimdall_pol_oktaid_string.lower() == "everyone":
heimdall_policies_dict['tags'].append("all_okta_access")
heimdall_policies_dict['expression'] = "//Generated by criteria builder, Operator: or\nvar result = false;\nif /*identity-provider*/(claims.user.ag.identityProviderId === \"" + okta_client_id +"\")/*end identity-provider*/ { result = true; } else { return false; } \nreturn result;"
heimdall_policies_dict['entitlementLinks'].append('all_okta_access-' + heimdall_pol_tag_name.replace("_", ""))
heimdall_policies_list_dict.append(heimdall_policies_dict)
else:
# Loops the csv field for application okta id to create a list of tags to follow the REST API JSON structure
# The policy also adds entitlements based on tag, this tag matches the same tag when the entitlement was created
# This is what makes the policy to be bound to the entitlement
for endpoints_pol_okta_id in heimdall_pol_oktaid_clean:
heimdall_policies_dict['tags'].append('oktaid-' + endpoints_pol_okta_id + "-" + heimdall_pol_tag_name.replace("_", ""))
heimdall_policies_dict['entitlementLinks'].append('oktaid-' + endpoints_pol_okta_id + "-" + heimdall_pol_tag_name.replace("_", ""))
# Each policy will be a dictionary following the policy JSON data structure
# The next line appends each dictionary into a list, to save the values of each dictionary into a variable
heimdall_policies_list_dict.append(heimdall_policies_dict)
else:
pass
# AWS Assumed Roles Data Structure Creation
print("Adding Assumed Roles to AWS Resolver...")
# Get the Existing AWS Assumed Roles to avoid duplicates
existing_aws_assumed_roles = get_aws_site['nameResolution']['awsResolvers'][0]['assumedRoles']
for existing_aws_account_ids in existing_aws_assumed_roles:
aws_account_id_list.append(existing_aws_account_ids['accountId'])
# Evaluates line by line of the CSV file
for heimdall_assumed_line in heimdall_master_list:
if heimdall_assumed_line[8].upper().replace(" ", "") == "Y":
# Create the assumed role JSON Data Structure
heimdall_assumed_role = create_assumed_roles_structure()
heimdall_aws_account_id = heimdall_assumed_line[4]
heimdall_aws_region_id_list = heimdall_assumed_line[5].split(',')
# Condition to check for empty strings and to avoid repeated account ids
if heimdall_aws_account_id != "" and heimdall_aws_account_id not in aws_account_id_list:
# Append account ID to a list to avoid duplicates
aws_account_id_list.append(heimdall_aws_account_id)
heimdall_assumed_role['accountId'] = heimdall_assumed_line[4]
for heimdall_aws_region_id in heimdall_aws_region_id_list:
heimdall_assumed_role['regions'].append(heimdall_aws_region_id.replace(" ",""))
# Add new account IDs configs
get_aws_site['nameResolution']['awsResolvers'][0]['assumedRoles'].append(heimdall_assumed_role)
else:
pass
else:
pass
###########################################################################################################################
# Start of API Calls #
###########################################################################################################################
"""
At this stage, the data structure for the entitlements and policies has been created.
The next step is to perform the REST API calls to GET the bear token, and then
POST entitlements and policies.
"""
# Start of REST API call to POST Entitlements by looping the list of dictionaries created before.
print("Uploading Entitlements - DNS Based...")
for api_entitlement in heimdall_entitlements_list_dict:
print("POST " + api_entitlement['name'])
post_operations(token, api_entitlement, 'entitlements', ops_url_var)
print("*" * 60)
print('\n')
print("Uploading Entitlements - AWS Resolver Based...")
for api_entitlement_aws in heimdall_entitlements_aws_list_dict:
print("POST " + api_entitlement_aws['name'])
post_operations(token, api_entitlement_aws, 'entitlements', ops_url_var)
print("*" * 60)
# Start of REST API call to POST policies by looping the list of dictionaries created before.
print('\n')
print("Uploading Policies...")
for api_policy in heimdall_policies_list_dict:
print("POST " + api_policy['name'])
post_operations(token, api_policy, 'policies', ops_url_var)
print("*" * 60)
# Run a REST API call using the data above
print('\n')
print("Adding AWS Assumed Roles to Resolvers")
put_operations(token, get_aws_site, 'sites', ops_url_var)
print("Upload complete...")
print("Have a nice day!")
if __name__ == '__main__' :
main()