iam-key-age

# Written 24/09/2021 by Andrew Stringer
# Prurpose is to detect users with AWS IAM access keys older than a certain number of days (accesskey below)
# Should be run once per week via CloudWatch Events. 
# Uses the "email" value in Tags, so these need to be set for users.
 
import boto3, os, time, datetime, sys, json
from datetime import date
from botocore.exceptions import ClientError
 
 
# age of keys
accesskey = 180
AWS_REGION = 'eu-west-2'
 
iam = boto3.client('iam')
email_list = []
def lambda_handler(event, context):
    print("All IAM user emails that have AccessKeys ", accesskey, " days or older")
    for userlist in iam.list_users()['Users']:
            userKeys = iam.list_access_keys(UserName=userlist['UserName'])
            # print("username:- ", userlist['UserName'], "Keys:- ", userKeys['AccessKeyMetadata'][0]['AccessKeyId'], "\n")
            for keyValue in userKeys['AccessKeyMetadata']:
                    if keyValue['Status'] == 'Active':
                            currentdate = date.today()
                            active_days = currentdate - keyValue['CreateDate'].date()
                            if active_days >= datetime.timedelta(days=accesskey):
                                userTags = iam.list_user_tags(
                                    UserName=keyValue['UserName'])
                                email_tag = list(filter(lambda tag: tag['Key'] == 'email', userTags['Tags']))
                                if(len(email_tag) == 1):
                                    email = email_tag[0]['Value']
                                    email_list.append(email)
                                    #print("email_list--:- ", email_list)
 
    print("End of gathering, start of sending. \n\n")
 
    aws_account_id = context.invoked_function_arn.split(":")[4]
 
 
    email_unique = list(set(email_list))
    print("Unique email", email_unique)
    RECIPIENTS = email_unique
    SENDER = "mer@company.systems"
 
    SUBJECT = "IAM Access Key Rotation"
    BODY_TEXT = ("Your IAM Access Key need to be rotated in AWS Account: " + str(aws_account_id) + " as it is older than " + str(accesskey) + " days old.\r\n"
                "Log into AWS and go to your IAM user to fix: https://console.aws.amazon.com/iam/home?#security_credential"
                )
    BODY_HTML = ("Your IAM Access Key need to be rotated in AWS Account: " + str(aws_account_id) + " as it is older than " + str(accesskey) + " days old. Log into AWS and go to your https://console.aws.amazon.com/iam/home?#security_credential to create a new set of keys.")
    CHARSET = "UTF-8"
 
    # print("debug", RECIPIENTS, SENDER, AWS_REGION, SUBJECT)
 
    client = boto3.client('ses',region_name=AWS_REGION)
    try:
        response = client.send_email(
            Destination={
                'ToAddresses': ['me@company.systems',],
                'BccAddresses': RECIPIENTS,
            },
            Message={
                'Body': {
                    'Html': {
                        'Charset': CHARSET,
                        'Data': BODY_HTML,
                    },
                    'Text': {
                        'Charset': CHARSET,
                        'Data': BODY_TEXT,
                    },
                },
                'Subject': {
                    'Charset': CHARSET,
                    'Data': SUBJECT,
                },
            },
            Source=SENDER,
        )
    except ClientError as e:
        print(e.response['Error']['Message'])
    else:
        print("Email sent! Message ID:"),
        print(response['MessageId'])
 
 
aws/iam-key-age.txt · Last modified: 15/03/2024 11:06 by andrew