/* Program with a race condition for you to exploit.
 *
 * Save as "race-2.c" and compile with "gcc -O -Wall -o race-2 race-2.c".
 * Become root, then do "chown root race-2; chmod 4755 race-2".
 *
 * Happy cracking!
 *
 * Stephan Neuhaus
 */
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, const char* argv[]) {
  if (argc == 1) {
    fprintf(stderr, "usage: %s file\n", argv[0]);
    return 1;
  } else if (access(argv[1], R_OK) == 0) {
    int fd = open(argv[1], O_RDONLY); /* Can't fail, we checked */
    unsigned char* buf = malloc(1024);

    if (buf != 0) {
      ssize_t bytes_read = read(fd, buf, 1024);
      while (bytes_read > 0) {
	write(1, buf, bytes_read);
	bytes_read = read(fd, buf, 1024);
      }
      return 0;
    } else {
      fprintf(stderr, "%s: can't malloc\n", argv[0]);
      perror(argv[0]);
      return 1;
    }
  } else {
    fprintf(stderr, "%s: you can't access \"%s\"\n", argv[0], argv[1]);
    perror(argv[0]);
    return 1;
  }
}

