Verify user and password against a file created by htpasswd
Asked Answered
G

2

39

Is there a way, from the command line, to check a user and password against a file created by htpasswd, the tool provided by Apache?

Goldagoldarina answered 10/6, 2014 at 17:12 Comment(2)
Hmm. There's a htpasswd tag for questions about the htpasswd program, but the system won't let it coexist with the .htpasswd tag...Depopulate
You still haven't accepted the answer. Shame on you.Almeida
P
52

You can use the htpasswd tool for this.

# create htpasswd_file with user:password
$ htpasswd -cb htpasswd_file user password
Adding password for user user

# verify password for user
$ htpasswd -vb htpasswd_file user wrongpassword
password verification failed

$ htpasswd -vb htpasswd_file user password
Password for user user correct.

Exit status is 0 for success, 3 for failure.

Profane answered 19/10, 2016 at 12:31 Comment(1)
It's generally more secure to omit -b and type the password into a prompt. Using the above command, the plaintext password may end up in your .bash_history.Leta
E
42

Assuming you create the password using the following command and "myPassword" as the password

htpasswd -c /usr/local/apache/passwd/passwords username

This will create a file that looks like

username:$apr1$sr15veBe$cwxJZHTVLHBkZKUoTHV.k.

The $apr1$ is the hashing method, sr15veBe is the salt, and the last string is the hashed password. You can validate it using openssl using

openssl passwd -apr1 -salt sr15veBe myPassword

which will output

$apr1$sr15veBe$cwxJZHTVLHBkZKUoTHV.k.

A pipeline which you could use would be:

username="something"
htpasswd -c /usr/local/apache/passwd/passwords $username
****Enter password:****

salt=$($(cat passwords | cut -d$ -f3)
password=$(openssl passwd -apr1 -salt $salt)
****Enter password:****

grep -q $username:$password passwords 
if [ $? -eq 0 ]
 then echo "password is valid"
else 
 echo "password is invalid"
fi

You may need to change your openssl command, as Apache's htpasswd command crypts slightly differently on each system.

For more information, visit Apache's page on the topic at http://httpd.apache.org/docs/2.2/misc/password_encryptions.html

Eudemonics answered 10/6, 2014 at 17:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.