Tuesday, 30 December 2008

Recovering a box without the root password or a user account

How to rescue a Linux box where you've lost the root password, and you don't have an account. (This is equivalent to saying, how to take control of a Unix system)

We'll do this in 4 stages:

1) prepare a temporary account to use to log into the system
2) boot the target system using an alternative boot media
3) remove the root password, and set up the temporary account
4) boot the system normally, and log in via the temporary account, then switch to the root user, and assume control of the system

1) prepare a temporary account to use to log into the account

On a separate Unix system, add a temporary user via your preferred method, and give it a password. Now extract the hashed password from /etc/shadow on that system. Assuming that you have called the account 'temp', this command will extract it in one line:

grep ^temp: /etc/shadow|awk -F: '{print $2}'

It'll look something horribly unfriendly like $1$ndbiqpq5$4DVeD3KsBmlHZv8jre3S31 - make a careful note of it. There's no escaping this bit.

2) Set up your boot media - be it a CD, a DVD, a PXE kernel, a bootable data stick - whatever you want to use, insert it as appropriate in the machine and turn it on. So long as you can get a terminal session, it'll do. The Redhat install CDs even mount the system for you to /mnt/sysimage - but otherwise do this manually.

3) On the target system, find and edit the /etc/passwd file, you're looking for the root entry, which should be right at the top. It'll look something like this:

root:x:0:0:root:/root:/bin/ksh

Delete out the 'x' in the second column, so it now reads:

root::0:0:root:/root:/bin/ksh

You'll also need to add in a line for a temporary user:

temp:x:9999:10:Temporary - remove after use!:/home/temp:/bin/ksh

Now find and edit the /etc/shadow file. Again, you'll need to edit the root entry, which will look something like:

root:$1$ndbiqpq5$4DVeD3KsBmlHZv8jre3S31:13244:0:99999:7:::

Replace this completely with the line:

root::::

Also add a line for the temporary user such as:

temp:$1$ndbiqpq5$4DVeD3KsBmlHZv8jre3S31:14243:0:99999:7:::

Be sure to replace the second column with the password hash that you know, rather than the example one I use here.

4) Boot the system normally. Log in using the temporary account and password, and acquire a terminal session. Switch to the root user (su -) - you should not be prompted for a password and should simply become the root user. With this power, you should now edit the /etc/passwd file once more, and add back the x you removed earlier, so that:

root::0:0:root:/root:/bin/ksh

becomes:

root:x:0:0:root:/root:/bin/ksh

Now set a new root password - 'passwd' or 'passwd root', and remove the temporary account 'userdel temp'

You now have root access to the system, and can add new accounts as required.

No comments: