Exploits in Python - Hexadecimal String Manipulation

I am new to python and trying to port a simple exploit that I wrote for (just nop sled, shell code and return address). This is not for vile purposes, but rather for a security lecture at a university.

Given the sixth line (deadbeef), what are the best ways:

  • represents it as a sequence of bytes
  • add or subtract value
  • reverse order (for x86 memory layout, i.e. efbeadde)

Any tips and tricks about common tasks in writing exploits in python are also welcome.

+4
source share
3 answers

In Python 2.6 and later, you can use the built-in bytearray class.

To create a bytearray object:

 b = bytearray.fromhex('deadbeef') 

To change a byte, you can reference it using array notation:

 b[2] += 7 

To cancel bytearray in place, use b.reverse() . To create an iterator that iterates over it in reverse order, you can use the function reversed : reversed(b) .

You might also be interested in the new bytes class in Python 3, which is similar to bytearray but immutable.

+4
source

Not sure if this is the best way ...

 hex_str = "deadbeef" bytes = "".join(chr(int(hex_str[i:i+2],16)) for i in xrange(0,len(hex_str),2)) rev_bytes = bytes[::-1] 

Or it might be easier:

 bytes = "\xde\xad\xbe\xef" rev_bytes = bytes[::-1] 
0
source

In Python 2.x, regular str values ​​are binary. You can use the binascii module b2a_hex and a2b_hex functions to convert to and from hexadecimal.

You can use regular string methods to modify or otherwise reorder your bytes. However, to do some arithmetic, you will need to use the ord function to get the numeric values ​​for individual bytes, then chr to convert the result back, followed by concatenation to assemble the changed string.

For mutable sequences with simpler arithmetic, use the array module with type code 'B' . They can be initialized from a2b_hex results if you start with hexadecimal.

0
source

All Articles