Skip to content

Instantly share code, notes, and snippets.

@qti3e
Last active June 12, 2020 11:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qti3e/34e35c85156cbd611226117d08f46436 to your computer and use it in GitHub Desktop.
Save qti3e/34e35c85156cbd611226117d08f46436 to your computer and use it in GitHub Desktop.
#include <stdlib.h> // for NULL
#include <sys/mman.h> // for mmap
#include <stdio.h>
#include <string.h>
#include <stdint.h>
unsigned char data[] = {
// "Hello\n"
0x48, 0x65, 0x6c, 0x6c, 0x6f, 0xA
};
unsigned char code[] = {
0x55, // push %rbp
0x48, 0x89, 0xe5, // mov %rsp,%rbp
0xba, 0x06, 0x00, 0x00, 0x00, // mov $0x6,%edx ; msg len
0xb9, 0x00, 0x00, 0x00, 0x00, // mov ????,%ecx ; msg to write
0xbb, 0x01, 0x00, 0x00, 0x00, // mov $0x1,%ebx ; file descriptor
0xb8, 0x04, 0x00, 0x00, 0x00, // mov $0x4,%eax ; system call number (sys_write)
0xcd, 0x80, // int $0x80 ; call kernel
// 0xeb, 0xe8, // jmp $0xe8
// To call test3()
0xb8, 0x00, 0x00, 0x00, 0x00, // mov ????,%eax ; system call number (sys_write)
0xff, 0xd0, // callq *%rax
0xb8, 0x01, 0x00, 0x28, 0x00, // mov $0x37,%eax
0xc9, // leaveq
0xc3, // retq
0x55, // push %rbp
0x48, 0x89, 0xe5, // mov %rsp,%rbp
0xb8, 0x02, 0x00, 0x32, 0x00, // mov $0x37,%eax
0xc9, // leaveq
0xc3, // retq
0x55, // push %rbp
0x48, 0x89, 0xe5, // mov %rsp,%rbp
0xb8, 0x00, 0x00, 0x00, 0x00, // mov $0x37,%eax
0xc9, // leaveq
0xc3, // retq
};
void test() {
printf("called C function test()\n");
}
void test2() {
printf("called C function test2()\n");
}
void test3() {
printf("called C function test3()\n");
}
void execute () {
char *ptr = mmap(NULL, sizeof(code), PROT_READ | PROT_WRITE | PROT_EXEC
, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
int start = 10;
int num = (uintptr_t) &data;
while (num > 0) {
code[start++] = num % 256;
num /= 256;
}
int test_ptr = (uintptr_t) &test3;
start = 27;
num = test_ptr;
while (num > 0) {
code[start++] = num % 256;
num /= 256;
}
memcpy(ptr, code, sizeof(code));
char offset = 0;
unsigned long ret;
unsigned long op;
asm(" movl %0, %%eax"
:
: "b" (test_ptr)
: "eax"
);
asm(" call *%rax");
while (offset >= 0) {
printf("> info: Run code at offset 0x%lx\n", offset);
ret = ((unsigned long (*)()) ptr + offset)();
// asm(
// "movq -40(%rbp), %rdx;"
// "movl $0, %eax;"
// "call *%rdx;"
// );
// int i;
// asm("\t movl %%ebx,%0" : "=r"(i));
// printf("S: %d\n", i);
op = ret & 0xFFFF;
offset = (ret & 0xFFFF0000) >> 16;
// printf("%lx\n", ret);
// printf("%lx\n", a);
// printf("%lx\n", b);
switch (op) {
case 0:
printf("Program finished executation\n");
offset = -1;
break;
case 1:
test();
break;
case 2:
test2();
break;
}
}
munmap(ptr, sizeof(code));
printf("Exiting from C program :tada:!\n");
exit(0);
}
int main() {
execute();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment