Using Python’s struct.pack function in exploit development

By October 7, 2018 Walkthrough

When writing exploits in Python, at some point you commonly gain control over the EIP register. When you gain control of this, you will want to overwrite it with a value of your choice in either big-endian or little-endian format. The most common way of entering this data in Python is to manually write it. In the QuickZip exploit for example, if we are going to jump to 0x6D7E512A (a POP POP RET sequence) on a little-endian system, we would enter:


seh = '\x2A\x51\x7E\x6D'

This works, but because we’re reversing the order of the bytes, we’re prone to typos when we copy it from Immunity Debugger, OllyDbg, or another tool. Instead, I recommend that you use Python’s struct library to pack the value for use. In this case, we’re trying to convert an integer (remember that hex is a numeric system) into four bytes in big or little-endian format. To convert the number directly to little-endian format, we can use the <l syntax, where < is saying little-endian (if we use > that’s big endian) and a four byte integer (L).


# to little-endian
from struct import pack
seh = pack('<L', 0x6d7e512a)

or


# to big-endian
from struct import pack
seh = pack('>L', 0x6D7E512A)

the benefit of this is that we no longer need to manually reverse the order and can instead copy and paste, reducing the risk of errors.

Small tip, but hope it helps!

Kevin Kirsche

Author Kevin Kirsche

Kevin is a Principal Security Architect with Verizon. He holds the OSCP, OSWP, OSCE, and SLAE certifications. He is interested in learning more about building exploits and advanced penetration testing concepts.

More posts by Kevin Kirsche

Leave a Reply