Skip to main content

Command Palette

Search for a command to run...

Scan AWS IAM Keys In A Commit

Updated
1 min read
Scan AWS IAM Keys In A Commit

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

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()

🚀 Test A Commit

  • Create text file eg. sample.txt which contains an AWS key

  • Run test

⚡ $ ./scan-iam-keys.py 
Detect AKIAZUFR7JW2ZBEOKUVR

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

More from this blog

V

Vu Dao

102 posts

🚀 AWSome Devops | AWS Community Builder | AWS SA || ☁️ SimflexCloud ☁️