4

I'm quite new to python and trying to port a simple exploit I've written for a stack overflow (just a nop sled, shell code and return address). This isn't for nefarious purposes but rather for a security lecture at a university.

Given a hex string (deadbeef), what are the best ways to:

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

Any tips and tricks regarding common tasks in exploit writing in python are also greatly appreciated.

Mike B.
  • 123
  • 1
  • 7

3 Answers3

4

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

To create your bytearray object:

b = bytearray.fromhex('deadbeef')

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

b[2] += 7

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

You may also be interested in the new bytes class in Python 3, which is like bytearray but immutable.

Samir Talwar
  • 14,220
  • 3
  • 41
  • 65
0

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 might be simpler:

bytes = "\xde\xad\xbe\xef"
rev_bytes = bytes[::-1]
Claudiu
  • 224,032
  • 165
  • 485
  • 680
0

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

You can use ordinary string methods to reverse or otherwise rearrange your bytes. However, doing any kind of arithmetic would require you to use the ord function to get numeric values for individual bytes, then chr to convert the result back, followed by concatenation to reassemble the modified string.

For mutable sequences with easier arithmetic, use the array module with type code 'B'. These can be initialized from the results of a2b_hex if you're starting from hexadecimal.

Walter Mundt
  • 24,753
  • 5
  • 53
  • 61