title: How to bypass the check of setuid
body: <p>I am now taking a security class. And the professor asked us to exploit a program to gain higher privilege.
  This is the code</p>
  
  <pre><code>    #include &lt;stdio.h&gt;
      #include &lt;stdlib.h&gt;
      #include &lt;unistd.h&gt;
      #include &lt;string.h&gt;
      #include &lt;sys/types.h&gt;
      #include &lt;sys/stat.h&gt;
  
  
      #define BUFSIZE 512
  
      int main(int argc, char *argv[]) {
      struct stat buf;
      char cmd[BUFSIZE];
      FILE *f = NULL;
  
      if (argv[1] == NULL) {
      fprintf(stderr, "Please provide an argument\n");
      exit(1);
      }
  
      if (stat(argv[1], &amp;buf)) {
      fprintf(stderr, "Can't stat the file\n");
      exit(1);
      }
  
      if (buf.st_gid != getegid()) {
      fprintf(stderr, "The file must be owned by group %d\n", getegid());
      exit(1);
      }
  
      sleep(1);
  
      if ((f = fopen(argv[1], "r")) == NULL) {
      fprintf(stderr, "Cannot open command file\n");
      return 1;
      }
  
      while (fgets(cmd, BUFSIZE, f)) {
      if ((cmd[0] == '\n') || (cmd[0] == 0x7f)) {
      fprintf(stderr, "Found empty line, quitting!\n");
      return 2;
      }
      system(cmd);
      }
  
      printf("Done!\n");
      return 0;
      }
  </code></pre>
  
  <p>The particular situation is:
  There is a binary code for this program for us to run. And the SUID of the binary code is set to higher level(here I assume level2). However, buf.st_gid != getegid() will always check if the file we specified is owned by root. Most important thing is, I only have level1 privilege. There is only one file owned by level2 I can use which is provided by our professor. And I certainly tried to pass in that filename. But nothing happens. I don't know if there is anyway I can exploit this program.(To execute some commands during runtime using the privilege of level2)</p>