Thursday, December 2, 2010

simple xor solution

A friend sent out a challenge piece of malware that had some simple XOR obfuscation, so I whipped up a quick python script to deobfuscate it.  Please note I just started doing more python than c/cpp, so this code may suck ;)

This will only work if the binary obfuscated has the same key for each byte, and null bytes aren't XOR'd.  You could obviously modify or add a function for specific cases.

nicer looking code available here: http://ds.pastebin.com/iYRz9URd


#==================================================================
#= !!!IMPORTS!!!
#==================================================================
import sys
#==================================================================
#= XOR function
#= Take each byte of the old file
#= XOR it with the key
#= Return the result.
#==================================================================
def XorIt(file, key):
newFile = ''
ctr = 0

for x in file:
if file[ctr] != '\x00':
# if the byte is not 0 XOR it
newFile += chr(ord(file[ctr]) ^ key)
ctr += 1

elif file[ctr] == '\x00':
# else it is 0 so leave it
newFile += "\x00"
ctr = ctr+1

return newFile
#==================================================================
#= Get file as array
#==================================================================
def getFileAsBytes(fName):
f = open(fName, "rb")
data = f.read()
f.close()
return data

#==================================================================
#= Take file[0] and xor it with 'M', then take file[1] and xor it with 'Z'
#= check if both keys are the same, if so the same key was used.
#= Could add another check for the PE sig too
#==================================================================
def findXorKey(file):

key = 'Key Not Found :('
tmp1 = ord(file[0]) ^ ord('M')
tmp2 = ord(file[1]) ^ ord('Z')

if tmp1 == tmp2:
key = tmp1
return key

#==================================================================
#= MAIN
#= Open a file as an array
#= Take the first byte, xor it with a 'M', save result as tmpKey1
#= Take the second byte, xor it with a 'Z', save result as tmpKey2
#= Compare keys, if they're they same, thats our key.
#= Pass the key & array to the XorIt function which returns the new file
#= Write the new file to disk
#==================================================================
if __name__ == '__main__':
NumArgs = len(sys.argv) - 1

if NumArgs < 1 or NumArgs > 2:
print "!!! ERROR !!!"
print "Use: python " + sys.argv[0] + " [file_to_deobfuscate]\n"
sys.exit(1)

if NumArgs < 3:
# get the file name
File = sys.argv[1]
# open it as a byte array
bFile = getFileAsBytes(File)
key = findXorKey(bFile)
print "Key ID'd as: " + hex(key)
print "Running XOR algo now..."
newFile = XorIt(bFile, key)
File += '.xord'
f = open(File, 'wb')
f.write(newFile)
f.close()
print "Finished, new file was saved as " + File + "."