So my question is straight forward given a linux username and a password how can I test if it is a valid account?
#! /bin/bash
# (GPL3+) Alberto Salvia Novella (es20490446e)
passwordHash () {
password=${1}
salt=${2}
encryption=${3}
hashes=$(echo ${password} | openssl passwd -${encryption} -salt ${salt} -stdin)
echo $(substring ${hashes} "$" "3")
}
passwordIsValid () {
user=${1}
password=${2}
encryption=$(secret "encryption" ${user})
salt=$(secret "salt" ${user})
salted=$(secret "salted" ${user})
hash=$(passwordHash ${password} ${salt} ${encryption})
[ ${salted} = ${hash} ] && echo "true" || echo "false"
}
secret () {
secret=${1}
user=${2}
shadow=$(shadow ${user})
if [ ${secret} = "encryption" ]; then
position=1
elif [ ${secret} = "salt" ]; then
position=2
elif [ ${secret} = "salted" ]; then
position=3
fi
echo $(substring ${shadow} "$" ${position})
}
shadow () {
user=${1}
shadow=$(cat /etc/shadow | grep ${user})
shadow=$(substring ${shadow} ":" "1")
echo ${shadow}
}
substring () {
string=${1}
separator=${2}
position=${3}
substring=${string//"${separator}"/$'\2'}
IFS=$'\2' read -a substring <<< "${substring}"
echo ${substring[${position}]}
}
passwordIsValid ${@}
You can validate that a given password is correct for a given username using the shadow file.
On most modern distributions, the hashed passwords are stored in the shadow file /etc/shadow (which is only readable by root). As root, pull the line from the shadow file for the given user like so:
cat /etc/shadow | grep username
You will see something like this:
username:$1$TrOIigLp$PUHL00kS5UY3CMVaiC0/g0:15020:0:99999:7:::
After the username there is $1. This indicates that it is an MD5 hash. After that there is another $, then (in this case) TrOIigLp followed by another $. TrOIigLp is the salt. After that is the hashed password, which was hashed using the salt - in this case PUHL00kS5UY3CMVaiC0/g0.
Now, you can use openssl to hash the given password using the same salt, like so:
openssl passwd -1 -salt TrOIigLp
Enter the given password when prompted, the openssl command should compute the MD5 hash using the salt provided, and it should be exactly the same as the above from the shadow file. The -1 in the above command is for MD5 hashing.
If you are concerned about security (which you should be), the accepted answer represents a security risk by leaving the plaintext password in the ~/.bash_history
file. With this in mind, it would be better to try logging in, or perhaps removing this entry from the ~/.bash_history
.