Monday, March 21, 2011

password reset from shadow file in ubuntu 10.10

Recently I was trying to write a script for changing password automatically for a user.I required something else for this but I found one similar script while searching over Internet.While I was experimenting with this on my ubuntu 10.10 system, I did a terrible mistake.At the place of username, I put my main account username.Not only this,I used "pwgen" program to generate random password which was there in the script and I blindly used it.

The script I used is below:-

touch pass.txt
chmod 600 pass.txt

# generate a nice secure password and put it in a file
pwgen > pass.txt

# get the password hash
ph=$(makepasswd --clearfrom=pass.txt --crypt-md5 |awk '{print $2}')

# Set the password
usermod -p $ph "username"

Now, first time I used it using sudo, It asked for password.Now this script randomly generated a new passowrd and set for my account.Now, a new password was hashed in /etc/shadow file which I didn't know.Next time, when I used it again,it asked for password which was changed randomly.So,I could not give correct password.

Now, I thought how would I login after next reboot.I asked someone who told me to use a live cd of ubuntu to change shadow file.In shadow file, password is stored encrypted corresponding to each username.Now, I was preparing for a back up.Still, I wasn't sure it will work.

When I rebooted,something clicked in my mind.I booted in recovery mode.Then using root shell, I opened /etc/shadow file.Usually it opens in read-only mode.But since I was root that time, I removed the hash of my username.I removed everything that was there between first 2 colon(:). I did it only for my username and root.Hence, password was omitted.Now I reboot again and reset the password using passwd command and it didn't ask for current password.I didn't know that we could reset our password in recovery mode.

I knew that this similar method worked in ubuntu 8.04. But I thought they removed this as a bug.Now it worked for me.I can't decide if it is a good or bad thing.Since I changed my password in emergency,It is cool. But someone else can access my account by resetting my password.