Reversing py2exe executables

By TJ Nelson, Fri 30 March 2018, modified Fri 30 March 2018, in category Malware

malware, python, reverse_engineering

Reversing Python (py2exe) Malware

This post will be based on a CHSinfoSec Meetup in March 2018. The Slides from this talk are here:

Reversing Python Malware Slides

The sample from this example is CannibalRAT (sha256):83d49f14ebb6641f1b813614a40e7df2d200096b8aae198e6298125f47b55b59

You can download the MALWARE sample HERE BEWARE THIS IS MALWARE

You can also review the original analysis of this sample here: Talos Intelligence Blog - CannibalRat

Below you will find the source code for the scripts used as well as links to videos showing the process.

Extract Additional Imports from PE Overlays

get_overlay.py:

import pefile
import sys

filename = sys.argv[1]
with open(filename, "rb") as s:
    r = s.read()

pe = pefile.PE(filename)
offset = pe.get_overlay_data_start_offset()

with open(filename + ".app", "wb") as t:
    t.write(r[offset:])

[command] python get_overlay.py <filename>

asciicast

Extract resources from PE file using wrestool

[command] wrestool -Rax <filename> -o output_folder>

asciicast

Extract main python files from PYTHONSCRIPT

unpack_pythonscript.py:

import marshal, imp, sys

def main():
    f = open(sys.argv[1], "rb")
    f.seek(17)
    print "==skipping_header=="

    unmarshal = marshal.load(f)

    for i in range(0, len(unmarshal)):
        open(str(i) + ".pyc", "wb").write(imp.get_magic() + '\0' * 4 + marshal.dumps(unmarshal[i]))

    f.close()
    print "==done=="

if __name__ == "__main__":
    main()

[command] python unpack_pythonscript.py <filename>

asciicast

Decompile .pyc files with uncompyle6

[command] uncompyle6 <filename> > <filename>.py

asciicast

Putting it all together

This is the process of decompiling Cannibal RAT and extracting the C2 information from the Python source code. WARNING: Those urls are dangerous and should not be navigated to.

For more information take a look at http://blog.talosintelligence.com/2018/02/cannibalrat-targets-brazil.html

asciicast