-
-
Save WheresWardy/4f6d4a38a77a4ef23ac9 to your computer and use it in GitHub Desktop.
Find an AWS IAM user corresponding to an AWS Access Key
This file contains 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
#!/usr/bin/env python | |
# Find the IAM username belonging to the TARGET_ACCESS_KEY | |
# Useful for finding IAM user corresponding to a compromised AWS credential | |
# Requirements: | |
# | |
# Environmental variables: | |
# AWS_PROFILE | |
# python: | |
# boto | |
import os | |
import sys | |
import boto3 | |
def help(): | |
print("AWS_PROFILE=main find_iam_user.py AWS_ACCESS_KEY_ID") | |
def find_key(access_key): | |
iam = boto3.client('iam') | |
marker = False | |
while True: | |
if marker: | |
users = iam.list_users(Marker=marker) | |
else: | |
users = iam.list_users() | |
for user in users['Users']: | |
user_access_keys = iam.list_access_keys(UserName=user['UserName']) | |
for key in user_access_keys['AccessKeyMetadata']: | |
if access_key == key['AccessKeyId']: | |
print('Target key belongs to: {}'.format(user['UserName'])) | |
return True | |
if users['IsTruncated']: | |
marker = users['Marker'] | |
else: | |
break | |
return False | |
def main(): | |
try: | |
target_access_key = sys.argv[1] | |
except IndexError: | |
help() | |
sys.exit(0) | |
if target_access_key in ['-h', '--help']: | |
help() | |
sys.exit(0) | |
account = os.getenv('AWS_PROFILE', 'main') | |
print("Searching in account profile '{}'...".format(account)) | |
if not find_key(access_key=target_access_key): | |
print('Did not find access key ({}) in IAM users.'.format(target_access_key)) | |
sys.exit(1) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment