Pablo Fernandez
Pablo Fernandez

Reputation: 287730

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?

Upvotes: 42

Views: 34885

Answers (3)

Valery Bersenev
Valery Bersenev

Reputation: 21

use the utility to create a custom htpasswd database - example bash script:

#!/bin/bash
tpass="mypassword";
mlogin="mylogin";
pass_file="usersdb";
touch $pass_file|:>$pass_file;
htpasswd -p -b $pass_file $mlogin  $(openssl passwd -1 -noverify $tpass);
...

next, script forthen a ready-made script to check login and password for validity (bash):

#!/bin/bash
## input login pass
access=($*);
## file vpnpasswd( login:password) - apache2-utils 
vpnusers="usersdb";

if htpasswd -vb $vpnusers ${access[0]} ${access[1]}; then 
  echo "correct";
else 
  echo "false";
fi

The application of this pair of scripts can be multifunctional, openvpn (auth pam), web and others.

Upvotes: 0

Eren Güven
Eren Güven

Reputation: 2374

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.

Upvotes: 55

Jonathan Wheeler
Jonathan Wheeler

Reputation: 2699

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

Upvotes: 43

Related Questions