Skip to content

Instantly share code, notes, and snippets.

@dduvnjak
Forked from DmZ/pre-commit
Last active September 26, 2023 00:29
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save dduvnjak/ce08f917f7ead5f126ef to your computer and use it in GitHub Desktop.
Save dduvnjak/ce08f917f7ead5f126ef to your computer and use it in GitHub Desktop.
Git pre-commit hook to search for Amazon AWS API keys.
#!/bin/sh
if git rev-parse --verify HEAD >/dev/null 2>&1
then
against=HEAD
else
# Initial commit: diff against an empty tree object
against=5da2c1fe8f6458e32d11110e0ebdd915e472c6e0
fi
# Redirect output to stderr.
exec 1>&2
# Check changed files for an AWS keys
KEY_ID=$(git diff --cached --name-only -z $against | xargs -0 cat | perl -nle'print $& if m{(?<![A-Z0-9])[A-Z0-9]{20}(?![A-Z0-9])}')
KEY=$(git diff --cached --name-only -z $against | xargs -0 cat | perl -nle'print $& if m{(?<![A-Z0-9])[A-Z0-9]{20}(?![A-Z0-9])}')
if [ "$KEY_ID" != "" -o "$KEY" != "" ]; then
echo "Found patterns for AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY"
echo "Please check your code and remove API keys."
exit 1
fi
# Normal exit
exit 0
@jhammerman79
Copy link

Hey dduvnjak,

Your second regex is identical to your first, and is neither match my dummy secret key. Did you forget to differentiate them?
Joe

@brianantonelli
Copy link

Here's the correct pattern for secret key:

KEY=$(git diff --cached --name-only -z $against | xargs -0 cat | perl -nle'print $& if m{(?<![^A-Za-z0-9/+=])[A-Za-z0-9/+=]{40}(?![^A-Za-z0-9/+=])}')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment