Linux Bash Setuid – Setuid Bit Seems to Have No Effect on Bash

bashlinuxsetuid

I was experimenting a bit and noticed something strange: setting the setuid bit on a copy of bash located at /usr/bin/bash-test seemed to have no effect. When I ran an instance of bash-test, my home directory was not set to /root and when I ran the whoami command from bash-test, my username was not reported as being root, suggesting that bash-test was not running as root. However, if I set the setuid bit on whoami, I was reported as being root in any shell, as expected.

I tried setting the setuid bit on /usr/bin/bash as well and observed the same behavior.

Why is bash not running as root when I set the setuid bit on it? Could selinux have something to do with this?

Best Answer

The explanation is kind of annoying: bash itself is the reason. strace is our friend (must be SUID root itself for this to work):

getuid()                                = 1000
getgid()                                = 1001
geteuid()                               = 0
getegid()                               = 1001
setuid(1000)                            = 0
setgid(1001)                            = 0

bash detects that it has been started SUID root (UID!=EUID) and uses its root power to throw this power away, resetting EUID to UID. And later even FSUID, just to be sure...:

getuid()                                = 1000
setfsuid(1000)                          = 1000
getgid()                                = 1001
setfsgid(1001)                          = 1001

In the end: no chance. You have to start bash with UID root (i.e. sudo).

Edit 1

The man page says this:

If the shell is started with the effective user (group) id not equal to the real user (group) id, and the -p option is not supplied, no startup files are read, shell functions are not inherited from the environment, the SHELLOPTS, BASHOPTS, CDPATH, and GLOBIGNORE variables, if they appear in the environment, are ignored, and the effective user id is set to the real user id. If the -p option is supplied at invocation, the startup behavior is the same, but the effective user id is not reset.

But this does not work for me. -p isn't even mentioned among the startup options. I also tried --posix; didn't work either.

Related Question