C: escalate privileges in Linux by backing this program

1k views Asked by At

What is a vulnerability of this program?

I am currently stuck on a hacking exercise and have no idea what to do!

What do you think 'path' means? Because I think it's important.

#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);
  strcat(path, "/script.sh");

  strcpy(buf, "#!/bin/bash\necho Hello.\ndate\nrm \"$0\"\n");

  umask(0);
  if ((fd = open(path, O_CREAT | O_EXCL | O_WRONLY, 02760)) < 0) {
        perror("open");
        return 1;
  }
  write(fd, buf, strlen(buf));  
  close(fd);

  printf("please wait for us to run your script");  
  fflush(stdout);
  for (i = 0; i < 5; i++) {
        printf(".");
        fflush(stdout);
        sleep(1);
  }
  printf(" starting script\n");

  execl("/bin/sh", "/bin/sh", path, (char *) 0); 
  perror("execl");
  return 0;
}
1

There are 1 answers

6
tofro On

Well.

The program writes a script that it later executes with the permissions of the user.

The umask (0) system call actually makes that file world-writeable (implicitely - the open call makes it group-writable - Thanks to Daniel Jour for pointing this out-, but if the first command that anyone from your group would inject into that file would be a chmod, it could be escalated).

As pointed out in the comments, anyone from your group would be able to inject whatever he wants executed with the user's permissions and on the user's behalf by simply writing all the commands to that named file while the program is so nice and waits five seconds for him to do so.

And a short comment on "do not help people hacking" - comments: What the OP is doing is trying to learn about possible vulnerabilities in programs, and we're still on a pretty basic level here. Any programmer should be grateful if he is made aware of such possible pitfalls in his code. Trying to keep such stuff under the hood simply helps hackers and doesn't make anything more secure.