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

Windows OS Architecture

πŸ’‘ Goal: Understand how Windows is built under the hood β€” from User Mode to Kernel Mode, system layers, and what makes it tick. This is foundational for everything from malware development to EDR evasion.


🧠 What is an Operating System?

An OS acts as a middleman between:

  • You (the user / programs) and
  • Hardware (CPU, RAM, Disk, etc.)

It:

  • Manages processes and memory
  • Handles file I/O
  • Provides APIs to run apps
  • Controls devices through drivers

os a

🧩 Key Components Breakdown

πŸ”Ή User Mode

  • Apps like notepad.exe, chrome.exe
  • Can’t directly talk to hardware or manage memory
  • Must ask Kernel Mode via System Calls
  • Hosts subsystems (e.g., Win32, POSIX, WOW64)

πŸ”Έ Subsystems

  • Win32: Main API for GUI apps
  • WOW64: Lets 32-bit apps run on 64-bit Windows
  • POSIX: Legacy support for Unix-style tools

πŸ”Έ Kernel Mode

  • Has full access to memory, devices, drivers
  • Runs privileged code (Ring 0)
  • Includes the Kernel, Executive, Drivers, and HAL

🧱 Executive (NTOS)

Think of it as the “brains” of the kernel

Includes:

  • Object Manager (handles Windows objects like files, processes)
  • Memory Manager (allocates and pages memory)
  • Process Manager (creates, manages threads/processes)
  • Security Reference Monitor (permission enforcement)

βš™οΈ Kernel (Core)

  • Deals with low-level threading, interrupt handling, synchronization

πŸ“¦ Device Drivers

  • .sys files like disk.sys, kbdclass.sys
  • Run in kernel mode and interact directly with hardware

🧬 HAL (Hardware Abstraction Layer)

  • Allows Windows to run on different hardware by abstracting CPU/IO differences
  • File: hal.dll

πŸ”€ User Mode vs Kernel Mode

FeatureUser ModeKernel Mode
Privilege LevelRing 3 (low)Ring 0 (high)
Memory AccessOwn virtual memoryFull system memory
Crash ImpactJust the appWhole system (BSOD)
Direct Hardware Access❌ Noβœ… Yes
Exampleexplorer.exentoskrnl.exe, disk.sys

βš™οΈ System Call Flow (Behind the Scenes)

When you run calc.exe, here’s what happens:

  1. You click a shortcut
  2. Explorer.exe launches calc.exe using CreateProcess
  3. CreateProcess β†’ Win32 API
  4. Win32 API β†’ System Call (like NtCreateProcess)
  5. Kernel validates permissions, allocates memory
  6. Kernel returns handle, app runs

➑️ Every “simple” action is backed by 100+ low-level operations.


πŸ§ͺ Hands-On Practice

Want to see the layers in action? Try these:

# On Windows PowerShell
Get-Process | Select-Object Name, Path, Id

# Peek into ntoskrnl usage
Get-WmiObject -Query "Select * from Win32_OperatingSystem"

# View loaded drivers (kernel-mode)
driverquery /v

Use Process Hacker or WinDbg to see threads, handles, and kernel objects live.


🧠 Summary

  • Windows is a hybrid kernel OS with clear User Mode and Kernel Mode
  • User Mode apps can’t touch hardware directly β€” they rely on System Calls
  • Kernel Mode contains the brain (ntoskrnl.exe), drivers, and HAL
  • Everything you do β€” launching apps, copying files β€” goes through this architecture