/* 
 * This is just a basic vulnerable program to demonstrate 
 * how to overwrite/modify jmp_buf's to modify the course of 
 * execution.
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <setjmp.h>

#define ERROR -1
#define BUFSIZE 16

static char buf[BUFSIZE];
jmp_buf jmpbuf;

u_long getesp()
{
   __asm__("movl %esp,%eax"); /* the return value goes in %eax */
}

int main(int argc, char **argv)
{
   if (argc <= 1)
   {
      fprintf(stderr, "Usage: %s <string1> <string2>\n");
      exit(ERROR);
   }

   printf("[vulprog] argv[2] = %p\n", argv[2]);
   printf("[vulprog] sp = 0x%lx\n\n", getesp());

   if (setjmp(jmpbuf)) /* if > 0, we got here from longjmp() */
   {
      fprintf(stderr, "error: exploit didn't work\n");
      exit(ERROR);
   }

   printf("before:\n");
   printf("bx = 0x%lx, si = 0x%lx, di = 0x%lx\n",
          jmpbuf->__bx, jmpbuf->__si, jmpbuf->__di);

   printf("bp = %p, sp = %p, pc = %p\n\n", 
          jmpbuf->__bp, jmpbuf->__sp, jmpbuf->__pc);

   strncpy(buf, argv[1], strlen(argv[1])); /* actual copy here */

   printf("after:\n");
   printf("bx = 0x%lx, si = 0x%lx, di = 0x%lx\n",
          jmpbuf->__bx, jmpbuf->__si, jmpbuf->__di);

   printf("bp = %p, sp = %p, pc = %p\n\n", 
          jmpbuf->__bp, jmpbuf->__sp, jmpbuf->__pc);

   longjmp(jmpbuf, 1);
   return 0;
}
