Advertisement
01ttouch

Sample self-modifying code

Jul 12th, 2015
264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.80 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5. #include <sys/mman.h>
  6. #include <stdint.h>
  7.  
  8. /*
  9. f definition:
  10. 00000000004005e6 <f>:
  11.     4005e6:     55          push   %rbp
  12.     4005e7:     48 89 e5        mov    %rsp,%rbp
  13.     4005ea:     be 01 00 00 00      mov    $0x1,%esi
  14.                ^^^^^^^^^^^ this is what i change
  15. so it's f+5
  16. */
  17. uint32_t f() {
  18.     printf("%d\n", 1);
  19. }
  20.  
  21. int main() {
  22.     uint32_t *p;
  23.     /* I found that ready */
  24.     void *page = (void *) ((unsigned long) (&f) & ~(getpagesize() - 1));
  25.  
  26.     p = malloc(sizeof(uint32_t));
  27.  
  28.     /* mark the code section we are going to overwrite as writable. */
  29.     mprotect(page, getpagesize(), PROT_READ | PROT_WRITE | PROT_EXEC);
  30.  
  31.     while (*p < 100) {
  32.         f();
  33.         memcpy(p, (f+5), sizeof(uint32_t));
  34.         *p += 1;
  35.         memcpy((f+5), p, sizeof(uint32_t));
  36.     }
  37.  
  38.     return 0;
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement