Sunday, 2 August 2015

It's time to create a bash script that will take inputs - Username and Password, from the user and validate if the username-password combination is correct. There will be two essential steps involved in this script- check if username is valid and in case username is valid, check if password associated with that username is valid.

Let's start scripting!

1. Check if username is valid

This, surely, is the easier part of the script. Validating a user is very straight-forward, as you can use id command with option -u or read /etc/passwd (using 'grep' command) file to do so (Read about /etc/passwd file format here). If the exit status is "0", then it's a valid user, else it's not. For those who are new to bash scripting- Exit status can be checked using echo $?.

2. Check if Password is valid

Now, let's suppose that, the username is valid and next step will be verifying the password. If you had read our article on /etc/shadow file format, you would have understood what I will be explaining here.

This file stores the passwords in encrypted format, for every user, on a separate line. Besides the hashed passwords, it stores other details also, from which we need to extract the password for comparison. /etc/shadow stores these details delimited with a colon (:) as below:

1. Hash Algorithm: This field denotes the hashing algorithm used to create the hashed password. The digit 6 describes that, SHA-512 algorithm is used, in this case. Some more of them are enlisted below:

2. Salt Value: Salt values are used to make the hash value stronger. These are the random type of data that is used to combine with the original password and then the hashed version of that is used as the encrypted password.3. Password: This field stores the hashed version of the combination of original password and salt value.

Considering that user has provided the password, say mandar, we will try to create hashed value using the password entered by the user, the salt value (6) and the hashing algorithm (SHA-512) as below: