Playing a CTF, I am trying to gain access to level 3 (you have to gain access sequentially from level 1 to level 2 and so on...), and in the level 2 directory there's this source code 2.c and along with it an executable called "2". If you look at the code, you can see the vulnerability that when I run script 2 in the background, I am be able to quickly modify (within the 5s window) the script.sh file in home directory by giving it any command I want it to run. So far I ran the commands in this similar manner echo -e "#!/bin/bash\ncat /var/challenge/level3/devel\n" >> script.sh

With these types of commands I was even able to copy all of its contents and move it to my home directory, and yet no matter what I do, I can't get access to level 3 directory. What am I doing wrong? I tried to do chmod and chown of that file but it still says not permitted.

#include <fcntl.h>
#include <limits.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>

int main(int argc, char * argv[]) {
  char buf[1024], path[PATH_MAX + 1];
  int fd, i;

  strcpy(path, getpwuid(getuid()) -> pw_dir); //determine user's home directory
  strcat(path, "/script.sh");
  strcpy(buf, "#!/bin/bash\necho Hello.\ndate\nrm \"$0\"\n");
  umask(0); //set file mode creation

  if ((fd = open(path, O_CREAT | O_EXCL | O_WRONLY, 02760)) < 0) { // 276 = --w-rwxrw-
    return 1;

  write(fd, buf, strlen(buf));
  printf("please wait for us to run your script");
  for (i = 0; i < 5; i++) {

  printf(" starting script\n");
  execl("/bin/sh", "/bin/sh", path, (char * ) 0);
  return 0;
  • I'm not clear about why this isn't working for you but I can say the comment about the file permissions is incorrect.
    – kenlukas
    Commented Jan 23, 2023 at 12:43
  • Am I correct that the executable for "2" is setuid?
    – Brian
    Commented Jan 23, 2023 at 22:14

1 Answer 1


I found the answer.

It looks like the vulnerability in this code is the use of strcpy() and strcat() function which are vulnerable to buffer overflow attack. Also, the code is creating a file in user's home directory with hardcoded file name script.sh and with full permissions which could be a security risk if the file contain malicious commands.

In the end, I could execute the command and elevate my privileges.

While you run the file ./2 & in background, use another shell to modify script.sh file

Run l33t in the modified script

echo -e "#!/bin/bash\nl33t" >> script.sh

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .