Hex escape strings in Python: Shellcodes

Those of you who write proof of concept exploit code in Python might have run into trouble trying to interpolate some hex value in between NOP sleds in Python. Consider the following code as an example:

code = "%X" % (130 + length(var), )
shellcode = '\x00\x00\x00\x00' + '\x%s' + '\x00\x00' % (code, )

Python won’t let you do that. It will spit back an “invalid \x escape” error and die. A friend today ran into a similar problem. I tried a couple of variations of %s and %X but to no avail. I then did what I do when I am stumped over a problem: went over to #python on irc.freenode.net to seek advice. A kind soul pointed out the solution.

shellcode = '\x00\x00' + ('\\x' + code).decode('string_escape') + '\x00\x00'

One thought on “Hex escape strings in Python: Shellcodes

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s