Non-root user getting root access after running “sudo vi /etc/hosts”

editorsSecuritysudo

On a linux machine, a non-root user open a file,

$ sudo vi /etc/hosts

and quit saying :sh

to get root access.

1) With above, How a non-root user becomes a root user?

2) Why Linux allow such hacking approach to breach security?

Best Answer

The non-root user became root as soon as they successfully ran sudo (given the assumed root target user); they started running vi as root. When you ask vi for a shell, it dutifully runs a shell, as the current user -- root! I should clarify that you should not "quit" vi with the :sh command, as that's asking for a shell. Quit with :q instead.

Linux allows such functionality because that's specifically what sudo is intended to do! Perhaps you've seen the lecture that sudo gives:

We trust you have received the usual lecture from the local System Administrator. It usually boils down to these three things:

#1) Respect the privacy of others.

#2) Think before you type.

#3) With great power comes great responsibility.

sudo offers a limited "speed bump" to this when it comes to granting "ALL" access, in the form of the ! negation operator, often demonstrated as:

jill        SERVERS = /usr/bin/, !SU, !SHELLS

where jill is granted permission to run programs from /usr/bin, but not anything listed in the SU or SHELLS aliases.

The sudoers man page has a whole "Security Notes" section when it comes to granting large-scale access via sudo and then trying to restrict it.

Limitations of the ‘!’ operator

It is generally not effective to “subtract” commands from ALL using the ‘!’ operator. A user can trivially circumvent this by copying the desired command to a different name and then executing that.

and

In general, if a user has sudo ALL there is nothing to prevent them from creating their own program that gives them a root shell (or making their own copy of a shell) regardless of any ‘!’ elements in the user specification.

and more pertinently:

Preventing shell escapes

Once sudo executes a program, that program is free to do whatever it pleases, including run other programs. This can be a security issue since it is not uncommon for a program to allow shell escapes, which lets a user bypass sudo's access control and logging. Common programs that permit shell escapes include shells (obviously), editors, paginators, mail and terminal programs

Related Question