Exploiting /etc/passwd and Creating a Hash
Exploiting a Writable /etc/passwd
While enumerating users, we found that user7 is a member of the root group with gid 0. We already know from the LinEnum scan that the /etc/passwd file is writable for the user. So user7 can edit /etc/passwd.
Understanding /etc/passwd
The /etc/passwd file stores essential information required during login: user account information. It is a plain text file listing the system's accounts, giving each one useful information like user ID, group ID, home directory, and shell.
The /etc/passwd file should have general read permission, as many command utilities use it to map user IDs to user names. Write access, however, must be limited to the superuser/root account. When it isn't, or a user has erroneously been added to a write-allowed group, we have a vulnerability that allows creating a root user we can access.
Understanding the /etc/passwd Format
The /etc/passwd file contains one entry per line for each user account on the system. All fields are separated by a colon : symbol, for a total of seven fields. A typical entry looks like:
test:x:0:0:root:/root:/bin/bash
[as divided by colon (:)]
Username: used when the user logs in. It should be between 1 and 32 characters.Password: an x character indicates the encrypted password is stored in /etc/shadow. You use the passwd command to compute the hash of a password or to store/update it in /etc/shadow; here the password hash is stored as an "x".User ID (UID): each user must be assigned a UID. UID 0 is reserved for root, UIDs 1-99 are reserved for other predefined accounts, and UID 100-999 are reserved by the system for administrative and system accounts/groups.Group ID (GID): the primary group ID (stored in the /etc/group file).User ID Info: the comment field. It lets you add extra information about the user such as full name or phone number. Used by the finger command.Home directory: the absolute path to the directory the user lands in at login. If this directory does not exist, the user's directory becomes /.Command/shell: the absolute path of a command or shell (/bin/bash). Typically this is a shell, but it does not have to be.
How to Exploit a Writable /etc/passwd
It's simple: with a writable /etc/passwd file, we can write a new line entry following the format above and create a new user. We add a password hash of our choice and set the UID, GID and shell to root, letting us log in as our own root user.
Create a password-compliant hash to add to /etc/passwd with openssl:
openssl passwd -1 -salt salthere passwordhere
To make this compatible with an /etc/passwd file, format the hash appropriately:
new:$1$new$p7ptkEKU1HnaHpRtzNizS1:0:0:root:/root:/bin/bash
NOTE: NOPASSWD plus a listed binary means we can run it as root without entering a password.
- In this scenario we would open vi as sudo:
sudo vi. - Then open a shell:
:!shand<enter>. - Boom, root shell.