Manual Kernel Mode Analysis With WinDbg VB2018 Vanja .

Transcription

Manual kernel mode analysis with WinDbgVB2018Vanja Svajcer@vanjasvajcer

M a n u a l ke r n e l m o d e a n a ly s i s w i t h W i n D b g Intro to WinDbg Setup Basic commands Taking it to the next level Scripting Extensions Malware analysis tips

Setting the scene

What is it GUI on top of DbgEng in Windows ntsd, csd kd

Installation and setup Debugging tools for Windows Part of WDK Part of SDK install Microsoft Store

Live debugging setup Interfaces: Serial (slow) Firewire (1392) USB Network (TCP/IP)DebuggerHostDebuggeeTarget

Live debugging setup - VM to VM Serial Network VirtualKD (VMM host to VM only)DebuggerVMDebuggeeTarget VM

Setup debugging over network1. find debugger’s ip v4 address2. choose any TCP port (e.g 55555)3. on the debugeebcdedit.exe -set loadoptions DISABLE INTEGRITY CHECKSbcdedit.exe -set TESTSIGNING ONbcdedit /debug onbcdedit /dbgsettings net hostip:w.x.y.z port:n key:xxxx

Start debugging1. Start the debuggerA. windbg -k net:port n,key KeyB. From GUI: File- Kernel Debug2. Reboot the debugee3. PROFIT!

W i n D b g Wo r k s p a ce s Setup ideal workspace Themes as registry values (can be moved by exportinginto a registry file) Stored in HKCU\Software\Microsoft\Windbg\Workspaces

W i n D b g Wo r k s p a ce fec46d7fc976 C835/windbg.reg

W i n D b g Wo r k s p a ce s .cmdtree - useful for learning and rememberingcommands https://github.com/vagnerpilar/windbgtree

D o w n l o a d i n g Sy m b o l s NT SYMBOL PATH - environment variable NT SYMBOL PATH ownload/symbols GUI download/symbols Command window .sympath download/symbols

Basic WinDbg

Logging .logopen filepath.logcloseSet verbose mode.hh - open help file

Registers and PseudoRegisters r vs r?r register flags/mask (rM) t0 to t19 csp, ip ra, extret, retreg peb, teb proc, thread iment (operator) extret

E x p l o r a t i o n co m m a n d s xdtdb, dw, dd, dq, dps, du, dakln - where is this?!dh - display pe header!ustrs

E x p l o r a t i o n co m m a n d s dx - Explore debugger object model

Disassembling u uf

C o n t ro lt [address] - trace (Step into)p [address] - proceed (Step over)pc (tc) - Step over until a call instruction is encounteredpt (tt) - Step over until returnggu - go up (return to the calling function and stop careful here) .process - set process context .thread - set register context

B re a k p o i n t s ba (hardware if possible)bp[ID] [Options] [Address [Passes]] [“CommandString"]bu (unresolved)bm (multiple) bl .bpcmds bc

B re a k p o i n t s Conditional bp Address "j (Condition) 'OptionalCommands'; 'gc' " bp Address ".if (Condition) {OptionalCommands} .else {gc}”bp kernel32!CreateEventW " c:\\commands.txt"

E xce p t i o n s sxe ld - break on module load sxe cpr - break on process creation sx - show all events/exceptions and their statuses

Output .printf .echo

It is all easy now

E x p re s s i o n E v a l u a t o r s .expr - checking and changing?@@masm, @@c , @@when evaluating a reg @sign is required eg. @ retreg(for all (pseudo) registers)

P o i n t e r d e re fe re n c i n g poi(rax)da @@c (((nt! EPROCESS *) @ proc)- ImageFileName)dwoqwo

Lists dt nt! LIST ENTRY 0x000 Flink 0x008 Blink: Ptr64 LIST ENTRY: Ptr64 LIST ENTRY #CONTAINING RECORD #FIELD OFFSET

Lists Walk a list!list -x "dt nt! LDR DATA TABLE ENTRY @ extret" @@(&@ peb- Ldr InLoadOrderModuleList)!list -x "dt nt! LDR DATA TABLE ENTRY @ extret BaseDllNameDllBAse" nt!PsLoadedModuleList

D e b u g g e r m a r k u p l a n g u a g e (D M L) .dml start.prefer dml 1 0Commands with /D switches!dml proclmD - lm with DML as a result.dml flow Start Target

Dump memory .writemem FileName Range .readmem Filename Range

Know your Windows

From: Windows Internals book

From: Windows Internals book

Object enumeration !object Available object types .for(r? t0 0; @ t0 40; r? t0 @ t0 1) { dt nt!OBJECT TYPE poi(nt!ObTypeIndexTable @ t0 * 8) Name}

Exploring Windows KPCR and KPCRB PCR (!PCR) dt nt! KPCR EPROCESS and KPROCESS OBJECT HEADER Loader Objects Driver and Device Objects IDT, GDT SSDT (and shadow)

Loaded modules lmvlmDm Pattern!lmi!for each module!object \Driver!handle!drvobj!devobj!devhandles

P ro ce s s e s a n d t h re a d s !process 0 0 !threads .tlist !for each processwalking csrss.exe handle table!peb!teb

Expected malware behavior

Loading drivers Disable integrity checking Enable test signing Use one of the utilities OSR Driver loader Novirusthanks

M a l i c i o u s ke r n e l a c t i v i t y Hooking code API functions Ntkernel !chkimage (for comparison of symbols) Driver MAJOR function handlers Tcpip.sys Hooking data Documented callbacks Undocumented tables Protected so watch for access to cr0

M a l i c i o u s ke r n e l a c t i v i t y Add file systems Exploit legacy drivers to disable integrity checks dq ci!g CiOptions (Windows 8 ) dq nt!g CiEnabled (Windows 7-)

U ro b o ro s / Tu r l aFrom: GData research

U ro b o ro s / Tu r l aFrom: GData research

U ro b o ro s / Tu r l aFrom: GData research

M a l i c i o u s ke r n e l a c t i v i t y - d e t e c t i o n Enumerate loaded driver objects and associated device objects chkimg -d Scan for driver major function hooks Scan callbacks Scan handle tables Scan memory for “hidden” modules

Check object for scheduled jobs kernel threads DPCs, APCs

C o m m o n (m a lw a re) c a l l e d f u n c t i o n s CmRegisterCallback - Registry callback for protection of registryvaluesPsSetCreateProcessNotifyRoutine - respawning the payload if thepayload process is terminatedPsSetLoadImageNotifyRoutine - to disable User Account ControlPsSetCreateThreadNotifyRoutine - registry and driver file protectionObRegisterCallbacks - to protect the payload from terminationIoCreateDeviceIoCreateSymbolic linkExAllocatePoolWithTag

M a l i c i o u s ke r n e l a c t i v i t y - d e t e c t i o n Enumerate loaded driver objects and associated device objects chkimg -d Scan for driver major function hooks Scan callbacks Scan handle tables Scan memory for “hidden” modules

Extensions swishdbgext (by Matt Suiche) wdbgark (by swwwolf) dbgkit (by Andrey Bazhan) .load !extname.help

Z e ro t h e d r i v e r n a m e

Detection

Scripting

Conditional statements .if, .then, .else j (ternary) - use with conditional breakpoints bp

Repetition .for.foreach.do.while.break.continue.block

Aliases aSaDalaS /x myAlias 5 1; .block{.echo {myAlias}} .block idiosyncrasy

D i s p l a y S S DT - s c r i p t i n gdps nt!KiServiceTable L50r? @ t3 *(unsigned int *) @@(nt!KiServiceLimit)r? @ t1 (int *) @@(nt!KiServiceTable).for (r? @ t2 0; @ t2 @ t3 ; r? @ t2 @ t2 1) {r? @ t4 @ t1[@ t2] 4.printf "%y\n", @ t4 @ t1}

Example 1 Set t0 to point to the head of the InLoadOrderModuleList of PEBr? @ t0 (nt! LIST ENTRY *) (&@ peb- Ldr- InLoadOrderModuleList) Traverse the list by following Flink field and get FullDllName.for (r? @ t1 @ t0- Flink; @ t0 ! @ t1; r? @ t1 @ t1- Flink){ Cast list entry to LDR DATA TABLE ENTRY (Offset 0) to get to the namer? @ t2 (nt! LDR DATA TABLE ENTRY *) @@(@ t1).printf "%msu\n", @@c (&@ t2- FullDllName)}

Example 2r? @ t0 (nt! LIST ENTRY*) @@(nt!PsActiveProcessHead).for (r? @ t1 @ t0- Flink;(@ t1 ! @ t0);r? @ t1 @ t1- Flink){r? @ t2 #CONTAINING RECORD(@ t1, nt! EPROCESS, ActiveProcessLinks).if (@@(@ t2- BreakOnTermination) 1){as /ma ProcName @@(@ t2- ImageFileName)as /x CritProc @@(@ t2- BreakOnTermination).block { .echo { ProcName} has BreakOnTermination { CritProc} }ad ProcNamead CritProc}}

Scripting Invoking scripts Filename Filename Filename Filename a Filename [arg1 arg2 arg3 .]

Javascript to rescue

J a v a s c r i p t t o re s c u e Chakracore engine integrated (EC6 implementation)Built on top of debugger object modelScriptingVisualizationExtending the model

Debugger Object model sLocal variablesSettings

Debugger Object model dx - new command to investigate Utility (send commands to xecuteCommand(“u”);

D e b u g g e r O b j e c t m o d e l a cce s i b l e f ro m J S// WinDbg JavaScript sample// Prints Hello Worldfunction initializeScript(){host.diagnostics.debugLog("*** Hello World! \n");}

J a v a s c r i p t co m m a n d s .load criptlist.scriptproviders

Javascript entry points ript()

6 4 b i t p ro b l e m s Javascript integers only 53 bit Special data class Int64 and the methods

Linq Language Integrated Query dx @ curprocess.Modules.Select(m m.Name).Where(n n.Contains(“maldll”)) dx @ currsession.TTD.Calls().Count()

Time travel debugging Record a tracemove forwards and backwards “in time”Set breakpoint on an API call and go backwardspgt-

Time travel debugging

Extensions

Loading and Checking Extensions .load.loadby.chainversion

Extensions JsproviderswishdbgextwdbgarkdbgkitmexsosPykd

Scripting - pyKD Python extension to make scripting easier!py pykdexample.py#!/usr/bin/env pythonfrom pykd import *zwcreateapis []zwcreateapis dbgCommand("x nt!ZwCreate*")for api in zwcreateapis.split("\n"):print api.split(" ")[1] #print name

R e l a x a n d b re a t h e !

Enabling the Good GuysSpreading security news, updates, andother information to the publicThreatSource Newslettercs.co/TalosUpdateSocial Media PostsFacebook: TalosGroupatCiscoTwitter: @talossecurityWhite papers, articles, & other informationtalosintelligence.comTalos Blogblog.talosintelligence.comInstructional Videoscs.co/talostube

R e fe re n ce s - s e t u p drivers/debugger/ drivers/debugger/getting-set-up-for-debugging ing-windowskernel-windbg ng-vmware-fusion#2298 https://communities.vmware.com/docs/DOC-15691 - vm to vm overa virtual serial port VMWare Windows

R e fe re n ce s - m a lw a re a n a ly s i s ndjavascript-analysis.html ing-netwith-help-of-windbg.html alysis-of-uroburos-using-windbg 10/Rootkit-analysis-Use-case-on-HIDEDRV-v1.6.pdf https://www.youtube.com/watch?v l2ZSG 96PoM -pykdscript-to-debug-flashplayer/

R e fe re n ce s - J a v a s c r i p t a n d o b j e c t m o d e l drivers/debugger/dx--display-visualizer-variables cts datamodel/

R e fe re n ce s - o t h e r s your-windbg-workspaceand-color-scheme/ - Workspace setup https://github.com/vagnerpilar/windbgtree - cmdtree rsenal/tree/master/WinDbg- WinDbg scripting 1 https://archive.codeplex.com/?p kdar - WinDbg scripting 2 - Archive available l%20rus - PyKD manual Russian only, translates OK http://windbg.info/download/doc/pdf/WinDbg cmds.pdf - WinDbg commandscheatsheet https://www.youtube.com/watch?v vz15OqiYYXo&feature share - WindowsInternals by Alex Sotirov http://terminus.rewolf.pl/terminus/ - Project Terminus UndocumentedStructures Diff

R e fe re n ce s - d r i v e r l o a d i n g t o o l s https://www.osronline.com/article.cfm?article 157 river-loader/ https://github.com/maldevel/driver-loader

R e fe re n ce s - e x t e n s i o n s spx?id 53304 - Mex https://github.com/comaeio/SwishDbgExt https://github.com/swwwolf/wdbgark trapper - PyKD https://github.com/corelan/windbglib - windbglib andmona.py https://github.com/pstolarz/dumpext - extension fordumping PE from memory http://www.andreybazhan.com/dbgkit.html - Dbgkit

R e fe re n ce s - b o o k s Practical Reverse Engineering: x86, x64, ARM, Windows Kernel,Reversing Tools, and Obfuscation (Chapters 3 and 4) Practical Malware Analysis: A Hands-On Guide to Dissecting MaliciousSoftware (Chapter 10) Malware Analyst's Cookbook and DVD: Tools and Techniques forFighting Malicious Code (Chapter 14) The Art Of Memory Forensics – Detecting Malware and Threats inWindows, Linux and Mac Memory Rootkit Arsenal Advanced Windows Debugging Windows Internals Windows NT Device Driver Development

R e fe re n ce s - v i d e o s https://www.youtube.com/playlist?list PLhx7txsG6t6n E2LgDGqgvJtCHPL7UFu - WinDbg tutorials by TheSourceLens https://www.youtube.com/watch?v s5gOWN9AAo&list PLb07KvumDAnD39kssVz7DgmvNH5j89k3b HackingLivestream #28: Windows Kernel Debugging Part I g-Tools-170Debugger-JavaScript-Scripting - WinDbg JavaScript scripting g-Tools-138Debugging-dx-Command-Part-1 - Dx command part 1 (and then 2) g-Tools-169Debugging-Tools-for-Windows-Team - for Debugger object model https://www.youtube.com/watch?v l1YJTg A914 - Time TravelDebugging

cisco.com

Practical Malware Analysis: A Hands-On Guide to Dissecting Malicious Software (Chapter 10) Malware Analyst's Cookbook and DVD: Tools and Techniques for Fighting Malicious Code (Chapter 14) The Art Of Memory Forensics – Detecting Malware and Threats in Windows, Linux and