-
Notifications
You must be signed in to change notification settings - Fork 3
/
fn_override.c
70 lines (66 loc) · 1.54 KB
/
fn_override.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
#include <stdio.h>
#include <stdlib.h>
#ifndef _WIN32
#include <sys/mman.h>
#else
#include <windows.h>
#endif
#include <sys/types.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
int libmonkey_override_by_ptr(void *orig, const void *target) {
#ifdef _LP64
#define JMP_SIZE 12
#define PTR_TYPE uint64_t
#define DST_TYPE PTR_TYPE
#define DST_ARG (PTR_TYPE)target
char op[JMP_SIZE];
/*two-byte movq*/
op[0] = 0x48;
op[1] = 0xb8;
/*two byte jmpq*/
op[10] = 0xff;
op[11] = 0xe0;
void *addrptr = op+2;
#else
#define JMP_SIZE 5
#define PTR_TYPE uint32_t
#define DST_TYPE int32_t
#define DST_ARG (DST_TYPE)(target-orig-JMP_SIZE)
char op[JMP_SIZE];
op[0] = 0xe9; /*jmp*/
void *addrptr = op+1;
#endif
#define FN_OFFSET orig - (((PTR_TYPE)orig)%4096)
#define MPROTECT_SIZE (((PTR_TYPE)orig+4095+JMP_SIZE)/4096)*4096 - \
((PTR_TYPE)orig-((PTR_TYPE)orig%4096))
#ifdef _WIN32
DWORD wtf;
if(!VirtualProtect(FN_OFFSET, MPROTECT_SIZE, PAGE_EXECUTE_READWRITE, &wtf))
{
DWORD dw = GetLastError();
LPVOID buf;
printf("got error\n");
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|
FORMAT_MESSAGE_FROM_SYSTEM|
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR)&buf,
0, NULL);
printf("VirtualProtect() failed!\n");
printf(buf);
return 0;
}
#else
if(mprotect(FN_OFFSET, MPROTECT_SIZE,PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
printf("mprotect failed!: %s\n", strerror(errno));
return 0;
}
#endif
*(DST_TYPE*)addrptr = DST_ARG;
memcpy(orig, op, JMP_SIZE);
return 1;
}