Highlighting a character string as a function

I am trying to learn how to execute shellcode from within a program, but I cannot get even the simplest code to run. The following code should only exit the terminal when it starts:

#include <stdlib.h> #include <string.h> #include <stdio.h> #include <sys/mman.h> char exitcode[] = "\xb0\x01\x31\xdb\xcd\x80"; int main() { int (*func)(); func = (int (*)())exitcode; (int)(*func)(); return 0; } 

But all I get is segfault. GDB says this happens when a program accesses a memory location exitcode [at (int) (* func) (); ], but I'm not sure why this is causing the problem. I am running a 64-bit Linux Mint OS. Any help is appreciated.

+5
source share
4 answers

Modern operating systems use memory protection. Memory pages have access rights, like files: readable, writable, executable. Your data segment of your program is usually located on an impossible page, and trying to execute it results in segfault.

If you want to execute dynamically written binary code from your program on linux, you first need to map the page using mmap() , which you can write, then put your code there, and then change it to read-only by executing using mprotect() . THEN you can jump there.

You can, for example, read this article for details.

EDIT . When it comes to security breaches, please note that the stack is also not being executed at this time ... so all of these old “hacker tutorials” will no longer work. If you're interested in new methods, read about result-oriented programming.

+6
source

The code should be marked as executable code. One way to do this is to copy this binary machine code into an executable buffer.

 #include <unistd.h> #include <sys/mman.h> #include <string.h> char exitcode[] = "\xb0\x01\x31\xdb\xcd\x80"; int main(int argc, char **argv) { void *buf; /* copy code to executable buffer */ buf = mmap (0,sizeof(exitcode),PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_ANON,-1,0); memcpy (buf, exitcode, sizeof(code)); /* run code */ int i = ((int (*) (void))buf)(); printf("OK. returned: %d", i); return 0; } 
+4
source

Your shellcode:

 mov $0x1,%al xor %ebx,%ebx int $0x80 

There are two problems:

  • Syscall 0x1 is sys_write on 64-bit (but on 32-bit sys_exit)
  • You must assign% rax, not% al. % rax will contain residues in high digits.
0
source

I had this problem and searched a lot to solve it.

You must use this code to compile C code (To disable stack protection and make it executable):

 gcc -fno-stack-protector -z execstack -o hello hello.c 

Tested in Cali 32/64 bit. No more segfault.

Good luck.

0
source

All Articles