get IAM users from all AWS accounts (organization)
Tags: aws, serverless, awsorganizations, awssecurity
Published: 2023-02-16 12:12:24

Hi,

IAM (Identity and Access Management) users are a critical component of any organization's security infrastructure. They represent the individuals or entities that have access to an organization's sensitive information, systems, and applications. It is essential to keep an eye on the IAM users of the entire organization for several reasons:

**Security**: IAM users are the gatekeepers of an organization's digital assets. If a hacker gains access to an IAM user account, they can potentially access confidential data, modify or delete important files, and even bring down the entire network. Monitoring IAM users can help identify suspicious activities, such as attempts to access restricted resources or unusual login patterns, allowing security teams to respond quickly and prevent unauthorized access.

**Compliance**: Many regulatory frameworks require organizations to have proper access controls in place and to monitor and audit user activity. Keeping an eye on IAM users can help organizations ensure that they are meeting compliance requirements and avoid costly fines and legal repercussions.

**User management**: Monitoring IAM users can help organizations identify inactive or unnecessary accounts, which can be removed or disabled, reducing the attack surface and improving the overall security posture. Additionally, organizations can use IAM user monitoring to identify users who have too many privileges and limit their access to reduce the risk of internal threats.

**Data protection**: By keeping an eye on IAM users, organizations can ensure that only authorized individuals have access to sensitive data. IAM user monitoring can help identify and alert security teams to any unusual access attempts, which can indicate a potential data breach.

In summary, keeping an eye on IAM users is critical to maintaining the security, compliance, and overall risk posture of an organization. It allows organizations to proactively identify potential threats and take action to mitigate risks before they can cause significant damage.

Here is how you can get the list of all IAM users in your organization:

1. Get all the member accounts.
2. Trigger "generate_credential_report" API on all the member accounts by assuming a role on the member accounts.
3. Trigger "get_credential_report" API on all the member accounts by assuming a role on the member accounts. 
4. Consolidate the report.

P.S: Step 2 and 3 are done separately as I was encountering report not ready exception sometimes.


If you're looking for further help, here is a snippet you can modify according to your need.

`
import json
import boto3
import io
import csv

from datetime import datetime

def lambda_handler(event, context):
    organizations_client = boto3.client('organizations')
    sts_client = boto3.client('sts')
    iam_client = boto3.client('iam')

    #1. Get all the member accounts
    marker=None
    paginator = organizations_client.get_paginator('list_accounts')
    page_iterator = paginator.paginate(PaginationConfig={
     'MaxItems': 200,
     'PageSize': 10,
        'StartingToken':marker
    })
    active_accounts=[]  
    f = open("/tmp/all_users.csv", "w+")
    temp_csv_file = csv.writer(f, escapechar=' ', quoting=csv.QUOTE_NONE)
    
    #2.Filter for only active accounts
    for page in page_iterator:        
        for account in page['Accounts']:
            if account['Status']=='ACTIVE':
                account=str(account['Id'])
                active_accounts.append(account)
    
    current_account = sts_client.get_caller_identity()['Account']
    consolidated_data=''
    
    #3.Generate Credentials Report
    for account in active_accounts:
        if account !=current_account:
            ROLE_ARN=f'arn:aws:iam::{account}:role/OrganizationAccountAccessRole'
            sts_response = sts_client.assume_role(RoleArn=ROLE_ARN, RoleSessionName=account)
            assumed_client=boto3.client('iam',aws_access_key_id=sts_response["Credentials"]["AccessKeyId"],aws_secret_access_key=sts_response["Credentials"]["SecretAccessKey"],aws_session_token=sts_response["Credentials"]["SessionToken"])
            assumed_client.generate_credential_report()
        else:
            response = iam_client.generate_credential_report()
    
    #4.Generate Credentials Report & consolidate
    for account in active_accounts:
        if account !=current_account:
            ROLE_ARN=f'arn:aws:iam::{account}:role/OrganizationAccountAccessRole'
            sts_response = sts_client.assume_role(RoleArn=ROLE_ARN, RoleSessionName=account)
            assumed_client=boto3.client('iam',aws_access_key_id=sts_response["Credentials"]["AccessKeyId"],aws_secret_access_key=sts_response["Credentials"]["SecretAccessKey"],aws_session_token=sts_response["Credentials"]["SessionToken"])
            response = assumed_client.get_credential_report()
            user_data=response['Content']
            user_data_decoded=user_data.decode('utf-8')
            consolidated_data=consolidated_data+user_data_decoded
        else:
            response = iam_client.get_credential_report()
            user_data=response['Content']
            user_data_decoded=user_data.decode('utf-8')
            consolidated_data=consolidated_data+user_data_decoded

    temp_csv_file.writerow([consolidated_data])
    f.close()
`