Пример #1
0
def repo_stats(output_file, dynamo_table, account_number=None):
    """
    Create a csv file with stats about roles, total permissions, and applicable filters over time

    Args:
        output_file (string): the name of the csv file to write
        account_number (string): if specified only display roles from selected account, otherwise display all

    Returns:
        None
    """
    roleIDs = (role_ids_for_account(dynamo_table, account_number) if account_number else
               role_ids_for_all_accounts(dynamo_table))
    headers = ['RoleId', 'Role Name', 'Account', 'Active', 'Date', 'Source', 'Permissions Count',
               'Repoable Permissions Count', 'Disqualified By']
    rows = []

    for roleID in roleIDs:
        role_data = get_role_data(dynamo_table, roleID, fields=['RoleId', 'RoleName', 'Account', 'Active', 'Stats'])
        for stats_entry in role_data.get('Stats', []):
            rows.append([role_data['RoleId'], role_data['RoleName'], role_data['Account'], role_data['Active'],
                         stats_entry['Date'], stats_entry['Source'], stats_entry['PermissionsCount'],
                         stats_entry.get('RepoablePermissionsCount'), stats_entry.get('DisqualifiedBy', [])])

    try:
        with open(output_file, 'wb') as csvfile:
            csv_writer = csv.writer(csvfile)
            csv_writer.writerow(headers)
            for row in rows:
                csv_writer.writerow(row)
    except IOError as e:
        LOGGER.error('Unable to write file {}: {}'.format(output_file, e))
    else:
        LOGGER.info('Successfully wrote stats to {}'.format(output_file))
Пример #2
0
def _repo_stats(output_file: str, account_number: str = "") -> None:
    """
    Create a csv file with stats about roles, total permissions, and applicable filters over time

    Args:
        output_file (string): the name of the csv file to write
        account_number (string): if specified only display roles from selected account, otherwise display all

    Returns:
        None
    """
    role_ids: Iterable[str]
    if account_number:
        access_advisor_datasource = AccessAdvisorDatasource()
        access_advisor_datasource.seed(account_number)
        iam_datasource = IAMDatasource()
        role_ids = iam_datasource.seed(account_number)
    else:
        role_ids = role_ids_for_all_accounts()

    headers = [
        "RoleId",
        "Role Name",
        "Account",
        "Active",
        "Date",
        "Source",
        "Permissions Count",
        "Repoable Permissions Count",
        "Disqualified By",
    ]
    rows = []
    roles = RoleList.from_ids(
        role_ids, fields=["RoleId", "RoleName", "Account", "Active", "Stats"])

    for role in roles:
        for stats_entry in role.stats:
            rows.append([
                role.role_id,
                role.role_name,
                role.account,
                role.active,
                stats_entry["Date"],
                stats_entry["Source"],
                stats_entry["PermissionsCount"],
                stats_entry.get("RepoablePermissionsCount", 0),
                stats_entry.get("DisqualifiedBy", []),
            ])

    try:
        with open(output_file, "w") as csvfile:
            csv_writer = csv.writer(csvfile)
            csv_writer.writerow(headers)
            for row in rows:
                csv_writer.writerow(row)
    except IOError as e:
        LOGGER.error("Unable to write file {}: {}".format(output_file, e),
                     exc_info=True)
    else:
        LOGGER.info("Successfully wrote stats to {}".format(output_file))
Пример #3
0
def _find_roles_with_permissions(permissions, dynamo_table, output_file):
    """
    Search roles in all accounts for a policy with any of the provided permissions, log the ARN of each role.

    Args:
        permissions (list[string]): The name of the permissions to find
        output_file (string): filename to write the output

    Returns:
        None
    """
    arns = list()
    for roleID in role_ids_for_all_accounts(dynamo_table):
        role = Role.parse_obj(
            get_role_data(dynamo_table,
                          roleID,
                          fields=["Policies", "RoleName", "Arn", "Active"]))
        role_permissions, _ = roledata.get_role_permissions(role)

        permissions = set([p.lower() for p in permissions])
        found_permissions = permissions.intersection(role_permissions)

        if found_permissions and role.active:
            arns.append(role.arn)
            LOGGER.info("ARN {arn} has {permissions}".format(
                arn=role.arn, permissions=list(found_permissions)))

    if not output_file:
        return

    with open(output_file, "w") as fd:
        json.dump(arns, fd)

    LOGGER.info('Ouput written to file "{output_file}"'.format(
        output_file=output_file))
Пример #4
0
def _find_roles_with_permissions(permissions: List[str],
                                 output_file: str) -> None:
    """
    Search roles in all accounts for a policy with any of the provided permissions, log the ARN of each role.

    Args:
        permissions (list[string]): The name of the permissions to find
        output_file (string): filename to write the output

    Returns:
        None
    """
    arns: List[str] = list()
    role_ids = role_ids_for_all_accounts()
    roles = RoleList.from_ids(role_ids,
                              fields=["Policies", "RoleName", "Arn", "Active"])
    for role in roles:
        role_permissions, _ = role.get_permissions_for_policy_version()

        permissions_set = set([p.lower() for p in permissions])
        found_permissions = permissions_set.intersection(role_permissions)

        if found_permissions and role.active:
            arns.append(role.arn)
            LOGGER.info("ARN {arn} has {permissions}".format(
                arn=role.arn, permissions=list(found_permissions)))

    if not output_file:
        return

    with open(output_file, "w") as fd:
        json.dump(arns, fd)

    LOGGER.info(f"Output written to file {output_file}")
Пример #5
0
def _repo_stats(output_file, dynamo_table, account_number=None):
    """
    Create a csv file with stats about roles, total permissions, and applicable filters over time

    Args:
        output_file (string): the name of the csv file to write
        account_number (string): if specified only display roles from selected account, otherwise display all

    Returns:
        None
    """
    roleIDs = (role_ids_for_account(dynamo_table, account_number)
               if account_number else role_ids_for_all_accounts(dynamo_table))
    headers = [
        "RoleId",
        "Role Name",
        "Account",
        "Active",
        "Date",
        "Source",
        "Permissions Count",
        "Repoable Permissions Count",
        "Disqualified By",
    ]
    rows = []

    for roleID in roleIDs:
        role_data = get_role_data(
            dynamo_table,
            roleID,
            fields=["RoleId", "RoleName", "Account", "Active", "Stats"],
        )
        for stats_entry in role_data.get("Stats", []):
            rows.append([
                role_data["RoleId"],
                role_data["RoleName"],
                role_data["Account"],
                role_data["Active"],
                stats_entry["Date"],
                stats_entry["Source"],
                stats_entry["PermissionsCount"],
                stats_entry.get("RepoablePermissionsCount"),
                stats_entry.get("DisqualifiedBy", []),
            ])

    try:
        with open(output_file, "w") as csvfile:
            csv_writer = csv.writer(csvfile)
            csv_writer.writerow(headers)
            for row in rows:
                csv_writer.writerow(row)
    except IOError as e:
        LOGGER.error("Unable to write file {}: {}".format(output_file, e),
                     exc_info=True)
    else:
        LOGGER.info("Successfully wrote stats to {}".format(output_file))
Пример #6
0
def find_roles_with_permission(permission, dynamo_table):
    """
    Search roles in all accounts for a policy with a given permission, log the ARN of each role with this permission

    Args:
        permission (string): The name of the permission to find

    Returns:
        None
    """
    for roleID in role_ids_for_all_accounts(dynamo_table):
        role = Role(get_role_data(dynamo_table, roleID, fields=['Policies', 'RoleName', 'Arn', 'Active']))
        permissions = roledata._get_role_permissions(role)
        if permission.lower() in permissions and role.active:
            LOGGER.info('ARN {arn} has {permission}'.format(arn=role.arn, permission=permission))