How to get SIGILL to send my program?

I'm trying to do some nasty hacking stuff with dynamically generated code, and I want the OS to send me SIGILL when it reaches an unknown opcode. This would allow me to add a layer of meta-information about my program and so on.

However, for my small test program, it seems that the OS does not send SIGILL, but sends either SIGBUS or SIGSEGV. I assume this means that the NX bit is set on the page where the memory is located.

Any tips on how to make an executable memory file?

For reference, here is my test program:

#include <stdio.h> #include <signal.h> #include <stdlib.h> #include <string.h> void SIGILL_handler(int sig) { printf("Handling SIGILL\n"); } typedef void(*FUNC)(void); int main() { signal(SIGILL, SIGILL_handler); int *bad = malloc(16); memset(bad, 255, 16); ((FUNC)bad)(); printf("Returning like it no big deal\n"); return 0; } 
+4
source share
2 answers

mprotect is your friend here. It is compatible with POSIX (SVr4, POSIX.1-2001), so it should work under OS X and Linux.

 int pagesize = sysconf(_SC_PAGE_SIZE); if (pagesize == -1) { perror("sysconf"); exit(1); } /* allocate 16 aligned pages */ void *bad = memalign(pagesize, 16 * pagesize); if (NULL == bad) { fprintf("aah, out of mem :-(\n"); exit(1); } if (-1 == mprotect(bad, 16 * pagesize, PROT_READ | PROT_WRITE | PROT_EXEC)) { perror("mprotect"); exit(1); } 

must do it.

2nd edit: memalign compatibility seems not so simple. I would try memalign , valloc under OS X and Linux, and if they don't work, just use regular malloc and add enough bytes to the returned pointer so that it is aligned :-).

+6
source

I understand that this is old, but if someone is trying to get SIGILL to generate, another alternative is to use the built-in assembly, for example:

 asm(".byte 0x0f, 0x0b"); 

or

 asm("ud2"); 
0
source

Source: https://habr.com/ru/post/1396872/


All Articles