Shellcode formats: hex, \x escapes, arrays and base64
Shellcode is just bytes, but it is rarely shared as a raw file. It turns up
inside source code, scripts, documents and reports, written in whatever form
the surrounding language needs. Payload generators offer most of these as
output formats (msfvenom’s -f option, for example: c, csharp, python,
powershell, hex, base64 and more).
Shellcode Emulator reads all of the formats below when you paste them, and says which one it recognised.
Hex
Two hex digits per byte, with or without spaces:
31c04090c3
31 c0 40 90 c3
To turn it into a file: xxd -r -p shellcode.hex shellcode.bin.
\x escapes in a string
The C, Python, Perl, Ruby and shell way: each byte as \x and two hex digits,
inside a string literal.
unsigned char buf[] =
"\x31\xc0\x40"
"\x90\xc3";
buf = b""
buf += b"\x31\xc0\x40\x90\xc3"
Two traps:
- Characters between escapes are bytes too.
"\x31\xc0@"is three bytes: the@is 0x40. Copying only the\x..parts loses it. - Other escapes count.
\nis 0x0a,\0is 0x00, and in C a backslash and up to three octal digits is one byte:\300is 0xc0.
Arrays of 0x values
C#, PowerShell, Java, Go, Rust and Nim write a byte array as a list:
[Byte[]] $buf = 0x31,0xc0,0x40,0x90,0xc3
byte[] buf = new byte[] { (byte) 0x31, (byte) 0xc0, (byte) 0x40 };
The array’s length (new byte[5]) is part of the code, not the data, so don’t
copy it along with the values.
Lists of 32-bit words
Some tools write four bytes per value, 0x9040c031. These are little-endian
on x86: the bytes in memory are 31 c0 40 90, the reverse of how the value
reads. Reading them in the order they’re written swaps every group of four.
Decimal arrays
VBA and VBScript have no hex literals, so their arrays are decimal:
buf = Array(49,192,64,144,195)
Java’s byte is signed, so a decimal Java array can hold negative values: -64
is 0xc0 (add 256 to any negative value).
JavaScript %u escapes
Older browser exploits pass shellcode to unescape() as %u escapes, two bytes
each:
unescape("%uc031%u9040")
Each %uXXYY is the bytes YY XX: little-endian again, so %uc031 is
31 c0.
Hex dumps
Output from xxd or hexdump -C has an offset column on the left and the
printable characters on the right. Only the middle is data. hexdump also
replaces repeated lines with a single *, so a run of identical lines has to be
expanded back to its length, up to the next offset.
Base64
Base64 is common in scripts and configuration: PowerShell droppers, for
example, often carry shellcode as a base64 string. base64 -d turns it back
into bytes. A string of only hex digits can also be valid base64, so check for hex
first.