Advertisement
Guest User

Untitled

a guest
Jul 8th, 2022
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.25 KB | None | 0 0
  1. #include <errno.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <limits.h>
  5. #ifndef PAGESIZE
  6.   #define PAGESIZE 4096
  7. #endif
  8.  
  9. #include <sys/mman.h>
  10.  
  11.  
  12. const unsigned char code[] = {
  13.     0x55,               // push   %rbp
  14.     0x48, 0x89, 0xe5,   // mov    %rsp,%rbp
  15.     0x89, 0x7d, 0xfc,   // mov    %edi,-0x4(%rbp)
  16.     0x89, 0x75, 0xf8,   // mov    %esi,-0x8(%rbp)
  17.     0x8b, 0x55, 0xfc,   // mov    -0x4(%rbp),%edx
  18.     0x8b, 0x45, 0xf8,   // mov    -0x8(%rbp),%eax
  19.     0x01, 0xd0,         // add    %edx,%eax
  20.     0x5d,               // pop    %rbp
  21.     0xc3                // ret
  22. };
  23.  
  24.  
  25. struct _foo {
  26.     unsigned char lpad[PAGESIZE - (2 << 6)];
  27.     unsigned char code[sizeof(code)];
  28.     unsigned char rpad[(2 << 6) - sizeof(code)];
  29. } __attribute__((packed));
  30.  
  31.  
  32. struct _foo foo;
  33.  
  34.  
  35. int main(void)
  36. {
  37.     memcpy(foo.code, code, sizeof(code));
  38.     size_t mask = PAGESIZE - 1;
  39.     unsigned char *foo_p = (unsigned char *)(((long) &foo + mask) & ~mask);
  40.     int (*f) (int, int) = (int (*) (int, int)) foo_p;
  41.     int x = 2;
  42.     int y = 2;
  43.  
  44.     if (mprotect(foo_p, sizeof(code), PROT_EXEC) < 0) {
  45.         printf("%s\n", strerror(errno));
  46.         return 1;
  47.     }
  48.  
  49.     int z = f(x, y);
  50.     printf("%d + %d = %d\n", x, y, z);
  51.     return 0;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement