HIBP Password Breach Bash Script

Another challenge – leverage the basic haveibeenpwned.com web API to see if passwords have been leaked in breaches.

Pretty simple criteria here so it’s not much of a problem. Openssl does what we want and bash script is posted below.

When I was writing this, it didn’t work at first because I was being an idiot and not accounting for the newline “\n” which was completely changing the submitted hash. Just a pointer for anyone else that is tempted to use echo in this sort of application. :)

#!/bin/bash
#
# HaveIBeenPwned Password/Hash Checker
# v1.1 - Mark M
# 
# Check password or hash against hibp.
#
# -p	Prompt for password to check
# -h	Use hash [hash] to check
#
# Simple func to leverage API
gethash(){
curl -A "hibp_checkverv1" -X GET https://api.pwnedpasswords.com/range/$TRUNC 2>/dev/null |\
 awk -F":" '{print "'$TRUNC'"$1" Count:"$2}'
}

USAGE="
`basename $0` [-f filename] [-h sha1-hash] [-p]
-h [sha1hash] checks given hash against HIBP
-p option will prompt for password"

optstring=h:p
while getopts $optstring opt
do
   case $opt in
      h)   MYHASH=$OPTARG;;
      p)   printf "Enter Password: "
           stty -echo
           read MYPASS
           stty echo ;;
      *)   echo "$USAGE.";exit 1;;
   esac
done

if [ "$MYPASS" ] && [ "$MYHASH" ]; then
   echo "File and Hash set. Only use one or the other."
   exit 1
elif [ ! "$MYPASS" ] && [ ! "$MYHASH" ]; then
   echo "No parameters."
   exit 1
fi


# Set required Vars
MYPASS=$(printf $MYPASS | tr -d '\n')

# Only hash with sha1 if password option was specified
if [ "$MYPASS" ]; then
   MYHASH=$(printf $MYPASS | openssl sha1 | awk '{print toupper($2)}')
fi

# Get first 5 chars into $TRUNC 
TRUNC=$(printf $MYHASH | cut -c 1-5)

# MYPASS no longer needed. Unset it.
unset MYPASS

# Run func and checks
printf "\nCheck HIBP for $TRUNC... Full hash is \033[33m$MYHASH\n\033[0m"
HASHLIST=$(gethash)
if [ "$HASHLIST" == "" ]; then
   printf "\nError retreiving Data from Web API\n"
   exit 1
fi

printf "Does it appear in list? "
HASHCHK=$(echo "$HASHLIST" | grep -o "$MYHASH")

if [ "$HASHCHK" == "$MYHASH" ]; then
   printf "\033[31;1m< YES >\n\033[0m"
else
   printf "\033[32;1m< NO >\n\033[0m"
fi
Tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *