DEV Community

loading...
Cover image for Scan AWS IAM Keys In A Commit

Scan AWS IAM Keys In A Commit

vumdao profile image Vu Dao ・2 min read

- Sometimes developers add their env file to git commit which contains AWS Access key, to avoid this, we can use git HOOK to check personal key first and use merge_request pipeline job to check before merging the commit to branch


What’s In This Document


🚀 How to scan all AWS keys

https://github.com/vumdao/scan-iam-keys/blob/master/scan-iam-keys.py

#!/usr/bin/env python
import boto3
import subprocess as sub
import re
import threading


def get_commit_change_content():
    output = sub.check_output(["git", "show"])
    return output


def scan_iam_access_keys():
    iam = boto3.client('iam')
    users = iam.list_users()['Users']
    commit_change = get_commit_change_content()

    def check_key(the_key):
        if re.search(the_key['AccessKeyId'], str(commit_change)):
            print(f"Detect {the_key['AccessKeyId']}")

    def check_user(the_user):
        user_name = the_user['UserName']
        print("Get keys")
        access_keys = iam.list_access_keys(UserName=user_name)['AccessKeyMetadata']
        for key in access_keys:
            check_key(key)
        print(f"Done {user_name}")

    for user in users:
        user_thread = threading.Thread(target=check_user, args=(user,))
        user_thread.start()


if __name__ == '__main__':
    scan_iam_access_keys()
Enter fullscreen mode Exit fullscreen mode

🚀 Test A Commit

  • Create text file eg. sample.txt which contains an AWS key
  • Run test
⚡ $ ./scan-iam-keys.py 
Detect AKIAZUFR7JW2ZBEOKUVR
Enter fullscreen mode Exit fullscreen mode

Notes:

  • For offline way, we can use the pattern (A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16} to scan the repository or the commit changes

🌠 Blog · Github · Web · Linkedin · Group · Page · Twitter 🌠

Discussion (0)

pic
Editor guide