Handle Tables & Object Manager

Objective:
Understand the role and internals of the Windows Object Manager, the structure and purpose of handle tables, kernel object creation and management, object security, and impersonation techniques. This knowledge is critical for reverse engineering, system analysis, kernel exploitation, and detection of privilege escalation and persistence techniques.


Introduction

Windows internally uses objects to represent resources—files, processes, threads, events, mutexes, semaphores, and more. The Object Manager is a kernel subsystem responsible for creating, managing, securing, and destroying these objects.

Each process maintains a private Handle Table, mapping numeric handles to kernel objects. Accessing these kernel objects securely and efficiently through handles is fundamental for Windows’ stability and security.

handle-tables-object-manager

Windows Object Manager Overview

The Object Manager (ntoskrnl.exe) manages:

  • Creation and deletion of kernel objects.
  • Object namespace management (hierarchical paths).
  • Security via Access Control Lists (ACLs).
  • Reference counting and lifetime management.

Common Kernel Objects

Object TypeDescription
ProcessExecuting program instance
ThreadUnit of execution within a process
FileRepresents open file or I/O device
EventSynchronization primitive
MutexMutual exclusion lock
SemaphoreSynchronization counter
TokenSecurity context (user privileges, groups)

Object Namespace

Kernel objects are structured hierarchically, similar to a file system:

Example paths:

\Device\HarddiskVolume1
\BaseNamedObjects\GlobalEvent

Use tools like WinObj (Sysinternals) to browse the object namespace.


Object Structures and Headers

Every object in kernel mode has a common header (OBJECT_HEADER) with metadata:

typedef struct _OBJECT_HEADER {
  LONG_PTR PointerCount;       // Number of active pointers
  LONG_PTR HandleCount;        // Active handle count
  PVOID    ObjectType;         // Pointer to OBJECT_TYPE structure
  PVOID    SecurityDescriptor; // ACL for the object
  UNICODE_STRING Name;         // Object name
  // ...
} OBJECT_HEADER;

This header precedes the actual object in memory.


Handle Tables

A Handle is an integer value referencing an object entry in a process-specific handle table.

  • Each process has its own handle table.
  • Maps handle values (integers) to pointers to kernel-mode objects.

Handle Table Entry (HANDLE_TABLE_ENTRY):

typedef struct _HANDLE_TABLE_ENTRY {
  union {
    PVOID Object;             // Pointer to actual object
    ULONG_PTR Attributes;
  };
  ACCESS_MASK GrantedAccess;  // Permissions for the handle
} HANDLE_TABLE_ENTRY;

Handle Tables allow controlled, indirect access to kernel objects.


Working with Handles (APIs)

Common APIs for working with handles:

API FunctionPurpose
OpenProcessGets a handle to an existing process
OpenThreadGets a handle to a thread
CreateFileOpens file/device handle
DuplicateHandleDuplicates existing handles
CloseHandleReleases the handle

Example (C++):

HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
CloseHandle(hProc);


NtQuerySystemInformation

A native NT API function that provides extensive system information.

NTSTATUS NtQuerySystemInformation(
  SYSTEM_INFORMATION_CLASS SystemInformationClass,
  PVOID                    SystemInformation,
  ULONG                    SystemInformationLength,
  PULONG                   ReturnLength
);

Common use:

  • Query process lists (SystemProcessInformation)
  • Handle information (SystemHandleInformation)

Example: Enumerating Handles

NtQuerySystemInformation(SystemHandleInformation, buffer, bufferSize, &returnedSize);

Enumerating Handles via PowerShell:

Get-Process | ForEach-Object {
  $_ | Select-Object -ExpandProperty Handles
}


Object Security & ACLs

Kernel objects include a Security Descriptor (SD):

  • Owner SID
  • Group SID
  • DACL (Discretionary ACL): who has access
  • SACL (System ACL): audit events on access

Example: Changing ACL via WinAPI:

SetSecurityInfo(hFile, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, pNewDacl, NULL);

Audit ACLs with:

Get-Acl '\\.\pipe\mypipe'


Object Reference Counting

Objects have two counters:

  • Handle Count: Number of handles referencing it.
  • Pointer Count: Direct kernel pointers referencing it.

When both reach zero, the object is destroyed automatically.


Kernel Objects and Impersonation

Windows supports Security Impersonation, allowing threads to execute with another user’s security context (token).

Impersonation Levels:

  • Anonymous: No identification.
  • Identification: Identity check only.
  • Impersonation: Access local resources as the impersonated user.
  • Delegation: Access remote resources as impersonated user.

Impersonation APIs:

  • ImpersonateLoggedOnUser
  • ImpersonateNamedPipeClient
  • SetThreadToken

Example Impersonation:

LogonUser(user, domain, pass, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, &hToken);
ImpersonateLoggedOnUser(hToken);
// Thread now has user privileges

Attackers exploit impersonation by stealing tokens from privileged processes (Token stealing via handle duplication).


Handle Duplication for Privilege Escalation

Attackers commonly duplicate high-privilege handles:

Example exploitation flow:

  1. Open a privileged process handle (OpenProcess).
  2. Duplicate its token (DuplicateHandle).
  3. Assign the duplicated token to the current process (SetThreadToken or SetTokenInformation).

Detection via Sysmon (Event ID 10 – ProcessAccess).


Common Attacker Techniques

TechniqueDescription
Handle HijackingDuplicate handles to privileged processes
Object ACL AbuseModify ACLs of kernel objects
Named Object HijackingHijack named objects (events/mutexes)
Kernel Object LeaksLeaking kernel object addresses

Defensive Strategies & Detection

Sysmon (Process Access Monitoring):

  • Track unusual handle duplications:
Sysmon Event ID 10: PROCESS_ACCESS

Handle & Object Auditing:

  • Use Process Hacker or Process Monitor.
  • Enumerate handles periodically for anomalies.

Object ACL Hardening:

  • Reduce unnecessary write permissions.
  • Regularly audit ACLs on critical named objects.

Tools for Handle & Object Analysis

ToolDescription
WinObjBrowse kernel object namespace (Sysinternals)
Process HackerReal-time handle/object analysis
handle.exeSysinternals command-line handle viewer
Process MonitorFile, registry, and handle monitoring
VolatilityForensic memory object & handle analysis

Example handle enumeration (handle.exe):

handle.exe -p 1234


Summary

  • Windows Object Manager controls lifecycle, security, and naming of kernel objects.
  • Each process has a handle table, mapping handles to kernel objects securely.
  • NtQuerySystemInformation provides detailed handle and object insights.
  • Impersonation techniques allow threads to execute with alternative user privileges.
  • Attackers leverage handle duplication and impersonation for privilege escalation.
  • Defensive controls include Sysmon monitoring, ACL auditing, and continuous handle enumeration.

Memory Management Internals

Objective:
Understand the internal architecture and functionality of Windows memory management, including virtual memory, physical memory mappings, distinctions between stack and heap allocations, and memory management concepts such as working sets, committed versus reserved memory. This knowledge is essential for reverse engineering, exploit development, malware analysis, and system performance optimization.


Introduction

Windows uses advanced virtual memory management to efficiently handle application and system memory. Understanding how Windows manages memory—from virtual addresses to physical memory mappings—enables better performance tuning, troubleshooting memory leaks, analyzing malware behaviors, and performing memory-based exploit development.

memory-management

Memory Management Overview

Windows memory management involves:

  • Virtual Address Space (VAS)
  • Physical Memory (RAM)
  • Paging and Page Tables
  • Heap and Stack allocations
  • Working Sets
  • Commit and Reserve

Virtual Memory Layout

Each Windows process has a unique virtual address space, typically:

  • User-mode space: Lower addresses (e.g., 0x00000000–0x7FFFFFFF on 32-bit; 0x0000000000000000–0x00007FFFFFFF on 64-bit)
  • Kernel-mode space: Higher addresses (e.g., 0x80000000–0xFFFFFFFF on 32-bit; 0xFFFF800000000000–0xFFFFFFFFFFFFFFFF on 64-bit)

x64 Windows Layout:

+------------------------------+ 0xFFFFFFFFFFFFFFFF
|      Kernel-mode space              |
+------------------------------+ 0xFFFF800000000000
|           Unused                              |
+------------------------------+ 0x00007FFFFFFFFFFF
|      User-mode space                 |
+------------------------------+ 0x0000000000000000


Stack vs Heap

Applications allocate memory using two main methods: Stack and Heap.

Stack

  • LIFO (Last In, First Out) data structure.
  • Used for function calls, local variables, return addresses.
  • Fixed-size, determined at thread creation (default ~1MB/thread).
  • Stack overflow occurs when usage exceeds allocated stack space.

Example stack allocation (automatic):

int foo() {
    int a = 10; // Stack allocated
    return a;
}

Heap

  • Flexible, dynamically-sized region.
  • Managed explicitly by malloc(), HeapAlloc(), new, VirtualAlloc().
  • Fragmentation can occur over time.

Example heap allocation (manual):

int* arr = (int*)malloc(10 * sizeof(int));


Working Sets

The Working Set is a set of physical memory pages currently used by a process.

  • Windows tracks per-process working sets.
  • Working sets dynamically change based on usage.
  • Windows trims working sets under memory pressure.

Use Task Manager or Process Explorer to examine Working Sets:

  • Private Working Set: memory exclusive to a process.
  • Shareable Working Set: memory shared between processes.

Inspect via PowerShell:

Get-Process | Select Name, WorkingSet, PagedMemorySize, PrivateMemorySize


Commit vs Reserve

When an application allocates virtual memory, Windows allows two different states:

Reserved Memory

  • Reservation of virtual address range without allocating physical memory or paging file.
  • Not usable until committed.
  • Used to ensure contiguous memory availability for future use.

Committed Memory

  • Backed by physical RAM or paging file.
  • Usable immediately by applications.
  • Counts against system commit limit.

Example (C++):

// Reserve virtual memory
LPVOID reserved = VirtualAlloc(NULL, 4096, MEM_RESERVE, PAGE_READWRITE);

// Commit reserved memory
LPVOID committed = VirtualAlloc(reserved, 4096, MEM_COMMIT, PAGE_READWRITE);


Paging and Page Tables

Windows uses paging to map virtual addresses to physical addresses.

  • Page size typically 4KB.
  • Uses Multi-level page tables (x64: PML4 → PDPT → PD → PT).
  • On access violation (page fault), Windows loads the requested page from disk if available (paging).

Example of Page Fault Handling:

  • A program references an address not in RAM.
  • CPU raises a page fault.
  • Windows kernel fetches the page from disk or allocates memory.
  • Instruction is retried.

Memory Protection & Permissions

Each page has memory protection attributes:

  • PAGE_EXECUTE_READWRITE: executable, readable, writable (often abused by malware)
  • PAGE_READONLY: read-only
  • PAGE_NOACCESS: no access permitted

Example memory permission change:

DWORD oldProtect;
VirtualProtect(address, size, PAGE_EXECUTE_READWRITE, &oldProtect);


Heap Internals

Windows provides several heaps per process:

  • Default Process Heap: created automatically at startup (GetProcessHeap()).
  • Private Heaps: created explicitly (HeapCreate()).

Heap allocations are tracked via internal heap structures:

  • Heap headers: track size, flags.
  • Heap fragmentation: caused by frequent allocations/deallocations.

Tools like WinDbg or !heap extension allow analysis of heap internals:

!heap -s          ; Summary of heaps
!heap -h 0xAddr   ; Analyze specific heap


Stack Internals

  • Each thread gets its own stack.
  • Stack grows downward (high → low addresses).
  • Stack Pointer (ESP/RSP) tracks current stack top.

Typical stack frame (x64):

+------------------------+
| Local Variables                 |
+------------------------+
| Saved Registers               |
+------------------------+
| Return Address                |
+------------------------+
| Function Parameters       |
+------------------------+


Memory Management APIs & Tools

Common Memory APIs:

FunctionPurpose
VirtualAllocReserve/commit virtual pages
VirtualFreeRelease/decommit memory
HeapAllocAllocate heap memory
HeapFreeFree heap memory
RtlAllocateHeapNT heap allocation API

Memory Analysis Tools:

  • VMMap: Detailed virtual memory analysis.
  • RAMMap: Physical memory usage inspection.
  • Process Hacker: Real-time memory allocation inspection.
  • WinDbg: In-depth debugging and analysis.

Malware and Exploit Use Cases

TechniqueAbuse Scenario
Heap SprayPreparing predictable memory layout for exploitation
Stack OverflowOverwriting return addresses for RCE
ROP GadgetsExecuting chained snippets of legitimate code in stack
Code InjectionAllocating executable memory (PAGE_EXECUTE_READWRITE)
Shellcode LoadingUsing VirtualAlloc/VirtualProtect to execute payloads

Memory Forensics & Detection

  • Use Volatility Framework for memory forensics:
volatility -f memory.dmp pslist
volatility -f memory.dmp malfind

  • Monitor abnormal allocations (PAGE_EXECUTE_READWRITE pages) with Sysmon:
Sysmon Event ID 10 (ProcessAccess)


Summary

  • Windows manages memory through complex virtual-to-physical mapping.
  • Stack is used for automatic, function-local allocations.
  • Heap handles dynamic memory, manually managed by developers.
  • Working Sets optimize performance and memory efficiency.
  • Commit and Reserve control memory usage strategy.
  • Understanding these internals enables effective memory forensics, exploit development, and performance tuning.

Threads and the TEB (Thread Environment Block)

Objective: Understand the internal workings of threads on Windows, the lifecycle of a thread from creation to termination, the critical role of the Thread Environment Block (TEB), and fundamentals of thread injection techniques. This foundational knowledge is crucial for system developers, reverse engineers, malware analysts, and red teamers.


Introduction

A thread is the smallest execution unit within a process on Windows, scheduled independently by the OS kernel. Every process contains at least one thread, but often many more. Each thread maintains its own state, CPU registers, stack, and local storage.

Central to each thread’s operation is the Thread Environment Block (TEB), a user-mode structure containing thread-specific data critical for thread execution, error handling, exception handling, and system call interfacing.

TEB

Thread Lifecycle

A typical thread undergoes these stages:

Creation → Scheduling → Execution → Waiting/Blocking → Termination

Detailed Steps:

  • Creation:
    Initiated via APIs like:
    • CreateThread()
    • RtlCreateUserThread()
    • NtCreateThreadEx()
  • Scheduling (Kernel):
    Windows uses priority-based preemptive scheduling:
    • Quantum: Thread time-slice allocated for execution.
    • Threads can have different priority levels (0 to 31).
  • Execution (User-Mode):
    Execution starts at thread entry function (LPTHREAD_START_ROUTINE).
  • Waiting/Blocking:
    Threads often enter waiting states (WaitForSingleObject(), Sleep(), I/O waits).
  • Termination:
    Ends via:
    • Returning from thread function
    • Calling ExitThread()
    • Termination by another thread (TerminateThread() – unsafe)

Thread Environment Block (TEB)

Each thread has a unique TEB, accessed quickly via the FS:[0x18] register on x86 or GS:[0x30] on x64.

Key TEB fields:

typedef struct _TEB {
    NT_TIB NtTib;
    PVOID  EnvironmentPointer;
    CLIENT_ID ClientId;           // Unique Thread ID and Process ID
    PVOID  ActiveRpcHandle;
    PVOID  ThreadLocalStoragePointer;
    PPEB   ProcessEnvironmentBlock; // Pointer to the PEB
    ULONG  LastErrorValue;
    ULONG  CountOfOwnedCriticalSections;
    PVOID  Win32ThreadInfo;
    ULONG  CurrentLocale;
    ULONG  FpSoftwareStatusRegister;
    // ... (more fields)
} TEB;

Notable Fields Explained:

  • ClientId: Contains the thread’s TID and owning PID.
  • ProcessEnvironmentBlock (PEB): Points to the process-wide PEB structure.
  • ThreadLocalStoragePointer: Points to thread-local storage (TLS).
  • LastErrorValue: Stores the last error value (GetLastError()).
  • NtTib: Contains:
    • Stack Base (StackBase)
    • Stack Limit (StackLimit)
    • Exception handler list

Accessing the TEB (x64):

mov rax, gs:[0x30] ; RAX now contains TEB pointer


Thread Creation APIs (Detailed)

1. CreateThread()

Commonly used high-level API:

HANDLE CreateThread(
  LPSECURITY_ATTRIBUTES lpThreadAttributes,
  SIZE_T dwStackSize,
  LPTHREAD_START_ROUTINE lpStartAddress,
  LPVOID lpParameter,
  DWORD dwCreationFlags,
  LPDWORD lpThreadId
);

2. NtCreateThreadEx() (Native)

Lower-level, flexible NTAPI:

NTSTATUS NtCreateThreadEx(
  PHANDLE ThreadHandle,
  ACCESS_MASK DesiredAccess,
  POBJECT_ATTRIBUTES ObjectAttributes,
  HANDLE ProcessHandle,
  PVOID StartRoutine,
  PVOID Argument,
  ULONG CreateFlags,
  SIZE_T ZeroBits,
  SIZE_T StackSize,
  SIZE_T MaximumStackSize,
  PVOID AttributeList
);

  • Powerful for cross-process thread injection.

Thread Injection Basics

Thread injection is a fundamental technique in malware development and red teaming, allowing execution of code in a remote process.

Thread Injection Workflow:

  1. Obtain Handle:
    OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
  2. Allocate Memory:
    VirtualAllocEx(hProc, ...)
  3. Write Payload:
    WriteProcessMemory(hProc, remoteMemory, ...)
  4. Create Remote Thread:
    CreateRemoteThread(hProc, ..., remoteMemory, ...)

Simplified Example (Remote Thread Injection):

// Open handle to target process
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);

// Allocate memory
LPVOID remoteMemory = VirtualAllocEx(hProcess, NULL, payloadSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);

// Write payload (shellcode or DLL loader)
WriteProcessMemory(hProcess, remoteMemory, payload, payloadSize, NULL);

// Start remote thread execution
CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)remoteMemory, NULL, 0, NULL);


Common Thread Injection Techniques

TechniqueDescription
CreateRemoteThreadDirect injection of threads into another process
NtCreateThreadExMore advanced version of CreateRemoteThread
QueueUserAPCInjecting asynchronous procedure calls
SetThreadContextHijacking an existing thread’s execution context

Detection and Analysis of Thread Injection

Indicators:

  • Suspicious CreateRemoteThread() calls targeting unexpected processes
  • Memory allocated (VirtualAllocEx) with execute permissions (PAGE_EXECUTE_READWRITE)
  • Threads created by processes other than expected parent processes

Tools for Detection:

  • Sysmon (Event ID 8: CreateRemoteThread)
  • Process Hacker, Process Monitor
  • API hooking (EDR solutions)
  • Memory scanners (Volatility, Rekall)

Thread Hijacking via TEB Manipulation (Advanced)

Malware can directly manipulate the TEB to hijack threads:

  • Overwrite TEB’s stack pointers or exception handlers
  • Intercept thread execution flow

Example (x64 Assembly):

mov rax, gs:[0x30]    ; TEB base
mov [rax+0x8], myStackBase   ; overwrite StackBase
mov [rax+0x10], myStackLimit ; overwrite StackLimit

This is advanced and dangerous but illustrates TEB exploitation potential.


Forensics and Incident Response Tips

  • Collect thread information during IR investigations:
Get-Process -Id $PID | Select -Expand Threads

  • Dump TEB structures and thread contexts with WinDbg or volatility.
  • Watch for abnormal thread creations in unexpected processes or sudden thread terminations.

Summary

  • Threads are fundamental units of execution managed by Windows.
  • Each thread maintains critical data in the TEB structure.
  • Threads can be created, injected, and manipulated by advanced APIs.
  • Injection techniques are commonly abused by malware and red teams.
  • Detection relies on system-level monitoring (Sysmon, API hooks).

Windows Process Creation Internals & PEB

Objective: Deeply understand how Windows creates new processes, detailing the internal workings of the CreateProcess API, kernel object management, memory mapping, and the structure and role of the Process Environment Block (PEB). This is essential knowledge for analyzing and understanding malware behavior, reverse engineering, and advanced debugging.


Introduction

Process creation on Windows is a sophisticated, multi-step procedure involving extensive kernel and user-mode coordination. At the center of this operation is the CreateProcess() API, which initializes process structures, allocates memory, maps executables, and prepares environment variables.

Each Windows process also maintains a Process Environment Block (PEB), a crucial data structure that contains runtime information about the loaded modules, command-line arguments, and more. The PEB is frequently leveraged by attackers and defenders for various advanced techniques.

Windows-Process-Creation

High-Level CreateProcess Flow

The general steps when calling CreateProcess():

  1. User-mode API Call:
    Application invokes kernel32!CreateProcessW or similar.
  2. Kernel Transition (ntdll):
    CreateProcessW invokes ntdll!NtCreateUserProcess.
  3. Kernel Mode Initialization (ntoskrnl):
    • Kernel creates EPROCESS object.
    • Initializes Virtual Address Descriptor (VAD) structures.
    • Maps ntdll.dll into new process address space.
  4. PE File Loading:
    • PE loader maps executable image sections.
    • Resolves imports and relocations.
    • Sets initial execution context (thread, stack, registers).
  5. Subsystem Notification (CSRSS):
    • Subsystem server creates structures for console/GUI.
  6. Initial Thread Execution:
    • Execution begins at the AddressOfEntryPoint.

Detailed Step-by-Step Flow

Step 1: User-mode API Invocation

When an application wants to start a new process, it uses:

BOOL CreateProcessW(
  LPCWSTR lpApplicationName,
  LPWSTR  lpCommandLine,
  LPSECURITY_ATTRIBUTES lpProcessAttributes,
  LPSECURITY_ATTRIBUTES lpThreadAttributes,
  BOOL    bInheritHandles,
  DWORD   dwCreationFlags,
  LPVOID  lpEnvironment,
  LPCWSTR lpCurrentDirectory,
  LPSTARTUPINFO lpStartupInfo,
  LPPROCESS_INFORMATION lpProcessInformation
);

This call eventually resolves down to an NTDLL syscall:

NtCreateUserProcess(&ProcessHandle, &ThreadHandle, ..., &ProcessParameters, ...);

Step 2: Kernel-side Initialization

Kernel (ntoskrnl) creates key kernel structures:

  • EPROCESS: Process kernel object
  • ETHREAD: Initial thread kernel object
  • VAD Tree: Virtual Address Descriptors for memory management
  • Initializes security tokens and handles

Step 3: PE Image Loading

Kernel PE loader:

  • Maps PE executable sections (.text, .data, etc.) into memory.
  • Handles relocations and import resolutions (IAT resolution).
  • Initializes the stack, heap, and default libraries (ntdll.dll).

Step 4: User-mode initialization (ntdll)

Upon kernel returning control, ntdll.dll runs user-mode initializations:

  • Executes TLS (Thread Local Storage) callbacks
  • Sets up user-mode stack and heap structures
  • Runs CRT (C Runtime) initialization (mainCRTStartup)

Step 5: Subsystem Initialization (CSRSS)

  • Windows subsystem (csrss.exe) notified to handle GUI or console session management.

Step 6: Main Thread Execution

  • Execution control transferred to the PE file’s AddressOfEntryPoint.

Process Environment Block (PEB)

The PEB is a crucial process structure located in user mode memory (fs:[0x30] on 32-bit, gs:[0x60] on 64-bit Windows).

typedef struct _PEB {
    BYTE Reserved1[2];
    BYTE BeingDebugged;
    BYTE Reserved2[1];
    PVOID Reserved3[2];
    PPEB_LDR_DATA Ldr;                // Loaded modules
    PRTL_USER_PROCESS_PARAMETERS ProcessParameters; // Command-line, env
    BYTE Reserved4[104];
    PVOID Reserved5[52];
    PPS_POST_PROCESS_INIT_ROUTINE PostProcessInitRoutine;
    BYTE Reserved6[128];
    ULONG SessionId;
} PEB, *PPEB;

Key Fields:

  • BeingDebugged: Indicates if a debugger is attached.
  • Ldr: Contains loaded module information (PEB_LDR_DATA).
  • ProcessParameters: Command line, environment variables, startup directory, window settings.

PEB_LDR_DATA Structure

This structure points to the loaded modules (DLLs) in the process:

typedef struct _PEB_LDR_DATA {
  ULONG Length;
  BYTE Initialized;
  PVOID SsHandle;
  LIST_ENTRY InLoadOrderModuleList;
  LIST_ENTRY InMemoryOrderModuleList;
  LIST_ENTRY InInitializationOrderModuleList;
  PVOID EntryInProgress;
} PEB_LDR_DATA, *PPEB_LDR_DATA;

These linked lists (InLoadOrderModuleList, etc.) contain information about every DLL mapped into the process memory, crucial for module enumeration.


RTL_USER_PROCESS_PARAMETERS Structure

Contains the runtime parameters of the process:

typedef struct _RTL_USER_PROCESS_PARAMETERS {
    ULONG MaximumLength;
    ULONG Length;
    ULONG Flags;
    ULONG DebugFlags;
    HANDLE ConsoleHandle;
    ULONG ConsoleFlags;
    HANDLE StandardInput;
    HANDLE StandardOutput;
    HANDLE StandardError;
    UNICODE_STRING CurrentDirectoryPath;
    HANDLE CurrentDirectoryHandle;
    UNICODE_STRING DllPath;
    UNICODE_STRING ImagePathName;      // Path to the executable
    UNICODE_STRING CommandLine;        // Process arguments
    PVOID Environment;                 // Environment block
    ULONG StartingX;
    ULONG StartingY;
    ULONG CountX;
    ULONG CountY;
    ULONG CountCharsX;
    ULONG CountCharsY;
    ULONG FillAttribute;
    ULONG WindowFlags;
    ULONG ShowWindowFlags;
    UNICODE_STRING WindowTitle;
    UNICODE_STRING DesktopInfo;
    UNICODE_STRING ShellInfo;
    UNICODE_STRING RuntimeData;
    RTL_DRIVE_LETTER_CURDIR CurrentDirectories[32];
    ULONG EnvironmentSize;
} RTL_USER_PROCESS_PARAMETERS, *PRTL_USER_PROCESS_PARAMETERS;

Common Malware & Defense Uses of PEB

Malware Uses:

  • Anti-debugging: Check BeingDebugged flag.
  • Module hiding: Manipulate PEB_LDR_DATA to hide loaded DLLs from tools like Process Explorer or debuggers.
  • Process injection: Read remote process PEB to locate modules and perform injection.

Defense Uses:

  • Forensics: Analyzing PEB structures to detect hidden modules or unusual command-line arguments.
  • Behavioral detection: Monitoring PEB accesses can indicate stealthy operations (like hiding loaded modules).

Practical Inspection of PEB

WinDbg Commands:

  • Inspect PEB:
!peb
  • View loaded modules:
lm
  • Dump PEB structure directly:
dt _PEB @$peb

Summary

  • Process creation (CreateProcess) is complex, involving kernel and user-mode coordination.
  • Key kernel objects (EPROCESS, ETHREAD) manage process lifecycle and resources.
  • The PEB contains vital runtime details and is heavily utilized by both malware and security tools.
  • Deep understanding aids in reverse engineering, malware analysis, and debugging.

PE File Format Deep Dive

Objective: Understand the internal structure of Windows Portable Executable (PE) files, including the DOS and NT headers, section table, and directory structures like the Import and Export Address Tables. This is foundational for reverse engineering, malware analysis, loader development, and shellcode injection.


Introduction

The PE (Portable Executable) format is the standard executable file format on Windows for .exe, .dll, .sys, .cpl, .ocx, and other binaries. It is based on the Common Object File Format (COFF) and is loaded and interpreted by the Windows PE loader.

The PE format is extremely modular and extensible, enabling the OS to map, load, resolve, and execute code with precision.


PE File Layout Overview

A PE file is a binary file with multiple headers, sections, and data directories. At a high level, it consists of:

+-----------------------------+
| MS-DOS Header (IMAGE_DOS_HEADER)
| MS-DOS Stub Program
+-----------------------------+
| PE Signature ("PE\0\0")
| COFF File Header (IMAGE_FILE_HEADER)
| Optional Header (IMAGE_OPTIONAL_HEADER)
+-----------------------------+
| Section Headers (IMAGE_SECTION_HEADER[])
+-----------------------------+
| Sections (.text, .data, .rdata, .rsrc, etc.)
+-----------------------------+

Let’s break down each of these components.


1. MS-DOS Header

Struct: IMAGE_DOS_HEADER
Size: 64 bytes

  • Legacy compatibility with MS-DOS (displays “This program cannot be run in DOS mode.”)
  • Key field: e_lfanew – offset to the PE Signature
typedef struct _IMAGE_DOS_HEADER {
  WORD   e_magic;      // "MZ"
  WORD   e_cblp;
  ...
  LONG   e_lfanew;     // Offset to PE header
} IMAGE_DOS_HEADER;


2. PE Signature

  • Always located at offset e_lfanew
  • 4-byte signature: "PE\0\0" or 0x00004550 (little endian)
  • Followed by the COFF File Header

3. COFF File Header (IMAGE_FILE_HEADER)

Defines characteristics of the executable.

typedef struct _IMAGE_FILE_HEADER {
  WORD  Machine;             // e.g., 0x8664 for x64
  WORD  NumberOfSections;
  DWORD TimeDateStamp;
  DWORD PointerToSymbolTable;
  DWORD NumberOfSymbols;
  WORD  SizeOfOptionalHeader;
  WORD  Characteristics;     // e.g., IMAGE_FILE_EXECUTABLE_IMAGE
} IMAGE_FILE_HEADER;


4. Optional Header (IMAGE_OPTIONAL_HEADER)

Despite the name, this is required for PE files.

Split into 3 parts:

  • Standard Fields
  • Windows-Specific Fields
  • Data Directories (Import Table, Export Table, etc.)

Key Fields:

typedef struct _IMAGE_OPTIONAL_HEADER {
  WORD  Magic;                // PE32: 0x10B, PE32+: 0x20B
  BYTE  MajorLinkerVersion;
  DWORD AddressOfEntryPoint; // RVA of main()
  DWORD ImageBase;           // Preferred base address
  DWORD SectionAlignment;
  DWORD FileAlignment;
  DWORD SizeOfImage;
  ...
  IMAGE_DATA_DIRECTORY DataDirectory[16];
} IMAGE_OPTIONAL_HEADER;


5. Section Headers (IMAGE_SECTION_HEADER[])

Each PE section has a 40-byte structure describing its properties.

Common Sections:

NamePurpose
.textCode (R-X)
.dataWritable initialized data (RW-)
.rdataRead-only data (R–)
.bss or .idataUninitialized globals
.rsrcResources (icons, dialogs, etc.)
.relocRelocation info for ASLR

Fields:

typedef struct _IMAGE_SECTION_HEADER {
  BYTE  Name[8];               // ".text", ".data", etc.
  DWORD VirtualSize;
  DWORD VirtualAddress;
  DWORD SizeOfRawData;
  DWORD PointerToRawData;
  DWORD Characteristics;       // Access permissions
} IMAGE_SECTION_HEADER;


6. Data Directories

The PE file includes 16 data directories, pointed to by the DataDirectory[] array inside the optional header.

IndexNameDescription
0Export TableFunctions exported by the PE
1Import TableFunctions imported from DLLs
2Resource TableDialogs, icons, strings
5Base RelocationASLR data
6Debug DirectoryPDB symbols
10TLS TableThread-Local Storage
14CLR HeaderFor .NET assemblies

7. Import Table

This is a critical structure for resolving API dependencies.

  • Located in .idata section
  • Uses IMAGE_IMPORT_DESCRIPTOR

Import Table Structure:

typedef struct _IMAGE_IMPORT_DESCRIPTOR {
  DWORD OriginalFirstThunk; // INT (names or ordinals)
  DWORD TimeDateStamp;
  DWORD ForwarderChain;
  DWORD Name;               // DLL name RVA
  DWORD FirstThunk;         // IAT (actual addresses)
} IMAGE_IMPORT_DESCRIPTOR;

  • INT (Import Name Table): RVAs to function names
  • IAT (Import Address Table): Populated by the loader with actual addresses of APIs

8. Export Table

Used by DLLs to expose functions to other programs.

typedef struct _IMAGE_EXPORT_DIRECTORY {
  DWORD Characteristics;
  DWORD TimeDateStamp;
  DWORD MajorVersion;
  DWORD MinorVersion;
  DWORD Name;
  DWORD Base;
  DWORD NumberOfFunctions;
  DWORD NumberOfNames;
  DWORD AddressOfFunctions;
  DWORD AddressOfNames;
  DWORD AddressOfNameOrdinals;
} IMAGE_EXPORT_DIRECTORY;

Exports can be:

  • By name
  • By ordinal
  • Forwarded exports (e.g., SHLWAPI.DLL!StrStrIW forwarded to NTDLL!StrStrIW)

Virtual Addresses vs File Offsets

  • RVA (Relative Virtual Address): Offset from the ImageBase
  • VA (Virtual Address): RVA + ImageBase
  • Raw Offset: Physical file offset (on-disk)

Use Section Table and alignments (FileAlignment, SectionAlignment) to convert RVA <-> File Offset.


PE Loading (by the OS)

  1. NTDLL loader maps PE into memory
  2. Resolves relocations if ImageBase is unavailable (ASLR)
  3. Parses Import Table and resolves API addresses
  4. Initializes TLS callbacks (if present)
  5. Jumps to AddressOfEntryPoint

Tools like x64dbg, CFF Explorer, PE-Bear, or PEview can visualize this.


PE Analysis Tips

ToolUsage
PE-BearStatic analysis of headers, imports, exports
die.exeDetects packers, file signatures
CFF ExplorerGUI editor for PE headers
x64dbgDynamic debugging of the loaded binary
dumpbin /headersCLI-based dump of PE structures
radare2CLI reverse engineering with PE support

Summary

  • PE format is the blueprint of how Windows binaries are structured and executed
  • Contains multiple headers (DOS, COFF, Optional) and section tables
  • Imports, exports, and relocation tables are essential for execution
  • Understanding PE layout is essential for malware reverse engineering, binary patching, and loader development

Windows Services & SCM Internals

Objective: Understand the architecture and functioning of Windows services, how the Service Control Manager (SCM) manages service lifecycles, service types, and dependencies, and how services can be created via the Windows API or directly through the registry. This is essential for both system developers and security professionals analyzing persistence or privilege escalation mechanisms.


Introduction

Windows services are background processes that operate independently of user logins, often running with high privileges. They’re essential for system functionality and are managed by the Service Control Manager (SCM). Many malware families and red teamers leverage Windows services for stealthy persistence, elevated execution, or lateral movement.


Core Concepts

What is a Windows Service?

A service is a long-running executable that performs system-level tasks, often without user interaction.

Examples:

  • Spooler (print services)
  • WinDefend (Windows Defender)
  • LanmanServer (file sharing)

What is SCM?

The Service Control Manager (services.exe) is a user-mode process that:

  • Loads service configurations from the registry
  • Starts, stops, and monitors services
  • Handles inter-service dependencies
  • Logs events to the Event Log

SCM Boot Flow

  1. services.exe is launched during Session 0 startup
  2. SCM reads the list of services from: HKLM\SYSTEM\CurrentControlSet\Services\
  3. It initializes service objects and sorts them by dependencies
  4. SCM launches services in the required order

Registry Structure for Services

Services are configured in the registry under:

HKLM\SYSTEM\CurrentControlSet\Services\&lt;ServiceName>

Common Values in a Service Key:

ValueTypeDescription
ImagePathREG_EXPAND_SZPath to the executable
TypeREG_DWORDService type
StartREG_DWORDStartup type
ErrorControlREG_DWORDBoot error handling
DisplayNameREG_SZFriendly name
DescriptionREG_SZService description
DependOnServiceREG_MULTI_SZServices that must start before this one

Service Startup Types

ValueMeaning
0x0Boot (loaded by boot loader)
0x1System (loaded by kernel, like file systems)
0x2Automatic
0x3Manual
0x4Disabled
0x5Delayed Auto-start (with DelayedAutoStart=1)

Service Types

Type ValueDescription
0x10Own process (most common)
0x20Share process (shared svchost.exe)
0x1Kernel driver
0x2File system driver
0x100Interactive process (legacy; rarely used now)

You can view this with:

Get-Service | Select-Object Name, StartType, Status, DependentServices


How Services Launch

Own Process

ImagePath directly points to an EXE that runs under services.exe.

Example:

ImagePath: C:\Program Files\MyService\service.exe

Shared svchost.exe Group

Many Microsoft services use svchost.exe with a -k switch to define the group.

Example:

ImagePath: %SystemRoot%\System32\svchost.exe -k netsvcs

Grouped service DLLs are defined in:

HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Svchost

And their DLL paths are in:

HKLM\SYSTEM\CurrentControlSet\Services\&lt;ServiceName>\Parameters\ServiceDll


Dependency Handling

Services can declare dependencies:

  • Service-level (DependOnService)
  • Group-level (DependOnGroup)

This forces SCM to order service startup so that dependencies are satisfied before launching a given service.


Creating a Service (API Method)

You can create services with the Windows API using CreateService() via C++, PowerShell, or .NET.

C++ Example

SC_HANDLE schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);

SC_HANDLE schService = CreateService(
    schSCManager, "MySvc", "My Service",
    SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
    SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
    "C:\\malware\\evil.exe", NULL, NULL, NULL, NULL, NULL);

PowerShell Equivalent

New-Service -Name "MySvc" -BinaryPathName "C:\malware\evil.exe" -DisplayName "My Service" -StartupType Automatic

This will appear under services.msc and persist across reboots.


Creating a Service (Registry Method)

You can also create services directly through the registry, often used by malware:

Manual Registry Entry

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Backdoor]
"ImagePath"="C:\\ProgramData\\backdoor.exe"
"Start"=dword:00000002
"Type"=dword:00000010
"ErrorControl"=dword:00000001
"DisplayName"="Windows Network Helper"

After writing this, start the service via:

sc start Backdoor


Service Abuse Scenarios

TacticDescription
PersistenceCreate a new service that runs on every boot
Privilege EscalationReplace an existing service binary if writable
DLL HijackingReplace ServiceDll in svchost group or use path search hijack
COM Hijack in serviceModify CLSID called by service
Execute as SYSTEMAny service started with LocalSystem can execute payloads with full privileges

Detecting Malicious Services

  1. Check startup entries:
Get-WmiObject win32_service | Where { $_.StartMode -eq "Auto" -and $_.StartName -eq "LocalSystem" }

  1. Look for unsigned binaries: Use sigcheck.exe from Sysinternals
  2. Audit unusual service names or paths: Look for non-standard install directories:
Get-WmiObject win32_service | Select Name, PathName | Where { $_.PathName -like "*AppData*" }

  1. Check registry manually: Explore:
HKLM\SYSTEM\CurrentControlSet\Services\


Summary

  • Services are critical Windows components controlled by the SCM.
  • The registry defines everything about a service: its path, type, startup behavior, and more.
  • Services can run as SYSTEM or other users, making them powerful for persistence or escalation.
  • They can be created via API or registry manipulation, and abuse is common in both malware and red teaming scenarios.
  • Defender strategies include signature verification, ACL hardening, AppLocker enforcement, and behavior monitoring.

Windows Scheduled Tasks

Objective: Understand the architecture and internals of Windows Task Scheduler, how scheduled tasks are created and executed, and how adversaries abuse them for persistence, privilege escalation, and lateral movement.


Introduction

Windows Task Scheduler is a built-in Windows service that enables automatic execution of tasks based on time, events, system state, or user actions. It is deeply integrated into the OS and extensively used for system maintenance, updates, telemetry, and administrative automation.

However, attackers abuse this trusted subsystem to establish stealthy persistence, execute malicious payloads with SYSTEM privileges, and bypass security controls.


Task Scheduler Architecture

Windows uses Task Scheduler 2.0, introduced in Vista, and backed by:

  • Task Scheduler Service (Schedule)
  • COM Interfaces (ITaskService, ITaskDefinition)
  • XML task definitions stored in system directories
  • Task Engine + Actions + Triggers model

Core Components

ComponentDescription
taskschd.dllMain Task Scheduler engine DLL
svchost.exe -k netsvcsHosts the Task Scheduler service
Task Scheduler LibraryLogical structure for all tasks
schtasks.exeCommand-line interface to manage tasks
taskeng.exeExecutes task actions (usually under user’s session)
taskhostw.exeLoads DLL-based scheduled tasks

Task Storage and Structure

Task File Locations

LocationPurpose
C:\Windows\System32\Tasks\Actual task .job files
HKLM\Software\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCacheRegistry mirror/cache of task metadata
C:\Windows\System32\Tasks\Microsoft\Windows\*Built-in OS tasks (defrag, telemetry, etc.)

Task File Format

  • Stored in XML format
  • Contains:
    • RegistrationInfo – Author, date, description
    • Triggers – Time, event, idle, logon, boot
    • Principals – Security context
    • Actions – What to run (Exec, ComHandler, etc.)
    • Settings – Constraints, retries, etc.

Example: Boot Persistence XML

&lt;Triggers>
  &lt;BootTrigger>
    &lt;Enabled>true&lt;/Enabled>
  &lt;/BootTrigger>
&lt;/Triggers>
&lt;Actions>
  &lt;Exec>
    &lt;Command>C:\malicious\rev.exe&lt;/Command>
  &lt;/Exec>
&lt;/Actions>


Triggers

Trigger types that can initiate a scheduled task:

Trigger TypeDescription
TimeTriggerAt a specific time
BootTriggerWhen system boots
LogonTriggerAt user logon
IdleTriggerWhen system is idle
EventTriggerBased on Windows event log
RegistrationTriggerWhen a task is registered
CustomTriggerWMI queries or custom events

Actions

Common types of actions defined within a task:

Action TypeDescription
ExecExecutes a command, script, or binary
ComHandlerCalls a COM class
SendEmailDeprecated
ShowMessageDeprecated

Example:

&lt;Exec>
  &lt;Command>C:\Windows\System32\calc.exe&lt;/Command>
&lt;/Exec>


Security Context (Principals)

Scheduled tasks can run under any account context:

  • SYSTEM – Full machine-level privilege
  • LOCAL SERVICE / NETWORK SERVICE
  • Administrator, User accounts
  • Group Managed Service Accounts (gMSA)

Privilege is set via:

&lt;Principal>
  &lt;UserId>S-1-5-18&lt;/UserId> &lt;!-- SYSTEM SID -->
  &lt;RunLevel>HighestAvailable&lt;/RunLevel>
&lt;/Principal>

If RunLevel is HighestAvailable, UAC elevation is requested.


Scheduled Task Abuse Techniques

1. Persistence via Task Registration

Create a malicious task to run a payload at boot/logon.

schtasks /create /tn "UpdateCheck" /tr "C:\temp\rev.exe" /sc onlogon /ru SYSTEM

PowerShell equivalent:

$action = New-ScheduledTaskAction -Execute "C:\temp\rev.exe"
$trigger = New-ScheduledTaskTrigger -AtLogOn
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "UpdateCheck" -RunLevel Highest -User "SYSTEM"

2. Privilege Escalation via SYSTEM Tasks

If a scheduled task runs as SYSTEM and is writeable by the user, an attacker can hijack it:

  • Modify its Action path
  • Replace the payload
  • Wait for it to trigger (e.g., at boot)

Check for vulnerable tasks:

Get-ScheduledTask | Where-Object {
    ($_.Principal.UserId -eq "SYSTEM") -and
    ((Get-Acl $("C:\Windows\System32\Tasks\" + $_.TaskName)).AccessToString -match "Everyone.*Write")
}

3. DLL Hijacking via taskhostw.exe

Some scheduled tasks load in-process COM handlers (DLLs):

  • Register a fake CLSID in registry
  • Drop malicious DLL in expected path
  • Task executes DLL as SYSTEM

Example Registry Setup:

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID\{malicious-guid}]
@="MyTask"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID\{malicious-guid}\InprocServer32]
@="C:\\evil.dll"
"ThreadingModel"="Apartment"

Then register a task with COMHandler using this CLSID.


Detection Techniques

TechniqueMethod
List all tasksschtasks /query /fo LIST /v
Task XML dumpschtasks /query /TN "TaskName" /XML
Check task folder ACLsicacls C:\Windows\System32\Tasks\*
Event Log: Task creationEvent ID 106 (Microsoft-Windows-TaskScheduler/Operational)
Event Log: Task executionEvent ID 200, 201, 202

Red Team Use Cases

Use CaseTechnique
EvasionSet execution at idle or obscure event
Covert ExecutionUse renamed schtasks.exe or COM-based API
Time-Based PersistenceRun only once at a delayed time
Remote Task DropVia schtasks /create /S <target> using stolen creds

Blue Team Tips

  • Monitor changes in HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule
  • Set audit rules on \Tasks\ folder
  • Use Sysmon Event ID 1 (Process Create) + correlate with task execution
  • Block schtasks.exe via AppLocker for standard users
  • Check for non-standard authors or empty descriptions

Summary

  • Task Scheduler is a core Windows subsystem used for automation and persistence.
  • It supports complex triggers, actions, and runs tasks in various privilege contexts.
  • Attackers can abuse it to execute payloads stealthily, elevate privileges, or persist across reboots.
  • Defenders can detect anomalies via XML inspection, ACL audits, and log monitoring.

Windows Registry Internals

Objective: Explore the internal structure and functionality of the Windows Registry, including its hive-based architecture, key-value model, data types, and how it enables system configuration. Understand how attackers leverage registry paths such as Run keys for persistence, and how defenders can detect and investigate these techniques.

Introduction

The Windows Registry is a centralized, hierarchical database used by the Windows operating system and many applications for configuration and operational data.

It stores everything from hardware driver configs, installed software settings, user preferences, and system boot configuration to startup execution paths, which makes it an attractive target for attackers seeking persistence and privilege escalation.


Registry Architecture Overview

The Windows Registry is structured like a file system:

  • Keys = Folders
  • Values = Files
  • Hives = Root-level logical divisions (backed by real files)

The Registry is accessible via:

  • Registry Editor (regedit.exe)
  • API calls like RegOpenKeyEx, RegQueryValueEx, RegSetValueEx
  • Command-line tools (reg.exe, powershell, regedit, wmic)

Core Registry Hives

Each hive maps to a physical file on disk. Hives are loaded into memory during system boot or user login.

Major Root Hives

HiveDescriptionBacking File
HKEY_LOCAL_MACHINE (HKLM)Machine-wide configurationSYSTEM, SOFTWARE, etc.
HKEY_CURRENT_USER (HKCU)Current logged-in user’s settingsNTUSER.DAT
HKEY_CLASSES_ROOT (HKCR)File extension and COM associationsAlias of HKLM\Software\Classes and HKCU\Software\Classes
HKEY_USERS (HKU)All user profiles loadedIncludes SID-named keys
HKEY_CURRENT_CONFIG (HKCC)Dynamic hardware profile dataDerived from HKLM\SYSTEM

Registry File Locations

FilePurposePath
SYSTEMKernel drivers, boot info%SystemRoot%\System32\Config\SYSTEM
SOFTWAREInstalled programs, OS settings%SystemRoot%\System32\Config\SOFTWARE
SECURITYLocal security policies%SystemRoot%\System32\Config\SECURITY
SAMLocal user/password database%SystemRoot%\System32\Config\SAM
NTUSER.DATCurrent user settings%UserProfile%\NTUSER.DAT

These files are locked during runtime and can be accessed offline using tools like FTK Imager or Registry Explorer.


Keys, Values, and Data Types

Keys

A key is similar to a directory and can contain:

  • Subkeys
  • Values
  • A default unnamed value

Values

Each key can contain one or more values, which consist of:

  • Name
  • Data Type
  • Data

Registry Data Types

TypeSymbolDescription
REG_SZStringPlain text string
REG_EXPAND_SZExpandable stringSupports environment variables
REG_DWORD32-bit numberOften used for flags/settings
REG_QWORD64-bit numberUsed in newer configurations
REG_BINARYBinary dataRaw hex, often device configurations
REG_MULTI_SZMulti-stringArray of strings, null-delimited

Registry Pathing

Registry paths are expressed like filesystem paths:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion

PowerShell can be used to browse and interact with registry keys as if they are drives:

cd HKLM:\SOFTWARE\Microsoft\Windows
Get-ItemProperty .


Run Key Persistence

One of the most abused persistence techniques is via the Run or RunOnce registry keys.

Common Run Key Paths

LocationDescription
HKLM\Software\Microsoft\Windows\CurrentVersion\RunRuns for all users at boot
HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnceRuns only once for all users
HKCU\Software\Microsoft\Windows\CurrentVersion\RunRuns at login for the current user
HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnceRuns only once for current user

Example (Manual Persistence)

Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" `
 -Name "Updater" `
 -Value "C:\Users\Public\updater.exe"

This would launch updater.exe at user logon.

Detection Tip:

  • Use Autoruns from Sysinternals or check registry directly:
Get-ItemProperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run'


Other Registry Persistence Locations

KeyPurpose
HKLM\Software\Microsoft\Active Setup\Installed ComponentsUsed by IE and apps to auto-start on login
HKLM\SYSTEM\CurrentControlSet\ServicesCreate a persistent service
HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\UserinitModify login initialization
HKLM\Software\Microsoft\Windows\CurrentVersion\ShellServiceObjectDelayLoadDelayed loading COM object
HKCU\Software\Microsoft\Windows NT\CurrentVersion\Windows\loadLegacy autorun vector
HKLM\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\RunPersistence in 32-bit view on 64-bit system

Registry Backup and Restore

Backup entire hives with:

reg export HKLM\Software software_backup.reg

Restore with:

reg import software_backup.reg

For forensics, extract registry hives offline and analyze them using:

  • Registry Explorer
  • Eric Zimmerman’s RECmd
  • FTK Imager
  • Autopsy or Volatility plugins for memory dumps

Registry Permissions and ACLs

Each key has its own ACL (Access Control List), viewable with:

(Get-Acl 'HKLM:\Software\Microsoft\Windows').Access

Tools like SetACL, PowerShell, or psexec can be used to escalate via insecure permissions (e.g., attacker can write to a privileged run key).


Red Team & Malware Use Cases

TechniqueAbuse
Startup ExecutionRun keys, RunOnce, ActiveSetup
Service HijackingModify ImagePath under Services
Userinit/LoginAppend malicious payload to Userinit or Shell
COM HijackRegister fake COM object in HKCR\CLSID
AV EvasionHide payload in registry as base64 or encrypted blob under benign key, decode in memory

Example of storing payload as encoded string:

Set-ItemProperty -Path "HKCU:\Software\Microsoft\Something" -Name "Config" -Value ([Convert]::ToBase64String([IO.File]::ReadAllBytes("payload.dll")))


Registry Forensics

For DFIR analysts, registry artifacts can indicate:

  • Malware persistence
  • User activity (recent files, typed paths)
  • USB device history (SYSTEM\CurrentControlSet\Enum\USBSTOR)
  • Program execution evidence (e.g., UserAssist, ShimCache)
  • MRU (Most Recently Used) lists

Recommended Tools:

  • Eric Zimmerman’s Registry Explorer + RECmd
  • NirSoft tools (ShellBagsView, USBDeview, etc.)
  • Velociraptor for live enterprise-wide registry search

Summary

  • The Windows Registry is a core part of system configuration and operation.
  • It uses hives, keys, values, and types to store structured data.
  • Persistence via Run keys is trivial and highly common.
  • Powerful red team techniques involve modifying service, COM, or logon keys.
  • Defensive tools can monitor or lock registry keys to prevent abuse.

Windows File System Internals (NTFS)

Objective: The NTFS (New Technology File System) is the default file system for modern Windows versions, designed to be secure, scalable, recoverable, and rich in metadata support.


Overview

The NTFS (New Technology File System) is the default file system for modern Windows versions, designed to be secure, scalable, recoverable, and rich in metadata support. Unlike FAT32 or exFAT, NTFS introduces complex data structures, a journaled metadata system, access control lists (ACLs), hard/soft links, and alternate data streams (ADS).


Key NTFS Features

FeatureDescription
Metadata-drivenEvery file and directory is stored as a metadata record in the MFT
JournalingChanges to critical metadata are recorded in the $LogFile before being committed
SecurityFull support for file permissions, ACLs, and encryption (EFS)
ADS (Alternate Data Streams)Allows multiple data streams per file
Compression & EncryptionBuilt-in per-file compression and support for EFS
Hard Links & Reparse PointsAdvanced linking and symbolic path redirection features
Sparse FilesSupport for efficiently handling large files with empty regions

The Master File Table (MFT)

At the heart of NTFS is the MFT (Master File Table). Think of it as the central database of the entire file system. Every file, folder, and metadata structure is stored as an MFT record, including internal system files.

MFT Layout

Each record in the MFT is 1024 bytes and contains:

  • File metadata (timestamps, size, attributes)
  • Pointers to the file’s data blocks (runs)
  • Named streams (e.g., ::$DATA)
  • File name entries (long and short names)

Key System Files in the MFT

Entry NamePurpose
$MFTThe Master File Table itself
$BitmapTracks which clusters are used/free
$LogFileJournals metadata changes
$SecureSecurity descriptors and ACLs
$VolumeVolume info (version, dirty flag)
$AttrDefList of valid attributes
$ExtendHouses extended features (like quotas, EFS, USN Journal)

File Record Attributes

Each NTFS file has a set of attributes that describe both the file and its contents. Attributes are stored either resident (inside the MFT entry) or non-resident (stored in separate clusters).

Common Attributes:

AttributeDescription
STANDARD_INFORMATIONBasic timestamps and permission flags
FILE_NAMELong and short name entries
DATAThe file’s actual data (can be named streams)
OBJECT_IDUnique identifier for tracking
SECURITY_DESCRIPTORNTFS ACLs
ATTRIBUTE_LISTUsed if the record can’t fit in one MFT entry

Resident Data

  • Small files (<700 bytes) are stored directly in the MFT.

Non-Resident Data

  • Larger files are stored elsewhere on disk and referenced via “data runs”.

File Metadata and Timestamps

NTFS tracks multiple timestamps:

  • Created: File creation time
  • Modified: Last content modification
  • MFT Changed: When metadata was last changed
  • Accessed: Last file access time

These are stored in STANDARD_INFORMATION and FILE_NAME attributes. Tools like MFTECmd or FTK Imager extract these for forensic timelines.


Alternate Data Streams (ADS)

NTFS supports multiple unnamed or named data streams in a single file. The main stream is usually :$DATA, but you can add hidden ones.

Example:

echo "secret" > notepad.txt:hidden
type notepad.txt:hidden

Forensics Concern:

  • ADS are often used to hide payloads or staging binaries.
  • dir /R will list streams in Windows.

Directory Structure & Indexing

NTFS directories are files themselves with INDEX_ROOT and INDEX_ALLOCATION attributes.

  • Small directories store entries directly inside the MFT (INDEX_ROOT)
  • Large directories spill over to other clusters (INDEX_ALLOCATION)

This design allows binary search indexing (B-tree like) instead of linear scanning.


Journaling with $LogFile

NTFS is a journaling file system.

  • $LogFile stores redo/undo logs for critical metadata changes.
  • Ensures metadata integrity after a power failure or crash.
  • Does not journal actual file content, only structural data.

This mechanism supports transactional consistency for files.


NTFS Recovery Concepts

NTFS uses a few safety mechanisms:

  1. $LogFile Recovery
    • Replay undo/redo entries post-crash
  2. CHKDSK
    • Scans metadata for inconsistencies
    • Can fix MFT, indexes, bitmap mismatches
  3. Volume Dirty Bit
    • Flag inside $Volume that triggers auto-CHKDSK

USN Journal (Change Journal)

Located in: $Extend\$UsnJrnl

  • Tracks all file-level changes (created, renamed, modified, deleted)
  • Used by tools like antivirus, backup software, and forensic tools
  • Each event is indexed by USN ID and timestamp

Enable / Query USN Journal:

fsutil usn queryjournal C:


NTFS Object IDs & Reparse Points

  • Object IDs: Unique GUIDs for file tracking
  • Reparse Points: Used for symbolic links, junctions, OneDrive placeholders

Types of reparse tags:

  • IO_REPARSE_TAG_SYMLINK – Symbolic link
  • IO_REPARSE_TAG_MOUNT_POINT – Junction
  • IO_REPARSE_TAG_APPEXECLINK – App execution alias

You can create symbolic links using:

mklink file2.txt file1.txt


Common NTFS Attacks and Abuses

Abuse TechniqueDescription
ADS PersistenceHide malicious DLLs or scripts in alternate streams
MFT Record AbuseCreate thousands of MFT entries to trigger slowdowns or detection blind spots
Symbolic Link HijackAbuse reparse points to redirect execution
USN Journal WipeDelete forensic history using low-level tools

Low-Level Tools for NTFS Exploration

ToolPurpose
NTFSInfo (Sysinternals)View cluster sizes, MFT layout
MFTECmd (Eric Zimmerman)Parse MFT and timestamps
FTK ImagerBrowse NTFS structure for forensics
fsutilQuery volume, reparse points, streams
NTFSWalkerInspect MFT and attributes
WinHex / 010 EditorView raw disk sectors and parse binary templates

Summary

  • NTFS is a highly advanced file system that embeds metadata, journaling, and fine-grained security into every file.
  • The MFT is the backbone of the file system, storing every file and folder as a database-like entry.
  • ADS, USN, and Reparse Points introduce both powerful features and potential attack surfaces.
  • NTFS journaling ($LogFile) and recovery structures provide strong integrity guarantees.

Windows Boot Process

Objective: Understand the internal steps that take place when a Windows machine powers on, leading up to the execution of user-level processes like explorer.exe.


Introduction

The Windows boot process involves several tightly coordinated stages that transition from firmware-level initialization (BIOS/UEFI) to the full-blown execution of the Windows operating system. Each phase has a critical role in preparing the system environment, loading essential files, initializing the kernel, and finally launching user-space processes.

This knowledge is fundamental when analyzing boot-time malware, rootkits, and persistence mechanisms that abuse early stages.


Boot Sequence Overview

Below is the high-level boot chain:

[BIOS / UEFI] 
    ↓
[Boot Manager (bootmgr)]
    ↓
[Windows OS Loader (winload.exe)]
    ↓
[Windows Kernel (ntoskrnl.exe)]
    ↓
[Session Manager Subsystem (smss.exe)]
    ↓
[Wininit.exe / Csrss.exe / Services.exe / Winlogon.exe]
    ↓
[User logon and Explorer.exe startup]

Each stage is explained in detail below.


1. BIOS or UEFI Firmware

BIOS (Legacy)

  • The Basic Input/Output System is firmware embedded on the motherboard.
  • Initializes CPU, RAM, keyboard, and storage controllers.
  • Scans for bootable devices using the boot order.
  • Loads the Master Boot Record (MBR) from the first sector of the disk (LBA 0).
  • MBR contains:
    • Boot code (446 bytes)
    • Partition table (64 bytes)
    • Boot signature (2 bytes)

UEFI (Modern)

  • Unified Extensible Firmware Interface replaces BIOS.
  • Stores boot configuration in EFI System Partition (ESP).
  • Loads .efi binaries like bootmgfw.efi directly from the FAT32-formatted ESP.
  • Supports Secure Boot and faster initialization.

Key Outcome: BIOS or UEFI hands off execution to bootmgr (via MBR or EFI).


2. Boot Manager (bootmgr)

Location:

  • BIOS: Found in the root of system partition (usually C:\)
  • UEFI: Located in \EFI\Microsoft\Boot\bootmgfw.efi

Responsibilities:

  • Reads Boot Configuration Data (BCD) from \Boot\BCD
  • Displays the boot menu (e.g., dual-boot options, recovery)
  • Selects which OS to boot (if multiple)
  • Loads the next-stage loader: winload.exe

Boot Configuration Data (BCD):

  • A binary registry-like file
  • Contains entries for OS boot parameters
  • Configurable via bcdedit

Key Outcome: bootmgr reads BCD and transfers control to winload.exe.


3. OS Loader (winload.exe)

Location:

  • C:\Windows\System32\winload.exe

Responsibilities:

  • Loads essential drivers and kernel images into memory:
    • ntoskrnl.exe (Windows kernel)
    • hal.dll (Hardware Abstraction Layer)
    • Boot-start drivers (from HKLM\SYSTEM\CurrentControlSet\Services)
  • Loads system registry hives into memory
    • SYSTEM hive is particularly crucial
  • Enables DEP, ASLR, Code Integrity (if configured)

Integrity and Security:

  • Verifies digital signatures on drivers if Secure Boot is enabled
  • If BitLocker is used, winload handles the decryption process

Transition:

  • After successful loading, winload calls into ntoskrnl.exe
  • Enters Protected Mode and switches to Kernel Mode

4. Kernel Initialization (ntoskrnl.exe)

Location:

  • C:\Windows\System32\ntoskrnl.exe

Responsibilities:

  • Initializes kernel subsystems:
    • Memory manager
    • Process scheduler
    • Interrupt dispatcher
    • Object manager
    • Security reference monitor
  • Starts the Hardware Abstraction Layer (hal.dll)
  • Initializes the System Service Descriptor Table (SSDT)
  • Mounts the system drive using file system drivers (ntfs.sys, etc.)

Driver Loading:

  • Executes boot-start and system-start drivers (loaded from registry)
  • Uses I/O manager to create device stacks

Key Transition:

  • Starts the first user-mode process: smss.exe (Session Manager)

5. Session Manager Subsystem (smss.exe)

Location:

  • C:\Windows\System32\smss.exe

Role:

  • The first user-mode process
  • Created by the kernel using PsCreateSystemProcess

Key Tasks:

  • Loads system environment variables from registry
  • Launches:
    • CSRSS (Client/Server Runtime Subsystem)
    • WININIT (Windows Initialization Subsystem)
  • Initializes the page file
  • Mounts additional volumes and prepares the Winlogon environment
  • Creates user sessions (Terminal Services, multi-session support)

Sessions:

  • Session 0: Reserved for system services
  • Session 1+: Used for interactive logon

Key Outcome: smss.exe spawns wininit.exe and csrss.exe.


6. Windows Initialization (wininit.exe)

Responsibilities:

  • Starts Service Control Manager (services.exe)
    • Loads all services marked as auto-start
  • Starts Local Security Authority (lsass.exe)
    • Handles authentication and policy enforcement
  • Starts Winlogon (winlogon.exe)
    • Manages user logon, Ctrl+Alt+Del
    • Loads GINA / Credential Providers

Csrss (Client/Server Runtime):

  • Handles console windows, thread management
  • Fundamental for GUI and Win32 subsystems

7. User Logon & Shell Startup

Winlogon.exe

  • Displays the logon screen
  • Invokes credential providers (e.g., password, PIN, smartcard)
  • Upon successful authentication, calls CreateProcessAsUser for:

Explorer.exe

  • Launches the Windows desktop, taskbar, file manager
  • Runs under the user’s security token

Summary: Boot Flow Timeline

StageComponentModeKey Action
Firmware InitBIOS/UEFIReal ModeHardware init
BootloaderbootmgrProtectedLoads BCD & winload
OS Loaderwinload.exeReal → Prot.Loads kernel & drivers
Kernel Initntoskrnl.exeKernel ModeInitializes OS subsystems
User Initsmss.exeUser ModeSets up sessions, spawns services
Wininit/Logonwininit, winlogonUser ModeStarts SCM, LSA, logon UI
User Shellexplorer.exeUser ModeLoads desktop

Advanced Tips

  • Safe Mode: Modifies BCD to restrict drivers (bcdedit /set {current} safeboot minimal)
  • Kernel Debugging: Use bcdedit /debug on and attach WinDbg over COM or network
  • Boot Tracing: Use tools like Process Monitor Boot Logging, xbootmgr, or boot trace logs via Windows Performance Toolkit
  • Early Launch Anti-Malware (ELAM): ELAM driver is the first AV component loaded during kernel init