Why can I start a root shell with sudo even with a '! ' in its shadow entry?
$cat /etc/passwd |grep -i root
root:x:0:0:root:/root:/bin/bash
$sudo cat /etc/shadow |grep -i root
root:!:17179:0:99999:7:::
In the second field of shadow file, !
means root user cannot login but why can I login to root user by sudo su
?
Why can't I login to root user by su root
or su -
?
Solution 1:
An !
in the shadow
entry's encrypted password field means that no password can authenticate against it. From man shadow
:
If the password field contains some string that is not a valid
result of crypt(3), for instance ! or *, the user will not be able
to use a unix password to log in (but the user may log in the
system by other means).
As the manual says, this does not mean that you can't login as root. It just means that you can't login as root using a password for the root account. (You can login as root via SSH using SSH keys, for example, if you had configured it earlier, even if the account is locked.)
sudo
normally authenticates with your password, not root's. This can be changed by setting one of targetpw
, rootpw
or runaspw
in sudoers
. If you set one these options, and try to use a password when the password is locked, that will fail.
Solution 2:
Now let's look at the commands accordingly:
-
sudo su
:-
sudo
runs the commandsu
(substitute user) with root privileges so even if the/etc/shadow
says or hasroot:!:17179:0:99999:7:::
it will still run commands with root privileges.
-
-
su -
orsu root
:- This actually switches to the root user which from the
/etc/shadow
file can not log in so using these commands will not work. If you want them to work then the root account must be unlocked by giving it a password.
- This actually switches to the root user which from the
Summary:
su -
0r su root
switches to user root, does not exist so it can't happen, but sudo su
runs switch command with root
privileges, so in this case it will go if you are in the sudo
group. You're not actually logging in as root in this case, just acting as root so it will go.
Source: What is the difference between 'su -' and 'su root'?