Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Item assignment to bytes object?

GAHH, code not working is bad code indeed!

  in RemoveRETNs
      toOutput[currentLoc - 0x00400000] = b'\xCC' TypeError: 'bytes' object does not support item assignment

How can I fix this?

inputFile = 'original.exe'
outputFile = 'output.txt'
patchedFile = 'original_patched.exe'

def GetFileContents(filename):
    f = open(filename, 'rb')
    fileContents = f.read()
    f.close()

    return fileContents

def FindAll(fileContents, strToFind):
    found = []

    lastOffset = -1

    while True:
        lastOffset += 1
        lastOffset = fileContents.find(b'\xC3\xCC\xCC\xCC\xCC', lastOffset)

        if lastOffset != -1:
            found.append(lastOffset)
        else:
            break

    return found

def FixOffsets(offsetList):
    for current in range(0, len(offsetList)):
        offsetList[current] += 0x00400000
    return offsetList

def AbsentFromList(toFind, theList):
    for i in theList:
        if i == toFind:
            return True
    return False

# Outputs the original file with all RETNs replaced with INT3s.
def RemoveRETNs(locationsOfRETNs, oldFilesContents, newFilesName):
    target = open(newFilesName, 'wb')

    toOutput = oldFilesContents

    for currentLoc in locationsOfRETNs:
        toOutput[currentLoc - 0x00400000] = b'\xCC'

    target.write(toOutput)

    target.close()

fileContents = GetFileContents(inputFile)
offsets = FixOffsets(FindAll(fileContents, '\xC3\xCC\xCC\xCC\xCC'))
RemoveRETNs(offsets, fileContents, patchedFile)

What am I doing wrong, and what can I do to fix it? Code sample?

like image 853
Clark Gaebel Avatar asked Dec 20 '09 01:12

Clark Gaebel


People also ask

How do you assign a byte to an object in Python?

Bytes and bytearray objects contain single bytes – the former is immutable while the latter is a mutable sequence. Bytes objects can be constructed the constructor, bytes(), and from literals; use a b prefix with normal string syntax: b'python'. To construct byte arrays, use the bytearray() function.

What is a bytes object in Python?

Strings and Character Data in Python The bytes object is one of the core built-in types for manipulating binary data. A bytes object is an immutable sequence of single byte values. Each element in a bytes object is a small integer in the range of 0 to 255.

What is Bytearray in Python?

Python | bytearray() function bytearray() method returns a bytearray object which is an array of given bytes. It gives a mutable sequence of integers in the range 0 <= x < 256. Syntax: bytearray(source, encoding, errors)


1 Answers

Change the return statement of GetFileContents into

return bytearray(fileContents)

and the rest should work. You need to use bytearray rather than bytes simply because the former is mutable (read/write), the latter (which is what you're using now) is immutable (read-only).

like image 117
Alex Martelli Avatar answered Oct 12 '22 22:10

Alex Martelli