Last active
August 29, 2015 14:00
-
-
Save Justasic/2ef4ac49fd7425dff39c to your computer and use it in GitHub Desktop.
Example of executing bytes from an array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
; Compile with nasm -f elf64 test.asm | |
BITS 64 | |
SECTION .text | |
global _start | |
_start: | |
sub rsp, 8 ; Align the stack pointer for a function call | |
mov rax, 0x14 ; Move syscall number 14 to rax (sys_getpid) | |
int 0x80 ; Call system call | |
push rax ; push rax to the stack | |
mov rbx, rax ; move rax to rbx | |
mov rax, 1 ; move syscall number 1 to rax (sys_exit) | |
int 0x80 ; call system call | |
ret ; return |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#if 0 | |
0000000000000000 <_start>: | |
0: 48 83 ec 08 sub $0x8,%rsp | |
4: b8 14 00 00 00 mov $0x14,%eax | |
9: cd 80 int $0x80 | |
b: 50 push %rax | |
c: 48 89 c3 mov %rax,%rbx | |
f: b8 01 00 00 00 mov $0x1,%eax | |
14: cd 80 int $0x80 | |
16: c3 retq | |
#endif | |
char code[] = | |
{ | |
0x48, 0x83, 0xec, 0x08, // sub rsp, 0x8 | |
0xb8, 0x14, 0x00, 0x00, 0x00, // mov rax, $0x14 | |
0xcd, 0x80, // int 0x80 | |
0x48, 0x89, 0xc3, // mov rbx, rax | |
0xb8, 0x01, 0x00, 0x00, 0x00, // mov rax, 0x1 | |
0xcd, 0x80, // int 0x80 | |
0xc3 // ret | |
}; | |
char code2[] = | |
{ | |
0x48, 0x83, 0xec, 0x08, // sub rsp, 0x8 | |
0xb8, 0x14, 0x00, 0x00, 0x00, // mov rax, 0x14 | |
0xcd, 0x80, // int 0x80 | |
0x50, // push rax | |
0xc3 // ret | |
}; | |
#include <stdio.h> | |
#include <unistd.h> | |
#include <string.h> | |
#include <sys/mman.h> | |
#ifdef __cplusplus | |
// C++ does not like casting pointers to function pointers | |
// so this union works around that. | |
#define CAST(f, s) function_cast<f>(s) | |
template<class F> F function_cast(void *buf) | |
{ | |
union | |
{ | |
void *buf; | |
F func; | |
} cast; | |
cast.buf = buf; | |
return cast.func; | |
} | |
#else | |
// C doesn't give 2 shits about pointers. Foot-shooting it is~ | |
# define CAST(f, s) (f)s | |
#endif | |
int main() | |
{ | |
printf("Our corrent PID: %d\n", getpid()); | |
// Make a mmapped buffer so we can copy and execute the code | |
void *buf = mmap(0, sizeof(code2), PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_ANON, -1, 0); | |
memcpy(buf, code2, sizeof(code2)); | |
int (*funct)(void) = CAST(int (*)(void), buf); | |
printf("PID returned to us via func: %d\n", funct()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hooray for foot-shooting!