part 3: cleaning and optimising shellcode

In Part 2: Building the shellcode, we created a bind shell on port 4444 which accepts connections from any host and then interacts with “/bin/sh” to facilitate remote code execution. Our shellcode however was littered with null bytes and would probably not be very useful if embedding in any exploit code.

In this final part, we will clean our code and remove any null bytes from our shellcode. We will also look at removing unnecessary instruction to make our shellcode smaller if possible. Lets get started.

Lets break this down and tackle these one at a time. Firstly, we’ll deal with our eax syscall values:

b8 66 00 00 00 mov eax,0x66

We can see that upon assembling, the compiler converted 102 to it’s hex value of 0x66. Seeing as this is a single byte, maybe we can write it to just al (the smallest byte of eax) instead of the whole eax register.

Metasploit has a great tool for this that can help you quickly find the values of assembly instructions called “metasm”.

Note: If you do not have Metasploit installed, please follow the installation instructions provided by Rapid7 or one of many great tutorials about installing Metasploit like this one from Carlos Perez (darkoperator).

/opt/metasploit-framework/tools/metasm_shell.rb

Test the following instructions and see which ones return results with no null bytes:

mov eax, 0x66
mov ax, 0x66
mov al, 0x66

If we look at these results, the only one that is going to work for us is “mov al, 0x66”

This concludes this training on shellcode writing in assembly. If you just follow the steps and do research, anything is possible. My goal when starting this post was to make shellcode less intimidating and if you feel that you have walked away after reading this with a better understanding of how shellcode interacts with the system then I am satisfied.

I hope to create more posts as I head further down this SLAE and I recommend that anyone who is in the information security field take the course and let Vivek turn you into a shellcode ninja.