Pro Yearly is on sale from $80 to $50! »

Becks.io#5 Get start to Old Driver in Windows Kernel

33246db62d13c2b91289bff69c485822?s=47 NotSurprised
December 12, 2019

Becks.io#5 Get start to Old Driver in Windows Kernel

This talk will introduce the windows kernel driver architecture and dev & debug step, then share some driver problems that make PoE in last year.

33246db62d13c2b91289bff69c485822?s=128

NotSurprised

December 12, 2019
Tweet

Transcript

  1. NotSurprised @ Becks.io notsurprisedtw@gmail.com

  2. https://speakerdeck.com/notsurprised /becks-dot-io-number-5-get-start-to-old-driver-in-windows-kernel

  3. Intro • UCCU Hacker • AIS3 2016 trainee • SITCON

    2019 speaker • MOPCON 2019 speaker • ITRI Engineer (serve my country) • 5-years Bachelor & Master of NSYSU Email : notsurprisedtw@gmail.com > NotSurprised
  4. > • Windows Driver Background • Driver Compiling & Dev.

    & Dbg • Vul-Driver & PoE
  5. None
  6. > • Some malwares use device drivers to escalate privileges

    – VirtualBox CVE-2014-2477 • Device Drivers already present in some Red Team toolkits – Mimikatz uses a driver (mimidrv.sys) to facilitate injection
  7. > • Windows Driver Model (WDM) • Windows OS driver

    catalogues : – bus driver (e.g. USB, PCI) – function driver (e.g. USB Adaptor) – filter driver (e.g. Anti-Virus)
  8. > & • After Windows 7, Filter compiling was migrate

    into VS, and refracture WDF, Minifilter from WDM • Minifilter is more easier to compile that traditional Filter, dynamic install/attach/unload also the new feature for minifilter
  9. > • VXD (Virtual X Driver) – Windows 95、Windows 98

    • KDM (Kernel Driver Model) – Windows NT • WDM (Windows Driver Model) – Windows 2000 ~ Windows 8.1 – DDK (Driver Developer Kit) • WDF (Windows Driver Frameworks) – Windows 7 ~ Windows 10 – WDK (Windows Driver Kit)
  10. > • WDM • KMDF • WDDM • NDIS (miniport,

    filter, protocol) • WFP • Native 802.11 • WDI • FileSystem (MiniFilter) • PortCls • KS
  11. > Windows ~= Microkernel + LibOS ~= Monolithic Like source:

    Wikipedia
  12. > Applicaton Windows Servicce UserMode PnP Manager Setupapi.dll WMI Service

    WDM WMI Routine PnP Manager Power Manager I/O Manager function filter HAL ... ... .inf .cat registry I/O system Driver Kernel Mode User Mode
  13. > • Example, CreateFileA(); ProcessXXX.exe.CreateFileA() Kernel32.dll.CreateFileA() KERNELBASE.dll.CreateFileA() KERNELBASE.dll.CreateFileW() KERNELBASE.dll.CreateFileInternal() Ntdll.dll.NtCreateFile()

    Ntoskrnl.exe.KiFastSystemCall.NtCreateFile() Ntoskrnl.exe.KiSystemService.NtCreateFile() DriverXXX.sys.PreOperationCallback()
  14. > • In Windows OS kernel-mode is stack-like architecture, this

    kind Layered driver Architecture also been called Driver Stack. source : MSDN source: MSDN
  15. > Envuroment Subsystem/ Dlls I/O System Kernel Mode User Mode

    I/O Manager IRP header IRP stack location File Object Device Object Driver Object Start I/O Routine ISR DPC Routine Driver Entry & Dispatch Routine Unload Routine Create Read Write …
  16. > Envuroment Subsystem/ Dlls I/O System Kernel Mode User Mode

    I/O Manager IRP File System Manager Volumn Manager IRP source: The Windows 2000 Device Driver Book
  17. > Envuroment Subsystem/ Dlls I/O System Kernel Mode User Mode

    I/O Manager KMDF Manager I/O target KMDF DriverA KMDF DriverB KMDF DriverC KMDF0 / wdf01000.sys
  18. > Kernel Mode User Mode Reflector(Filter) Kernel Mode Driver Kernel

    Mode Driver Windows Kernel Driver Manager Applications Win32 API UMDF Driver UMDF Framework UMDF Runtime Reflector(Filter) Kernel Mode Driver UMDF Driver UMDF Framework UMDF Runtime UMDF Host Process UMDF Host Process Local Device Stack Local Device Stack WUDFx02000.dll UMDFCtrlDev
  19. > IRP FiDO FiDO FiDO FDO FiDO FiDO PDO Upper

    Filter Driver C Upper Filter Driver B Upper Filter Driver A Lower Filter Driver B Lower Filter Driver A Function Driver Bus Driver source: Windows Internals
  20. > • IRP(I/O Request Packets) work flow in Windows OS:

    source : MSDN Calculate drivers number and allocate IRP, then dispatcher to • WDF • function driver
  21. > Enviroment Subsystem/ Dlls I/O System Kernel Mode User Mode

    I/O Manager Filter Manager File System Manager File System Manager IRP IRP IRP MiniFilterDriverA MiniFilterDriverB MiniFilterDriverC 1. 2. 3. 4. 5. 6. 7.
  22. > • Extension Register • Kernel Dispatcher • CommunicationUK •

    Degree (Altitude) • Events • Handlers
  23. > Envuroment Subsystem/ Dlls I/O System Kernel Mode User Mode

    I/O Manager Filter Manager File System Manager File System Manager IRP IRP IRP MiniFilterDriverA MiniFilterDriverB MiniFilterDriverC 7. 6. 5. 4. 3. 2. 1.
  24. > • IRP (I/O Request Package) is a data structure

    in Windows kernel, it has been designed to store input/output data • IRP is a complicate data structurer, there’s 2 major attributes: MajorFunction & MinorFunction, which stand for IRP’s major type and type’s detail description • Same MajorFunction will present different behaviors with different MinorFunctions
  25. > • IRP_MJ_DIRECTORY_CONTROL • IRP_MJ_READ • IRP_MJ_WRITE • IRP_MJ_QUERY_INFORMATION •

    IRP_MJ_SET_INFORMATION • IRP_MJ_CREATE • IRP_MJ_CLEANUP • IRP_MJ_CLOSE • IRP_MJ_DEVICE_CONTROL • IRP_MJ_LOCK_CONTROL • IRP_MJ_SET_VOLUME_INFORMATION • IRP_MJ_QUERY_SECURITY • IRP_MJ_SET_EA • ……
  26. > • IRP_MJ_DIRECTORY_CONTROL • IRP_MJ_READ • IRP_MJ_WRITE • IRP_MJ_QUERY_INFORMATION •

    IRP_MJ_SET_INFORMATION • IRP_MJ_CREATE • IRP_MJ_CLEANUP • IRP_MJ_CLOSE • IRP_MJ_DEVICE_CONTROL • IRP_MJ_LOCK_CONTROL • IRP_MJ_SET_VOLUME_INFORMATION • IRP_MJ_QUERY_SECURITY • IRP_MJ_SET_EA • ……. FILE_CREATED FILE_DOES_NOT_EXIST FILE_EXISTS FILE_OPENED FILE_OVERWRITTEN (overwrite) FILE_SUPERSEDED (replace) FILE_ALLOCATION_INFORMATION FILE_BASIC_INFORMATION (insert、time、privilege) FILE_DISPOSITION_INFORMATION (delete) FILE_END_OF_FILE_INFORMATION FILE_LINK_INFORMATION FILE_POSITION_INFORMATION FILE_RENAME_INFORMATION (rename) FILE_VALID_DATA_LENGTH_INFORMATION
  27. > Oringinal IRP Filter Framework IRP source: MSDN source: MSDN

  28. > Write Buffer Prevent ransomware, we can use these information

    to compare entropy & sdhash
  29. > Use these information to determine file should be backup

    or not (size, position, format) source: MSDN
  30. None
  31. • After Microsoft publish minifilter framework, there also come up

    with WDM to WDF, Windows 7 to Windows 10. Microsoft migrate those develop framework into Visual Studio. Notice that there still lots version conflict problems • WDK installer can be downloaded from official website, SDK should be select to install during Visual Studio installing progress • Visual Studio 2017 & 2019 default not install SDK, need to select the checkbox • ARM/ARM64 > 、 、
  32. > SDK should fit WDK, but VS, SDK first

  33. >

  34. > 、 、

  35. > 、 、 • Dev. Env. Consistency

  36. > • Change target platform from [build setting] to [project

    -> driver settings]
  37. > • Change target platform from [build setting] to [project

    -> driver settings]
  38. > https://code.msdn.microsoft.com/windowsapps/Windows-Driver-Kit-WDK-81-cf35e953#content

  39. > There’s no printf() in kernel >.0

  40. >

  41. >

  42. > • cmd.exe (system administrator ) > bcdedit /set TESTSIGNING

    ON Enable by command
  43. >

  44. • 終於把檔案安裝進 System32\drivers 中 >

  45. > • driver.inf 安裝完成後的 driver 註冊表項

  46. > • 亦可使用 WinObj 檢查安裝成果。

  47. > Sample code problem.

  48. > In Virtual Machine

  49. > SERVICE_BOOT_START (0) SERVICE_SYSTEM_START (1) SERVICE_AUTO_START (2) SERVICE_DEMAND_START (3) SERVICE_DISABLED

    (4)
  50. > • SERVICE_BOOT_START (0) (DevieceDriverOnly) • SERVICE_SYSTEM_START (1) (DevieceDriverOnly) •

    SERVICE_AUTO_START (2) • SERVICE_DEMAND_START (3) • SERVICE_DISABLED (4)
  51. > Do not test driver on your host.

  52. None
  53. > • UTF16 encode : 魯 a = 9B 6F

    00 61 • ASCII encode : 9B 6F 00 61 = › o a String Type Description char *str = {"kd string"} ANSI string wchar_t *wstr = {L"kd string"} Unicode string size_t len = strlen(str) ANSI string len size_t wlen Unicode string len printf("%s %ws %d %d", str, wstr, len, wlen) print format OutputDebugString("%s", wstr) print format
  54. > C WDK unsigned long ULONG unsigned char UCHAR unsigned

    int UINT void VOID unsigned long * PULONG unsigned char * PUCHAR unsigned int* PUINT void * PVOID
  55. > HANDLE Event UNICODE_STRING ObjectName Length MaximumLength Buffer 4 byte

    2 byte 2 byte 4 byte HANDLE Event UNICODE_STRING ObjectName Length MaximumLength Padding Buffer 8 byte 2 byte 2 byte 4 byte 8 byte
  56. > • On Microsoft Windows 2000 and later versions of

    the operating system, "\??" is equivalent to "\DosDevices". • For example, the object name of the "C:\WINDOWS\example.txt" file is "\DosDevices\C:\WINDOWS\example.txt". Path Type Description \\abc\xyz MSDN C:\abc\xyz MSDN \\.\C:\abc\xyz MSDN \\?\C:\abc\xyz MSDN \\?\UNC\abc\xyz MSDN \??\UNC\abc\xyz MSDN ?\UNC\abc\xyz Undocumented in WindowsServer 2012 2016
  57. >

  58. Driver Entry create port > Push Block into port WDK

    SAMPLE : minispy.sys
  59. > Add data into Block Buffer

  60. > Call function to Kernel add IRP data into buffer

  61. > • User module User-mode extract data from communication port,

    according data structure in UK.h to split the data buffer
  62. > Filter Manager Read Write Rename Delete User mode Kernel

    mode I/O Manager Minispy(Kernel) File System Driver Physical Device Minispy(User) Storage Driver Stack MinispyUK.h
  63. > • Use Driver to change IRP content. • If

    need error message, deny it. Fake I/O
  64. > WDK SAMPLE : ObCallback.sys Register to sniffer Process create

    event Sniffer launch Process command
  65. > WDK SAMPLE : usbview.sys Enumerate USB Device

  66. > • csrss.exe -> NtCreateFile -> IRP_MJ_READ (Kbdclass) • WDK

    Sample: kbfiltr.sys
  67. None
  68. >

  69. >

  70. >

  71. >

  72. >

  73. > • Copy .pdb and add srv*c:\MyServerSymbols*https://msdl.microsoft.com/download/symbols to WinDBG symbol

    path.
  74. > • !analyze -v

  75. > • Windbg (Host) + VM (OS & Driver) +

    serial port
  76. > • bcdedit /debug on • bcdedit /dbgsettings serial debugport:{PortNumber}

    baudrate:{Number} • bcdedit /dbgsettings
  77. > • .sympath srv*c:\Symbols*http://msdl.microsoft.com/download/symbols;

  78. >

  79. >

  80. >

  81. >

  82. None
  83. • Windows drivers – Signed – WHQL signed – EV

    signing cert (A Must for Win10 signing process) > source: この勇者が俺TUEEEくせに慎重すぎる
  84. > • LoJax • Slingshot • MSI+ASUS+GIGABYTE+ASROCK

  85. > LoJax • First UEFI malware found in the wild

    • Implant tool includes RwDrv.sys driver from RWEverything • Loads driver to gain direct access to SPI controller in PCH • Uses direct SPI controller access to rewrite UEFI firmware
  86. > Slingshot • APT campaign brought along its own malicious

    driver • Active from 2012 through at least 2018 • Exploited other drivers with read/write MSR to bypass Driver Signing Enforcement to install kernel rootkit
  87. > • ASRock Drivers – CVE Name: • CVE-2018-10709, CVE-2018-10710,

    CVE-2018-10711, CVE-2018-10712 • ASUS Drivers – CVE Name: • CVE-2018-18537, CVE-2018-18536, CVE-2018-18535 • GIGABYTE Drivers – CVE Name: • CVE-2018-19320, CVE-2018-19322, CVE-2018-19323, CVE-2018-19321 • ......
  88. > ASROCK + ASUS + GIGABYTE • Arbitrary ring0 virtual

    memory read/write • Port mapped I/O access • MSR Register access • Arbitrary physical memory read/write • CR register access • ......
  89. > • Most drivers specify only the FILE_DEVICE_SECURE_OPEN characteristic. This

    ensures that the same security settings are applied to any open request into the device's namespace.
  90. source: apple daily

  91. >

  92. > Maybe FILE_DEVICE_SECURE_OPEN has been defined as 0?

  93. > source: 焼きたて!! ジャぱん

  94. >

  95. >

  96. > Windows Internal 7th Windows 7 Device Driver source: Tom

    and Jerry
  97. > • MinimumRequiredLength – The minimum buffer size, in bytes,

    that the driver needs to process the I/O request.
  98. > • Model specific registers (MSR) exist in CPUs. Contrary

    to the name, some MSRs are actually part of the official x86 or x64 architecture and not "model specific" • The transition to kernel-mode is done via an MSR – syscall -> read MSR -> call MSR pointer (Ring-0) -> kernel function handles the syscall logic • Default on modern systems we only care about MSR_LSTAR (0xc0000082) • Can inspect via rdmsr command in windbg
  99. > • You can probably see where this is going

    • Exposed wrmsr (__writemsr) instruction gives us a pointer to overwrite primitive – Function pointer is called when any syscall is issued – Called from Ring-0 source: Fireeye
  100. > source: Fireeye

  101. > source: Fireeye

  102. > • Win8+ Supervisor Mode Execution Prevention (SMEP) - BSODs

    if CPU detects execution of a user-mode VA while in Ring-0 • As a response to Spectre and Meltdown Microsoft added Kernel Page Table Isolation (KPTI), KPTI maintains a separate set of page tables for user- and kernel-mode EZ MODE ~Win8 SMEP Win8+ Spectre+Meltdown KPTI source: Fireeye
  103. None
  104. > • HyperV & PatchGuard catches MSR and CR3/CR4 modifications

    • Adding some sort of cookie check post-CR3 restoration could raise the bar – Require attackers to also have arbitrary kernel reads • More driver install notifications – Hardware drivers have confirmation prompts on install – but not software drivers? • Windows Driver Samples should import their security advises on MSDN
  105. > • Device Driver Debauchery and MSR Madness – Ryan

    Warns & Tim Harrison - FireEye • Get off the kernel if you can’t drive – Jesse Michael - DEFCON 27 • Reverse Engineering and Bug Hunting On KMDF Drivers – Enrique Nissim - IOActive • Windows Drivers Attack Surface – Ilja Van Sprundel • Windows Internals 6,7, MSDN – Microsoft • Practical Malware Analysis – Michael Sikorski & Andrew Honig
  106. None
  107. None
  108. > • 在 Win64,PatchGuard x64 一言不合就藍屏 Process/3rdAPI (wxWidgets.lib) Windows API

    System Service Dispatcher (KiSystemService) NtCreateFile SSDT User Mode Kernel Mode ntdll.dll NtClose P.S. 如何破解PatchGuard有一整串討論跟實作喔~
  109. 因為是載入 Driver,所以所調用的 Kernel API 時 Table 所指的記憶體位置並不確定 因此,直接用 Kernel 函數名稱取址並非其運行時

    Table 所指的記憶體位置 Hook 函數時需要另外使用 MmGetSystemRoutineAddress( ) 函數確切取得運行時記憶體位置 > • In Win32 System Service Dispatcher (KiSystemService) NtCreateFile SSDT User Mode Kernel Mode ntdll.dll NewCreateFile
  110. > • 根據函數名稱找到 SSDT 位址 • cli 關閉中斷(interrupt) • 關閉處理器寫入保護

    (0fffefffh取代CR0保護) • 改寫函數指標(pointer) • 復原處理器寫入保護 • sti 開啟中斷
  111. None
  112. > • Hold the shift while click reboot button. SHIFT

    One Time Solution source: Netflix
  113. > One Time Solution

  114. > • cmd.exe (system administrator ) > bcdedit /set TESTSIGNING

    ON Enable by command Inndy大神: 也可以在 Kernel 找到確切驗證位址後關掉
  115. > • I assume you build your own dirver already,

    if you try to use sign function within VS project, that’s another issue. • You should already have .cat, .sys & .inf (with sign function in VS, you will get your own usable .cer if you set it right.)
  116. > • MakeCert -r -pe -ss TEST -n "CN=TEST.org" test.cer

    > • CertMgr /add minispy.cer /s /r localMachine root • CertMgr /add minispy.cer /s /r localMachine trustedpublisher
  117. > • SignTool sign /v /s TestCertStoreName /n TestCertName /t

    http://timestamp.verisign.com/scripts/timstamp.dll DriverFileName.sys