Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Header files
- #include <stdio.h>
- #include <sys/mman.h>
- #include <unistd.h>
- #include <udis86.h>
- #include "global.h" // Contains typedefines for byte, ulong, ushort etc...
- #include <cstring>
- bool ProtectMemory(void * addr, int flags)
- {
- // Constant holding the page size value
- const size_t pageSize = sysconf(_SC_PAGE_SIZE);
- // Calculate relative page offset
- size_t temp = (size_t) addr;
- temp -= temp % pageSize;
- // Update address
- addr = (void*) temp;
- // Update memory area protection
- return !mprotect(addr, pageSize, flags);
- }
- size_t SizeRequired(void * target, int len)
- {
- // Temporary variable
- size_t required = 0;
- ud_t disas;
- ud_init(&disas);
- // Setup the disassembly buffer
- ud_set_input_buffer(&disas, (byte*) target, 14/*20*/);
- ud_set_mode(&disas, 32);
- // Loop until there is enough memory for a jump
- while((required += ud_disassemble(&disas)) < len);
- // Return the amount
- return required;
- }
- const byte jmpOp[] = { 0xE9, 0x00, 0x00, 0x00, 0x00 };
- int Test(void)
- {
- printf("This is testing\n");
- return 5;
- }
- int MyTest(void)
- {
- printf("This is ******\n");
- return 9;
- }
- typedef int (*TestType)(void);
- int main(int argc, char * argv[])
- {
- // Fetch addresses
- byte * test = (byte*) &Test;
- byte * myTest = (byte*) &MyTest;
- // Call original
- Test();
- size_t req = SizeRequired((void*) test, sizeof(jmpOp));
- // Update memory access for 'test' function
- ProtectMemory((void*) test, PROT_EXEC | PROT_WRITE | PROT_READ);
- // Allocate memory for the trampoline
- byte * trampoline = new byte[sizeof(jmpOp) + req];
- // Do copy operations
- memcpy(trampoline, test, req);
- memcpy(test, jmpOp, sizeof(jmpOp));
- // Setup trampoline
- trampoline += req;
- *trampoline = 0xE9;
- // I think this address is incorrect, how should I calculate it? With the current
- // status (commented 'sizeof(jmpOp)') the compiler complains about "Illegal Instruction".
- // If I uncomment it, and use either + or -, a segmentation fault will occur...
- *(uint*)(trampoline + 1) = ((uint) test - (uint) trampoline) + sizeof(jmpOp) - req;
- trampoline -= req;
- // Make the trampoline executable (and read/write)
- ProtectMemory((void*) trampoline, PROT_EXEC | PROT_WRITE | PROT_READ);
- // Setup detour
- *(uint*)(test + 1) = ((uint) myTest - (uint) test) - sizeof(jmpOp);
- // Call 'detoured' func
- Test();
- // Call trampoline (crashes)
- ((TestType) trampoline)();
- Test();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement