Exemplo n.º 1
0
def repo_all_roles(account_number, commit=False):
    """
    Repo all eligible roles in an account.  Collect any errors and display them at the end.

    Args:
        account_number (string)
        commit (bool): actually make the changes

    Returns:
        None
    """
    errors = []

    role_ids_in_account = roledata.role_ids_for_account(account_number)
    roles = Roles([])
    for role_id in role_ids_in_account:
        roles.append(
            Role(roledata.get_role_data(role_id),
                 fields=['Active', 'RoleName']))

    roles = roles.filter(active=True)

    for role in roles:
        errors.append(repo_role(account_number, role.role_name, commit=commit))

    if errors:
        LOGGER.error('Error(s) during repo: \n{}'.format(errors))
    else:
        LOGGER.info('Everything successful!')
Exemplo n.º 2
0
def repo_stats(output_file, account_number=None):
    roleIDs = roledata.roles_for_account(
        account_number
    ) if account_number else roledata.role_ids_for_all_accounts()
    headers = [
        'RoleId', 'Role Name', 'Account', 'Date', 'Source',
        'Permissions Count', 'Disqualified By'
    ]
    rows = []

    for roleID in roleIDs:
        role_data = roledata.get_role_data(roleID)
        for stats_entry in role_data.get('Stats', []):
            rows.append([
                role_data['RoleId'], role_data['RoleName'],
                role_data['Account'], stats_entry['Date'],
                stats_entry['Source'], stats_entry['PermissionsCount'],
                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))
Exemplo n.º 3
0
def find_roles_with_permission(permission):
    for roleID in roledata.role_ids_for_all_accounts():
        role_data = roledata.get_role_data(roleID)
        permissions = _get_role_permissions(role_data)
        if permission in permissions:
            LOGGER.info('ARN {arn} has {permission}'.format(
                arn=role_data['Arn'], permission=permission))
Exemplo n.º 4
0
def _find_role_in_cache(role_name):
    """Return a tuple with arn and role from cache matching supplied rolename or None, None"""
    found = False

    for roleID in roledata.roles_for_account(CUR_ACCOUNT_NUMBER):
        role_data = roledata.get_role_data(roleID)
        if role_data['RoleName'].lower() == role_name.lower():
            found = True
            break

    if found:
        return role_data
    else:
        return None
Exemplo n.º 5
0
def _find_role_in_cache(account_number, role_name):
    """Return role dictionary for active role with name in account

    Args:
        account_number (string)
        role_name (string)

    Returns:
        dict: A dict with the roledata for the given role in account, else None if not found
    """
    found = False

    for roleID in roledata.role_ids_for_account(account_number):
        role_data = roledata.get_role_data(roleID,
                                           fields=['RoleName', 'Active'])
        if role_data['RoleName'].lower() == role_name.lower(
        ) and role_data['Active']:
            found = True
            break

    if found:
        return roledata.get_role_data(roleID)
    else:
        return None
Exemplo n.º 6
0
def find_roles_with_permission(permission):
    """
    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 roledata.role_ids_for_all_accounts():
        role = Role(
            roledata.get_role_data(roleID,
                                   fields=['Policies', 'RoleName', 'Arn']))
        permissions = roledata._get_role_permissions(role)
        if permission.lower() in permissions:
            LOGGER.info('ARN {arn} has {permission}'.format(
                arn=role.arn, permission=permission))
Exemplo n.º 7
0
def display_roles(account_number, inactive=False):
    """
    Display a table with data about all roles in an account and write a csv file with the data.

    Args:
        account_number (string)
        inactive (bool): show roles that have historically (but not currently) existed in the account if True

    Returns:
        None
    """
    headers = [
        'Name', 'Refreshed', 'Disqualified By', 'Can be repoed', 'Permissions',
        'Repoable', 'Repoed', 'Services'
    ]

    rows = list()

    roles = Roles([
        Role(roledata.get_role_data(roleID))
        for roleID in tqdm(roledata.role_ids_for_account(account_number))
    ])

    if not inactive:
        roles = roles.filter(active=True)

    for role in roles:
        rows.append([
            role.role_name, role.refreshed, role.disqualified_by,
            len(role.disqualified_by) == 0, role.total_permissions,
            role.repoable_permissions, role.repoed, role.repoable_services
        ])

    rows = sorted(rows, key=lambda x: (x[5], x[0], x[4]))
    rows.insert(0, headers)
    # print tabulate(rows, headers=headers)
    t.view(rows)
    with open('table.csv', 'wb') as csvfile:
        csv_writer = csv.writer(csvfile)
        csv_writer.writerow(headers)
        for row in rows:
            csv_writer.writerow(row)
Exemplo n.º 8
0
def repo_stats(output_file, 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 = roledata.role_ids_for_account(
        account_number
    ) if account_number else roledata.role_ids_for_all_accounts()
    headers = [
        'RoleId', 'Role Name', 'Account', 'Date', 'Source',
        'Permissions Count', 'Disqualified By'
    ]
    rows = []

    for roleID in roleIDs:
        role_data = roledata.get_role_data(
            roleID, fields=['RoleId', 'RoleName', 'Account', 'Stats'])
        for stats_entry in role_data.get('Stats', []):
            rows.append([
                role_data['RoleId'], role_data['RoleName'],
                role_data['Account'], stats_entry['Date'],
                stats_entry['Source'], stats_entry['PermissionsCount'],
                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))
Exemplo n.º 9
0
def display_roles(account_number, inactive=False):
    headers = [
        'Name', 'Disqualified By', 'Can be repoed', 'Permissions', 'Repoable',
        'Repoed', 'Services'
    ]

    rows = list()

    if inactive:
        roles_data = {
            roleID: roledata.get_role_data(roleID)
            for roleID in tqdm(roledata.roles_for_account(account_number))
        }
    else:
        roles_data = roledata.get_data_for_active_roles_in_account(
            account_number)

    for roleID, role_data in roles_data.items():
        rows.append([
            role_data['RoleName'],
            role_data.get('DisqualifiedBy', []),
            len(role_data.get('DisqualifiedBy', [])) == 0,
            role_data['TotalPermissions'],
            role_data.get('RepoablePermissions', 0), role_data['Repoed'],
            role_data.get('RepoableServices')
        ])

    rows = sorted(rows, key=lambda x: (x[4], x[0], x[3]))
    rows.insert(0, headers)
    # print tabulate(rows, headers=headers)
    t.view(rows)
    with open('table.csv', 'wb') as csvfile:
        csv_writer = csv.writer(csvfile)
        csv_writer.writerow(headers)
        for row in rows:
            csv_writer.writerow(row)