Example #1
0
def analyze_policy_directory(policy_directory, account_id, from_audit_file, finding_type, excluded_role_patterns):
    """
    Audits a directory of policy JSON files.

    :param policy_directory:
    :param db_session:
    :param from_audit_file:
    :param findings_obj: Findings object

    :return: policy_findings: A dictionary of policy names as keys.
    The values for those are a list of actions. Like this:
    credentials_exposure_findings = [
        {
            "PolicyName": [
                "ecr:GetAuthorizationToken"
            ]
        },
        {
            "PolicyName2": [
                "redshift:getclustercredentials"
            ]
        }
    ]
    """
    policy_file_list = list_files_in_directory(policy_directory)
    policy_findings = {}
    finding = {}
    actions_list = []
    requested_actions = []
    expanded_actions = []
    for policy_file in policy_file_list:
        actions_list.clear()
        requested_actions.clear()
        expanded_actions.clear()
        this_file = policy_directory + '/' + policy_file
        policy_name = policy_file.rsplit(".", 1)[0]
        # If the policy name matches excluded role patterns, skip it
        reg_list = map(re.compile, excluded_role_patterns)
        if any(regex.match(policy_name) for regex in reg_list):
            continue
        requested_actions = get_actions_from_json_policy_file(this_file)
        expanded_actions = determine_actions_to_expand(requested_actions)
        actions_list = determine_risky_actions(
            expanded_actions, from_audit_file)

        actions_list.sort()  # sort in alphabetical order
        actions_list = list(dict.fromkeys(actions_list))  # remove duplicates
        # try:
        if actions_list:
            finding[finding_type] = copy.deepcopy(actions_list)
            finding['account_id'] = account_id
            policy_findings[policy_name] = copy.deepcopy(finding)
            # Store the account ID
        else:
            finding['account_id'] = account_id
        # print(finding['account_id'])
        # except KeyError as k_e:
        #     print(k_e)
        #     continue
    return policy_findings
Example #2
0
def download_remote_policies(profile=None,
                             customer_managed=True,
                             attached_only=True):
    # Credentials profile selection
    if profile:
        profile = profile
    else:
        profile = "default"
    iam_session = login(profile, "iam")
    sts_session = login(profile, "sts")
    # Get the account ID for use in folder directory naming
    account_id = sts_session.get_caller_identity()["Account"]

    # Directory names
    policy_file_directory = home + config_directory + 'policy-analysis' + '/' + account_id
    customer_managed_policy_file_directory = policy_file_directory + '/' + 'customer-managed'
    aws_managed_policy_file_directory = policy_file_directory + '/' + 'aws-managed'

    create_directory_if_it_doesnt_exist(policy_file_directory)
    create_directory_if_it_doesnt_exist(customer_managed_policy_file_directory)
    create_directory_if_it_doesnt_exist(aws_managed_policy_file_directory)

    policy_group = PolicyGroup()
    policy_group.set_remote_policy_metadata(iam_session, customer_managed,
                                            attached_only)
    policy_names = policy_group.get_policy_names()
    policy_group.set_remote_policy_documents(iam_session)

    # Determine whether we should store it in the customer-managed or aws-managed directory
    if customer_managed:
        filename_directory = customer_managed_policy_file_directory
    else:
        filename_directory = aws_managed_policy_file_directory

    print("Writing the policy files to " + filename_directory)
    print("")
    for policy_name in policy_names:
        # get the default policy version for that specific policy
        document = policy_group.get_policy_document(policy_name)
        filename = filename_directory + '/' + policy_name + '.json'
        write_json_file(filename, document)
    print(
        "If you want to analyze the policies, specify the policy file in the analyze-iam-policy command\n"
    )
    print("The list of policies downloaded are:")
    print("")
    only_files = list_files_in_directory(filename_directory)
    for filename in only_files:
        print(filename)
Example #3
0
def create_audit_directory():
    """
    Creates directory for analyze_iam_policy audit files and places audit files there.
    """
    audit_directory_path = HOME + CONFIG_DIRECTORY + AUDIT_DIRECTORY_FOLDER
    create_directory_if_it_doesnt_exist(audit_directory_path)
    destination = audit_directory_path

    existing_audit_files_directory = os.path.abspath(os.path.dirname(__file__)) + '/data/audit/'
    source = existing_audit_files_directory
    file_list = list_files_in_directory(existing_audit_files_directory)

    for file in file_list:
        if file.endswith(".txt"):
            shutil.copy(source + '/' + file, destination)
            print("copying " + file + " to " + destination)
Example #4
0
def create_default_overrides_file():
    """
    Copies over the overrides file in the config directory

    Essentially:
    cp $MODULE_DIR/policy_sentry/shared/data/access-level-overrides.yml ~/policy_sentry/access-level-overrides.yml
    """
    existing_overrides_file_directory = os.path.abspath(
        os.path.dirname(__file__)) + '/data/'
    file_list = list_files_in_directory(existing_overrides_file_directory)

    source = existing_overrides_file_directory
    destination = HOME + CONFIG_DIRECTORY + '/'
    for file in file_list:
        if file.endswith(".yml"):
            shutil.copy(source + '/' + file, destination)
            print("copying overrides file " + file + " to " + destination)
Example #5
0
def create_audit_directory():
    """
    Creates directory for analyze_iam_policy audit files and places audit files there.

    Essentially:
    mkdir -p ~/.policy_sentry/audit
    cp -r $MODULE_DIR/policy_sentry/shared/data/audit/ ~/.policy_sentry/audit/
    """
    create_directory_if_it_doesnt_exist(AUDIT_DIRECTORY_PATH)
    destination = AUDIT_DIRECTORY_PATH

    existing_audit_files_directory = os.path.abspath(
        os.path.dirname(__file__)) + '/data/audit/'
    source = existing_audit_files_directory
    file_list = list_files_in_directory(existing_audit_files_directory)

    for file in file_list:
        if file.endswith(".txt"):
            shutil.copy(source + '/' + file, destination)
            print("copying " + file + " to " + destination)
Example #6
0
def analyze_iam_policy(from_audit_file, policy, from_access_level):
    """
    Analyze IAM Actions given a JSON policy file
    """
    db_session = connect_db(database_file_path)

    if os.path.exists(policy):
        if os.path.isdir(policy):
            print("Evaluating policy files in " + policy)
        else:
            print("Evaluating policy file: " + policy)
    else:
        print("File/directory does not exist: " + policy +
              "\nPlease provide a valid path.")
        exit()

    if os.path.isdir(policy):
        file_list = list_files_in_directory(policy)
        print("Access level: " + from_access_level)
        for file in file_list:
            this_file = policy + '/' + file
            analyze(this_file, db_session, from_access_level, from_audit_file)
    elif os.path.isfile(policy):
        analyze(policy, db_session, from_access_level, from_audit_file)