1
AD ADVANCE CED M MALWARE RE THR THREATS
NO HAT 2019 (BERGAMO / ITALY)
NO HAT 2019 (Bergamo / IT ITALY)
by y Alexandre Bor Borges
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
AD ADVANCE CED M MALWARE RE ALEXANDRE BORGES MALWARE AND - - PowerPoint PPT Presentation
AD ADVANCE CED M MALWARE RE ALEXANDRE BORGES MALWARE AND SECURITY RESEARCHER THR THREATS NO HAT 2019 (Bergamo / IT ITALY) by y Alexandre Bor Borges 1 NO HAT 2019 (BERGAMO / ITALY) Agenda: In Intr troductio ion Anti
1
NO HAT 2019 (BERGAMO / ITALY)
by y Alexandre Bor Borges
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
NO HAT 2019 (BERGAMO / ITALY)
2
Malware and Security Researcher Speaker at DEF CON USA 2019 Speaker at DEF CON USA 2018 Speaker at DEF CON China 2019 Speaker at CONFidence Conference 2019 (Poland) Speaker at HITB 2019 Amsterdam Speaker at BSIDES 2019/2018/2017/2016 Speaker at H2HC 2016/2015 Speaker at BHACK 2018 Working on Android/iOS Reversing, Rootkits and Digital Forensics. Referee on Digital Investigation: The International Journal of Digital Forensics & Incident Response
Agenda:
In Intr troductio ion Anti ti-Reversing .N .NET mal alware Roo
tkits ts BIO IOS/UEFI thr threats Con
lusio ion
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY
3
Last talk lks in in conferences:
DEF EF CON USA 2019 2019: ab abstract: t: http tps:// //www.defcon.org/htm tml/ l/defcon-27/d /dc-27 27- spe speakers.htm tml# l#Borges sl slid ides: : http: tp://www.bla lackstormsecurit ity.com/docs/ALEXANDREBORGES_DEFCO N_2 _2019.pdf CONFidence Con
2019: ab abstract: t: http tps:// //confid idence-conference.org/2019/bio io.html# l#id=37486 sl slid ides: http tp://www.bla lackstormsecurit ity.com/CONFIDENCE_2019_ALEXANDRE.p df df
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
4
DEF EF CON Chi hina 2019:
abstract: http
tps:// //www.defcon.org/h /html/ l/dc-china-1/d /dc-cn cn-1- spe speakers.htm tml# l#Borges sl slid ides: http: tp://w /www.bla lackstormsecurit ity.com/docs/DEFCON_CHINA_ALEXANDR E.p E.pdf HITB ITB Amsterdam 2019: :
abstract:
http tps://conference.hitb.org/h /hitbsecconf2019ams/speakers/ale lexandre- bor borges/ sl slid ides: http tp:// //www.bla lackstorm rmsecurit ity.com/d /docs/H /HITB_AMS_2019.pdf DEF EF CON USA 2018: :
abstract: http
tps:// //www.defcon.org/h /html/ l/defcon-26/d /dc-26 26- spe speakers.htm tml# l#Borges sl slid ides: http tp:// //www.bla lackstorm rmsecurit ity.com/d /docs/D /DEFCON2018.pdf
Malw alwovervie iew Tool: l: http
tps:// //git ithub.com/ale lexandreborges/m /malwoverview
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
NO HAT 2019 (BERGAMO / ITALY)
5
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
6
In Infection can starts fr from an user r acti ction (a (as usual) l) or
secu ecurit ity vu vuln lnerabil ilit ities in in th the e system en envi vironmen ent: The e attacker fin finds a XXE (X (XML External Entit tity) vu vuln lnerabili lity. The XXE in injection occ
injecting a mali licious .d .dtd file file. . The e in injec ected ed fir first t payload con
ects to
e hos
lled by th the e attacker. A A sec econ
is downloaded fr from th the e rem emote e hos
This is payload is is a dropper, whic ich downloads a th thir ird and en encry crypted payload. . The e th thir ird payload is is composed by tw two part rts: a nativ tive cod
managed cod
. The e nativ tive payload (DL (DLL) is is in injec ected in into
The e in injec ected ed nativ tive payload decry ecrypts and execute th the e managed ed payload. The e managed payload downloads and excu cutes th the e rea eal l malw lware. The in infecti tion starts: a rootkit it fol
BIOS/UEFI in infection.
Fin Find a a XXE XXE vu vuln lnerabilit ity XXE XXE injection Do Download a a pa paylo load Dr Dropper Nati tive pa paylo load Rem emote injection
Man anag aged pa payload is is loa loaded
Do Download the rea eal l pa paylo load Rea eal infection
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
7
We e shou
ld remember th that t a ty typic ical l nativ tive ap appli lication can als lso
load th the e .NE .NET ru runti time and execute a managed cod
CLR CLRCrea eateInstance( e( ): ): provid ides th the e ICL ICLRMetaHost in interf erface. ICL ICLRMetaHost::GetRunTime( ): ): gets ts th the e ICL ICLRRuntimeInfo. . ICL ICLRRuntimeInfo::GetInterface( ): ): Loa Loads th the e CLR CLR in into
the e cur current process an and returns run runti time in inter erface poin
ICL ICLRRuntimeHost::ExecuteApplic icati tion( ): ): speci ecifies es th the e applic licati tion to
e acti ctivated in in a new dom
in. ICL ICLRRuntimeHost::Start( ): ): starts th the e th the e run runtime. . ICL ICLRRuntimeHost::ExecuteInDefaultAppDomain( ): ): in invok
thod in in th the e .NET managed assembly (this steps does not work for all .NET assembly’s meth thod). Thus, in in th this is case, e, starts th the e managed assem embly. . Fin inally ly, th the e rea eal l in infec ecti tion starts. .
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
8
Obvio viously, all ll mon
itorin ing too
e exp xpectin ing for th the e ty typic ical l remote e in injec ection: Cr Crea eateToolhelp32Snapshot( ) Mod
( ) Mod
xt( ( ) Wcs cscmp( ( ) ) (c (comparis ison) Vir irtualAll llocEx( ( ) Mod
threats tr try to
eing detec ected by usin ing g oth
thods as APC (A (Asynchronous Procedure Ca Call ll) in injection to
ing g Cr Crea eateRemoteThread ad( ) ) / / Vir irtualAll llocEx( ) fu funct ctions. A quick ick refresh abou
injection: APCs work as a callb allback fu funct ction th that t ar are executed (KiU KiUserApcDispatcher( ) ) ) ) with ithin a con
xt or
thread. Attaching an APC C to
C queu eue e of
the e target th thread, so
it is is pos
ible le to
th this is th threa ead to
load a malic icious DL DLL. . Writ riteProces essMemory( ) Cr Crea eateRemoteT eThread( ) Wait itForSingleO eObje ject Vir irtualFreeE eEx( ) GetP tProcessAddres ess( ) ) / / GetR tRemoteT eThread( )
NO HAT 2019 (BERGAMO / ITALY)
9
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
Fin indin ing an an ale alertab able e th thread fr from th the e user er-land is is not
easy task. Ho However, when en it it is is analy lyzed fr from th the e kern ernel l mod
, so
e have e th the e KT KTHREAD stru tructure, , whic ich in indic icates it. it. One e of
the e pos
le approaches es wou
ld be e to
ead th the e con
xt of
e th thread (GetThreadContext xt( )) ) , , detect ct if if it it is is calli lling on
t fu funct ctions whic ich is is associate to
lertable e state: : Wait itForSingleObje jectEx( ), ), Wait itForMulti tiple leObje jects tsEx( ), ), Slee leepEx( ), ), MsgW gWaitForMult ltip ipleO eObje jectsEx( ) ) and Sign ignalObje jectAndWait( ). Ver erify fy reg egisters to
chec eck th the e “Alertable parameter” (T (True or
lse) e) fr from ea each ch men entioned system call. ll. At t en end, , for
each ch aler lertable fu functi tion fou
e can use e GetT tThreadContext( ) ) + + Queu eueU eUserAPC( ) ) to
into
the e APC queu eue e of
the e target th thread, so
load a mali licious DL DLL, for example.
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
10
In In a unbeli eliable e way, most th thes ese e dropped malware e sample les (tr (trojans) als lso con
inue e hoo
ing (SetWindowsHookEx( ) ) with ith WH_KEYBOARD filt filter or
example) e) GUI I applic lications for
ecordin ing any sin ingle gle user er in inter eraction (WM_KEYUP, , WM_KEYDOWN messages and so
). Two known cla class of
ed are e even ent t hook
essage hoo
. Mes essage hoo
in inter ercept t (m (monit itors/logs/passes/blocks) any win indow mes essage before it it rea eachin ing th the e win indows procedure. . It It is is als lso used to
inject a DL DLL in into
I process. Even ent t hook
inEventHook( )) ) ar are als also
inter eres estin ing bec ecau ause th they y mak ake pos
licati tion to
eceive notif
enever an even ent t occ
. Rem emember th that t on
e of
the e SetW tWin indowsHookEx( ) ) parameters is is a handle le to
DLL th that t con
le to
the e DL DLL th that t hold
the e hoo
.
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
11
Attackers are carel eless bec ecause th they eith either hoo
ll th threads (th (thread ID ID == == 0) ) with ithin th the e des esktop ob
inter ercep ept all all even ents ts (EVENT_MIN/EVENT_MAX). To
lyze tr troja jans hoo
ing GUI I applic lications, probably ly Vol
lity is is th the best t shot
Non
thess, few advanced malw lware can make ou
lives es a bit it harder while ile tri tring g to
cquire memory. . The e mem emory acq cquisition too
ls usuall lly use e APIs Is such ch as MmMapMemoryDumpMdl( ), ), MmMapIoSpace( ), ), MmMapLockedPagesSpecify ifyCache( e( ) ) and ZwMapViewOfSection( ) ) for
ing physical to
virtual l mem emory. Of course, malware’s authors have tried hoo
ing th these fu funct ctions to
inder th the mem emory acq cquis isit ition by usin ing kern ernel l driv rivers (r (rootkits). Additi itionally ly, th this is driv river cou
ld be e hid idden en by manip ipulating th the e PsLoadedModule leList glob global l struc
PsLo Loaded edModuleLis ist hold
loaded kern ernel l mod
, which ich are protected by KP KPP (K (Kernel l Patch ch Guard): kd> > !a !analy lyze e -show 109
NO HAT 2019 (BERGAMO / ITALY)
12
ALEXANDRE BORGES – MALWARE AND SECURITY RESEACHER.
kd> > !lis !list t "-t t nt!_ t!_EPROCESS.Acti tiveP eProcessLinks.Flin ink -e e -x x \"d "dt t nt!_ t!_EPROCESS Im ImageFile leName\"( "(poi( i(nt!PsActiv iveProcessHea ead) ) - @@c++ ++(#FIELD_OFFSET(nt!_EPROCESS,ActiveProcessLinks)))" Usin ing g Vol
lity (v (vols lshell) l), you
find th that PsActiveProcessHea ead field field comes es fr from th the e _K _KDDEBUGGER_DATA64 stru tructure e (shown in in th the e next slid lide) e)). On Win indows, th the e KP KPCR stru tructure (dt t _KP KPCR) ) is is used ed to
find th the e KdVersionBlock field field. . From th this is field field, we e rea each th the e _D _DBGKD_GET_VERSION64 stru tructure th that t con
lin linked lis list t of
_KDDEBUGGER_DATA64 stru trutu tures (w (we can use th the GetD tDebuggerData( ) ) fu funct ction to
t th this is stru tructure). Thus, w we e are able le to
find th the e ker ernel l deb ebugger bloc lock (r (rep epresented by KdDebuggerDataBlock), whic ich its its ty type is is _KDDEBUGGER_DATA64. Fin inally ly, at t _K _KDDEBUGGER_DATA64 s stru tructure e (b (by th the e way, th that t is is en encry rypted ed on
mem emory) you
e able le to
find th the e PsAct ctiveP eProcessHead field field and ou
field PsLo Loaded edModuleLis ist , , whic ich are glob global l variables es.
NO HAT 2019 (BERGAMO / ITALY)
13
from wdbgexts.h header.
_KDDEBUGGER_DATA64 struct (on volshell plugin, use dt(“_KDDEBUGGER_DATA64”)), which can be found by using GetDebuggerData( ) function.
ALEXANDRE BORGES – MALWARE AND SECURITY RESEACHER.
Receives a value from the kernel variable PsLoaded ModuleList.
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
14
0: kd> dt _DRIVER_OBJECT ntdll!_DRIVER_OBJECT +0x000 Type : Int2B +0x002 Size : Int2B +0x008 DeviceObject : Ptr64 _DEVICE_OBJECT +0x010 Flags : Uint4B +0x018 DriverStart : Ptr64 Void +0x020 DriverSize : Uint4B +0x028 DriverSection : Ptr64 Void +0x030 DriverExtension : Ptr64 _DRIVER_EXTENSION +0x038 DriverName : _UNICODE_STRING +0x048 HardwareDatabase : Ptr64 _UNICODE_STRING +0x050 FastIoDispatch : Ptr64 _FAST_IO_DISPATCH +0x058 DriverInit : Ptr64 long +0x060 DriverStartIo : Ptr64 void +0x068 DriverUnload : Ptr64 void +0x070 MajorFunction : [28] Ptr64 long 0: kd> dt _KLDR_DATA_TABLE_ENTRY uxtheme!_KLDR_DATA_TABLE_ENTRY +0x000 InLoadOrderLinks : _LIST_ENTRY +0x010 ExceptionTable : Ptr64 Void +0x018 ExceptionTableSize : Uint4B +0x020 GpValue : Ptr64 Void +0x028 NonPagedDebugInfo : Ptr64 _NON_PAGED_DEBUG_INFO +0x030 DllBase : Ptr64 Void +0x038 EntryPoint : Ptr64 Void +0x040 SizeOfImage : Uint4B +0x048 FullDllName : _UNICODE_STRING +0x058 BaseDllName : _UNICODE_STRING +0x068 Flags : Uint4B +0x06c LoadCount : Uint2B +0x06e u1 : _KLDR_DATA_TABLE_ENTRY::<unnamed-type-u1> +0x070 SectionPointer : Ptr64 Void +0x078 CheckSum : Uint4B +0x07c CoverageSectionSize : Uint4B +0x080 CoverageSection : Ptr64 Void +0x088 LoadedImports : Ptr64 Void +0x090 Spare : Ptr64 Void +0x098 SizeOfImageNotRounded : Uint4B +0x09c TimeDateStamp : Uint4B
NO HAT 2019 (BERGAMO / ITALY)
15
ALEXANDRE BORGES – IT IS NOT ALLOWED TO COPY OR REPRODUCE THIS SLIDE.
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
16
Basically, the order to load a driver is NtLoadDriver( ) IopLoadDriverImage( ) IopLoadDriver( ) MmLoadSystemImageEx( ): The MmLoadSystemImageEx( ) creates a driver section referenced by DriverSection field from _DRIVER_OBJECT structure, which points to a _KLDR_DATA_TABLE_ENTRY entry. Thus, after the driver section is created, so an entry in created and inserted into the doubly linked list (entries are of type _KLDR_DATA_TABLE_ENTRY), which is also pointed by the PsLoadedModuleList. PsLoadedModuleList is a global variable declared as PLIST_ENTRY, which points to a LIST_ENTRY structure represented the _LIST_ENTRY type In this case, Flink pointer takes us to the entries of type KLDR_DATA_TABLE_ENTRY struct. As we mentioned, PsLoadedModuleList is protected by KPP, but malware can use another path to remove an entry: MiProcessLoaderEntry( ). Microsoft recently fixed this “trick” on Windows 10... apparently...
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
NO HAT 2019 (BERGAMO / ITALY)
17
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
18
Worse, th there e are oth
ti-forensic ic tech echniq iques used ed by advanced ed malware th threa eats. Obfu fuscation aim ims to
ing g reversed, in intelle llectual property and, , in in
icious cod
Usuall lly, ID IDA Pro SD SDK can help elp us bec ecause we e can extend ID IDA Pro fu functi tionalit itie ies by wri ritin ing plu lugin gins, whic ich is is appropria iate to:
unpacking cod
de de-obfuscate code
gath ther IO IOCs. Mod
ckers / / protectors: Vmprotec ect (v (ver ersion 3.4 .40 als lso
ects .N .NET ) Them emida Arxan Agile gile .NE .NET Mos
t protec ectors have e used ed with ith 64 64-bit it cod
(and malware). ).
NO HAT 2019 (BERGAMO / ITALY)
19
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
Do Download th the e ID IDA SDK fr from http tps://www.hex- rays.com/products ts/id ida/support/download.shtml (lik (likel ely, you
ill nee eed a professional acc ccount). Co Copy it it to
idasdk695/) with ithin in th the ID IDA Pro in installa lation dir irectory. Cr Crea eate a project in in Vis isual l Stu tudio 2017 (Fil ile e Ne New Cr Create e Proje ject Vis isual C+ C++ Win indows De Desktop Dy Dynamic-Link Lib Library (DL (DLL)). ). Ch Change e few proje ject properti ties as shown in in th this is slid lide e and next on
es.
NO HAT 2019 (BERGAMO / ITALY)
20
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
In Incl clude th the e “__NT__;__IDP__” in in Processor De Defin init itions and ch change Runti time e Lib Library to
(take care: it it is is NOT /M /MTd).
NO HAT 2019 (BERGAMO / ITALY)
21
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
Add id ida.l .lib (fr from C: C:\Program Files iles (x86 (x86)\IDA 6.9 .95\idasdk695\li lib\x86_win_vc_32) ) to
itional De Dependencie ies and its its fold
itional l Lib Library Di Directories. . Add “/EXPORT:PLUGIN” to
itional l Optio tions. .
NO HAT 2019 (BERGAMO / ITALY)
22
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
Don’t forget necessary headers. Ini nitia ializ izatio ion fun functio ion. Mak Make the the pl plugi gin avail ilable le to
this idb db and and kee eep the the pl plugi gin load
n me memory
Cl Clean-up task asks. Fun Functio ion to
be call alled wh when user user act activ ivates the the pl plug ugin in. Sim Simple le (a (and nd inc ncomple lete) ) URL URL reg
NO HAT 2019 (BERGAMO / ITALY)
23
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
Plug ugin in stru tructure. Pl Plug ugin wi will be be act activated by y com
inatio ion AL ALT-C. It t gets ts the the nu number of
strings from “Strings view” It t gets ts strin trings. Th The e cor
ly it.
t che hecks whe whether the the strin tring g ma matches to
the URL URL reg egex. If f che hecks, so
ea == == strin trinfo.
NO HAT 2019 (BERGAMO / ITALY)
24
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
URLs RLs fou
within th this mali malicio ious dri
AL ALT T + + C
NO HAT 2019 (BERGAMO / ITALY)
25
roo
t@kali:/malwoverv rview# pyt ython malw alwoverv rview.py -r r d.r d.re71.cn -b b 1 1 | | mor
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
NO HAT 2019 (BERGAMO / ITALY)
26
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
NO HAT 2019 (BERGAMO / ITALY)
27
Mod
fuscators / / protectors has sever eral fea eatu tures: They protect and ch chec eck th the e memory in integ egrit
, it it is is not
ible e to
clean executable fr from th the memory because orig
instructions are not
ecod
in th the e mem emory. Alm lmost all ll of
them em provide stri tring en encry ryption. . IA IAT fr from pack ckers lik like Themida keeps on
ly on
function (Tls lsSetValu lue( )). ). In Instructions are e virt virtualized and tu turned in into
virtual machin ine in instr tructions (R (RIS ISC in instr tructions). ). Obfu fuscation is is stack based ed, so
it is is hard to
le vir virtualized ed cod
e static tically. In Instructions are e en encry crypted on
emory as addit itional memory la layer. .NE .NET protectors ren ename clas classes, meth thods, field fields an and external l references es. . Vir irtualized ed cod
is poly
ther ere are many rep epresen entations referrin ing th the e same CP CPU in instr tructi tion.
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
NO HAT 2019 (BERGAMO / ITALY)
28
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
Ther ere are als lso fake e push in instructions. Ther ere are many dea ead and usele eless cod
es. . Ther ere is is som
ing g unconditional jumps. All ll ob
fuscators use e cod
flatten enin ing. Pack ckers have few anti ti-debugger and anti ti-vm tric tricks. It It is is not
easy to
iden entify tify whether th the e program is is virt virtualized or
Prologues and epilo ilogues fr from each ch fu funct ction cou
Ha Have you
tried ed to
en an advanced pack cker in in ID IDA Pro? Fir irst sigh ight: on
ly red ed and gr grey bloc locks (n (non
And many oth
tricks...
NO HAT 2019 (BERGAMO / ITALY)
29
B C H D DISP DISPATCHER A I G F E 2 3 Ins Instr tructio ion de decoder In Instr tructio ion
A, B, C, C, ... ar are han handle lers suc uch as as han handle ler_add, han handle ler_s _sub, han handle ler_push... Op Opcodes fr from
a cus ustom ins nstruction set. t.
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
Init Initialization Fetch Dec Decode
RVA A RVA A + + pr proc
base add address an and oth
asks. Ins nstructio ions ar are stor
n an an en encry rypted form
NO HAT 2019 (BERGAMO / ITALY)
30
ha handler 1 ha handler 2 ha handler 3 ha handler 4 ha handler 7 ha handler 5 ha handler 6
fun function poi pointer 1 fun function poi pointer 2 fun function poi pointer 3 fun function poi pointer 4 fun function poi pointer 7 fun function poi pointer 5 fun function poi pointer 6
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
fu functio ion po poin inter table le (lik (likely en encry rypted) en encr_1 en encr_n en encr_2 en encr_3 en encr_5 en encr_4 ... ... 1 2 3 4 5 n-1 n vm vm_add vm vm_n vm vm_sub vm vm_xor vm vm_push vm vm_pop ... ...
de decrypted ins instructions en encrypted ins instructions ind indexes
rec ecovering an and de decry rypting fu funcions
NO HAT 2019 (BERGAMO / ITALY)
31
#i #inclu lude <s <stdio.h> in int t main ain (v (void) { in int t ab aborges = = 0; 0; while ile (ab (aborges < 30 30) { printf(“%d\n”, aborges); ab aborges++ ++; } return 0; 0; }
Loa Loadin ing lib ibs abo aborges s = = 0 abo aborges s < < 30 30 pri printf( ) abo aborges++ retu turn 0
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
NO HAT 2019 (BERGAMO / ITALY)
32
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
Or Orig iginal Program
NO HAT 2019 (BERGAMO / ITALY)
33
cc cc = = 1 cc cc != != 0 swit itch(cc)
abor aborges < < 30
cc cc = = 0 cc cc = = 3 br break abo aborges s = = 0 cc cc = = 2 2 br break pr prin intf abo aborges++ br break cc cc = = 2 loa
ibs cc = 1 cc = 2 cc = 3
Dis Disavantages: Los Loss of
erformance Easy to
identi tify fy th the CF CFG fla flattening
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
NO HAT 2019 (BERGAMO / ITALY)
34
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
The e ob
fuscator-ll llvm is is an exce cell llent project to
e used ed for cod
install ll it, it, it it is is rec ecommended to
file fir first t (b (bec ecause th the e lin linkage stage): fallo llocate -l l 8GB B /swapfil ile ch chmod 600 /swapfil ile mkswap /swapfile le swapon /swapfil ile swapon --
apt-get in install l llvm llvm-4.0 apt-get in install l gcc cc-multil ilib ib (in (install l gcc cc lib lib support to
it) git git clo clone e -b llvm llvm-4.0 http tps://gi github.com/obfuscator-llvm/obfuscator.g .git mkdir build ild ; ; cd cd build ild/ cm cmake -DCMAKE_BUILD_TYPE=Rele lease -DL DLLVM_INCLUDE_TESTS=OFF ../ ../obfuscator/ make e -j7 j7 Pos
ible e usages: ./ ./build ld/bin/cla lang g ale lexborges.c -o
lexborges -mll llvm -fla fla ./b ./build ld/bin/cla lang g ale lexborges.c -m32 -o
lexborges -mll llvm -fla fla ./b ./build ld/bin/cla lang g ale lexborges.c -o
lexborges -mll llvm -fla fla -mllv lvm -sub
NO HAT 2019 (BERGAMO / ITALY)
35
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
Main dispatcher Prologue and initial assignment
NO HAT 2019 (BERGAMO / ITALY)
36
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
Main blocks from the program
NO HAT 2019 (BERGAMO / ITALY)
37
.text xt:00401000 loc_401000: ; ; CODE XRE REF: _mai ain+Fp .text xt:00401000 pus push eb ebp .text xt:00401001 mov v eb ebp, esp esp .text xt:00401003 xor
ea eax, ea eax .text: t:00401005 jz jz sho short rt ne near r ptr tr lo loc_40100D+1 .text xt:00401007 jnz jnz ne near ptr tr loc
.text xt:0040100D .text: t:0040100D loc loc_40100D: ; ; CODE XRE REF: .text: t:00401005j .text xt:0040100D ; ; .text xt:00401007j .text xt:0040100D jm jmp p ne near ptr tr 0D0A8837h
Si Simple op
and an anti ti-dis isassembly tec echniq ique
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
NO HAT 2019 (BERGAMO / ITALY)
38
00401040 call ll + $5 00401045 pop ecx 00401046 inc inc ecx 00401047 inc inc ecx 00401048 add ecx, x, 4 00401049 add ecx, x, 4 0040104A push ecx 0040104B ret 0040104C su sub ecx, x, 6 0040104D dec ecx 0040104E dec ecx 0040104F jm jmp 0x4 x401320
Call all stack man anip ipulation:
Do you know what’s hap happening he here?
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
NO HAT 2019 (BERGAMO / ITALY)
39
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
NO HAT 2019 (BERGAMO / ITALY)
40
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
Double-click the result....
NO HAT 2019 (BERGAMO / ITALY)
41
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
NO HAT 2019 (BERGAMO / ITALY)
42
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
NO HAT 2019 (BERGAMO / ITALY)
43
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
There is is not
cquiring tem emperature e data in in vir virtu tual machin ines es. Ther erefore, , malware is is able le to
wheth ther th they are ru running on
irtual machin ines es or
.
Ph Physical l Hos Host: C: C:\> > VM VM_Test2 t2.exe St Status: OK OK Th Thus, , the pr program is s ru running in a a ph physical hos host! Vi Virtual l Machin ine: C: C:\> > VM VM_Test2 t2.exe This pr program IS IS RUN RUNNING in a a vir virtual l mach achine!
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
NO HAT 2019 (BERGAMO / ITALY)
44
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
NO HAT 2019 (BERGAMO / ITALY)
45
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
Mos
t of
the e tim time, .NE .NET malware dem emands same procedures while ile analy lyzing th them: unpacking / / decry ecrypti ting th the e em embedded res esources es. dumpin ing unpacked nativ tive cod
from memory. fin findin ing th the bin inary ry dec ecry ryptin ing routi tine. dec ecompili ling it it usin ing g programs such ch as dnSpy, Ilsp Ilspy, .NE .NET refle lector, and so
. som
es, we e fin find en encry rypted stu tuff usin ing g known ob
fuscators/p /packers such ch as as Do Dotf tfuscator, Agile gile, Eaxf xfuscator.NET, Skater and many oth
Furt rther in inter eresting tool
lyze and understand .NE .NET run runtime are e availa lable le: Mem emoScope.Net: http tps://gith thub.com/f /fremag/MemoScope.Net Shed ed --
.NET run runti time in inspec ector: http tps://git ithub.com/enkomio/shed ed SuperDump, for
crash dump analy lysis: http tps:// //github.com/Dynatrace/superdump Du DumpMin iner: http tps://gith thub.com/d /dudikel eleti/DumpMin iner Mem emAnaly lyzer: http tps://gith thub.com/Alois is-xx/MemAnaly lyzer Sharpla lab: https://sharplab.io/ ObjectLayoutInspector to
lyze in inter ernal l stru tructu tures of
the e CLR CLR ty types at t run runti time (http tps:// //github.com/SergeyTeplyakov/Obje jectLayoutInspector)
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
46
Im Important t meth thods durin ring .N .NET th threat t analy lysis is: System.Reflection.A .Assembly.Load( ) System.Reflection.A .Assembly.LoadFile le() System.Reflection.MethodInfo.Invoke( ) GetT tType ( ( ) ) GetM tMethod( ) ) In Invoke( ) ) (th this is is is a ty typic ical l Reflec flection approach) GetA tAssembly lyName( ) ) + + GetT tType( ) ) + + GetM tMethod( ) ) + + In Invoke( ) Fin indResource( ) ) + + Siz izeOfRes esource( ) ) + + Loa LoadRes esource( ) ) + + Lo LockResource( ) Res esources es.ResourceManager.GetObje ject( t( ) AssemblyLoader.A .Attach( ) ) + + AssemblyLoader.Resolv lveAssembly( ) ) (r (resolves external assemblie ies in in run runti time) GetE tExecutingAssembly ly( ) ) (u (usin ing g durin ring reflecti tion) Nati tive e fu funct ctions are usuall lly calle lled by usin ing g P/In /Invoke.
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
47
Many .NE .NET malware samples es kee eep decry ecrypters, unpackers and and hoo
ing routi tines in in th the e .cc .cctor( ) ) cla class con
Oth ther meth thods such ch as .ct .ctor( ) ) and Fin inalize( ) ) are als lso used ed to
the e same mali licious fu funct ctions. Furthermore, I’ve have seen hijacking in key functions such as IC ICorJitCompile ler::compile leMethod( ) ) , , which ich belo elong to
JIT is is res esponsible for cr creatin ing th the e nativ tive cod
Many malware e auth thors have e programmed dir irectl tly in in IL IL (In (Intermediate e La Language) and, in indeed, it it is is in interesting approach because: : IL IL is is stack based ed, so we don’t find any instruction related to register
entu tuall lly, malw lware e th threats have e attacked th the e .N .NET ET run runti time e to
the e system or
en th the e JIT
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
48
External assemblies that referred by the assembly (AssemblyRef table). Native modules referred by the assembly. The module name is in the ModuleRef.
MANIFEST
Custom attribute used by the compiler (or tools) and defined in the CustomAttribute metadata table (0x0C). Assembly name
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
49
Managed resource Information about the code such as MVID (used in the Registry to point the native version of the code) and relevant flags such as WINDOWS_GUI and 32BITREQUIRED. constructors
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
50
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
51
Listing domains of the CLR process.
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
52
Get a list of managed threads. Of course, we could used the -special
COM Threading Model: STA: Single Thread Apartment MTA: Multi Thread Apartment Threat state: (0x0) Newly initialized thread. / (0x020) It can enter a Join / (0x200) background thread.
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
53
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
54
PreJIT: pre-compiled code JIT: compiled Code NONE: the code hasn’t been compiled by the JIT.
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
55
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
56
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
57
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
58
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
NO HAT 2019 (BERGAMO / ITALY)
59
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
NO HAT 2019 (BERGAMO / ITALY)
60
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
Roo
its are e leth thal.
It makes pos possib ible to to loa
any malic licious s code fr from an anywere (e (even en encry rypted an and fr from
a hid hidden sto torage) an and compromis ise the ker ernel by y dis disablin ing the code integrity mod
(KCS), so so mak akin ing pos possib ible to to loa
alicio ious ker ernel dr driv ivers (r (roo
. Rem emember that an any malicious driver can “bypass” intermediate driver layers. . Upper-level class filter driver Upper-level filter driver Function Driver Lower-level class filter driver Low-level device filter driver Bus Filter driver Bus Driver Driv Driver de development is s us usually ly do done in pa pair ir, , whe here the cl class s dr driv iver ha handle gen eneral tasks, , while ile the min iniport- dr driv iver implement spe specific rou
to the indiv ivid idual l de device. Us Usin ing the ri right I/O I/O control cod
(I (IOCT CTL_SCSI_PASS_TRH OU OUGH_DIRECT CT) , , the mali alicious dr driv iver is s ab able le to “bypass” protections pr provide by y pr programs. s. Malicious driver Kernel Filter Driver Security Application Filter driver 3 Security Application Filter driver 2 Security Application Filter driver 1 Disk filter driver Bus Filter Driver IRP IoCallDriver()
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
61
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
62
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
63
Th Ther ere ar are tw two
handle lers th that ar are no not t de default
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
64
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
65
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
66
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
67
IR IRP_MJ_DIRECTORY_CONTROL req equest t is is rel elated to
eadDirectoryChangesW( ) ) or
ZwQueryDirectoryFile( ). ). Thus, th the rootkit it cou
ld be tr trying to
intercept any attempt to
e lis listed ed in insid ide an speci ecific dir irectory. Sop
istic icated malware e tr try to
change lo lower la layers at t devic vice stac
le, it it cou
interestin ing to
infect ct th the SCS CSI min inip iport driv river in instead of
ile System Dr Driver. Root
inter ercept rea ead/writ ite e req equests fr from hard dis isk by: manipulating th the e Majo jorFunction arr rray (IR (IRP_MJ_DEVICE_CONTROL and IR IRP_INTERNAL_CONTROL) of
the e DR DRIVER_OBJECT CT stru tructu ture. . Du During g an in infec ection process, malw lware e th threads force th the e reb ebooting by callin lling ZwRaiseHardError( ) ) for loa loading th the e mali licious driv river. Root
lly hoo
imple lement t a new version of
the ZwCreate( ) ) fu function for
in inter ercepti ting g all ll op
en req eques ests sen ent t to
vices (s (same fu functi tions used ed by AV).
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
68
Addit itionall lly, malw lware e th threads have: e: hoo
ed th the e Dr Driv iverUnload( ) ) rou
ine to
eing g unloa loaded. protected itse itself lf fr from bein eing removed by: : mod
fyin ing routi tines es such ch as IR IRP_MJ DE DEVICE_CONTROL. hoo
ing requests goin
the dis isk (IO IOCT CTL_ATA_* and IO IOCTL_SCSI_*). ). used ed IoR
egisterShutdownNotif ification( ) rou
ine for reg egis isterin ing th the e driv river to
ecei eive an IR IRP_MJ_SHUTDOWN noti
icati tion when en th the e system is is goin
to
is way, it it is is able le to
the malic icious driv river in in th the next boo
in case e it it is is nece ecessary ry. Co Compromis isin ing IN INT 1 in inter errupti tion, whic ich is is res esponsible e for
andli ling deb ebugging g even ents ts. Hid Hiding part rtit itions/fil ilesystems at t en end of
the e dis
itionally, en encry rypting th them em.
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
69
Ker ernel l Ca Callb llback Funct ctions: in in few wor
ich are e mod
are used ed by mon
like anti ti-virus th that t ale lerts ts th the kern rnel l mod
cific ic even ent t ocu
Mos
llback meth thods are: PsSetLoadImageNoti tify fyRouti tine: it it provides noti
ication when en a process, lib library
ernel l mem emory ry is is mapped in into
emory. IoR IoRegi gisterFsRegis istrationChange: it it provid ides notif
en a files filesystem bec ecomes es avail ilable. IoR IoRegi gisterShutdownNotif ification: th the e driv river han andle ler (IRP (IRP_MJ_SHUTDOWN) when en th the e system is is abou
t goin
KeR eRegisterBugCheckCall llback: it it help elps th the e driv rivers to
elp a noti
(for clea cleaning task) before e a sustem cr crash. PsSetCreateThreadNotify fyRoutine: : in indic icates a routine th that t is is calle lled every ry tim time when en a th thread starts or
ends. .
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
70
PsS sSetCreateProcessNotify ifyRoutin ine: whe hen a a pr proc
arts ts or
finis ishes, thi this call llback is s invoked (r (roo
its an and AVs). ). Dbg bgSetD tDebugPri rintCall llback: it t is s use used for
ing de debug mess essages. CmRegis isterCallb lback( ) / / CmRegis isterCallb lbackEx( ) ar are e call lled by driv drivers to
egis ister a Reg egis istry tryCallb lback rout
ine, whi hich is s call lled every ery tim time a a thr thread pe perform rms an an ope
ion on
the reg egis istry ry. Mal alware thr threats use use thi this call llback to
eep the the system pe persis istence: if f someone remove the Registry’s entry, so the entry is re-in inserted.
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
71
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
72
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
73
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
74
Every ery min inimum Troja jan uses es C2 C2 ch channel to
l th the e target t an and exf xfil iltrate in information and daily ily attacks uses es Cob Cobal l Str trik ike, Sliv liver, Faction and so
However, malware’s authors need to write their own code or use Social Media (Twitter...) Co Common C2 C2 uses es ob
vious fu funct ctions: Win inInet: In Inter ernetOpen( ) ) + + In InternetConnect( ) ) / / In InternetOpenURL( ) URLM LMon: : URLDownloadToFile le( ) COM: : Co CoInitia ialize( e( ) ) + + CoC CoCreateInstance( ) Win inSock v2: : WSAStartup( ), ), sock
), bin ind( ), ), lis listen( ), ), acce ccept( ), ), con
), sen end( ( ), ), rec ecv( ), ), shutdown( ) Oth ther er C2 C2 samples es are still till based ed NDIS (Ne (Network Dr Driv iver In Interface e Speci ecification). Usin ing g NDIS makes pos
e to
pack ckets in in a lo low le level. el.
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
75
About NDIS, you
ld remember few facts cts abou
it: Pack ckets rec eceiv ived gen enerate in inter errupts ts call llback Min iniportInterrupt( ) ) defin fined by usin ing g MIN INIPORT_ISR ty type (r (regis istered by calli lling Ndis isMReg egisterInterruptE tEx( ) ) ). ). Min inip iportInterrupt( ) ) makes es min inimum wor
(sim imil ilar to
rivers in in Lin Linux) ) and hands over the “heavy” work (I/O (I/O processing, for example) to
the e Min inip iportInterruptDPC( ). ). The e min inip iport driv river cou
ll th the e Ndis isMQueu eueDpcEx( ) ) or
isMQueueDpc( ) ) fu funct ctions to
eques est addit itional deferred procedure calls lls (DP (DPCs) for oth
processors. De Dependin ing on
the in interrupt generated by th the netw twork in interface, th the min iniport driv river cou
ld dis isable new in inter errupts ts fr from th the e netw twork in inter erface e until til all ll pen endin ing DP DPCs are processed ed. . Fin inally ly, th the min inip iport driv river can call ll th the Ndis isMDeregis isterInterruptEx( ) ) to
elea ease e res esources.
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
76
Thus, th the id idea is is to
try to
intercept th the pack ckets arriv iving (NdisInterlockedInsertHeadLis ist( ) ) for
le), before th the e DP DPC processin ing or
all ll netw twork com
icati tion usin ing g NDIS because tools are not able to “catch” it. Anoth ther approach wou
e use e Win indows Soc
ernel el API I (W (WSK): WSK Clie Client / / Soc
t Str tructure (Ba (Basic, Lis Listen enin ing, Da Datagram, Con Connection-Orie iented ed and Str trea eam) Win inSock Kernel l Events ts are used by WSK subsystem for
g WSK applic licati tions when en sock
t even ents ts such ch as data bein eing g rec eceiv ived by a soc
sock
isconnection. Several fu functi tions such ch as WskAcceptEvent( ), ), WskInspectEvent( ), ), WskRecei eiveF eFromEvent( ) ) , , WskReceiveEvent( ), ), WskDis isconnectEvent( ), ), WskSendBacklogEvent( ) ) and WskAbortEven ent( ) ) used ed for
ling even ents. Do Doubtl tless, th ther ere are multi ltiples WSK fu funct ctions such ch as Wsksocket( ), ), WskSocketConnect( ), ), WskControlSocket( ), ), WskBin ind( ), ), WskAccept( ), ), WskConnect( ), ), WskSendTo( ), ), WskReceiv iveFrom( ), ), WskSen end( ), ), WskRecei eive( e( ), ), WskDisconnect( t( ), ), and so
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
77
Furt rthemore, any meth thod for
inter ercepting th the e netw twork com
ld be e alw lways con
idered: IR IRP Filt ilter Dr Drivers Tcp cpip.sys driv river Rem emember th that t when en com
ecution flo flow is is skip ipped, so
it bypasses most mon
ls too
endin ing IR IRP req equest dir irectly ly to
the e devic vices ob
ch as as \De Device\TCP or
Device\UDP. The e gen eneral l procedure for
inter erceptin ing th the e netw twork com
is ver ery sim imil ilar to
ing a files filesystem driv river: Get t a poin
the e netw twork driv rivers ob
ject (tcp cpip ip.sys) by usin ing g fu funct ctions such ch as ObReferenceObjectB tByName( ). ). Get t a a De Devi viceObje ject han andle le to
the e lin linked ed lis list t of
vice ob
jects. Fin ind th the e TCP CP and UDP DP devic vices. . Get t a a referen ence to
thes ese e netw twork devic vices. Mon
itor/in intercept th the e com
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
78
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
79
Ot Other Win inDbg com
!v !volumes !po !portlis ist ffffe001b2c89070 !in !instance ffffe001b2c8b070
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
NO HAT 2019 (BERGAMO / ITALY)
80
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
NO HAT 2019 (BERGAMO / ITALY)
81
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
BIOS MBR EFI VBR Bootmgr Bootmgfw.efi BCD winload.exe kdcom.dll ELAM ntoskrnl.exe Code Integrity
UEFI EFI is sup uppor
ndows 7 SP1 SP1 x64
ci.dll HAL.dll
Classifie ies mo module les as as goo
, bad bad and and unk unknown. Add Addit itio ionall lly, it t deci decides whe whether load
a mod module le or
not acc accordin ing to
the po polic icy. Bo Boot
its cou
ld attack it t be befor
ing the the ker ernel l and and ELA
IPL
It t ho holds the the bo boot
con
iguratio ion infor
ion The he bo boot
uses the the INT NT 13h h disk disk servi ervice (fr (from
mo mode) ) to
access the the di disk ser ervic ice in n pr prot
mode de. Su Subvertin ing g INT NT 13h h wou
ld be be lethal l be because wi winl nload.exe use use it t to
ts mo module les. Code integrity is shared between kernel and ci.dll, but nt!CiEnable variable controls everything (Win 7 only).
NO HAT 2019 (BERGAMO / ITALY)
82
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
SEC PEI DXE BDS
TSL (Transient. System Load) FLASH Bo Boot
uard OS OS Sec Secure Bo Boot
UEFI EFI Sec Secure Bo Boot
UEFI EFI Sec Secure Bo Boot
IBB
malw malware and and expl ploit its attack her here
Hypervisor
Windows Boot Loader
Kernel drivers Windows ELAM 3rd party drivers Apps
Th The e Wind ndows uses uses the the UEFI EFI to
the Hyp Hyperv rvis isor and and Sec Secure Ker ernel. l.
Ac Acts s on
dr drivers tha hat ar are e executed be before Win indows be being loa loaded and and ini initialized.
BIO BIOS S Gu Guard Mo Modi dify fyin ing g an an existin ing g DXE dri driver (or (or add add a a ne new w
e) cou
ld al allow mali malicio ious execution at t DXE stag age. It t is po possib ible le to
modify ify a UE UEFI FI DXE dri driver by y com
the SPI SPI fl flash ash pr prot
, so
ypassin ing/d /dis isabli ling g the the UEFI EFI Sec Secure Bo Boot
.
NO HAT 2019 (BERGAMO / ITALY)
83
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
Of Of course, , it t is s pr pretty eas easy to to disa disassemble a a MBR BR in ID IDA Pro: dd dd.exe -v v if=\\.\PHYSICALDRIVE0 of=
s=512 count=1 Se Set t the of
set to to 0x7 0x7c00 an and dis disassemble it t as as 16 16-bit code. . Clean
NO HAT 2019 (BERGAMO / ITALY)
84
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
Infected
NO HAT 2019 (BERGAMO / ITALY)
85
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
C:\> > "C: C:\Program File Files (x (x86 86)\VMware\VMware Wor
ion\vmware-vdiskmanager.exe" " -r r Win indows_7_x86-cl2 l2-000002.vmdk -t 0 0 infected.vmdk roo
t@kali:~# qem qemu-img convert -f f vm vmdk -O raw infected.vmdk infected.raw roo
t@kali:~# dd dd if=infected.r .raw of=
roo
t@kali:~# fi file le mbr br_in infected.bin br br_infected.bin in: DO DOS/MBR boo boot sec sector Ins Install ll Boc Bochs an and cr create a a boc bochsrc file file po poin inting to to the con
above:
rom
image: fi file= = "C: C:\Prog
Files es (x (x86)\Bochs-2.6.9\BIOS-bochs-la latest" vgar aromim image: : fi file= = "C: C:\Prog
Files (x (x86)\Bochs-2.6.9\VGABIOS-lg lgpl-la latest" meg megs: : 32 ata0: en enable led=1 =1, ioad
=14 ata0-master: : ty type=d =dis isk, pa path="C: C:\VMs\in infected.raw", mod mode=fla flat, cyli linders=1024, hea heads=16, spt=6 t=63 bo boot:
disk vga: a: extension=vbe mo mous use: : en enable led=0 log
: nul nul log
prefix fix: : %t% %t%e%d pan panic: : act action
er error: act actio ion=repor
info:
actio ion=report deb debug: : act actio ion=ig ignore # # di displa lay_li library: wi win3 n32, op
tions="gu gui_ i_debug" g"
NO HAT 2019 (BERGAMO / ITALY)
86
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
NO HAT 2019 (BERGAMO / ITALY)
87
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
Infected MBR being debugged
NO HAT 2019 (BERGAMO / ITALY)
88
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
Anot nother r way to
debug and and an analy lyze a a MBR R usin using ID IDA Pro
s also also si simple le: Dowlo load the the id ida.py fr from
http: tp://hexblo log.com/i /ida_pro/fil iles/m /mbr_bochs.z .zip Cop
the ida.py to your preferred folder (I’ve copied it to Bochs ins install llatio ion fol
r), ed edit it the the fi first lin lines to
adapt it it to
# # Som
ts SECT CTOR_SIZE = = 512 BOOT_START = = 0x7C00 BOOT_SIZE = = 0x7 x7C00 + + SECT CTOR_SIZE * * 2 BOOT_END = = BOOT_START + + BOOT_SIZE SECT CTOR2 = = BOOT_START + + SECT CTOR_SIZE MBRNAME = = "C:\VMs\mbr_infected.bin in" IM IMGNAME = = "C "C:\VMs\in infected.raw"
NO HAT 2019 (BERGAMO / ITALY)
89
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
A better approach is is to
e a deb ebugger in instea ead of
ing g an em emulator. If If you
ing g VMware e Workstation, , ch change th the e .vm vmx con
iguration file file fr from th the e target machine to
inclu clude th the e foll
lines es: monitor.debugOnStartGuest32 = "TRUE“ / monitor.debugOnStartGuest64 = "TRUE“ Br Brea eaks on
the e fir first in instr truction sin ince ce th the e power on
deb ebugS gStub.li listen.gues est32 = = "TRUE“ / debugStub.listen.guest64 = “TRUE” Enable les gu gues est t deb ebugging. debugS gStub.hideBreakpoints = = "TRUE“ Use e hardware brea eakpoint in instea ead of
ing soft
e brea eakpoin ints. Power on
the vir irtu tual l machine. La Launch th the e ID IDA Pro, go
Debugger Attach Rem emote GDB deb ebugger
NO HAT 2019 (BERGAMO / ITALY)
90
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
We’ve set Ho Hostname as “localhost” bec ecause we e starts th the e deb ebugger in in th the e same hos
th the e VM. The e deb ebugging g por
e 8832 8832. . Aft fter con
igurin ing th the e De Debug applic licati tion setu tup, click click on
K button and ch choose “attach to the process started on target” as shown belo elow.
NO HAT 2019 (BERGAMO / ITALY)
91
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
Aft fter deb ebugger starting, go
iews Open en subvie views Seg egmen ents (o (or hit it SHI HIFT+F7), righ right clic click and go
Ch Change e th the e “Segment bitness” option to 16-bit (r (remember: MBR BR run run in in rea eal mod
ich is is 16-bit it):
NO HAT 2019 (BERGAMO / ITALY)
92
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
Go Go to to Deb Debugg gger Br Brea eakpoints Add br breakpoint Se Set t the br breakpoint at t 0x7 0x7c00 (s (start of
.
NO HAT 2019 (BERGAMO / ITALY)
93
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
Con Continue the pr process ss (F9 (F9) an and dis discard eventual exceptio ions. .
NO HAT 2019 (BERGAMO / ITALY)
94
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
Ex Exis ists ot
her SPI fl flash pr prot
ions tha that t ar are e se set t up up at t DXE E stag age: : SMM_BWP (S (SMM BIO IOS Wri rite Prot
ion): pr prot
I fl flash ag again inst writ ritin ing fr from
alware runn running out
the SMM. . BLE (B (BIOS Loc
Enable le bit): bit): pr prot
the SPI I fl flash ag again inst una unauthoriz ized writ
rtunately ly, it it can be be mod
ified by mal alware wit ith SMM priv privil ileges. BIO IOSWE (B (BIOS Wri rite En Enable le Bit) t): it is a kind of “control bit”, which is use used to
allow a a BIO IOS upd update. . Prot
Ranges: it t is s des designed to
prot
specif ific reg egio ions as as SPI I fl flash, for
Add ddit itio ionall lly, the there ar are e si six x Prot
Ranges reg egis isters: PR0 R0 to
R5. No
doubts, it t is s a a goo
prot
ion ag again inst ch changes fr from
because its policies can’t be changed from SMM.
NO HAT 2019 (BERGAMO / ITALY)
95
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
ch chip ipsec_util il.py spi spi dum dump spi spihit itb.bin in
NO HAT 2019 (BERGAMO / ITALY)
96
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
https: s://github.com/LongSoft/UEFITool
NO HAT 2019 (BERGAMO / ITALY)
97
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
Capsule update is used update the UEFI components. Poss
ible le pl place to
ise the the UEFI EFI image.
NO HAT 2019 (BERGAMO / ITALY)
98
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
ch chip ipsec_util il.py de decode spi spi.bin
Rem emember th that t a BIO BIOS update cou
e com
ed by dif ifferent parts ts such ch as CP CPU mic icrocode e (in (internal firm firmware), Gbe (h (hardware netw twork stack), BM BMC (Ba (Baseboard Management t Co Controll ller, which ich provid ides monitorin ing and management), AMT (A (Act ctive e Management Pla latf tform, whic ich provides es remote acce ccess to
vices), ME ME (M (Man anagemen ent t en engin gine), EC C (E (Embed edded ed Con Controlle ler) and so
. ME ME: an x86 x86 con
ler th that t provid ides root-of
EC EC: : defin fines which ich component has rea ead/write acce ccess to
It als lso wor
ecurit ity root of
trust.
NO HAT 2019 (BERGAMO / ITALY)
99
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
ch chip ipsec_main in --
le com
Unfortunatel ely, th the e SM SMM BIO BIOS writ ite e protection (SM (SMM_BWP), , whic ich protects ts th the e en enti tire e BIO BIOS area, is is not
enable
NO HAT 2019 (BERGAMO / ITALY)
100
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
ch chip ipsec_main in.py -m com
lock
The e HS HSFSS.FLOCKDN bit it, whic ich com
from HS HSFSTS SPI MMIO Reg egis ister, prevents ch changes to
rite e Protection Enable e bit it. At t end, a malw lware couldn’t disable the SPI protected ranges to
le acce ccess to
I flas flash mem emory. .
NO HAT 2019 (BERGAMO / ITALY)
101
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
python ch chip ipsec_main.py --
le common.bios_ts
BIO BIOS Top
llows a fault lt-tole lerant update of
BIOS boo
t bloc lock. If If BIO BIOS Top
is not
locked, so
edirect th the e res eset vect ector execution to
the e back ckup boo
loadin ing a mali alicious book
.
NO HAT 2019 (BERGAMO / ITALY)
102
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
pyth ython chi chipsec_main in.py --
SMRR (System Management Range Registers) block the access to SMRAM (reserved by BIOS SMI handlers) while CPU is not in SMM mode, preventing it to execute SMI exploits on cache.
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER NO HAT 2019 (BERGAMO / ITALY)
103
Conclusion
How do do you
now whe hether you
r .N .NET T run runti time wasn’t compromised? Cou
ld the the JIT JIT en engin ine fr from
r systems be be com
ised? Are you sure that you don’t have a roo
tkit t runn runnin ing in n you
How oft
do you
upgrade driv drivers fr from
r systems? How oft
do you
upgrade fi firm rmware fr from
and de devic ices? Have you
er ch check if f the the BIO IOS/U /UEFI pr prot
ions ar are e en enable le in n ALL systems? Th Think abo about the these poi points...
NO HAT 2019 (BERGAMO / ITALY)
104
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER
NO HAT staff. You, , who have reserved some tim ime attend my y talk lk. Remember: the best of this is lif life are people
NO HAT 2019 (BERGAMO / ITALY)
105
Malware and Security Researcher Speaker at DEF CON USA 2019 Speaker at DEF CON USA 2018 Speaker at DEF CON China 2019 Speaker at CONFidence Conference 2019 (Poland) Speaker at HITB 2019 Amsterdam Speaker at BSIDES 2019/2018/2017/2016 Speaker at H2HC 2016/2015 Speaker at BHACK 2018 Working on Android/iOS Reversing, Rootkits and Digital Forensics. Referee on Digital Investigation: The International Journal of Digital Forensics & Incident Response
itter: @ale le_sp_brazil il @bla lackstormsecbr
tp://www.blackstormsecurity.com
LinkedIn: http tp:// //www.linkedin.com/in in/ale leborges es
il: ale lexandreborges@blackstormsecurity.com
ALEXANDRE BORGES – MALWARE AND SECURITY RESEARCHER