-
Notifications
You must be signed in to change notification settings - Fork 5
/
inject.c
73 lines (61 loc) · 2.42 KB
/
inject.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <stdio.h>
#include <dlfcn.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <unistd.h>
//Set this to 0 if you don't want to see log messages
const int PRINT_INFO = 1;
int hookReplacementFunction() {
printf("Calling replacement function!\n");
return 3;
}
//Print the first 16 bytes after the given address
static void printBytes(int64_t *address) {
int i;
for (i = 0; i < 4; i++) {
printf("*(address+%d):\t%08x\n", i * 4, htonl((int)*(address+i)));
}
}
__attribute__((constructor))
static void ctor(void) {
if (PRINT_INFO)
printf("Injection dylib constructor called.\n");
//"If filename is NULL, then the returned handle is for the main program."
void *mainProgramHandle = dlopen(NULL, RTLD_NOW);
//Get a pointer to the original function using dlsym
int64_t *origFunc = dlsym(mainProgramHandle , "hookTargetFunction");
if (PRINT_INFO)
printf("Original function address: 0x%llx\n", (int64_t)origFunc);
//Get a pointer to the replacement function
int64_t *newFunc = (int64_t*)&hookReplacementFunction;
if (PRINT_INFO)
printf("Replacement function address: 0x%llx\n", (int64_t)newFunc);
//Calculate the relative offset needed for the jump instruction
//Since relative jumps are calculated from the address of the next instruction,
// 5 bytes must be added to the original address (jump instruction is 5 bytes)
int32_t offset = (int64_t)newFunc - ((int64_t)origFunc + 5 * sizeof(char));
if (PRINT_INFO)
printf("Offset: 0x%x\n", offset);
//Make the memory containing the original funcion writable
//Code from http://stackoverflow.com/questions/20381812/mprotect-always-returns-invalid-arguments
size_t pageSize = sysconf(_SC_PAGESIZE);
uintptr_t start = (uintptr_t)origFunc;
uintptr_t end = start + 1;
uintptr_t pageStart = start & -pageSize;
mprotect((void *)pageStart, end - pageStart, PROT_READ | PROT_WRITE | PROT_EXEC);
if (PRINT_INFO) {
printf("Before replacement: \n");
printBytes(origFunc);
}
//Set the first instruction of the original function to be a jump
// to the replacement function.
//E9 is the x86 opcode for an unconditional relative jump
int64_t instruction = 0xe9 | offset << 8;
*origFunc = instruction;
if (PRINT_INFO) {
printf("After replacement: \n");
printBytes(origFunc);
}
}