Skip to content

Instantly share code, notes, and snippets.

@iashwash
Forked from OnlyInAmerica/find_iam_user.py
Last active September 23, 2015 17:46
Show Gist options
  • Save iashwash/60f411be9bd4a73ac37c to your computer and use it in GitHub Desktop.
Save iashwash/60f411be9bd4a73ac37c to your computer and use it in GitHub Desktop.
Find an AWS IAM user corresponding to an AWS Access Key
# Modified from https://gist.github.com/OnlyInAmerica/9964456
# Find the IAM username belonging to the TARGET_ACCESS_KEY
# Useful for finding IAM user corresponding to a compromised AWS credential
#
# Usage:
# python find_iam_user AWS_KEY_ID
#
# Requirements:
#
# Environmental variables:
# AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY
# python packages:
# boto
import sys
import os
import boto.iam
def find_user(key_id):
"""
Returns the dictionary of the user or False for the owner of key_id
Iterates through all keys for all IAM users and compares the IDs
"""
iam = boto.connect_iam()
users = iam.get_all_users('/')['list_users_response']['list_users_result']['users']
for user in users:
for key_result in iam.get_all_access_keys(user['user_name'])['list_access_keys_response']['list_access_keys_result']['access_key_metadata']:
aws_access_key = key_result['access_key_id']
if aws_access_key == key_id:
return user
return False
def print_user(key_id):
"""
Given an AWS_ACCESS_KEY, prints out the username belonging to the user.
Returns True if found, else False
"""
user = find_user(key_id)
if user:
print('Key %s belongs to user %s'%(key_id, user['user_name']))
return True
else:
print('Did not find access_key_id %s'%(key_id))
return False
def print_usage():
""" Prints Usage Instructions"""
print("Usage: python %s AWS_ACCESS_KEY_ID [--help|-h]"%(os.path.basename(__file__)))
def main():
if '--help' in sys.argv or '-h' in sys.argv:
print_usage()
sys.exit(0)
if len(sys.argv) > 2:
print('ERROR: Too many arguments')
print_usage()
sys.exit(1)
elif len(sys.argv) > 1:
key_id = sys.argv[1]
else:
print('ERROR: Must provide key.')
print_usage()
sys.exit(1)
sys.exit(not print_user(key_id))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment