/*
 * Sample code for Local Exploitation
 *
 * "I was feeling a bit creative today.."
 *
 * This might look a bit scary for the newbies, but exploiting this
 * should be relatively easy and very very reliable exploitation
 * is possible even ASLR
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

struct functions {
   void (*hi)();
   void (*bye)();
};

void func_hi()
{
   printf("Hello world\n");
}

void func_bye()
{
   printf("Bye bye world\n");
}

int main(int argc, char **argv)
{
   char buf[512];
   char *ptr = NULL;
   int count;
   int flag;
   struct functions *f = NULL;
   char *ebuf = malloc(128);
   assert(ebuf != NULL);

   while(fgets(buf, sizeof(buf) - 1, stdin)) {
      count = *((int*)buf + 10);
      flag = *((int*)buf + 20);
      
      count &= 0xFF;
      flag &= 0xFF;

      if((flag & 0xFF) == 0x10) {
         printf("The Big Bang created the earth\n");
         f = (struct functions*) malloc(sizeof(*f));
         assert(f != NULL);
         f->hi = (void*) func_hi;
         f->bye = (void*) func_bye;
      }

      if((flag & 0xFF) == 0x20) {
         printf("Theory of hyperspace predicts life even after the end\n");
         ptr = (char*) malloc(count);
         assert(ptr != NULL);
         fgets(ptr, count - 1, stdin);
      }

      if((flag & 0xFF) == 0x50) {
         printf("Cheong w000\n");
         if(f) {
            f->hi();
            f->bye();

            free(f);
            f = NULL;
         }

         if(ptr) {
            free(ptr);
            ptr = NULL;
         }
      }

      if((flag & 0xFF) == 0x30) {
         printf("The Garden of Eden\n");
         if(ptr)
            strcpy(ebuf, ptr);
      }
   }
}

