Skip to content

Instantly share code, notes, and snippets.

@dduvnjak
Last active May 9, 2017 14:18
Show Gist options
  • Save dduvnjak/d4067caba7ff8cbf8a33a5da880c5eb2 to your computer and use it in GitHub Desktop.
Save dduvnjak/d4067caba7ff8cbf8a33a5da880c5eb2 to your computer and use it in GitHub Desktop.
#!/bin/bash
# --- Command line
refname="$1"
oldrev="$2"
newrev="$3"
# --- Safety check
if [ -z "$GIT_DIR" ]; then
echo "Don't run this script from the command line." >&2
echo " (if you want, you could supply GIT_DIR then run" >&2
echo " $0 <ref> <oldrev> <newrev>)" >&2
exit 1
fi
if [ -z "$refname" -o -z "$oldrev" -o -z "$newrev" ]; then
echo "Usage: $0 <ref> <oldrev> <newrev>" >&2
exit 1
fi
scan_aws_secrets() {
# Reusable regex patterns
local aws="(AWS|aws|Aws)?_?" quote="(\"|')" connect="\s*(:|=>|=)\s*"
local opt_quote="${quote}?"
pattern1='[A-Z0-9]{20}|[A-Za-z0-9/\+=]{40}'
pattern2="${opt_quote}${aws}(SECRET|secret|Secret)?_?(ACCESS|access|Access)?_?(KEY|key|Key)${opt_quote}${connect}${opt_quote}[A-Za-z0-9/\+=]{40}${opt_quote}"
pattern3="${opt_quote}${aws}(ACCOUNT|account|Account)_?(ID|id|Id)?${opt_quote}${connect}${opt_quote}[0-9]{4}\-?[0-9]{4}\-?[0-9]{4}${opt_quote}"
combined_patterns=''
for pattern in $pattern1 $pattern2 $pattern3; do
combined_patterns=${combined_patterns}${pattern}"|"
done
combined_patterns=${combined_patterns%?}
GREP_OPTIONS= LC_ALL=C git grep -nwHEI $combined_patterns $1
}
# convert git-diff-tree output to BASH array
array=(`git diff-tree --name-only --diff-filter=ACMR $newrev`)
ret=0
# iterate over all array elements
for index in ${!array[*]}; do
# skip index zero, because this contains a SHA1, not a filename
if [ $index -ne 0 ]; then
file=${array[$index]}
#echo "$index: $file"
RESULT=$(scan_aws_secrets $newrev:$file)
if [ $? -eq 0 ]; then
echo -e "\n'$file' contains AWS secrets. Please remove them before trying to push.\n"
ret=1
fi
fi
done
# --- Finished
exit $ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment