Tip of the Trade: Strong Passwords Made Easy

Tip of the Trade: Strong Passwords Made Easy

August 6, 2007

Discuss this article in the ServerWatch discussion forum

Adding new users to a Linux system is pretty easy, but you can still automate and save a few steps by using a simple script that incorporates standard commands. This simple script uses pwgen to generate a random 8-character password. Then it uses openssl to create an MD5 hash, which the useradd command then uses to enter the new hashed password into /etc/shadow. You don't need to use the passwd command.

PASSWORD=`pwgen -cn -1`
PW_HASH=`openssl passwd -1 ${PASSWORD}`
useradd  -p ${PW_HASH} ${USER}
echo Your new user account has been created with the username \"${USER}\", and the password \"${PASSWORD}\".

Give the script a catchy name like usergen, and be sure to make it executable. The only option, and it is required, is to supply the username:

# ./usergen  fcracker
Your new user account has been created with the username "fcracker", 
		and the password "osh9ExiY".

You can easily tweak it by using the standard options for the individual commands, such as adding your users to extra groups, or assigning a non-default login shell. There are some useradd differences in the various Linux distributions. For example, on Debian, the default is to not create a home directory. On Fedora, a home directory is created by default. So Debian users must use useradd -m to create a properly populated home directory. Adding users to extra groups is the same on both Fedora and Debian: useradd -G group1,group2,group3. The groups must already exist.

Want to know what the other openssl passwd options are? See man 1ssl passwd, or make a mistake on purpose:

$ openssl passwd -fffooo
Usage: passwd [options] [passwords]
where options are
-crypt             standard Unix password algorithm (default)
-1                 MD5-based password algorithm

-apr1              MD5-based password algorithm, Apache variant

Notice that there is no automatic expiration on the password to force the user to create a new password at first login. This is because we went to the trouble of creating a strong password; that's the one the user retains.