Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verify user and password against a file created by htpasswd

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?

like image 747
pupeno Avatar asked Jun 10 '14 17:06

pupeno


People also ask

How does htpasswd encryption work?

htpasswd encrypts passwords using either bcrypt, a version of MD5 modified for Apache, SHA1, or the system's crypt() routine.

How do I generate htpasswd password?

Use the htpasswd generator to create passwords for htpasswd files. Just enter username and password and an entry for a htpasswd file is generated. You can use the htaccces Authentication generator to create a htaccess file that will password protect your site or a directory.

Is htpasswd secure?

htpasswd are actually yielding a screen for your user name and password, it is secure. If the combination of the user name and password isn't valid, Apache will return a HTTP 403: Forbidden header, which means the request has never been passed to PHP.


2 Answers

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.

like image 140
Eren Güven Avatar answered Sep 22 '22 06:09

Eren Güven


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

like image 34
Jonathan Wheeler Avatar answered Sep 23 '22 06:09

Jonathan Wheeler