Skip to content

Instantly share code, notes, and snippets.

@msullivan
Last active August 29, 2015 13:57
Show Gist options
  • Save msullivan/9359405 to your computer and use it in GitHub Desktop.
Save msullivan/9359405 to your computer and use it in GitHub Desktop.
Some of the worst code I have ever written
// setcontext pushes the return address onto the stack in order to
// restore it by running ret. It would be bad if we wrote to the
// parent's thread stack, for obvious reasons. Instead we set up
// our own stack for it to go on and we generate code that restores
// the real %esp and then does a jmp to the real %eip.
size_t bullshit_ministack[2];
bullshit_ministack[1] = ctx.uc_mcontext.gregs[REG_ESP];
char ret_code[6] = { 0x5c /* pop %esp */, 0xe9 /* jmp rel32 */ };
uint32_t target_eip = ctx.uc_mcontext.gregs[REG_EIP] + 2; // skip the int
uint32_t next_eip = (uint32_t)ret_code+sizeof(ret_code);
*((int *)&ret_code[2]) = target_eip - next_eip;
// Fuck you, security.
void *ret_base = (void *)((uint32_t)ret_code & ~(PAGE_SIZE-1));
mprotect(ret_base, 2*PAGE_SIZE, PROT_READ|PROT_WRITE|PROT_EXEC);
// Get ready to go back
ctx.uc_mcontext.gregs[REG_EAX] = 0; // Return value
ctx.uc_mcontext.gregs[REG_ESP] = (uint32_t)&bullshit_ministack[1];
ctx.uc_mcontext.gregs[REG_EIP] = (uint32_t)ret_code;
setcontext(&ctx);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment