For some reason, there’s no really easy way to compile assembly directly to shellcode. The closest thing I’ve found to convert binary to shellcode is this bash one-liner from commandlinefu that parses the output from objdump:
|
1 2 3 |
objdump -d ./PROGRAM|grep '[0-9a-f]:'|grep -v 'file'|cut -f2 -d:|cut -f1-6 -d' '|tr -s ' '|tr 't' ' '|sed 's/ $//g'|sed 's/ /\x/g'|paste -d '' -s |sed 's/^/"/'|sed 's/$/"/g' |
nasm2shell, as2shell and bin2shell convert NASM, GNU as and binary files directly to shellcode, respectively. Get the tarballĀ for all three here.
I put this together because I wasn’t able to find a way to convert NASM or GNU assembly directly to shellcode, and the process of manually compiling assembly and parsing the binary file into a c-escaped hex string was a waste of time between iterations. This package accelerates the process of creating shellcode from assembly files.
Using nasm2shell, you can write shellcode routines in NASM and parse them directly from the assembly source:
|
1 2 3 4 |
$ nasm2shell hello32.nasm "xebx1dx31xc0x31xdbx31xc9x31xd2x83xc0x04x83xc3x01x59x83xc2x0excdx80x31xc0x83xc0x01x31xdbxcdx80xe8xdexffxffxffx48x65x6cx6cx6fx2cx20x77x6fx72x6cx64x21x0a" |
as2shell converts GNU assembly to shellcode:
|
1 2 3 4 |
$ as2shell exit.s "x31xc0xb0x01x31xdbxcdx80" |
bin2shell does the same thing for any raw binary file, in case you’re not using NASM or GAS:
|
1 2 3 4 |
$ bin2shell hello32.bin "xebx1dx31xc0x31xdbx31xc9x31xd2x83xc0x04x83xc3x01x59x83xc2x0excdx80x31xc0x83xc0x01x31xdbxcdx80xe8xdexffxffxffx48x65x6cx6cx6fx2cx20x77x6fx72x6cx64x21x0a" |
To install, get the tarball, unzip it and type
make
. To install the files to your system, type
sudo make install
. Then the commands can be invoked from any directory on your system.
Convert binary to hex in C
nasm2shell and as2shell are wrappers that compile assembly to machine code and pass the resulting binary file to bin2shell. bin2shell converts binary to c-escaped shellcode with the following function (from bin2shell.c):
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
/* * given the pointer to a buffer and the buffer's length, * print the contents of the buffer as an escaped hexadecimal string */ void printhex(uint8_t* buffer, int length) { int i; printf("""); for(i=0; i<length; i++) { if(buffer[i]<0x10) // print leading 0, ie x0f instead of xf printf("\x0%x", buffer[i]); else printf("\x%x", buffer[i]); } printf(""n"); return; } |
This seems to be a pretty sought-after method, so maybe this function will be helpful to someone else. Converting a char to its hex equivalent is as simple as
printf("\x%x", char);
Thanks Mark! I use an almost similar bash onliner but your tool provides a much cleaner and portable solution. Keep up the good work.
BTW, do you have a GitHub repo?
Glad it helped. I have a seriously neglected github because most of my coding (recently) has been kind of proprietary, but there are some cool jquery widgets on there…