Linux – Preventing malware from sniffing the sudo password

linuxmalwareSecuritysudo

I often hear people citing sudo as one of the main barriers to malware infecting a Linux computer.

The most commen argument seems to go along the lines of: Root privileges are required to modify system configuration, and a password is required to gain root privileges, so malware can't modify system configuration without prompting for a password.

But it seems to me that by default on most systems, once malware has infected an admin account, privilege escalation is trivial — the malware just has to wait for the user to run sudo.

What methods exist for malware to gain root privileges when the user runs sudo, and how can we protect against them?

Edit: I'm specifically interested in protecting against a compromised admin account; that is to say, an account which has full root privileges with sudo (e.g. the user's account on a typical desktop system).

Best Answer

Once a piece of malware has gained access to a user's account, it can:

1. Create a bash alias (in the current shell, and in ~/.bashrc) to a command which fakes the [sudo] password for $USER: prompt, and steals the user's password.

alias sudo='echo -n "[sudo] password for $USER: " && \
            read -r password && \
            echo "$password" >/tmp/sudo-password'

2. Similarly, it can place an executable named sudo in ~/.bin, and modify the PATH variable to achieve the same effect: PATH="$HOME/.bin:$PATH"

3. Catch key presses through the X server, watch for the word sudo, then try the text between the next two Enter key presses as the password.

4. A similar thing can be done in any environment (the console, Wayland, X) using e.g. $LD_PRELOAD.

5. If malware infects a shell that uses sudo, and sudo caches credentials, the malware can continouosly check if it is possible to sudo without a password:

while : ; do
    echo | sudo -S echo "test" &>/dev/null && break
    sleep 10
done
sudo echo "We now have root access"


Prevention:

1 & 2. Use \/bin/sudo. The \ ignores aliases, and /bin/… ignores $PATH. Alternatively, add an alias such as: ssudo="\/bin/sudo", and always use ssudo instead of sudo. It seems unlikely that a virus would be clever enough to remap this alias.

3. Avoid typing your password when using X11. Instead, use a virtual console, or Weston.

5. Set timestamp_timeout=0 in /etc/sudoers.


The only way to completely eliminate the chance of the sudo password being sniffed, seems to be to avoid it altogether. Instead, login as root to a virtual console.

According to Alexander Peslyak: "the only safe use for su [and sudo] is to switch from a more privileged account to a less privileged one…"


On a side note, sudo does have some countermeasures:

  • sudo reads from tty instead of stdin, so alias sudo='tee -a /tmp/sudo-password | sudo' breaks sudo (but does capture the password).
Related Question