Organization

This book is organized into four parts.

Though veteran researchers may be able to skim through topics at random, it's suggested that the book be read from beginning to end (given that later chapters tend to build upon earlier ones).

Part I – Foundations

Chapter 1 Setting the Stage

Chapter 2 Into the Catacombs: IA-32

Chapter 3 Windows System Architecture

Chapter 4 Rootkit Basics

Part I of this book focuses on prerequisite material. To an beginner who's eager to study more advanced topics, this may seem like a lot of ground to cover. These first four chapters will provide the conceptual basis you need to comfortably experiment with more sophisticated concepts later on.

Part II – System Modification

Chapter 5 Hooking Call Tables

Chapter 6 Patching System Routines

Chapter 7 Altering Kernel Objects

Chapter 8 Deploying Filter Drivers

Part II of the book examines how a rootkit can modify a system to undermine its normal operation. The discussion follows a gradual progression, starting with simple techniques and moving on to more complicated ones. In the end, the runtime state of a machine is made up of instructions and data. Patching a system with a rootkit boils down to altering either one or both of these constituents.

Anyone who has studied Gong Fu will tell you that for every attack there is a defense. Thus, each chapter concludes with a discussion of countermeasures that may be utilized by security software packages. When appropriate, this book examines ways to foil these countermeasures (i.e. counter-countermeasures, if you will).

Part III – Anti-Forensics

Chapter 9 Defeating Live Response

Chapter 10 Defeating File System Analysis

Chapter 11 Defeating Network Analysis

Chapter 12 Countermeasure Summary

On the battlefield, it’s essential to understand the vantage point of your adversary. Hence, Part III assumes the mindset of a forensic investigator. We look at various techniques that can be employed to unearth a rootkit and then examine the countermeasures that a rootkit might utilize to evade detection. In doing so, we end up borrowing many tactics which traditionally have been associated with viruses and other types of malware.

Part IV – End Material

Chapter 13 The Tao of Rootkit Implementation

Chapter 14 Closing Thoughts

Appendix

Part IV examines what might be referred to as macro issues. Specifically, the book discusses general strategies that transcend any particular software/hardware platform. I also provide an Appenidx with code listings so that you can scan through the examples without having to reference a secondary source.

Table of Contents

Preface: Meta-Data

The King’s New Body Armor

General Approach

Include an Adequate Review of Prerequisite Material
Keep the Book As Self-Contained As Possible
Demonstrate Ideas Using Modular Examples

Organization of the Book

Intended Audience

Conventions

Acknowledgements

Part I – Foundations

Chapter 1 Setting the Stage

Forensic Evidence

First Principles

Semantics
Rootkits: The Kim Philby of System Software
Who is Using Rootkit Technology?
The Feds
The Spooks
The Suits

The Malware Connection

Infectious Agents
Adware and Spyware
Rise of the Botnets
Malware versus Rootkits
Job Security: The Nature of the Software Industry

Closing Thoughts


Chapter 2 Into the Catacombs: IA-32

IA-32 Memory Models

Physical Memory
Flat Memory Model
Segmented Memory Model
Modes of Operation

Real Mode

Case Study: MS-DOS
Isn't this a Waste of Time? Why Study Real Mode?
The Real Mode Execution Environment
Real Mode Interrupts
Segmentation and Program Control
Case Study: Dumping the IVT
Case Study: Logging Keystrokes with a TSR
Case Study: Hiding the TSR
Case Study: Patching the TREE.COM command
Synopsis

Protected Mode

The Protected Mode Execution Environment
Protected Mode Segmentation
Protected Mode Paging
Protected Mode Paging: A Closer Look

Implementing Memory Protection

Protection through Segmentation
Limit Checks
Type Checks
Privilege Checks
Restricted Instruction Checks
Gate Descriptors
Protected Mode Interrupt Tables
Protection through Paging
Summary

Chapter 3 Windows System Architecture

Physical Memory

Physical Address Extension (PAE)
Data Execution Prevention (DEP)
Address Windowing Extensions (AWE)
Pages, Page Frames, and Page Frame Numbers

Memory Protection

Segmentation
Paging
Linear to Physical Address Translation
Long-Hand Translation
A Quicker Approach
Another Quicker Approach

Virtual Memory

User Space Topography
Kernel Space Dynamic Allocation
Address Space Layout Randomization (ASLR)

User-Mode & Kernel-Mode

How versus Where
Kernel-Mode Components
User-Mode Components

The Native API

The IVT Grows Up
Hardware and the System Call Mechanism
System Call Data Structures
The SYSENTER Instruction
The System Service Dispatch Tables
Enumerating the Native API
Nt*() versus Zw*() System Calls
The Life-Cycle of a System Call
Other Kernel-Mode Routines
Kernel-Mode API Documentation

The Boot Process

Startup for BIOS Firmware
Startup for EFI Firmware
The Windows Boot Manager
The Windows Boot Loader
Initializing the Executive
The Session Manager
Wininit.exe
Winlogon.exe
The Major Players

Design Decisions

How Will Our Rootkit Execute at Runtime
What Constructs Will Our Rootkit Manipulate

Chapter 4 Rootkit Basics

Rootkit Tools

Development Tools
Diagnostic Tools
Reversing Tools
Disk Imaging Tools
Tool Roundup

Debuggers

Configuring CDB.exe
Symbol Files
Windows Symbols
Invoking CDB.exe
Controlling CDB.exe
Useful Debugger Commands
Examine Symbols Command (x)
List Loaded Modules (lm and !lmi)
Display Type Command (dt)
Unassemble Command (u)
Display Commands (d*)
Registers Command (r)
The KD.exe Kernel Debugger
Different Ways to use a Kernel Debugger
Configuring KD.exe
Preparing the Hardware
Preparing the Software
Launching a Kernel-Debugging Session
Controlling the Target
Useful Kernel-Mode Debugger Commands
List Loaded Modules Command (lm)
!process
Registers Command (r)
Working with Crash Dumps
Method #1
Method #2
Crash Dump Analysis

A Rootkit Skeleton

Kernel-Mode Driver Overview
A Minimal Rootkit
Handling IRPs
DeviceType
Function
Method
Access
Communicating with User-Mode Code
Sending Commands from User-Mode
Source Code Organization
Performing a Build
WDK Build Environments
Build.exe

Loading A KMD

The Service Control Manager (SCM)
Using sc.exe at the Command Line
Using the SCM Programmatically
Registry Footprint
ZwSetSystemInformation()
Writing to the \Device\PhysicalMemory Object
Modifying Driver Code Paged to Disk
Leveraging an Exploit in the Kernel

Installing and Launching A Rootkit

Launched by the Operating System
Launched by a User-Mode Application
Use the SCM
Use an Auto-Start Extensibility Points (ASEP)
Install the Launcher as an Add-On to an Existing Application
Defense In-Depth
Kamikaze Droppers
Rootkit Un-Install

Self-Healing Rootkits

Auto-Update

Windows Kernel-Mode Security

Kernel-Mode Code Signing (KMCS)
Kernel Patch Protection (KPP)
Restricted Access to \Device\Physicalmemory

Synchronization

Interrupt Request Levels
Deferred Procedure Calls (DPCs)
Implementation

Commentary


Part II – System Modification

Chapter 5 Hooking Call Tables

Hooking in User-Space: The IAT

DLL Basics
Exported Routines
Load-Time Dynamic Linking
Run-Time Dynamic Linking
Injecting a DLL
The AppInit_DLLs Registry Value
The SetWindowsHookEx() API Call
Using Remote Threads
PE File Format
The DOS HEADER
RVAs
The PE Header
Walking a PE on Disk
Hooking the IAT

Hooking in Kernel-Space

Hooking the IDT
Handling Multiple Processors – Solution #1
Naked Routines
Issues with Hooking the IDT
Hooking Processor MSRs
Handling Multiple Processors – Solution #2
Hooking the SSDT
Disabling the WP Bit - Technique #1
Disabling the WP Bit - Technique #2
Hooking SSDT Entries
SSDT Example: Tracing System Calls
SSDT Example: Hiding a Process
SSDT Example: Hiding a Directory
SSDT Example: Hiding a Network Connection
Hooking IRP Handlers
Hooking the GDT – Installing a Call Gate

Hooking Countermeasures

Checking for Kernel-Mode Hooks
Checking for User-Mode Hooks
Parsing the PEB – Part I
Parsing the PEB – Part II

Counter-Countermeasures


Chapter 6 Patching System Routines

Binary Patching versus Runtime Patching
The Road Ahead

Runtime Patching

Detour Patching
Detour Jumps
Example-1 Tracing Calls
Detour Implementation
Acquire the Address of the NtSetValueKey()
Initialize the Patch Meta-Data Structure
Verify the Original Machine Code against a Known Signature
Save the Original Prolog and Epilog Code
Update the Patch Meta-Data Structure
Lock Access and Disable Write Protection
Inject the Detours
The Prolog Detour
The Epilog Detour
Post-Game Wrap-Up
Example-2 Subverting Group Policy
Detour Implementation
Initializing the Patch Meta-Data Structure
The Epilog Detour
Mapping Registry Values to Group Policies
Example-3 Granting Access Rights
Detour Implementation

Binary Patching

Subverting the Master Boot Record
The MBR In-Depth
The Partition Table
Patch or Replace?
Hidden Sectors
Bad Sectors and Boot Sectors
Rogue Partition
MBR Loader
IA-32 Emulation
Vbootkit

Instruction Patching Countermeasures


Chapter 7 Altering Kernel Objects

The Cost of Invisibility

Issue #1: The Steep Learning Curve
Issue #2: Concurrency
Issue #3: Portability and Pointer Arithmetic
Branding the Technique: DKOM
Objects?

Revisiting the EPROCESS Object

Acquiring an EPROCESS Pointer
Relevant Fields in EPROCESS
UniqueProcessId
ActiveProcessLinks
Token
ImageFileName

The DRIVER_SECTION Object

The Token Object

Authorization on Windows
Locating the Token Object
Relevant Fields in the Token Object

Hiding a Process

Hiding a Driver

Manipulating the Access Token

Using No-FU

Countermeasures

Cross View Detection
High-Level Enumeration: CreateToolhelp32Snapshot()
High-Level Enumeration: PID Bruteforce
Low-Level Enumeration: Processes
Low-Level Enumeration: Threads
Related Software
Field Checksums
Counter-Countermeasures

Commentary: Limits of the 2-Ring Model

The Last Lines of Defense


Chapter 8 Deploying Filter Drivers

Filter Driver Theory

Driver Stacks and Device Stacks
The Lifecycle of an IRP
Going Deeper: The Composition of an IRP
IRP Forwarding
IRP Completion

An Example: Logging Keystrokes

The PS/2 Keyboard Driver and Device Stacks
Lifecycle of an IRP
Implementation

Adding Functionality: Dealing with IRQLs

Dealing with the Elevated IRQL
Sharing Nicely: The Global Buffer
The Worker Thread
Putting It All Together

Key Logging: Alternative Techniques

SetWindowsHookEx
GetAsyncKeyState

Other Ways to Use Filter Drivers


Part III – Anti-Forensics

Chapter 9 Defeating Live Response

IDS, IPS, and Forensics
Anti-Forensics
Data Destruction
Data Hiding
Data Transformation
Data Contraception
Data Fabrication
File System Attacks

The Live Incident Response Process

The Forensic Investigation Process
Collecting Volatile Data
Performing a Port Scan
Collecting Nonvolatile Data
The Debate over Pulling the Plug
Countermeasures

RAM Acquisition

Software-Base Acquisition
KntDD.exe
Autodump+
LiveKd.exe
Crash Dumps
Hardware-Based Acquisition
Countermeasures

Chapter 10 Defeating File System Analysis

File System Analysis

Forensic Duplication
Recovering Deleted Files
Enumerating ADSes
Acquiring File Meta-Data
Removing Known Good Files
File Signature Analysis
Static Analysis of an Unknown Executable
Runtime Analysis of an Unknown Executable

Countermeasures: Overview

Countermeasures: Forensic Duplication

Reserved Disk Regions
Live Disk Imaging

Countermeasures: Deleted File Recovery

Countermeasures: Acquiring Meta-Data

Altering Timestamps
Altering Checksums

Countermeasures: Removing Known Files

Move Files into the “Known Good” List
Introduce “Known Bad” Files
Flood the system with Foreign Binaries
Keep off a List Entirely by Hiding
Out-of-Band Hiding
In-Band Hiding
Application Layer Hiding: M42

Countermeasures: File Signature Analysis

Countermeasures: Executable Analysis

Foiling Static Executable Analysis
Cryptors
Encryption Key Management
Packers
Augmenting Static Analysis Countermeasures
Foiling Runtime Executable Analysis
Attacks against the Debugger
Breakpoints
Detecting a User-Mode Debugger
Detecting a Kernel-Mode Debugger
Detecting a User-Mode or a Kernel-Mode Debugger
Detecting Debuggers via Code Checksums
Landmines
Obfuscation
Obfuscating Application Data
Obfuscating Application Code
The Hidden Price Tag

Borrowing Other Malware Tactics

Memory Resident Rootkits
Data Contraception
The Tradeoff: Footprint versus Failover

Chapter 11 Defeating Network Analysis

Worst Case Scenario: Full Content Data Capture

Tunneling: An Overview

HTTP
DNS
ICMP
Peripheral Issues

The Windows TCP/IP Stack

Windows Sockets 2
Raw Sockets
Winsock kernel API
NDIS
Different Tools for Different Jobs

DNS Tunneling

DNS Query
DNS Response

DNS Tunneling: User-Mode

DNS Tunneling: WSK Implementation

Initialize the Application’s Context
Create a Kernel-Mode Socket
Determine a Local Transport Address
Bind the Socket to the Transport Address
Set the Remote Address (the C2 Client)
Send the DNS Query
Receive the DNS Response

NDIS Protocol Drivers

Building and Running the NDISProt 6.0 Example
An Outline of the Client Code
An Outline of the Driver Code
The Protocolxxx() Routines
Missing Features

Chapter 12 Countermeasure Summary

Live Incident Response

File System Analysis

Network Traffic Analysis

Why Anti-Forensics?


Part IV – End Material

Chapter 13 The Tao of Rootkit Implementation

Run Silent, Run Deep

Development Mindset

On Dealing with Proprietary Systems

Staking Out the Kernel

Walk before You Run: Patching System Code

Walk before You Run: Altering System Data Structures

The Advantages of Self-Reliant Code

Leverage Existing Work

Use a Layered Defense

Study Your Target

Separate Mechanism from Policy


Chapter 14 Closing Thoughts


Appendix

Chapter 2

KillDOS
HookTSR
HideTSR
Patch

Chapter 3

SSDT

Chapter 4

Skeleton (Kernel-Mode Component)
Skeleton (User-Mode Component)
Installer
Hoglund
SD
HBEAT (Client and Server)
IRQL

Chapter 5

RemoteThread
ReadPE
HookIAT
HookIDT
HookSYSENTER
HookSSDT
HookIRP
HookGDT
AntiHook (Kernel-Space and User-Space)
ParsePEB

Chapter 6

TraceDetour
GPODetour
AccessDetour
MBR Disassembly
MBR Loader

Chapter 7

No-FU (User-Mode Portion)
No-FU (Kernel-Mode Portion)
TaskLister
findFU

Chapter 8

KiLogr-V01
KiLogr-V02

Chapter 10

TSMod
Slack
MFT
Cryptor

Chapter 11

UserModeDNS
WSK-DNS