Guest User

test.c

a guest
Sep 18th, 2012
92
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <fcntl.h>
  3. #include <sys/mman.h>
  4. #include <sys/types.h>
  5. #include <unistd.h>
  6. #include <stdlib.h>
  7. #include <assert.h>
  8.  
  9. /* Shellcode testbed
  10.  *
  11.  * man mmap:
  12.  *  mmap()  creates a new mapping in the virtual address space of the call-
  13.  *          ing process.  The starting address for the new mapping is specified
  14.  *          in addr.  The length argument specifies the length of the mapping.
  15.  *
  16.  * */
  17. int
  18. main (int argc, char *argv[])
  19. {
  20.     void *p;
  21.     int fd;
  22.     off_t size;
  23.  
  24.     if (argc != 2)
  25.       {
  26.       printf ("Usage:\n\t%s shellcode.bin\n", argv[0]);
  27.       exit (-1);
  28.       }
  29.  
  30. //Open tha file
  31.     fd= open (argv[1], O_RDONLY);
  32.     assert ( fd != -1);
  33. //Read the size
  34.     size = lseek (fd, 0, SEEK_END);
  35.     lseek (fd, 0, SEEK_SET);
  36.     assert ( size != 0);
  37. //Allocates a virtual memory map RWX
  38.     p = mmap (NULL, size, PROT_EXEC | PROT_READ | PROT_WRITE,
  39.           MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
  40.     printf ("Memory@%p\n", p);
  41.  
  42. //Reads content of the "binary" file into mem
  43.     assert(size == read (fd, p, size));
  44.  
  45. //Close the file so the shellcode inherits only 0,1,2
  46.     close (fd);
  47.  
  48. //Call the first instruction in mem
  49.     printf ("Passing control to the shellcode...\n");
  50.     ((void (*)()) p) ();
  51.     printf ("The shellcode has returned to main!\n");
  52.     exit (-1);
  53. }
RAW Paste Data