Advanced Windows Post-Exploitation
Advanced Windows Post-Exploitation
Windows
Post-Exploitation
Malware
Forward Engineering
whoami /all
● @zerosum0x0
● @aleph___naught
R8-R15
Windows x64 Fastcall
1. No more cdecl/stdcall/fastcall/thiscall/register/safecall madness
2. Function Arguments
a. Rcx
b. Rdx
c. R8
d. R9
e. Stack
FLAGS
Memory Map IO
● Reserved memory addresses
● BIOS data area
● VGA display memory
CR0
CR1
● Reserved
○ #UD exception when trying to access
CR2
● Page Fault Linear Address
● When page fault occurs, address accessed stored here
CR3
● Contains base address of page table entries
● Used when translating a virtual address to physical
CR4
Exceptions
● Faults
● Traps
● Aborts
IDT
● Interrupt Descriptor Table
● When interrupted, register states saved
● Function mappings for interrupts
○ 0 - division by 0
○ 1 - debug fault/trap
○ 3 - breakpoint (0xcc) trap
○ 8 - double fault abort
○ 13 - general protection fault/trap
○ 32-255 - available for software/hardware use
System Calls
● Transition from user to kernel, back
● Required to do anything interesting
● "Privilege gate"
● Special handler
○ mov ecx, 0xc0000082 ; IA32_LSTAR
○ rdmsr
○ eax+edx
○ wrmsr
Windows History
MS-DOS
● 1981 - 2000
● Real Mode
● Licensed 86-DOS to IBM
Windows 3.1
● Real mode no longer supported
● Introduced the Windows Registry
● First version to have command.com execute programs from GUI
Windows 95
● Compatible with 16-bit MS-DOS programs/drivers
● VxD in 32-bit protected mode
● Virtual real mode
OS/2
● Early IBM/Microsoft OS
○ Xenix Team
● command.com (MS-DOS Prompt) -> cmd.exe
● OS switches between protected and real mode
● Protected mode successor of DOS
● Legacy support = ETERNALBLUE
Windows NT
● "New Technology"
● Multi-user OS
○ Proper process isolation
● Kernel free of 16-bit relics
● VxD Replaced by NT Drivers
○ Now, standard WDM (Windows Driver Model) since Win 98/2000
Windows 10
● Hardened kernel
○ Major rollouts such as Redstone 1/2/3
● x64 Long Mode capability
○ Kernel full of 32-bit relics
● Drivers must be signed
● UAC
Windows Ecosystem
NT Boot Sequence
● winload.exe
○ core drivers
○ ntoskrnl.exe
■ Smss.exe
● Wininit.exe
○ Services.exe
○ lsass.exe
● Csrss.exe
○ winsrv.dll
○ win32k.sys
● winlogon.exe
○ explorer.exe
Executable .exe
Signature = PE\0\0
File Header
winnt.h
Optional Header
winnt.h
Optional Header (cont.)
winnt.h
PE DLLCharacteristics
winnt.h
PE Data Directories
winnt.h
Export Directory
Import Descriptor
PE Section
winnt.h
Common Names for Sections
● .text - code
● .data - variables
● .rdata - constant variables
● .pdata - exceptions
PE Subsystems
winnt.h
RVA vs. File Offset
● Many structs have fields called "Relative Virtual Address"
● This is an offset after the Windows loader runs
● What about on disk"
○ Have to loop sections
○ See if falls within base address
DLLs
Entry Point
BOOL WINAPI DllMain(
);
RunDLL Entry Point
void CALLBACK EntryPoint(
HWND hwnd,
HINSTANCE hinst,
LPSTR lpszCmdLine,
int nCmdShow
);
DLL Load Order
1. Program directory
2. Current working directory
3. System directory
4. Windows directory
5. Path directories
Proxy DLL (Load Order Hijacking)
Reserved DLL List
● HKLM\System\Current Control Set\Control\Session Manager\KnownDLLs
NTDLL.DLL
● Loaded into every process
○ Besides minimal/pico processes
○ LdrInitializeThunk()
● Compatibility layer
○ Most, but not all, functions forward here
○ API can be broken by Microsoft
■ No guarantees like Windows API
● Generally, must manually resolve functions
○ Many kernel32.dll directly "forward"
● Allows Microsoft to make breaking changes
● Rarely used by non-malicious programs
○ "Native API"
KERNEL32.DLL
● Basic Windows API functionality
○ LoadLibraryA()
○ CreateProcess()
● Mostly forwards directly to NTDLL
○ No breaking changes
● Loaded into most processes
ADVAPI.DLL
● Service control functions
○ OpenSCManager()
● Logon functions
○ LogonUser()
KERNELBASE.DLL
● Designed so some systems can support sub-functionality
● Moved functionality out of:
○ ADVAPI.DLL
○ KERNEL32.DLL
● Function calls are either:
○ Forwarders
○ Stubs
GDI32.DLL
● Video rendering/output
● Font management
● In .NET: System.Drawing
● GDI+
SHELL32.DLL
● Regsvr32 installation
○ DllInstall()
○ DllRegisterServer()
● Path functions
○ PathFileExists()
○ PathAppend()
● Shell functions
○ ShellExecute()
WS2_32.DLL
● Windows Sockets
● Networking functionality
USER32.DLL
● Windowing GUI functions
○ MessageBoxA()
● Timers
● IPC
DINPUT8.DLL
● Not really updated in some time
● Good DLL to proxy for hacking video games
○ Also get direct access to input functions
● https://github.com/zerosum0x0/dinput-proxy-dll
○ Complete reverse engineering of internal structs and vtables
AppInit_DLLs
● Local Hooks
● Global Hooks
● Registry keys
○ HKLM\SOFTWARE\Microsoft\Windows NT \CurrentVersion\Windows
■ LoadAppInit_DLLs
■ RequireSignedAppInit_DLLs
■ AppInit_DLLs
● https://www.apriorit.com/dev-blog/160-apihooks
Code/DLL Injection
DLL Injection
● Migrate to another process
● Common for game hacking
● Common for malware
● Some sorcery for advanced stuff
Basic DLL Injection
Basic DLL Injection Downsides
● Touches disk
● DLL shows up in PEB_LDR_DATA
○ EnumProcessModules()
○ CreateToolhelp32Snapshot() - TH32CS_SNAPMODULE, TH32CS_SNAPMODULE32
■ Module32First()
■ Module32Next()
DLL Unlink
● PEB_LDR_DATA
● Remove DLL from list
○ Flink
○ Blink
● Won't show up with user mode tools
○ Effectively "lost"
Native DLL Injection
● Uses NTDLL.DLL functions instead
○ NtWriteProcessMemory()
○ NtCreateThreadEx()
● Generally, more params, more work
● Attempt at obfuscation
Reflective DLL Injection
https://github.com/stephenfewer/ReflectiveDLLInjection
ReflectiveLoader()
1. Searches backward in memory for DOS MZ header
a. _ReturnAddress() intrinsic
2. Resolve functions from PEB
a. LoadLibraryA()
b. GetProcAddress()
c. VirtualAlloc()
d. NtFlushInstructionCache()
e. Metasploit: VirtualLock()
3. Emulate Windows Loader
a. Allocate memory for real DLL
b. Map sections according to PE headers
c. Fix up imports
4. Call DllMain()
Reflective DLL Injection Downsides
● Current techniques caught by EAF/IAF
○ Proposed bypass
● Sometimes imports additional required libraries into PEB
○ API Sets
■ api-ms-win-*.dll
■ ext-ms-win-*.dll
Inject DLL x86 -> x64
● QueueUserAPC()
● NtQueueApcThread()
● Shellcode sorcery
○ Transform
● /c/meterpreter/source/common/arch/win/i386/base_inject.c
ThreadContinue
● SetThreadContext()
○ Set remote thread's registers
○ Volatile registers not preserved
● NtContinue()
○ Set local thread's registers
○ Volatile registers preserved!
● Avoids CreateRemoteThread() and primitives
DEMO: threadcontinue
Atom Bombing
● Inject via "Atom Tables"
○ GlobalAddAtom()
○ GlobalGetAtomName()
■ write-what-where
● Queues an APC
○ NtQueueApcThread()
■ 3 parameters
● ROP chain
○ NtSetContextThread()
○ Allocate RWX memory
○ Copy shellcode from RW code cave
○ Execute
● Avoids WriteProcessMemory() and primitives
.NET Assembly Injection
● MSCOREE.DLL
○ CLRCreateInstance()
■ COM Object
■ Create .NET context in native land
● One per process
○ ExecuteInDefaultAppDomain()
■ Execute any CLR code
● https://blog.adamfurmanek.pl/2016/04/16/dll-injection-part-4/
Shim Engine / App Compat
● Backwards compatibility layer
● Increases Attack Surface
● User Shim Engine
○ shimeng.dll
● Kernel Shim Engine
Code Caves
Process Hollowing
Office Macros VBA
● Full access to WinAPI
● Load a DLL
○ Used by @hackerfantastic to "beat" Windows 10 S
Spoof Parent Process
● Vista+
○ CreateProcess() - LPPROC_THREAD_ATTRIBUTE_LIST
● XP and earlier
○ Inject a DLL...
Pre-Main Execution
C++ Instantiation of Global Object
● Constructors called before main
● On stack and heap
DEMO: IGO
TLS Callbacks
● Thread Local Storage
● Callbacks on thread execution
○ Including the main thread
DEMO: TLS
Inline Assembly
● __asm{};
● In x64, #include <intrin.h>
○ No naked functions
■ Generates prologues/epilogues
● Use clang or Intel compiler
Using 32-bit Registers on x64
● Good technique to shrink code size
○ No REX prefix byte (i.e. 0x48)
● Clear top 32 bits
DEMO: runshellcode
File System
File System and Filter Drivers
● Intercept most file I/O operations
● Often useful for hash-based AV
○ Log
○ Observe
○ Modify
○ Prevent
Alternate Data Streams
● Property of NTFS
○ Used for "dirty bit" of downloaded files
○ downloaded.file:Zone.Identifier
■ ZoneId=0: Local machine
■ ZoneId=1: Local intranet
■ ZoneId=2: Trusted sites
■ ZoneId=3: Internet
■ ZoneId=4: Restricted sites
● Commands:
○ type rootkit.exe > c:\windows\system32\fakelog.txt:rootkit.exe
○ start "c:\windows\system32\fakelog.txt:rootkit.exe"
■ XP--
○ mklink rootkit.exe c:\windows\system32\fakelog.txt:rootkit.exe
○ dir /r | findstr ":$DATA"
8dot3name
● Shortcut/autocomplete for paths
● C:\PROGRA~1\SOMEPA~1\SECOND~2\evil.dll
● Leads to tilde enum web vulnerabilities
Unquoted Service Paths
● Services that point to .exe
○ Have space in name
○ Do not use quotes
● Privilege escalation potential
○ Can hijack the .exe path
○ Service will run rogue .exe
UAC Bypasses
HKCU Trickery
● Medium integrity can write to HKCU
● Auto-elevating binaries
● eventvwr.exe by @enigma0x3
○ HKCU\Software\Classes\mscfile\shell\open\command
● sdclt.exe by @enigma0x3
○ HKCU\Software\Classes\exefile\shell\runas\command
● fodhelper.exe by winscripting.blog
○ HKCU\Software\Classes\ms-settings\shell\open\command
● UACME by @hFireF0X
○ Future work, 35+ methods
Stinger
● CIA Vault7/@tiraniddo
● Process:
○ Duplicate the token of an elevated process
○ Lower mandatory integrity level
○ Create a new restricted token
○ Impersonate
○ Secondary Logon service spawns a high IL process
Credential Theft
Asynchronous Keylogger
SHORT WINAPI GetAsyncKeyState(
_In_ int vKey
);
DEMO: asynclogger
Hook Keylogger
HHOOK WINAPI SetWindowsHookEx(
_In_ int idHook,
_In_ HOOKPROC lpfn,
_In_ HINSTANCE hMod,
_In_ DWORD dwThreadId
);
BOOLEAN PasswordFilter(
_In_ PUNICODE_STRING AccountName,
_In_ PUNICODE_STRING FullName,
_In_ PUNICODE_STRING Password,
_In_ BOOLEAN SetOperation
);
NTSTATUS PasswordChangeNotify(
_In_ PUNICODE_STRING UserName,
_In_ ULONG RelativeId,
_In_ PUNICODE_STRING NewPassword
);
Password Filters
● Enable password filters
● Modify registry (passfilter.bat)
● Reboot
● ClearText passwords captured
DEMO: passfilter
Inject winlogon.exe
● Inject a DLL into winlogon.exe
○ Keylogger
● Lock the workstation
DEMO: locklogger
MSGINA.DLL
● Graphical Identification and Authentication
● HKLM\SOFTWARE\Microsoft\Windows
NT\CurrentVersion\Winlogon\GinaDLL
● Older OS only
Winlogon Credential Providers
● Designed to implement 2FA etc.
● Implement one of two COM types
○ ICredentialProviderCredential
○ ICredentialProviderCredential2
● Fake Login Screen
○ Credential scraper!
Fake Logon Screen
● Credential Providers
○ Formerly MSGINA.DLL
● COM Objects
● Proxy real COM objects
○ Log password box
○ Forward to real COM
DEMO: fakelogon
Sekurlsa::logonPasswords
● Passwords stored obfuscated in LSASS.EXE
● Format changes with Windows versions
● SAMSRV.DLL
● GentilKiwi made Mimikatz
○ Parses these structures
● NotPetya
Credential Guard
● Opt-in
● Newer Mitigation
● LSASS memory untouchable
○ Hardware enforced
Print Screen
● Store clipboard data
● Emulate "Print Screen"
● Copy clipboard buffer
● Restore clipboard buffer
DEMO: printscreen
Screenshot
● Query screen device context
● Copy buffer to file
● GDI+
DEMO: screenshot
Function Hooking
Inline Hooks
● Intercept function calls
○ Overwrite prologue with jmp
● Trampolines
Raw Assembly Hook
● Patch first few bytes of function
● JMP rel
○ <2GB away, 5 bytes
● MOV reg, JMP reg
○ 12 bytes
● PUSH imm, RET
○ 12 bytes
● JMP [RIP + 0], imm
○ 14 bytes
● http://www.ragestorm.net/blogs/?p=107
DEMO: rawhook
Microsoft Detours
● Official function hooking library from Microsoft Research
● x64 is not free
Mhook
● http://codefromthe70s.org/mhook22.aspx
● Free support for x64
NTSTATUS DriverEntry(
_In_ struct _DRIVER_OBJECT *DriverObject,
_In_ PUNICODE_STRING RegistryPath
);
Driver Object
typedef struct _DRIVER_OBJECT {
PDEVICE_OBJECT DeviceObject;
PDRIVER_EXTENSION DriverExtension;
PUNICODE_STRING HardwareDatabase;
PFAST_IO_DISPATCH FastIoDispatch;
PDRIVER_INITIALIZE DriverInit;
PDRIVER_STARTIO DriverStartIo;
PDRIVER_UNLOAD DriverUnload;
PDRIVER_DISPATCH MajorFunction[IRP_MJ_MAXIMUM_FUNCTION+1];
} DRIVER_OBJECT, *PDRIVER_OBJECT;
I/O Request Packets (IRPs)
● The Driver Stack
○ The heart of all driver functionality
● I/O Manager
○ CreateFileA() -> IRP_MJ_CREATE
● Plug and Play
● Power Manager
Major Functions
IRP_MJ_CLEANUP
IRP_MJ_CLOSE
IRP_MJ_CREATE
IRP_MJ_DEVICE_CONTROL
IRP_MJ_FILE_SYSTEM_CONTROL
IRP_MJ_FLUSH_BUFFERS
IRP_MJ_INTERNAL_DEVICE_CONTROL
IRP_MJ_PNP
IRP_MJ_POWER
IRP_MJ_QUERY_INFORMATION
IRP_MJ_READ
IRP_MJ_SET_INFORMATION
IRP_MJ_SHUTDOWN
IRP_MJ_SYSTEM_CONTROL
IRP_MJ_WRITE
Nt vs. Zw
● Zw means nothing
● User Mode
○ NtReadFile == ZwReadFile
● Driver calls NtReadFile
○ Is previous mode user?
■ Extra checks
● Validation
● ProbeForRead()/ProbeForWrite()
● Driver calls ZwReadFile
○ Sets previous mode to kernel
■ Kernel components intrinsic trust
APC (Asynchronous Procedure Calls)
● Borrow a thread
○ Must be in an Alertable state
■ I.e. Sleeping
● Can be queued from kernel or user mode
● Useful for I/O completion
○ Queue back to initiator
DPC (Deferred Procedure Call)
● Each processor has a DPC Queue
● Useful to do work at a later time
○ Not a time critical function
● By definition: not a NT "thread"
IRQL
● Multi-layered interrupt priority system
● PASSIVE_LEVEL
○ User mode code, most kernel operations
● APC_LEVEL
○ During APCs, Page Faults
● DISPATCH_LEVEL
○ During DPCs, Thread Scheduler
○ Cannot be pre-empted
● DIRQL
○ Device interrupts
Filter Drivers
● File System Filters
○ Adds behavior to existing file system
■ Log
■ Observe
■ Modify
■ Prevent
● Minifilter
KMDF/UDMF
● KMDF
○ Higher-level interface to WDM
○ Not as powerful
● UMDF
○ Simpler to write/debug
■ No BSOD
○ Limited hardware interaction
■ USB
■ Firewire
Kernel Keyloggers
● Acting keyboard drivers
● Moderately difficult to write
● Moderately difficult to detect
Winsock Kernel (WSK)
● Network library for kernel mode
● Can be used for servers
○ HTTP.SYS
○ SRV.SYS
Thread Callback
NTSTATUS PsSetCreateThreadNotifyRoutine(
_In_ PCREATE_THREAD_NOTIFY_ROUTINE NotifyRoutine
);
void SetCreateThreadNotifyRoutine(
_In_ HANDLE ProcessId,
_In_ HANDLE ThreadId,
_In_ BOOLEAN Create
);
Process Callback
NTSTATUS PsSetCreateProcessNotifyRoutine(
_In_ PCREATE_PROCESS_NOTIFY_ROUTINE NotifyRoutine,
_In_ BOOLEAN Remove
);
void SetCreateProcessNotifyRoutine(
_In_ HANDLE ParentId,
_In_ HANDLE ProcessId,
_In_ BOOLEAN Create
);
IOCTLs
● Control a driver from usermode
○ "Packets"
■ Opcode
■ In buffer
■ Out buffer
● Drop to ring0
○ Perform some function
● Root of many driver vulnerabilities
○ IOCTL does something unsafe
■ User-mode memory
CAPCOM.sys
https://github.com/tandasat/ExploitCapcom
WINIO.sys
http://blog.rewolf.pl/blog/?p=1630
NTIOLib.sys
Process Lists
● At least 3 "known" process lists
○ ActiveProcessLinks
○ MmProcessLinks
○ SessionProcessLinks
● PatchGuard
○ Checks 4, 5, 26, 27: Type x process list corruption
DKOM
● EPROCESS List
○ Unlink (hide) process by changing Flink/Blink
DEMO: puppetstrings
Protected Processes
● At least 3 revisions so far
● Other user mode processes can't touch you
● EProcess.Flags2
○ ProtectedProcess - NT 6.0/6.1
Reflective Driver Injection
● Possible, no published generic techniques
● Nation-state malware kinda does this
● As we see, worth exploring
Nation-State Malware
Turla
● Turla APT
● First use of puppet strings?
○ Loaded vulnerable VirtualBox driver
○ Disabled driver signature enforcement
■ Inspiration for DSEFix project by @hfiref0x
sKyWIper/Flame
● Modular components with LUA
● Stored recon data in SQLite
● DLL Injection
○ ZwCreateSection()/ZwMapViewOfSection()
○ LoadLibraryA()/LoadLibraryEx()
■ AKA in PEB
■ Used RWX sections
● Fake audio driver
● Forged a MD5 Microsoft signature
PeddleCheap
● Equation Group/Shadow Brokers
● DoublePulsar/DanderSpritz
● DLL injection
○ NtCreateSection()/NtMapViewOfSection()
○ AKA in PEB
Hammertoss
● APT29
● Communication via Twitter
○ Generates new handle every day
● Steganography
○ In JPGs after JEOF
○ Hashtags containing offsets and decryption keys
● Replaced wermgr.exe
○ Persistence via app crashes
Biggest Non-Secret
● Nation-State Malware uses same lame techniques as all malware
○ Besides the 0-days