DEV Community

Cover image for Scan AWS IAM Keys In A Commit
πŸš€ Vu Dao πŸš€
πŸš€ Vu Dao πŸš€

Posted on

4 2

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

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 🌠

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

Try REST API Generation for MS SQL Server.

DevOps for Private APIs. With DreamFactory API Generation, you get:

  • Auto-generated live APIs mapped from database schema
  • Interactive Swagger API documentation
  • Scripting engine to customize your API
  • Built-in role-based access control

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay