aboutsummaryrefslogtreecommitdiffstats
path: root/ptrace-offset-finder.c
blob: d339c181fb2b7c584b876dcc67d54e819f8b230e (plain) (blame)
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
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/user.h>
#include <sys/ptrace.h>
#include <sys/reg.h>

int main(int argc, char *argv[])
{
	int fd[2];
	pipe2(fd, O_NONBLOCK);
	int child = fork();
	if (child) {
		close(fd[1]);
		char buf;
		for (;;) {
			wait(NULL);
			if (read(fd[0], &buf, 1) > 0)
				break;
			ptrace(PTRACE_SYSCALL, child, NULL, NULL);
		}
		
		struct user_regs_struct regs;
		for (;;) {
			ptrace(PTRACE_SINGLESTEP, child, NULL, NULL);
			wait(NULL);
			ptrace(PTRACE_GETREGS, child, NULL, &regs);
#if defined(__i386__)
#define instruction_pointer regs.eip
#define upper_bound 0xb0000000
#elif defined(__x86_64__)
#define instruction_pointer regs.rip
#define upper_bound 0x700000000000
#else
#error "That platform is not supported."
#endif
			if (instruction_pointer < upper_bound) {
				uint32_t instruction = ptrace(PTRACE_PEEKTEXT, child, instruction_pointer, NULL);
				int operator = instruction & 0xFF;
				if (operator == 0xe8 /* call */) {
					int32_t offset = ptrace(PTRACE_PEEKTEXT, child, instruction_pointer + 1, NULL) + 5;
					printf("0x%lx\n", instruction_pointer + offset);
					break;
				}
			}
		}
	} else {
		ptrace(PTRACE_TRACEME, 0, NULL, NULL);
		close(fd[0]);
		dup2(fd[1], 2);
		execl("/bin/su", "su", "not-a-valid-user", NULL);
	}
	return 0;
}