Python 3: Write to stdout in binary mode 1

Python scripts are often used to generate payloads for attacks, e.g. buffer overflows. Also, it is useful to send the payload to stdout, so that it can be redirected to the target process or, for different kinds of attacks, saved to a file.

However, since Python 3 all strings (type str) are encoded in Unicode and the print() function does not print binary data (types bytes or bytearray) directly, but only its representation, which looks like b’…’:

print(b"evil payload \xDE\xAD\xBE\xEF.")
# Output: b'evil payload \xde\xad\xbe\xef.'

Writing to stdout directly doesn’t even work:

import sys

sys.stdout.write(b"evil payload \xDE\xAD\xBE\xEF.")
# TypeError: must be str, not bytes

The solution is to write to stdout’s underlying binary buffer:

import sys

sys.stdout.buffer.write(b"evil payload \xDE\xAD\xBE\xEF.")

Alternatively, you can simply write to a file opened in binary mode instead:

with open("payload.dat", "wb") as fh:
    fh.write(b"evil payload \xDE\xAD\xBE\xEF.")

Leave a comment

Your email address will not be published. Required fields are marked *


One thought on “Python 3: Write to stdout in binary mode