Last active
October 30, 2017 23:41
-
-
Save andymotta/24b5f26a4239c41ed636b0416b0ca135 to your computer and use it in GitHub Desktop.
Find all active IAM access keys that have never been used
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import boto3 | |
| from botocore.exceptions import ClientError | |
| import datetime | |
| from datetime import date | |
| import os, re | |
| global DEFAULT_AGE_THRESHOLD_IN_DAYS | |
| DEFAULT_AGE_THRESHOLD_IN_DAYS = 7 | |
| def main(): | |
| access = generate_access_list() # Use sts_assume instead | |
| for p in access: | |
| #this will loop through every boto profile on your machine | |
| try: | |
| if p == 'default': | |
| print "Skipping 'default' access profile" | |
| continue | |
| print "Checking " + p + "..." | |
| os.environ["AWS_PROFILE"] = p | |
| # Create a custom session to switch profiles later | |
| session = boto3.session.Session() | |
| global iam | |
| iam = session.client('iam') | |
| get_inactive_access_keys_last_used() | |
| except: | |
| print "Skipping " + p | |
| continue | |
| def generate_access_list(): # replace this mess with sts_assume | |
| access_file = os.path.join(os.environ['HOME'], '.aws', 'credentials') | |
| with open (access_file, 'r') as f: | |
| lst = [] | |
| for line in f.readlines(): | |
| if re.search(r'\[.*?\]', line): | |
| profile = line[line.find("[")+1:line.find("]")] | |
| lst.append(profile) | |
| return lst | |
| def get_inactive_access_keys_last_used(): | |
| try: | |
| for user in iam.list_users()['Users']: | |
| now = date(datetime.date.today().year, datetime.date.today().month, datetime.date.today().day) | |
| for access_key in iam.list_access_keys(UserName = user['UserName'])['AccessKeyMetadata']: | |
| if access_key['Status'] == 'Active': | |
| response = iam.get_access_key_last_used(AccessKeyId = access_key['AccessKeyId']) | |
| if 'LastUsedDate' not in response['AccessKeyLastUsed']: | |
| access_key_created_date = access_key['CreateDate'] | |
| access_key_created_date = date(access_key_created_date.year, access_key_created_date.month, access_key_created_date.day) | |
| age = (now - access_key_created_date).days | |
| if age >= DEFAULT_AGE_THRESHOLD_IN_DAYS: | |
| print('User {0} has never used active key {1} created {2} days ago.'.format(user['UserName'], access_key['AccessKeyId'], age)) | |
| except ClientError as e: | |
| if e.response['Error']['Code'] == 'InvalidClientTokenId': | |
| print "Not authorized to perform iam maintainence" | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment