Use struct.pack in Python when writing binary exploits

When writing binary exploits in Python, or any other language, it can become really annoying having to prepend each byte with \x. Like \xef\xbe\xad\xde or \xde\xad\xbe\xef depending if it’s little or big endian. It makes the code unreadable and it just take too much time.

By using the pack function in Python’s struct module, it is a lot easier working with these sort of things.

#!usr/bin/python

from struct import pack

def p(x):
    return pack('<L', x)

shellcode = '.....'

payload = ''
payload += '\x90'*254       # nopsled
payload += shellcode        # shellcode
payload += p(0xbffff7ba)    # eip

print payload

The < represents little-endian and the captial L means unsigned long (4 bytes).

Struct module documentation