Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
# Blacklist needs to know the current account
config['filter_config']['BlacklistFilter']['current_account'] = account_number
for plugin_path in config.get('active_filters'):
plugin_name = plugin_path.split(':')[1]
plugins.load_plugin(plugin_path, config=config['filter_config'].get(plugin_name, None))
for plugin in plugins.filter_plugins:
filtered_list = plugin.apply(roles)
class_name = plugin.__class__.__name__
for filtered_role in filtered_list:
LOGGER.info('Role {} filtered by {}'.format(filtered_role.role_name, class_name))
filtered_role.disqualified_by.append(class_name)
for role in roles:
set_role_data(dynamo_table, role.role_id, {'DisqualifiedBy': role.disqualified_by})
LOGGER.info('Getting data from Aardvark')
aardvark_data = _get_aardvark_data(config['aardvark_api_location'], account_number=account_number)
LOGGER.info('Updating with Aardvark data')
for role in roles:
try:
role.aa_data = aardvark_data[role.arn]
except KeyError:
LOGGER.info('Aardvark data not found for role: {} ({})'.format(role.role_id, role.role_name))
else:
set_role_data(dynamo_table, role.role_id, {'AAData': role.aa_data})
LOGGER.info('Calculating repoable permissions and services')
roledata._calculate_repo_scores(roles, config['filter_config']['AgeFilter']['minimum_age'], hooks)
for role in roles:
return_message="Unable to find role {} in account {}".format(
message.role_name, message.account
),
)
role_data = dynamo.get_role_data(dynamo_table, role_id, fields=["OptOut"])
if "OptOut" not in role_data or not role_data["OptOut"]:
return ResponderReturn(
successful=False,
return_message="Role {} in account {} wasn't opted out".format(
message.role_name, message.account
),
)
else:
dynamo.set_role_data(dynamo_table, role_id, {"OptOut": {}})
return ResponderReturn(
successful=True,
return_message="Cancelled opt-out for role {} in account {}".format(
message.role_name, message.account
),
error = _delete_policy(name, role, account_number, conn)
if error:
LOGGER.error(error)
errors.append(error)
if repoed_policies:
error = _replace_policies(repoed_policies, role, account_number, conn)
if error:
LOGGER.error(error)
errors.append(error)
current_policies = get_role_inline_policies(role.as_dict(), **conn) or {}
roledata.add_new_policy_version(dynamo_table, role, current_policies, "Repo")
# regardless of whether we're successful we want to unschedule the repo
set_role_data(
dynamo_table, role.role_id, {"RepoScheduled": 0, "ScheduledPerms": []}
)
repokid.hooks.call_hooks(hooks, "AFTER_REPO", {"role": role})
if not errors:
# repos will stay scheduled until they are successful
set_role_data(
dynamo_table,
role.role_id,
{"Repoed": datetime.datetime.utcnow().isoformat()},
)
_update_repoed_description(role.role_name, **conn)
_update_role_data(
role,
dynamo_table,
conn["account_number"] = account_number
for name in deleted_policy_names:
error = _delete_policy(name, role, account_number, conn)
if error:
LOGGER.error(error)
if repoed_policies:
error = _replace_policies(repoed_policies, role, account_number, conn)
if error:
LOGGER.error(error)
current_policies = get_role_inline_policies(role.as_dict(), **conn) or {}
roledata.add_new_policy_version(dynamo_table, role, current_policies, "Repo")
set_role_data(
dynamo_table, role.role_id, {"Repoed": datetime.datetime.utcnow().isoformat()}
)
_update_repoed_description(role.role_name, **conn)
_update_role_data(
role,
dynamo_table,
account_number,
config,
conn,
hooks,
source="ManualPermissionRepo",
add_no_repo=False,
)
LOGGER.info(
"Successfully removed {permissions} from role: {role} in account {account_number}".format(
permissions=permissions, role=role.role_name, account_number=account_number
role_data["OptOut"]["reason"],
timestr,
)
),
)
else:
current_dt = datetime.datetime.fromtimestamp(time.time())
expire_dt = current_dt + datetime.timedelta(opt_out_period)
expire_epoch = int((expire_dt - datetime.datetime(1970, 1, 1)).total_seconds())
new_opt_out = {
"owner": message.requestor,
"reason": message.reason,
"expire": expire_epoch,
}
dynamo.set_role_data(dynamo_table, role_id, {"OptOut": new_opt_out})
return ResponderReturn(
successful=True,
return_message="Role {} in account {} opted-out until {}".format(
message.role_name, message.account, expire_dt.strftime("%m/%d/%y")
),
repoed_policies, deleted_policy_names = roledata._get_repoed_policy(
role.policies[-1]["Policy"], repoable_permissions
)
if _inline_policies_size_exceeds_maximum(repoed_policies):
error = (
"Policies would exceed the AWS size limit after repo for role: {} in account {}. "
"Please manually minify.".format(role_name, account_number)
)
LOGGER.error(error)
errors.append(error)
continuing = False
# if we aren't repoing for some reason, unschedule the role
if not continuing:
set_role_data(
dynamo_table, role.role_id, {"RepoScheduled": 0, "ScheduledPerms": []}
)
return
if not commit:
_logprint_deleted_and_repoed_policies(
deleted_policy_names, repoed_policies, role_name, account_number
)
return
conn = config["connection_iam"]
conn["account_number"] = account_number
for name in deleted_policy_names:
error = _delete_policy(name, role, account_number, conn)
if error:
* 60
* CONFIG["repo_requirements"].get("exclude_new_permissions_for_days", 14)
)
# only copy non-expired items to the new dictionary
for permission, expire_time in list(current_ignored_permissions.items()):
if expire_time > current_time:
new_ignored_permissions[permission] = current_ignored_permissions[
permission
]
for permission in newly_added_permissions:
new_ignored_permissions[permission] = new_perms_expire_time
role.no_repo_permissions = new_ignored_permissions
set_role_data(
dynamo_table, role.role_id, {"NoRepoPermissions": role.no_repo_permissions}
)
for policy_name, policy in repoed_policies.items():
try:
ca.call('iam.client.put_role_policy', RoleName=role.role_name, PolicyName=policy_name,
PolicyDocument=json.dumps(policy, indent=2, sort_keys=True))
except botocore.exceptions.ClientError as e:
error = 'Exception calling PutRolePolicy on {role}/{policy}\n{e}\n'.format(
role=role.role_name, policy=policy_name, e=str(e))
LOGGER.error(error)
errors.append(error)
current_policies = get_role_inline_policies(role.as_dict(), **conn) or {}
roledata.add_new_policy_version(dynamo_table, role, current_policies, 'Repo')
# regardless of whether we're successful we want to unschedule the repo
set_role_data(dynamo_table, role.role_id, {'RepoScheduled': 0})
repokid.hooks.call_hooks(hooks, 'AFTER_REPO', {'role': role})
if not errors:
# repos will stay scheduled until they are successful
set_role_data(dynamo_table, role.role_id, {'Repoed': datetime.datetime.utcnow().isoformat()})
_update_repoed_description(role.role_name, **conn)
_update_role_data(role, dynamo_table, account_number, config, conn, hooks, source='Repo', add_no_repo=False)
LOGGER.info('Successfully repoed role: {}'.format(role.role_name))
return errors
if not aardvark_data:
return
batch_processing = config.get("query_role_data_in_batch", False)
batch_size = config.get("batch_processing_size", 100)
role.aa_data = aardvark_data[role.arn]
roledata._calculate_repo_scores(
[role],
config["filter_config"]["AgeFilter"]["minimum_age"],
hooks,
batch_processing,
batch_size,
)
set_role_data(
dynamo_table,
role.role_id,
{
"AAData": role.aa_data,
"TotalPermissions": role.total_permissions,
"RepoablePermissions": role.repoable_permissions,
"RepoableServices": role.repoable_services,
},
)
roledata.update_stats(dynamo_table, [role], source=source)
)
LOGGER.info(
"Updating roles with Aardvark data in account {}".format(account_number)
)
for role in roles:
try:
role.aa_data = aardvark_data[role.arn]
except KeyError:
LOGGER.warning(
"Aardvark data not found for role: {} ({})".format(
role.role_id, role.role_name
)
)
else:
set_role_data(dynamo_table, role.role_id, {"AAData": role.aa_data})
LOGGER.info(
"Calculating repoable permissions and services for account {}".format(
account_number
)
)
batch_processing = config.get("query_role_data_in_batch", False)
batch_size = config.get("batch_processing_size", 100)
roledata._calculate_repo_scores(
roles,
config["filter_config"]["AgeFilter"]["minimum_age"],
hooks,
batch_processing,
batch_size,
)