Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Run-Time Code Injection
#include <cstdio>
#include <sys/mman.h>
#include <sys/types.h>
#include <cstring>
int main(int argc, const char * argv[])
// What we want to execute. in amd64, 0x90 is a no-op and 0xC3 is ret.
unsigned char execute[] = {0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0xC3};
// Get a proper page to use.
void *lPage = mmap(nullptr, sizeof(execute), PROT_READ|PROT_WRITE, MAP_ANON|MAP_SHARED, -1, 0);
// Put our machine code there.
memcpy(lPage, execute, sizeof(execute));
// We need execute rights on this memory.
mprotect(lPage, sizeof(execute), PROT_READ|PROT_EXEC);
// Tell C++ that this addess is executable, and acts like a function with no args or any return value
void (*func)(void);
func = (void (*)(void))lPage;
// Call it. Segfaults if we failed, so fingers crossed!
// We must not have failed! Hurray!
return 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment