Getting access key age AWS Boto3

Viewed 6551

I am trying to figure out a way to get a users access key age through an aws lambda function using Python 3.6 and Boto 3. My issue is that I can't seem to find the right api call to use if any exists for this purpose. The two closest that I can seem to find are list_access_keys which I can use to find the creation date of the key. And get_access_key_last_used which can give me the day the key was last used. However neither or others I can seem to find give simply the access key age like is shown in the AWS IAM console users view. Does a way exist to get simply the Access key age?

4 Answers

This simple code do the same stuff without converting a lot of time etc:

import boto3
from datetime import date

client = boto3.client('iam')
username = "<YOUR-USERNAME>"
res = client.list_access_keys(UserName=username)
accesskeydate = res['AccessKeyMetadata'][0]['CreateDate'].date()
currentdate = date.today()
active_days = currentdate - accesskeydate
print (active_days.days)

Upon further testing, I've come up with the following which runs in Lambda. This function in python3.6 will email users if their IAM keys are 90 days or older.

Pre-requisites

all IAM users have an email tag with a proper email address as the value.

Example;

  • IAM user tag key: email
  • IAM user tag value: someone@gmail.com

every email used, needs to be confirmed in SES

    import boto3, os, time, datetime, sys, json
    from datetime import date
    from botocore.exceptions import ClientError

    iam = boto3.client('iam')
    email_list = []
    def lambda_handler(event, context):
        print("All IAM user emails that have AccessKeys 90 days or older")
        for userlist in iam.list_users()['Users']:
                userKeys = iam.list_access_keys(UserName=userlist['UserName'])
                for keyValue in userKeys['AccessKeyMetadata']:
                        if keyValue['Status'] == 'Active':
                                currentdate = date.today()
                                active_days = currentdate - \
                                    keyValue['CreateDate'].date()
                                if active_days >= datetime.timedelta(days=90):
                                    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)

        email_unique = list(set(email_list))
        print(email_unique)
        RECIPIENTS = email_unique
        SENDER = "AWS SECURITY "
        AWS_REGION = os.environ['region']
        SUBJECT = "IAM Access Key Rotation"
        BODY_TEXT = ("Your IAM Access Key need to be rotated in AWS Account: 123456789 as it is 3 months or older.\r\n"
                    "Log into AWS and go to your IAM user to fix: https://console.aws.amazon.com/iam/home?#security_credential"
                    )
        BODY_HTML = """
        AWS Security: IAM Access Key Rotation: Your IAM Access Key need to be rotated in AWS Account: 123456789 as it is 3 months or older. Log into AWS and go to your https://console.aws.amazon.com/iam/home?#security_credential to create a new set of keys. Ensure to disable / remove your previous key pair.
                    """            
        CHARSET = "UTF-8"
        client = boto3.client('ses',region_name=AWS_REGION)
        try:
            response = client.send_email(
                Destination={
                    'ToAddresses': 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'])

Using the above methods you will only get the age of the access keys. But as a best practice or a security approach, you need to check the rotation period, when the keys are last rotated. If the keys rotation age is more than 90 days you could alert your team.

The only way to get the rotation age of the access keys is by using the credentials report from IAM. Download it, parse it, and calculate the age.

Related