Agent Skills › gmh5225/awesome-game-security

gmh5225/awesome-game-security

GitHub

提供现代游戏反作弊架构分析指南,涵盖EAC、Vanguard等系统原理及内核监控、驱动保护、内存检测等技术细节。适用于游戏安全研究、漏洞分析及对抗策略评估。

9 skills 3,070

Install All Skills

npx skills add gmh5225/awesome-game-security --all -g -y
More Options

List skills in collection

npx skills add gmh5225/awesome-game-security --list

Skills in Collection (9)

提供现代游戏反作弊架构分析指南,涵盖EAC、Vanguard等系统原理及内核监控、驱动保护、内存检测等技术细节。适用于游戏安全研究、漏洞分析及对抗策略评估。
分析EAC, BattlEye, Vanguard等反作弊系统 研究Windows内核回调与驱动保护机制 探讨DMA威胁或手动映射检测技术 进行游戏安全逆向工程或行为遥测分析
.claude/skills/anti-cheat/SKILL.md
npx skills add gmh5225/awesome-game-security --skill anti-cheat-systems -g -y
SKILL.md
Frontmatter
{
    "name": "anti-cheat-systems",
    "description": "Guide for modern game anti-cheat architecture, Windows kernel monitoring, and detection tradeoffs. Use this skill when analyzing EAC, BattlEye, Vanguard, FACEIT AC, kernel callbacks, handle protection, manual-map detection, boot-start drivers, BYOVD, DMA threats, or behavioral telemetry in game security research."
}

Anti-Cheat Systems & Analysis

Overview

This skill covers layered anti-cheat design across kernel drivers, privileged services, in-game components, and backend telemetry. It is most useful for mapping how modern anti-cheats monitor process handles, image loads, memory integrity, driver trust, virtualization abuse, DMA threats, and suspicious input behavior on Windows.

README Coverage

  • Anti Cheat > Guide
  • Anti Cheat > Stress Testing
  • Anti Cheat > Driver Unit Test Framework
  • Anti Cheat > Anti Debugging
  • Anti Cheat > Page Protection
  • Anti Cheat > Binary Packer
  • Anti Cheat > CLR Protection
  • Anti Cheat > Anti Disassembly
  • Anti Cheat > Sample Unpacker
  • Anti Cheat > Dump Fix
  • Anti Cheat > Encrypt Variable
  • Anti Cheat > Lazy Importer
  • Anti Cheat > Anti-Cheat Programming
  • Anti Cheat > Compile Time
  • Anti Cheat > Shellcode Engine & Tricks
  • Anti Cheat > Obfuscation Engine
  • Anti Cheat > Screenshot
  • Anti Cheat > Game Engine Protection:*
  • Anti Cheat > Open Source Anti Cheat System
  • Anti Cheat > Analysis Framework
  • Anti Cheat > Detection:*
  • Anti Cheat > Signature Scanning
  • Anti Cheat > Information System & Forensics
  • Anti Cheat > Dynamic Script
  • Anti Cheat > Kernel Mode Winsock
  • Anti Cheat > Fuzzer
  • Anti Cheat > Windows Ring3 Callback
  • Anti Cheat > Windows Ring0 Callback
  • Anti Cheat > Winows User Dump Analysis
  • Anti Cheat > Winows Kernel Dump Analysis
  • Anti Cheat > Sign Tools
  • Anti Cheat > Backup File / Backup Drivers
  • Anti Cheat > Black Signature
  • Windows Security Features

Major Anti-Cheat Systems

Easy Anti-Cheat (EAC)

  • Multi-component architecture with service, driver, and game-facing protections
  • Process integrity verification and memory inspection
  • Runtime driver loading with strong client-side enforcement
  • Used by: Fortnite, Apex Legends, Rust

BattlEye

  • Kernel driver plus service and game module coordination
  • Handle protection, process monitoring, and memory scanning
  • Strong focus on injected code and runtime tampering visibility
  • Used by: PUBG, Rainbow Six Siege, DayZ

Vanguard (Riot Games)

  • Boot-start kernel driver with early visibility into later-loaded drivers
  • Boot-time initialization
  • Driver allowlisting and aggressive system trust checks
  • Used by: Valorant, League of Legends

FACEIT AC

  • Kernel-level competitive anti-cheat with strong process and driver monitoring
  • Emphasis on platform integrity and low tolerance for hostile drivers
  • Often discussed alongside Vanguard in kernel anti-cheat research

Valve Anti-Cheat (VAC)

  • User-mode detection
  • Signature-based scanning
  • Delayed ban waves
  • Used by: CS2, Dota 2, TF2

Other Systems

  • PunkBuster: Legacy FPS anti-cheat
  • FairFight: Server-side statistical analysis
  • nProtect GameGuard: Korean anti-cheat solution
  • XIGNCODE3: Mobile game protection
  • ACE (Tencent): Chinese market protection

Detection Mechanisms

Memory Detection

- Code section hashing and integrity verification
- Executable private memory and manual-map detection
- Injected module and anomalous image mapping detection
- Memory modification and stack provenance monitoring

Process Detection

- Handle access stripping and protected-process enforcement
- Thread start address, APC, and context inspection
- Debug register and hidden-thread monitoring
- Stack trace and module-correlation analysis

Kernel-Level Detection

- Driver verification, signature policy, and blocklist checks
- Callback registration and object access monitoring
- System call, dispatch table, and hook integrity checks
- PatchGuard, test-signing, and kernel trust state checks
- Kernel pool scanning (Segment Heap aware) for hidden drivers and shellcode

Kernel Pool Scanning (Segment Heap Era)

Why Segment Heap matters for anti-cheat:
Cheat drivers allocate memory in NonPagedPool for shellcode, hook tables,
hidden modules. The Segment Heap (19H1+) changed pool internals:
headers are HeapKey XOR encoded, allocation paths are split (kLFH, VS,
Segment, Large), metadata is isolated. Anti-cheat pool scanners must
understand these mechanisms to scan accurately without false positives.

Detection targets:

1. BigPool / Large Allocation scanning:
   - Walk nt!PoolBigPageTable (nt!PoolTrackTable)
   - Find allocations without corresponding DRIVER_OBJECT or loaded module
   - Detect manually mapped drivers that allocate large pool chunks
   - Large allocations have no inline header; metadata is external

2. VS Allocator chunk scanning:
   - Traverse _SEGMENT_HEAP → VsContext → SubsegmentList
   - Decode _HEAP_VS_CHUNK_HEADER using HeapKey:
     real_sizes = encoded_header ^ chunk_address ^ HeapKey
   - Check decoded chunk for suspicious PoolTag, executable content,
     or allocation without matching driver
   - VS chunks carry both _HEAP_VS_CHUNK_HEADER (encoded) and
     _POOL_HEADER (PoolTag still present)

3. kLFH bucket scanning:
   - _SEGMENT_HEAP → LfhContext → Buckets[] → AffinitySlots → Subsegments
   - kLFH randomizes block placement (harder to predict adjacency)
   - FreeHint encoded with LfhKey
   - Allocation pattern anomalies in specific size buckets can indicate
     pool grooming by cheat drivers

4. Suspicious PoolTag detection:
   - Cheat drivers use custom or rare tags; maintain blacklist
   - Cross-reference tags against known-good tag database (pooltag.txt)
   - Tags present in pool but absent from any loaded module = suspicious

5. Executable memory in NonPagedPool:
   - Find chunks with X permission but no corresponding module
   - Scan decoded chunk content for known cheat signatures, ROP gadgets,
     specific syscall stub patterns

6. Segment Heap integrity checks:
   - Validate _SEGMENT_HEAP.Signature == 0xDDEEDDEE
   - Verify VS chunk header encoding consistency
   - Detect tampered heap metadata (indicates heap exploitation attempt)

Required knowledge for scanner:
- nt!RtlpHpHeapGlobals (HeapKey, LfhKey) — obtained via pattern scan
- nt!ExpPoolQuotaCookie — for ProcessBilled decoding
- Per-pool-type _SEGMENT_HEAP instance addresses (nt!PoolVector)
- Allocation path determination (size → kLFH/VS/Segment/Large)

Anti-cheat KDP integration:
- Store detection rule tables in Secure Pool (ExAllocatePool3 + KDP)
- Rules become VTL0-immutable — cheat drivers cannot modify
  detection signatures even with kernel R/W primitives

Behavioral Analysis

- Raw input timing and pattern analysis
- Movement and aim anomaly detection
- Statistical improbability and ML-assisted scoring
- Telemetry collection and server-side review
- AI visual aimbot detection (input pattern + gameplay behavior)

AI Visual Aimbot Detection

AI visual cheats (OBS capture + YOLO + hardware input) are the hardest
class to detect because they involve no memory access, no code injection,
no kernel driver on the gaming PC. Detection must move to behavioral
analysis and environmental signals.

Input Pattern Analysis:
- Mouse movement micro-signature: AI-generated trajectories have
  characteristic acceleration profiles distinct from human muscle control
  even with smoothing and jitter injection
- Engagement timing: AI reacts within a narrow, consistent latency band
  (capture → inference → output, typically 20-50 ms total) that lacks
  the variance of human reaction time distributions
- Sub-pixel precision: hardware input devices report integer deltas,
  but AI-calculated movements exhibit systematic rounding patterns
  that differ from natural hand movement
- Correction patterns: AI trajectories show characteristic overshoot-and-settle
  patterns at consistent magnitudes; human correction is more variable
- Target switching: AI switches between targets with machine-like
  priority ordering (closest-to-crosshair or highest-confidence);
  humans exhibit attention bias and tunnel vision

Gameplay Behavioral Signals:
- Anomalous K/D ratio combined with other statistical outliers
- "Snap" engagement pattern: rapid crosshair movement to target
  followed by immediate fire, repeated consistently
- FOV-limited engagement: AI only engages targets within a specific
  pixel radius (the configured FOV), creating an unnatural engagement
  boundary visible in replay analysis
- Consistent headshot angle distribution that doesn't match
  the player's ranked skill bracket
- Engagement rate: AI engages available targets at a higher percentage
  than human players who miss, ignore, or react slowly to some targets

Environmental Detection:
- OBS process detection: Game Capture mode injects a graphics hook DLL
  (obs-graphics-hook64.dll) into the game process; detectable via
  loaded module enumeration, though banning it risks false-positive
  on legitimate streamers
- Window Capture detection: DXGI Desktop Duplication creates detectable
  API state (IDXGIOutputDuplication usage patterns)
- Frame readback detection: unusual GPU-to-CPU copy patterns
  (ReadbackTexture / staging resource creation at frame rate)
- Known hardware input device USB VID/PID signatures
  (KMBox, certain Arduino/Teensy boards)
- USB device enumeration anomalies: input device appearing/changing
  mid-session
- Logitech driver version detection: known exploitable G HUB versions
- Interception driver (interception.sys) loaded = high-risk signal

Server-Side Statistical Analysis:
- Aim trajectory reconstruction from server-received input deltas
- Compare aim distribution against player population at same rank
- Detect systematic per-frame aim correction vectors
  (AI produces consistent delta sequences)
- Cross-session pattern analysis: AI users show unnaturally stable
  performance metrics across sessions (low variance in accuracy)
- Replay-based ML classifiers trained on confirmed AI aimbot cases

Anti-AI Countermeasures (Game Design):
- Visual disruption: flashbang/smoke effects that confuse CV models
- Character skin variety and camouflage that reduce YOLO confidence
- Dynamic UI elements overlapping character models
- Server-side aim validation: reject physically impossible aim transitions
- Randomized character proportions or outline disruption to break
  trained model assumptions

Server-Side Replay Analysis for AI Aimbot Detection

Server-side detection operates on input telemetry data uploaded
from the client, independent of what runs on the gaming PC.
This is the strongest layer against zero-memory AI cheats.

Input Telemetry Collection:
- Record raw mouse delta (dx, dy) per tick at server tick rate
- Record timestamps of each input event (sub-millisecond precision)
- Record crosshair angle / view angle per tick
- Record fire events with corresponding view angle at fire time
- Record damage events with hit location (head/body/limb)
- Collect per-session: total engagement count, hit count,
  headshot count, K/D, average engagement distance

Replay-Based Trajectory Reconstruction:
- Reconstruct full crosshair trajectory from recorded input deltas
- Overlay trajectory onto 3D game state (player positions, obstacles)
- Identify "engagement windows": trajectory segments where crosshair
  moves toward and locks onto a target
- Measure per-engagement: time-to-target, overshoot magnitude,
  correction count, final hold time before fire

Statistical Features for AI Detection:
  (extracted from reconstructed trajectories)

Temporal features:
- Reaction time distribution: time from target visibility to
  first crosshair movement toward target
  → AI: narrow, consistent band (30-80 ms capture+inference+output)
  → Human: wide, right-skewed distribution (150-400 ms typical)
- Time-to-lock distribution: time from engagement start to
  crosshair on target
  → AI: consistent, speed-limited by smoothing algorithm
  → Human: highly variable, depends on initial angular distance

Spatial features:
- Trajectory curvature: AI Bézier curves have characteristic
  smooth, parametric curvature; human paths are more erratic
  with micro-corrections and random deviations
- Overshoot-correction ratio: AI smoothing algorithms produce
  predictable overshoot magnitudes; humans vary wildly
- End-point precision: AI consistently lands on bounding box
  center or specific offset; humans show scatter distribution
- Angular velocity profile: AI ramps up/down smoothly;
  humans have irregular acceleration spikes

Engagement pattern features:
- Target selection consistency: AI always picks closest-to-crosshair
  or highest-confidence target; humans show attention bias, tunnel
  vision, and suboptimal target priority
- FOV boundary effect: AI shows sharp engagement cutoff at
  configured pixel radius; humans have gradual falloff
- Engagement rate: percentage of visible targets engaged;
  AI engages more consistently than humans who miss, ignore,
  or react slowly to peripheral targets
- Multi-target switch pattern: AI switches with machine-like
  regularity; humans show grouping and hesitation

ML Classifier for AI Aimbot Detection

Feature engineering and model architecture for detecting
AI-generated mouse input at scale.

Feature Vector (per engagement window):
  f1:  reaction_time_ms
  f2:  time_to_lock_ms
  f3:  initial_angular_distance_deg
  f4:  trajectory_curvature_mean
  f5:  trajectory_curvature_std
  f6:  overshoot_magnitude_px
  f7:  correction_count
  f8:  final_hold_time_ms
  f9:  angular_velocity_max_deg_per_sec
  f10: angular_velocity_std
  f11: micro_correction_frequency (small deltas < 2px per tick)
  f12: trajectory_straightness_ratio (distance / path_length)
  f13: dx_dy_correlation (Pearson correlation of delta components)
  f14: delta_magnitude_entropy (Shannon entropy of |delta| sequence)
  f15: fire_timing_relative_to_lock_ms

Session-level aggregate features:
  s1:  headshot_ratio
  s2:  hit_ratio
  s3:  reaction_time_cv (coefficient of variation across engagements)
  s4:  engagement_rate (targets engaged / targets visible)
  s5:  k/d_ratio
  s6:  fov_engagement_boundary_sharpness
  s7:  target_selection_optimality_score
  s8:  trajectory_curvature_consistency (inter-engagement variance)

Model architecture options:
- Gradient Boosted Trees (XGBoost/LightGBM):
  Best for tabular feature vectors, interpretable feature importance,
  fast inference on server. Preferred for production deployment.
- Random Forest: simpler, less prone to overfitting on small datasets
- 1D-CNN / LSTM on raw delta sequences:
  Operates on raw (dx, dy, dt) sequences instead of engineered features.
  Can capture patterns human engineers might miss.
  Higher compute cost; suitable for batch/offline analysis.
- Ensemble: combine tree-based (tabular features) + sequence model
  (raw deltas) for highest accuracy

Training data:
- Positive samples: confirmed AI aimbot users (manual review, honeypot,
  or controlled testing with known cheat software)
- Negative samples: legitimate high-skill players (important: include
  top-percentile players to avoid false-positives on skilled play)
- Hard negatives: players with aim-assist controllers (console),
  players using legitimate accessibility tools

Evaluation metrics:
- False Positive Rate (FPR): must be extremely low (< 0.01%)
  for production deployment — banning legitimate players is catastrophic
- True Positive Rate (TPR): secondary to FPR; 70-85% TPR is acceptable
  if FPR is near-zero
- Use session-level aggregation: flag a player only if multiple
  sessions show consistent AI patterns (reduces both FP and FN)

Deployment pipeline:
  Client → input telemetry upload (per tick) → server telemetry DB
  → batch feature extraction (per engagement window)
  → ML inference (per session)
  → risk score aggregation (per player, across sessions)
  → threshold → manual review queue or automated action

Adversarial robustness:
- Cheat developers tune smoothing parameters to evade specific features
- Defense: retrain model periodically on newly confirmed samples
- Use feature combinations rather than single-feature thresholds
- Ensemble across multiple sessions reduces evasion success
- Raw sequence models (CNN/LSTM) are harder to evade than
  hand-crafted feature thresholds because the evasion space
  is higher-dimensional

Hardware Input Device Detection

Detecting KMBox and similar hardware input injectors at the
platform/driver level.

USB Enumeration Signals:
- Known VID/PID combinations for KMBox, Arduino Leonardo (2341:8036),
  Teensy (16C0:0486), generic CH340/CP2102 serial adapters
- USB device appearing/disappearing during game session
- Multiple HID mouse devices where only one physical mouse is expected
- USB device with HID mouse capability but no manufacturer string
  or generic "Arduino LLC" / "Teensyduino" manufacturer

USB HID Report Analysis:
- Hardware input devices generate genuine HID reports, but:
  - Report rate: KMBox/Arduino typically report at exactly the
    programmed rate (e.g., every 1ms or 8ms); real mice have
    polling rate jitter tied to USB microframe scheduling
  - Report timing: AI-injected movements arrive in bursts
    (idle → sudden burst of calculated deltas → idle),
    while human movement is continuous with natural pauses
  - Delta distribution: AI deltas cluster around computed values
    with optional noise; human deltas follow characteristic
    distributions per movement speed

Network Traffic Indicators (KMBox Net):
- KMBox Net uses UDP communication on the local network
- Packet pattern: consistent-size UDP packets at high frequency
  from a secondary device to the KMBox's IP
- If cheat PC is on the same network: detectable via
  network monitoring (firewall/router logs)

Driver-Level Detection:
- interception.sys: known driver signature, detectable via
  module enumeration and PiDDBCacheTable
- Logitech G HUB DLL injection: detect unexpected DLL loads
  into GHUB process, or specific exploitable GHUB versions
  via file version checking

Limitations:
- Pure hardware HID injection (KMBox, Arduino) is fundamentally
  indistinguishable from real mouse input at the HID protocol level
- Detection must rely on statistical input analysis rather than
  driver/device-level signatures
- Dual-machine setups with capture cards leave zero footprint
  on the gaming PC beyond the hardware input device

Anti-Cheat Architecture

User-Mode Components

  • Process scanner
  • Module verifier
  • Overlay detector
  • Screenshot capture

Kernel-Mode Components

  • Driver loader
  • Memory protection
  • System callback registration
  • Hypervisor and driver trust detection
  • VAD and executable memory inspection

Hypervisor-Level Components

- EPT-based memory access monitoring
- Callback list write protection via EPT hooks
- ETW structure integrity enforcement
- AC driver code page protection (prevent patching)
- VMCALL interface for policy configuration from kernel driver
- VM exit handlers for EPT violations on protected regions

Server-Side Components

  • Statistical analysis
  • Replay verification
  • Report processing
  • Ban management

Research Techniques

Static Analysis

  1. Dump and analyze AC drivers
  2. Reverse engineer detection routines
  3. Identify signature patterns
  4. Map callback registrations and trust boundaries

Dynamic Analysis

  1. Monitor system calls
  2. Track driver communications
  3. Inspect memory layout and module provenance
  4. Debug with kernel or hypervisor tools

Bypass Categories

Memory Access

  • Physical memory read/write
  • DMA-based access
  • Hypervisor memory virtualization
  • Driver-based access

DMA Cheat Detection Methodology

PCIe-Layer Detection Pipeline

Detection targets inconsistencies between what a device claims to be
and how it actually behaves. Each technique targets a specific
firmware emulation tier or class of gap.

Configuration Integrity:
- VID/DID/SVID/SDID against known-real-silicon allowlist
- Capability-chain walk: DWord-aligned Next pointers, no overlaps, no cycles
- Signature-residue scanning: Xilinx 7-series default byte patterns,
  Device Capabilities field bits, reserved-field defaults
- Capability presence consistency: donor model must expose expected caps
- BAR mask verification: write 0xFFFFFFFF, compare size mask vs donor

BAR Memory Probing:
- Send Memory Read TLPs to BAR ranges, validate responses by donor class
- NIC BAR0: register layout (ring descriptors, interrupt mask, link status)
- NVMe BAR0: controller registers (CAP, VS, CC, CSTS, AQA, ASQ/ACQ)
- XHCI BAR0: capability registers (CAPLENGTH, HCSPARAMS, HCCPARAMS)
- stock pcileech zerowrite4k returns all-zeros; loopaddr echoes address

R/W Consistency:
- Toggle writable bits (Command BME, Device Control MPS/MRRS, MSI Enable)
- Walk W1C bits (Status, AER Status): write 1s, confirm clear semantics
- Walk reserved bits: write 1s, confirm read-back as 0
- Per-register writable masks must match donor model exactly

Link-State Validation:
- Negotiated Width/Speed vs claimed capabilities (Gen4 x8 claim
  but Gen2 x1 reality = one-read contradiction)
- DLL Active, Slot Clock Config consistency
- ASPM behavioral validation: L0 ↔ L1 transition patterns must
  match donor class; never leaving L0 when ASPM is claimed = anomalous

AER Baselining:
- Compare correctable-error rates against per-silicon baseline
- Implausibly clean logs (zero correctables when donor normally
  produces Bad TLP / Replay Timer Timeout) = anomalous
- UR/CA response distribution to probes of unimplemented offsets

Completion Latency Fingerprinting

Real silicon: DRAM contention + internal arbiters → heavy-tailed
latency distributions. BRAM-backed emulators: fixed clock cycles
→ much lower variance.

Statistical methods:
- Kolmogorov–Smirnov test: compare empirical CDFs vs reference
- Hill estimator: tail index (real silicon has non-trivial tail)
- Anderson-Darling test: sensitive to tail differences

Tier-5 firmwares add LFSR-based jitter, but matching real
distribution shape (mean, variance, tail index, mode count)
requires modeling donor DRAM access patterns.

MSI/MSI-X Behavioral Validation

- Device with MSI Enable + programmed Address/Data + attached driver
  should produce interrupts
- Zero interrupts when driver should exercise device = anomalous
- Implausibly uniform arrival times (60 Hz heartbeat) = timer-driven
- MSI-X probe: mask vector → induce condition → observe PBA bit →
  unmask → observe interrupt firing. Real silicon passes; spoofed rarely does.

Cheat-Phase Access Pattern Recognition

Development phase: slow, broad scanning (MemProcFS signature search)
Execution phase: narrow, periodic reads (60–240 Hz) of small offset set

Execution phase statistical signature:
- High temporal periodicity
- Low address-space breadth
- Alignment to game-frame intervals
- Distinguishing features: Fano factor, autocorrelation at frame intervals,
  address-space coverage entropy

Honeypot regions effective when combined with IOMMU denial/fault logging,
hypervisor EPT traps, decoy IOVA mappings, or server-side behavioral traps.

IOMMU-Layer Detection

Fault-Rate Monitoring:
- Per-device fault rate from IOMMU fault-recording / WHEA
- Legitimate devices with correct drivers rarely fault
- Sustained nonzero rate = direct evidence of out-of-domain access

Domain Assignment Audit:
- Flag devices on passthrough/identity domains under strict mode
- Flag unexpectedly large IOMMU groups (poor ACS topology)
- Verify multi-function devices sharing Domain ID legitimately

ACS Topology Verification:
- Walk bridge topology, verify Source Validation, Translation Blocking,
  P2P Request/Completion Redirect on every relevant bridge
- Bridges without ACS = isolation holes

IOMMU Containment Primitives

Before ban verdict, containment protects the live match:

1. IOMMU domain sandbox: reprogram device domain to sandbox memory;
   cheat reads garbage data

2. Bus Master Enable clearance: toggle Command[2] to 0;
   effective for tier-0 through tier-3

3. Downstream Port Containment (DPC): if upstream port supports
   DPC Extended Capability (0x001D), trigger Contained state —
   all TLPs dropped, no firmware-side BME race

4. Anti-cheat-owned device domain: map only sandbox IOVAs

External Trust Anchors

When local kernel/hypervisor trust fails, external anchors close the gap:

TPM Remote Attestation:
- Server sends nonce → client requests TPM2_Quote(AIK, PCR_selection, nonce)
- Verifier checks: AIK signature, certificate chain, EK binding,
  nonce freshness, PCR composite matches known-good policy
- Compromised kernel cannot retroactively alter extend-only PCRs

Measured Boot PCR Relevance:
- PCR[0]: UEFI firmware code
- PCR[7]: Secure Boot policy + DMA Protection Disabled event
- PCR[17]: DRTM/Secure Launch measurement

UEFI Pre-Boot DMA Integrity:
- Verify DMAR/IVRS protection indicators
- Cross-check BIOS version against known vulnerable CVE lists
- Verify PCR[7] DMA Protection Disabled event state

Layered Detection Synthesis

No single signature is durable. Production pipeline layers:

1. Pre-game: IOMMU active, IR enabled, Secure Boot, VBS/HVCI,
   TPM provisioned, attestation validates, BIOS not vulnerable,
   ACS topology verified

2. Inventory: full 4 KB config dump per device, problem codes,
   SMBIOS slot cross-reference

3. Config integrity: per-donor reference database comparison

4. Behavioral sampling: Link Status, AER counters, interrupt rates,
   IOMMU fault rates, BAR content

5. Statistical analysis: latency distributions, interrupt distributions,
   ASPM transition rates

6. Cheat-phase: honeypot access, access pattern classifiers

Verdict requires multi-signal correlation — single signals can
false-positive; combinations rarely do. Three independent signals
push false-positive rates below practical threshold.

Firmware Sophistication Tiers (Detection Mapping)

Tier 0 (Stock):        VID/DID blacklist catches immediately
Tier 1 (Bridge):       Signature residue, driverless device detection
Tier 2 (Shadow):       R/W consistency probing catches write drops
Tier 3 (Overlay RAM):  BAR probing + class-functional A/B testing
Tier 4 (BAR+MSI):      Interrupt distribution + BAR content baselining
Tier 5 (Behavioral):   Multi-session latency/ASPM/AER statistical analysis
Tier 6 (Private):      Requires external trust anchors (TPM + attestation)

Forensic Evidence for DMA Cases

Capture on detection:
- Full 4 KB config dump + capability chain walk
- PCIe link state history (LTSSM, ASPM transitions)
- MSI/MSI-X arrival timeline
- AER correctable counts
- IOMMU fault log entries + domain assignments
- ACS bridge state
- Honeypot access records (EPT trap log)
- TPM PCR snapshot
- MCFG / DMAR / IVRS ACPI tables
- SMBIOS slot inventory + BIOS version
- Completion latency distribution histograms

Strongest evidence: hardware signal + behavioral signal + temporal correlation.
Three independent signals make false-positive appeals manageable.

Code Execution

  • Manual mapping
  • Thread hijacking
  • APC injection
  • Kernel callbacks

Detection Evasion

  • Signature mutation
  • Timing attack mitigation
  • Stack spoofing
  • Module hiding

Security Features Interaction

Windows Security

  • Driver Signature Enforcement (DSE)
  • PatchGuard/Kernel Patch Protection
  • Hypervisor Code Integrity (HVCI)
  • Secure Boot
  • TPM-backed attestation considerations

Virtualization Detection

  • VT-x/AMD-V detection
  • Hypervisor presence checks
  • VM escape detection
  • Timing-based detection

Hypervisor-Based Defense for Anti-Cheat

Concept:
- Use hypervisor (EPT/SLAT) to enforce anti-cheat protections
  from a privilege level above the kernel
- Even if attacker achieves kernel R/W (BYOVD, exploit),
  hypervisor-level enforcement remains intact
- EPT hooks replace traditional kernel hooks:
  operate outside the guest OS, invisible to kernel-level rootkits

EPT Hook Protection Targets:
- Anti-cheat driver executable pages
  → Prevents attackers from patching AC driver code in memory
- Kernel callback lists (PsSetCreateProcessNotifyRoutine, ObRegisterCallbacks)
  → Write authorization moved to hypervisor; kernel-level callback removal denied
- ETW-related structures
  → Unauthorized writes trigger EPT violations, caught by hypervisor
- EPP/AC process memory
  → Protects security software from silent tampering

Hypervisor vs Kernel-Level Threats:
- Common kernel-level attack chain:
  1. Attacker uses BYOVD or kernel exploit for R/W primitives
  2. Patches callbacks to remove AC notifications
  3. Tampers with ETW to disable telemetry
  4. Modifies AC driver code to blind detection
- With hypervisor defense:
  1. Same kernel R/W primitives obtained
  2. Write to protected callback list → EPT violation → VM exit
  3. Hypervisor evaluates context and denies unauthorized modification
  4. AC callbacks and telemetry remain intact

Advantages:
- Higher privilege than kernel — cannot be disabled by kernel rootkits
- Transparent to guest: no kernel patches needed
- Effective even after full kernel compromise
- Complements existing kernel-mode detection (callbacks, signatures, scans)

Limitations:
- Requires hardware virtualization support (VT-x/AMD-V)
- Performance overhead from VM exits on protected region access
- Complexity: must handle nested virtualization (VMware, Hyper-V)
- DMA attacks bypass hypervisor memory protections (separate threat)

Code Protection Techniques

Page Protection

- Executable page guard pages and trap-based integrity monitoring
- NX bit enforcement and DEP policy
- PAGE_GUARD + single-step trap for code coverage without patching
- VirtualProtect monitoring to detect runtime permission changes

Binary Packing & Encryption

- PE packers: UPX, Themida, VMProtect, Enigma, MPRESS
- CLR protection: .NET obfuscation (ConfuserEx, Dotfuscator, .NET Reactor)
- Encrypt Variable: runtime value encryption to frustrate memory scanners
- Lazy Importer: compile-time import hiding to avoid IAT-based detection
- Compile-time techniques: string encryption, constexpr obfuscation, COFF obfuscation

Shellcode & Obfuscation

- Shellcode engines: position-independent code generation, syscall stubs
- Obfuscation engines: OLLVM-based, custom LLVM passes, MBA (Mixed Boolean-Arithmetic)
- Anti-disassembly: opaque predicates, junk code insertion, control flow flattening

Heartbeat & Screenshot

Heartbeat Mechanisms

- Periodic client-to-server health check packets
- Encrypted challenge-response with server nonce
- Timing-based integrity: detect suspended or debugged processes
- Failure modes: silent disconnect, delayed ban, immediate kick

Screenshot Capture

- AC-initiated screen capture for manual or automated review
- BitBlt / PrintWindow / DXGI desktop duplication
- Anti-screenshot evasion: overlay hiding, DWM composition bypass
- Server-side ML classifiers for ESP/overlay detection in captured frames

Telemetry Pipeline

Client-Side Collection

- Module list enumeration and hash reporting
- Handle table snapshots for suspicious access patterns
- Stack trace sampling at periodic intervals
- Driver load events and callback registration state
- Hardware fingerprint (disk serial, NIC MAC, SMBIOS, GPU)

Transport & Server-Side

- Encrypted telemetry channel (TLS + custom encryption layer)
- Server-side aggregation and anomaly scoring
- ML-based behavioral clustering for ban waves
- Replay system integration for suspicious session review

Ethical Considerations

Research Guidelines

  • Focus on understanding, not exploitation
  • Report vulnerabilities responsibly
  • Respect Terms of Service implications
  • Consider impact on gaming communities

Legal Aspects

  • DMCA considerations
  • CFAA implications
  • Regional regulations
  • ToS enforcement

Resources Organization

Detection Research

- Anti-cheat driver analysis
- Detection routine documentation
- Callback enumeration tools

Bypass Research

- Memory access techniques
- Injection methods
- Evasion strategies

Tools

- Custom debuggers
- Driver loaders
- Analysis frameworks

Data Source

Important: This skill provides conceptual guidance and overview information. For detailed information use the following sources:

1. Project Overview & Resource Index

Fetch the main README for the full curated list of repositories, tools, and descriptions:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/README.md

The main README contains thousands of curated links organized by category. When users ask for specific tools, projects, or implementations, retrieve and reference the appropriate sections from this source.

2. Repository Code Details (Archive)

For detailed repository information (file structure, source code, implementation details), the project maintains a local archive. If a repository has been archived, always prefer fetching from the archive over cloning or browsing GitHub directly.

Archive URL format:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/archive/{owner}/{repo}.txt

Examples:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/archive/ufrisk/pcileech.txt
https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/archive/000-aki-000/GameDebugMenu.txt

How to use:

  1. Identify the GitHub repository the user is asking about (owner and repo name from the URL).
  2. Construct the archive URL: replace {owner} with the GitHub username/org and {repo} with the repository name (no .git suffix).
  3. Fetch the archive file — it contains a full code snapshot with file trees and source code generated by code2prompt.
  4. If the fetch returns a 404, the repository has not been archived yet; fall back to the README or direct GitHub browsing.

3. Repository Descriptions

For a concise English summary of what a repository does, the project maintains auto-generated description files.

Description URL format:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/description/{owner}/{repo}/description_en.txt

Examples:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/description/00christian00/UnityDecompiled/description_en.txt
https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/description/ufrisk/pcileech/description_en.txt

How to use:

  1. Identify the GitHub repository the user is asking about (owner and repo name from the URL).
  2. Construct the description URL: replace {owner} with the GitHub username/org and {repo} with the repository name.
  3. Fetch the description file — it contains a short, human-readable summary of the repository's purpose and contents.
  4. If the fetch returns a 404, the description has not been generated yet; fall back to the README entry or the archive.

Priority order when answering questions about a specific repository:

  1. Description (quick summary) — fetch first for concise context
  2. Archive (full code snapshot) — fetch when deeper implementation details are needed
  3. README entry — fallback when neither description nor archive is available
指导PCIe DMA威胁建模与防御,涵盖FPGA内存访问、pcileech及BAR/TLP行为。适用于研究IOMMU/VT-d防护、设备伪装检测及游戏安全中的DMA缓解策略,分析无代码执行硬件攻击的三层防御体系。
研究PCIe DMA攻击技术 分析FPGA内存访问漏洞 查询pcileech或TLP行为 评估IOMMU或VT-d防御机制 检测游戏反作弊中的DMA威胁
.claude/skills/dma-attack/SKILL.md
npx skills add gmh5225/awesome-game-security --skill dma-attack-techniques -g -y
SKILL.md
Frontmatter
{
    "name": "dma-attack-techniques",
    "description": "Guide for PCIe DMA threat modeling, FPGA-based memory access, and defensive implications in game security. Use this skill when researching pcileech, BAR and TLP behavior, page-table walking, IOMMU or VT-d, device impersonation, firmware mimicry, or DMA detection and mitigation in game security research."
}

DMA Attack Techniques

Overview

This skill covers Direct Memory Access research from the awesome-game-security collection, focusing on FPGA-based PCIe attacks, pcileech usage, physical-memory access workflows, and the defensive limits of software anti-cheat once a hostile device can read memory below the OS.

README Coverage

  • Cheat > DMA
  • Anti Cheat > Detection:DMA
  • Anti Cheat > Detection: Hacked Hypervisor
  • Anti Cheat > Detection:Virtual Environments
  • Anti Cheat > Detection:HWID
  • Windows Security Features

Threat Model

External DMA Cheat Architecture

A modern external DMA cheat consists of three components:

1. Cheat PC — runs the cheat application, signature databases,
   aim assistance, ESP rendering, and a network/USB link to the gaming PC.

2. DMA Card — an FPGA-based PCIe endpoint installed in the gaming PC
   (typically M.2 NVMe slot). Exposes a memory-read/write interface to
   the cheat PC. Uses Bus Master capability to issue Memory Read TLPs
   against the gaming PC's RAM.

3. Actuator (optional) — a USB HID emulator (microcontroller-based) that
   injects keyboard/mouse input on the gaming PC according to commands
   from the cheat PC, closing the loop.

The structural property that makes this threat distinctive:
no attacker code executes on the gaming PC. The DMA card performs
hardware-level transactions between the FPGA and the gaming PC's
memory controller, mediated by the chipset and (when configured) the IOMMU.
The gaming PC's OS, drivers, and anti-cheat see only a PCIe device
announcing itself through Configuration Space and performing what looks
like ordinary DMA.

Three Defense Layers

Layer              Mechanism                    What It Catches
─────────────────────────────────────────────────────────────────────────────
PCIe-layer         Inspect Config Space &        Identity mismatch — spoofed
fingerprinting     behavior at the bus level     device that doesn't match
                                                 real silicon's full signature

IOMMU              Use the IOMMU to bound        Out-of-domain DMA — device
enforcement        what physical memory the       trying to read game memory
                   device can touch               it wasn't allocated

External           TPM-anchored measured boot,   Boot-chain compromise — IOMMU
attestation        cloud-verified                or kernel itself subverted

PCIe Protocol Stack

Three Protocol Layers

Layer              Unit                Function
────────────────────────────────────────────────────────────────
Transaction        TLP                 Memory/IO/Config reads & writes,
                                       completions, messages
Data Link          DLLP                Acknowledgements, flow control
                                       credits, power management
Physical           Ordered Sets        Link training, equalization,
                                       clock recovery

A real device's behavior is shaped by all three layers.
An FPGA emulating a real device only fully controls the Transaction Layer;
the Physical and Data Link layers leak fingerprints that
BRAM-based emulation cannot fully hide.

TLP (Transaction Layer Packet) Format

Every TLP begins with a 3 DW (12-byte) or 4 DW (16-byte) header.
4 DW headers are used for 64-bit addresses and certain message types.

First DWord (DW0) encoding:
Bits       Field         Notes
[31:29]    Fmt[2:0]      Header format + data presence
[28:24]    Type[4:0]     TLP type (combined with Fmt)
[22:20]    TC[2:0]       Traffic Class (default 0)
[18]       Attr[2]       ID-Based Ordering (IDO)
[15]       TD            TLP Digest (ECRC trailer)
[14]       EP            Poisoned data
[13:12]    Attr[1:0]     Relaxed Ordering, No Snoop
[11:10]    AT[1:0]       Address Type (critical for ATS bypass)
[9:0]      Length[9:0]   Payload length in DWords (0x000 = 1024 DW = 4 KB)

Fmt[2:0] encoding:
000 = 3 DW header, no data
001 = 4 DW header, no data
010 = 3 DW header, with data
011 = 4 DW header, with data
100 = TLP Prefix

Key TLP types (Fmt + Type combinations):
Fmt  Type     TLP
000  0_0000   MRd (Memory Read, 3DW / 32-bit addr)
001  0_0000   MRd (Memory Read, 4DW / 64-bit addr)
010  0_0000   MWr (Memory Write, 3DW)
011  0_0000   MWr (Memory Write, 4DW)
000  0_0100   CfgRd0 (Config read — terminate at this device)
010  0_0100   CfgWr0
000  0_0101   CfgRd1 (Config read — forwarded by bridges)
010  0_0101   CfgWr1
000  0_1010   Cpl (Completion without data)
010  0_1010   CplD (Completion with data)
001  1_0rrr   Msg (Message, no data)
011  1_0rrr   MsgD (Message with data)

Detection-Relevant DW0 Fields

TC[2:0] — Traffic Class. Default 0; real silicon rarely uses non-zero TC.
A spoofed device generating non-zero TC is anomalous.

Attr[2:0] — RO/NS/IDO. A device emulating a NIC must follow that NIC's
typical NS/RO usage pattern; mismatches are visible.

AT[1:0] — Address Type:
  00 = Untranslated (IOMMU will translate)
  01 = Translation Request (ATS only)
  10 = Translated (device claims it has already translated via ATS)
This field is the basis of ATS bypass attacks.

TD — TLP Digest. If set, an ECRC trailer is present.
EP — Poisoned. Indicates data is known-bad.

TLP Routing and Requester ID

Three routing modes:
- Address routing — Memory and IO TLPs, matched against bridge apertures
- ID routing — Config TLPs and Completions, by BDF
- Implicit routing — Some Messages (broadcast, terminate at root)

DW1 carries the Requester ID (16 bits = Bus:Device:Function, "BDF")
and an 8-bit Tag for matching completions to requests.

The Requester ID is the entire input to per-device security policy:
IOMMU translation lookup, ACS source validation, AER source ID,
MSI/MSI-X routing. Anything that lets a device send TLPs with a
different Requester ID fundamentally compromises isolation.

Transaction categories:
- Posted (P) — fire-and-forget (Memory Writes, Messages)
- Non-Posted (NP) — requires completion (Memory Reads, IO/Config R/W)
- Completion (Cpl/CplD) — response to Non-Posted requests

Completion Status codes:
000 = Successful Completion (SC)
001 = Unsupported Request (UR)
010 = Configuration Request Retry Status (CRS)
100 = Completer Abort (CA)

UR vs CA distinction matters for spoofing detection — real silicon
responds differently to malformed config accesses vs accesses to
unimplemented offsets. Many spoofed firmwares hard-code one or the other.

Memory Read Completion Splitting

A single Memory Read TLP returns up to Max_Read_Request_Size (MRRS) bytes.
The completer splits the payload at any boundary >= RCB
(Read Completion Boundary, 64 or 128 bytes).
Each fragment cannot exceed Max_Payload_Size (MPS).

Each Completion carries:
- Lower Address[6:0] — lowest 7 bits of first byte address
- Byte Count[11:0] — bytes remaining (last fragment's Byte Count
  equals its own payload length)
- BCM — PCI-X compatibility (typically 0)
- Tag — matches originating MRd's Tag

The split pattern (fragment count, boundary positions) is a
strong fingerprint: real memory controllers produce characteristic
distributions of fragment sizes and inter-fragment gaps.
BRAM-backed emulators producing perfectly uniform 64-byte fragments
at constant cadence are anomalous.

Tag Space and Fingerprinting

- 5-bit Tag (original): 32 outstanding non-posted requests per Requester ID
- Extended Tag (PCIe 1.1+, Device Control[8]): 8-bit / 256 outstanding
- 10-Bit Tag (PCIe 4.0+, Device Control 2[12]): 1024 outstanding

Tag turnover discipline — which tags get reissued and how quickly —
reflects the device's internal request tracking pipeline.
Firmware that issues reads with no tag turnover (same tag, or monotonic
beyond negotiated limit) is observably distinct from real silicon.

MPS and MRRS as Fingerprints

Both are negotiated once at link bring-up and fixed for the session.
- Device Capabilities[2:0]: Max_Payload_Size_Supported
  (0=128, 1=256, 2=512, 3=1024, 4=2048, 5=4096 bytes)
- Device Control[7:5]: current MPS (must be <= Supported,
  set to minimum of all devices in hierarchy)
- Device Control[14:12]: Max_Read_Request_Size (same encoding)

The discriminator is donor consistency: a device claiming a donor
that is known to support larger payloads, different tag behavior,
or a different negotiated profile should match that donor under
the same root-port constraints.

Data Link Layer

DLLPs provide reliable delivery between Physical and Transaction layers.

DLLP          Purpose
─────────────────────────────────────────
Ack           TLP received correctly
Nak           TLP received with error; sender must replay
InitFC1/2     Flow control credit initialization at link bring-up
UpdateFC      Ongoing flow control credit updates
PM_*          Power management (L0s, L1 entry/exit)
Vendor        Vendor-defined

Flow control credits are per TLP category:
- PH / PD — Posted Header / Data
- NPH / NPD — Non-Posted Header / Data
- CplH / CplD — Completion Header / Data

Negotiated credit values are not generally exposed through standard
Link Capabilities register. They are visible in protocol-level traces,
some root-port/vendor performance counters, or FPGA-side debug.
Useful for lab fingerprinting and forensic captures, not normal
runtime config-space detection.

Physical Layer

Two details matter even without PHY-level instrumentation:

LTSSM (Link Training and Status State Machine):
- States: Detect → Polling → Configuration → L0 (operational)
  → L0s, L1, L2 (low-power) → Recovery → Hot Reset → Disabled → Loopback
- Observable via Link Status Register and root-port performance counters

Detection-relevant:
- Negotiated Link Width (Link Status[9:4]):
  Device advertising x16 but negotiating x1 is a tell
- Current Link Speed (Link Status[3:0]):
  Capability claims Gen4 but stays Gen2/Gen3 is anomalous
- Recovery cycle frequency:
  Comparative signal; materially different from donor reference is anomalous

ASPM (Active State Power Management):
- L0s and L1 are link-level low-power states
- A device claiming ASPM support in Link Capabilities but
  never transitioning out of L0 contradicts its class

Configuration Access Mechanisms

Two mechanisms on x86:

CAM (Legacy I/O-port path):
1. CPU writes to I/O port 0xCF8 (Bus:Device:Function:Register)
2. CPU reads/writes at I/O port 0xCFC
- Reaches only first 256 bytes
- Still used during early BIOS/UEFI boot

ECAM (Enhanced, MMIO path):
1. Read MCFG ACPI table for segment base addresses
2. Compute: addr = base + ((bus << 20) | (dev << 15) | (func << 12) | offset)
3. OS maps physical address into kernel virtual memory
- Required for Extended Configuration Space (0x100–0xFFF)
- Where AER, DSN, LTR, VSEC, ATS, PASID, SR-IOV live

On Windows, supported paths are:
- IRP_MN_READ_CONFIG / IRP_MN_WRITE_CONFIG
- BUS_INTERFACE_STANDARD.GetBusData / SetBusData
Production anti-cheat should use documented bus interfaces;
direct MCFG mapping is a lab-only technique.

PCIe Configuration Space

Legacy 256-Byte Header (Type 0 Endpoint)

Offset  Field                    Notes
0x00    Vendor ID (2B)           Chip manufacturer (e.g., 0x8086 Intel)
0x02    Device ID (2B)           Specific product
0x04    Command (2B)             BME (bit 2), MemSpace (bit 1), IOSpace (bit 0)
0x06    Status (2B)              Capabilities List (bit 4)
0x08    Revision ID + Class Code Class triplet: Base / Sub / ProgIF
0x0C    Cache Line / Latency /   Header Type 0x00 = endpoint,
        Header Type / BIST       0x01 = bridge, 0x80 = multi-function
0x10–27 BAR0–BAR5               Memory or I/O windows
0x2C    Subsystem Vendor ID      Often distinguishes board manufacturers
0x2E    Subsystem Device ID
0x30–33 Expansion ROM Base
0x34    Capabilities Pointer     Offset of first capability in linked list
0x3C    IRQ Line/Pin/Min/Max     Legacy INTx routing

BAR encoding (32-bit BAR):
bit 0:    0 = Memory BAR, 1 = I/O BAR
bits 2:1: 00 = 32-bit, 10 = 64-bit (BAR pair)
bit 3:    Prefetchable

BAR size discovery: write 0xFFFFFFFF to BAR, read back.
Lower bits (except type bits) come back as 0; rest form a size mask.
Real silicon's size masks are device-specific; a spoofed BAR with
64 KB mask when the donor uses 4 KB is detectable in one operation.

Capabilities Chain

If Status[4] is set, 0x34 points to the first capability.
Each capability has a 2-byte header: [ID | Next].
Next is DWord-aligned in 0x40–0xFF, or 0x00 to terminate.

Common capability IDs:
ID    Capability
0x01  PCI Power Management
0x05  MSI
0x10  PCI Express
0x11  MSI-X
0x12  SATA Configuration
0x13  PCI Advanced Features
0x14  Enhanced Allocation

Detection: walk the chain, validate each capability's declared size
doesn't overlap the next, Next is DWord-aligned and within bounds,
no cycle exists. A malformed chain is itself a signal.

PCIe Express Capability (ID 0x10)

The single most important capability for spoofing detection.

Offset  Field                    Notes
+0x02   PCIe Capabilities        Cap Version, Device/Port Type, Slot Impl
+0x04   Device Capabilities      MPS Supported, FLR, Phantom Functions
+0x08   Device Control           MPS current, MRRS, Error Enables
+0x0A   Device Status            CED, NFED, FED, URD, Transactions Pending
+0x0C   Link Capabilities        Max Link Speed/Width, ASPM, L0s/L1 latencies
+0x10   Link Control             ASPM Control, RCB, Link Disable, Retrain
+0x12   Link Status              Current Link Speed/Width, Link Training
+0x24   Device Capabilities 2    Completion Timeout Ranges, AtomicOp,
                                 OBFF, LTR mechanism
+0x28   Device Control 2         Completion Timeout Value, AtomicOp, LTR Enable
+0x2C   Link Capabilities 2      Supported Link Speeds Vector
+0x30   Link Control 2           Target Link Speed, Compliance
+0x32   Link Status 2            De-emphasis, EQ Phase status

Detection leverage per field:
- Device Type (+0x02[7:4]): must match donor's role
- MPS Supported (+0x04[2:0]): hard-IP ceiling contradicts donor
- FLR support (+0x04[28]): verify FLR changes same sticky/non-sticky
  state as claimed donor; naive firmware acknowledges FLR but continues
  unchanged, preserving impossible internal state
- Link Status (+0x12): Width/Speed are negotiated, observable, hard to
  lie about — hard IP reports what LTSSM actually achieved
- Slot Clock Config (+0x12[12]): must match real platform behavior
- Completion Timeout ranges (+0x24): selecting outside claimed ranges
  is a discriminator
- AtomicOp (+0x24[6-9]): server-class GPUs/NICs may support; FPGA
  hard IP almost never does. Mismatch is detectable.

MSI and MSI-X Capabilities

MSI (ID 0x05):
Message Control bits:
  [0]    MSI Enable
  [3:1]  Multiple Message Capable (0–5, representing 1–32 vectors)
  [6:4]  Multiple Message Enable (cannot exceed Capable)
  [7]    64-bit Address Capable
  [8]    Per-Vector Masking Capable

x86 MSI Address: bits [31:20] fixed at 0xFEE (LAPIC prefix)
  [19:12] Destination ID, [3] Redirection Hint, [2] Destination Mode
Message Data: [15] Trigger Mode, [10:8] Delivery Mode, [7:0] Vector

MSI-X (ID 0x11):
- Supports up to 2,048 vectors
- Table stored in BAR-mapped region (not Config Space)
- Each entry: 16 bytes (Addr Low, Addr High, Data, Vector Control)
- PBA (Pending Bit Array): bit-per-vector pending state

Naive MSI-X emulation failures:
- Ignores Vector Control Mask writes
- Sets PBA bits but never clears on unmask
- Returns hardcoded PBA values
- Doesn't retire pending interrupts when masks clear
Detection probe: mask vector → induce interrupt condition →
observe PBA bit → unmask → observe interrupt firing.
Real silicon satisfies this round trip; spoofed firmware rarely does.

AER Extended Capability (ID 0x0001)

Three error classes:
- Correctable: Receiver Error, Bad TLP, Bad DLLP, Replay Timer Timeout
- Uncorrectable Non-Fatal: Completion Timeout, Completer Abort, UR, ACS Violation
- Uncorrectable Fatal: Malformed TLP, DLL Protocol Error, Surprise Down

Each has Status (sticky, W1C), Mask, and Severity registers.
Header Log (16B) captures full TLP header of first logged uncorrectable error.

Detection:
- Absence of AER when donor model is known to expose it = mismatch
- Zero correctable-error count over long window when donor's silicon
  normally produces a baseline rate = anomalous
- Anomalous UR response patterns to probes of unimplemented offsets

Extended Capabilities

4-byte header at each offset:
[31:20] Next Capability Offset (0 to terminate)
[19:16] Capability Version
[15:0]  Extended Capability ID

Key Extended Capability IDs:
0x0001  AER
0x0002  Virtual Channel (VC)
0x0003  DSN (Device Serial Number, 8 bytes)
0x000B  Vendor-Specific Extended Capability (VSEC)
0x000D  ACS (Access Control Services)
0x000E  ARI
0x000F  ATS (Address Translation Services)
0x0010  SR-IOV
0x0015  Resizable BAR (RBAR)
0x0018  LTR (Latency Tolerance Reporting)
0x001B  PASID
0x001D  DPC (Downstream Port Containment)
0x001E  L1 PM Substates
0x001F  Precision Time Measurement (PTM)

Detection-relevant:
- DSN: 8-byte unique serial; donor-cloned firmware can collide
  with another player's identical card
- VSEC: Xilinx PCIe IP optionally emits VSEC blocks with
  characteristic Vendor ID + VSEC ID combinations
- ATS/PASID/SR-IOV presence on consumer-class donor is
  demographically suspicious — rare outside server-class hardware

IOMMU Architecture

Translation Flow

1. Device issues Memory TLP with target IOVA.
   TLP header carries 16-bit Requester ID (BDF).
2. TLP travels upstream through switches/bridges to root complex.
3. IOMMU intercepts, uses Requester ID to look up translation context.
4. IOMMU walks device's I/O page tables: IOVA → physical address.
5. Permission bits (Read, Write) checked against access type.
6. Success: TLP forwarded with translated physical address.
7. Failure: fault logged, device receives UR or CA completion.

Intel VT-d Internals

Two-level table lookup:

BDF → Root Table (256 entries, 16B each, indexed by Bus)
    → Context Table (256 entries, 16B each, indexed by Dev:Func)
      → Second-Level Page Tables (3–5 levels)
        → Final 4 KB physical page

Context Entry fields:
- SLPTPTR: Second-Level Page Table Pointer
- Domain ID: 16-bit (multiple devices can share a domain)
- AW: Address Width (3/4/5-level = 39/48/57-bit IOVA)
- T: Translation Type (untranslated-only, translated-only, or both)
- P: Present
- FPD: Fault Processing Disable

Page table entries (PTE, EPT-like format):
[0]      R - Read permission
[1]      W - Write permission
[7]      PS - Page Size (1=leaf super-page, 0=next-level table)
[N-1:12] Physical address of next-level table or 4 KB page

Super-pages: level-2 leaf = 2 MB, level-3 leaf = 1 GB.

Scalable Mode (VT-d 3.0+):
Context Entry → PASID Directory → PASID Table → per-PASID
first-level page-table roots. Enables Shared Virtual Memory (SVM).
Check RTADDR_REG.TTM to determine which mode is in effect.

AMD-Vi Internals

Single-level Device Table indexed directly by BDF:

BDF → Device Table Entry (32 bytes)
    → I/O Page Tables (1–6 levels)
      → Final page

DTE encodes:
- Page Table Root Pointer
- Mode (0–6, selects paging levels)
- Domain ID (16 bits)
- IR, IW — Default Read/Write permission
- GV — Guest Valid (nested translation)
- PASID-related fields

Page sizes: 4 KB, 2 MB, 1 GB.

IOTLB and Invalidation

Translations cached in IOTLB (I/O Translation Lookaside Buffer).
When mappings change, IOTLB must be invalidated.

Two distinct caches when ATS is in use:
- IOMMU's own IOTLB
- Device-side TLB (DevTLB) caching prior translations

Full invalidation with ATS requires:
1. IOMMU invalidates own IOTLB
2. IOMMU sends ATS Invalidate Request Message to device
3. Device drops affected DevTLB entries, replies with Invalidate Completion

If step 2 or 3 is skipped, device retains stale translations
and can DMA to unmapped addresses.

VT-d invalidation granularities:
- Global: flush entire IOTLB
- Domain-Selective: flush all entries for a Domain ID
- Page-Selective: flush specific IOVA range in a domain

Strict vs lazy invalidation:
Lazy mode defers IOTLB invalidation, batching them for performance.
Opens a window where stale translations remain valid — a device
whose driver has unmapped a buffer can still DMA to the old IOVA.

Fault Recording

VT-d: Fault Recording Registers — circular array capturing
  Requester ID, faulting IOVA, fault reason, TLP type.

AMD-Vi: Event Log Buffer — producer-consumer ring buffer of
  IO_PAGE_FAULT, INVALID_DEVICE_REQUEST, ATS-related events.

Both surface faults via interrupts and event-log entries.
On Windows, some IOMMU violations observable through WHEA/bug-check
paths and Driver Verifier DMA-violation telemetry.

Per-device fault rate is one of the most operationally useful
IOMMU-layer signals. Legitimate devices with correct drivers
rarely produce faults; sustained nonzero rate is direct evidence
of out-of-domain access attempts.

RMRR/IVMD:
ACPI DMAR table contains RMRR (Reserved Memory Region Reporting)
sub-tables declaring physical ranges devices need identity-mapped.
AMD-Vi has analogous IVMD (I/O Virtualization Memory Definition)
in the IVRS table. A defender should enumerate these and reject
configurations where suspect BDFs appear in RMRR scope or
RMRR ranges overlap game memory regions.

IOMMU Topology and Isolation

IOMMU Groups

Devices in the same IOMMU group may not be safely isolated from
one another. Group membership determined by:
- PCIe topology — devices behind a switch share a group
  unless the switch supports and enables ACS
- ACS state of upstream bridges
- Quirks for known-broken hardware

Linux: /sys/kernel/iommu_groups/N/devices/
Windows: equivalent constraints but no simple public group filesystem

ACS (Access Control Services, Extended Cap ID 0x000D)

ACS is a PCIe capability that switches/root ports advertise
to declare they can enforce isolation between downstream ports.

ACS Capability register enable bits:
Bit  Feature                      Effect
0    Source Validation (SV)        Drop TLPs with wrong Requester ID
1    Translation Blocking (TB)    Block AT=10 (Translated) TLPs
2    P2P Request Redirect (RR)    Force P2P requests upstream for IOMMU
3    P2P Completion Redirect (CR) Force P2P completions upstream
4    Upstream Forwarding (UF)     Forward upstream regardless
5    P2P Egress Control (EC)      Allow/deny P2P routing per-port
6    Direct Translated P2P (DT)   Allow P2P with translated addresses

Critical for untrusted endpoints: SV, TB, RR, and CR.
A switch missing Source Validation lets a malicious device spoof
its Requester ID, defeating per-BDF IOMMU translation.
A switch missing P2P Request Redirect allows devices on the same
switch to DMA directly to each other without IOMMU involvement.

Peer-to-Peer DMA

Devices on the same PCIe tree can send Memory TLPs directly to
each other's BAR ranges without involving system memory.
Without ACS forcing redirection, P2P TLPs never reach the IOMMU.

Plausible P2P DMA targets for cheat:
- GPU framebuffer — rendered game state
- Network adapter ring buffers — game traffic
- USB controller queues — input device data

Mitigation: ACS Translation Blocking + P2P Request Redirect
on every intermediate bridge. Defender must walk topology and
confirm both bits are active.

Interrupt Remapping

MSI/MSI-X interrupts are Memory Writes to 0xFEE00000–0xFEEFFFFF.
Without Interrupt Remapping (IR), any device with Bus Master enabled
can write to this range and trigger arbitrary interrupts — NMIs, SMIs,
or vectors targeting wrong CPU.

With IR enabled, IOMMU validates MSI/MSI-X writes and uses
remapping-table state to determine permitted destination.
IR is part of VT-d's broader DMA Remapping architecture.
Both VT-d and AMD-Vi have integrated equivalents.
Both should be mandatory in any anti-cheat threat model.

ATS, PASID, and Address Translation Trust

ATS (Address Translation Services, Extended Cap ID 0x000F)

ATS lets a device cache IOMMU translations locally:
1. Device issues Translation Request TLP (AT=01) with IOVA
2. IOMMU translates and responds with Translation Completion
   carrying physical address
3. Device caches translation in Device-side TLB (DevTLB)
4. Subsequent accesses issued with AT=10 (Translated) —
   IOMMU bypasses page-walk, trusting device's cached translation
5. On mapping changes, IOMMU sends Invalidation Request

Attack surface: malicious device claiming ATS can present
arbitrary AT=10 TLPs whose addresses were never approved
by the IOMMU. The IOMMU forwards them trusting the device's claim.

PASID (Extended Cap ID 0x001B)

Extends ATS to per-process address spaces. 20-bit PASID carried
in a TLP Prefix. IOMMU uses (Requester ID, PASID) jointly
to select translation context.

PASID enables Shared Virtual Memory (SVM) — primarily found in
datacenter NICs, AI accelerators. Presence on a consumer card
is anomalous.

ATS Trust Model and "ATS Untrusted" Mode

The fundamental trust assumption: device honestly reports
translations it has been granted. Unreasonable for external
Thunderbolt enclosures, FPGAs in M.2 slots, or untrusted
accelerator cards.

Modern OS/IOMMU stacks can treat endpoints as ATS-untrusted:
ATS is disabled, blocked by policy, or stripped.
Linux: pci=noats plus per-device quirks.
Windows: Kernel DMA Protection / DMAGuard matters, but don't
treat "Kernel DMA Protection: On" as proof every internal
endpoint is ATS-untrusted. Verify ATS state per endpoint.

Driver–IOMMU Contract and Bypass Catalog

Legitimate DMA Path (Windows)

1. Acquire DMA adapter: IoGetDmaAdapter / WDF wrapper
2. Allocate buffer: MmAllocateContiguousMemorySpecifyCacheNode
   or WdfCommonBufferCreate
3. Map for DMA: AllocateCommonBuffer / MapTransferEx
   - OS allocates IOVA from device's domain
   - Creates IOMMU page-table entries: [IOVA, IOVA+size) → physical pages
   - Returns IOVA to driver
4. Program device: driver writes IOVA into device's BAR registers
5. Device DMAs: TLPs arrive at IOMMU with BDF + IOVA
6. IOMMU translates: page-walk produces physical address
7. Completion and unmap: teardown IOMMU entries + IOTLB invalidation

In this model, device can DMA only to addresses the driver
explicitly mapped. Game memory is not in that range.

Six Paths to Out-of-Domain Access

1. IOMMU not active or not applied to this path
   VT-d/AMD-Vi disabled, OS not enforcing, device outside protected ports

2. Pre-boot DMA injection
   Inject before IOMMU initialized; requires firmware-level exploit

3. Identity-mapped / passthrough domains
   Legacy drivers request 1:1 mapping; modern strict-mode rejects it

4. Driver mapping over-allocation (Thunderclap class)
   OS maps full 4 KB page when buffer is smaller; adjacent kernel data exposed

5. Legitimate-path data exfiltration
   Cheat spoofed as NIC; OS network stack passes game packets through
   NIC's RX ring buffer (legitimately IOMMU-mapped). Cheat reads game data
   without leaving allowed mappings. Undetectable at IOMMU layer.

6. IOMMU page-table manipulation via kernel compromise
   BYOVD / vulnerable driver reprograms IOMMU tables.
   Requires code execution on gaming PC.

Approaches 1–3 are the foundation of most current DMA cheats.

IOMMU Bypass Catalog (16 Techniques)

#   Technique                   Mechanism                           Mitigation
─────────────────────────────────────────────────────────────────────────────────
1   IOMMU disabled              VT-d/AMD-Vi off in BIOS             Refuse misconfigured platforms
2   Pre-boot DMA                Firmware leaves injection window     UEFI updates; verify ACPI indicators
3   Identity/passthrough        1:1 IOVA-to-physical mapping        Strict-mode IOMMU policy
4   Driver over-allocation      Full 4 KB page, adjacent data       OS bounce buffers; strict mappings
5   ATS abuse                   AT=10 TLPs with arbitrary addrs     ATS Untrusted mode for non-allowlisted
6   ACS missing on bridge       P2P or spoofed Requester ID         Verify ACS state on all bridges
7   Lazy IOTLB invalidation    Stale translations valid briefly    Strict invalidation mode
8   FLR race                    FLR/Hot Reset race window           Synchronized FLR handling
9   SMM bypass                  SMM code exempt from IOMMU          Boot Guard / Platform Secure Boot
10  DMA-remapping driver bugs   Bugs in OS IOMMU manager            OS patching
11  Hypervisor escape           Compromised hypervisor              VBS / measured boot; TPM attestation
12  Interrupt injection (no IR) Write arbitrary interrupts           Mandatory IR enforcement
13  RMRR/IVMD scope abuse       Fake ACPI tables cover attacker     Measured boot; runtime RMRR audit
                                physical ranges
14  Snoop-bit manipulation      Stale cache lines visible           Strict snoop enforcement
15  PASID confusion             Misconfigured PASID Table           PASID-aware IOMMU programming
16  DMAR/IVRS spoofing          Compromised firmware, fake tables   Measured boot covering firmware

Techniques 1–6: active attack surface for current commercial DMA cheats
Techniques 7–13: academic, APT, firmware-level contexts
Techniques 14–16: largely theoretical

FPGA Hardware

Xilinx PCIe Integrated Block

Hardened IP block handling:
- Physical Layer (PHY, 8b/10b or 128b/130b, LTSSM, equalization)
- Data Link Layer (sequence numbers, replay buffer, flow control)
- Transaction Layer framing and parsing
- Subset of Configuration Space

IP core documentation:
- PG054 for 7-series
- PG156 for UltraScale Gen3
- PG213 for UltraScale+ Gen4

User logic interfaces over AXI-Stream (TX/RX) and separate
config management: cfg_mgmt_* (7-series), cfg_ext_* (UltraScale).

Detection consequences:
- Default fingerprints leak through: hard block populates Config Space
  with Xilinx-characteristic byte patterns
- 7-series firmware authors who don't understand cfg_mgmt_* leave
  subtle behavioral differences (some CfgTLPs return hard-block defaults)

FPGA Family Hierarchy

Artix-7 (consumer/mid-range, GTP transceivers, PCIe Gen2):
Chip       LUTs      BRAM(Kbit)  PCIe Hard Block
XC7A35T    20,800    1,800       Gen2 x4
XC7A50T    32,600    2,700       Gen2 x4
XC7A75T    46,200    3,780       Gen2 x4
XC7A100T   63,400    4,860       Gen2 x4
XC7A200T   134,600   13,140      Gen2 x4
(Smaller than T35 have no hard PCIe block)

Kintex-7 (high-end, GTX transceivers):
XC7K70T    41,000    4,860       Gen2 x8
XC7K160T   101,400   11,700      Gen2 x8
XC7K325T   203,800   16,020      Gen2 x8 / Gen3 x4
XC7K410T   254,200   28,620      Gen3 x8

Zynq UltraScale+ (ARM Cortex-A53 cores, GTH/GTY):
ZU2EG/CG   ~47,000   ~5.3M      Gen3 x4
ZU3EG/CG   ~70,000   ~7.6M      Gen3 x4
ZU4EG/EV   ~88,000   ~11.0M     Gen3 x8
ZU5EG/EV   ~117,000  ~18.0M     Gen3 x8
ZU6EG/CG   ~230,000  ~32.1M     Gen3 x16
(EV-suffixed: hardened H.265 codec for DMA + video-capture boards)

Resource Constraints and Capability

BRAM size caps:
  shadow config + writable overlay + BAR emulation + state machines.
  T35 (1.8 Mbit) struggles with full 4 KB shadow + 64 KB BAR + jitter buffers.
  T100 (4.86 Mbit) fits comfortably.
  Zynq ZU3 (7+ Mbit) has effectively unlimited room.

LUT count caps behavioral complexity:
  Each subsystem (MSI generator, ASPM FSM, AER counter, BAR responder)
  costs thousands of LUTs. T35 holds 1–2; T100 the full set;
  Kintex/Zynq adds runtime-reconfigurable parameter tables.

PHY transceiver family (GTP/GTX/GTH/GTY) has measurably different
signal characteristics; can sometimes be inferred from root-port
performance counters independent of firmware spoofing.

Form Factors

Form Factor           Description                 Detection
────────────────────────────────────────────────────────────────────
M.2 NGFF Key M        Internal NVMe slot           Dominant modern form;
                                                    physically invisible
M.2 + USB3 bridge     M.2 board with FT601         Gaming PC sees only M.2
PCIe x1/x4 add-in     Traditional add-in card      More physically visible
External USB3          USB3-to-PCIe (legacy)        Mostly obsolete
Combo boards           DMA + HDMI capture +         Complex device tree;
                       input injection              HDMI activity is fingerprint

M.2 slot populations are partially auditable from software through
PCI topology, ACPI, SMBIOS, storage inventory, and vendor board databases.
SMBIOS slot records are often incomplete for M.2, so detection should
be probabilistic and board-model-aware.

pcileech Framework

Project Lineage

Five upstream repositories:
- pcileech:       Host-side C application with attack modules
- pcileech-fpga:  FPGA firmware in Verilog/SystemVerilog, per-board variants
- MemProcFS:      Virtual filesystem mounting target memory as /proc-like tree
- LeechCore:      Low-level device abstraction library
- vmm:            Memory analysis engine (vmm.dll API)

Pipeline: FPGA → LeechCore → PCILeech attack modules / MemProcFS analysis

FPGA Firmware Architecture

Key modules:
- pcileech_pcie_a7.v / _us.v:        Top-level Artix-7 / UltraScale integration
- pcileech_pcie_tlps128_bram_rdwr.v:  128-bit TLP source/sink (AXI-Stream)
- pcileech_pcie_cfgspace_shadow.v:    Shadow config space in BRAM
- pcileech_cfgspace.coe:              Init data (stock: Xilinx 10EE:0666)
- pcileech_bar_impl_zerowrite4k.v:    Default BAR — absorbs writes, returns zero
- pcileech_bar_impl_loopaddr.v:       Alternative BAR — echoes address
- pcileech_bar_impl_none.v:           Disables BAR (returns UR)
- pcileech_pcie_cfg_a7.v:             Config management via cfg_mgmt_*
- pcileech_mux.v:                     TLP multiplexer
- pcileech_fifo.v:                    Internal staging FIFO

Two key architectural choices:
1. Shadow config is spoofable but not spoofed by default.
   .coe ships with placeholder Xilinx IDs. User must overwrite
   with real donor's dump and resynthesize.
2. BAR controller is functionally inert.
   zerowrite4k doesn't emulate device behavior.
   Active BAR probing catches stock builds in one operation.

Host-Side MemProcFS

Mounts target memory as filesystem:
M:\
├── pid\1234\
│   ├── name.txt
│   ├── modules\       ← loaded module list
│   ├── handles\
│   ├── vad\           ← virtual address descriptors
│   ├── memmap.txt
│   └── minidump\
├── sys\
├── name\game.exe\     ← lookup by process name
└── forensic\
    ├── yara\
    ├── timeline\
    └── registry\

Cheat development pattern:
1. Development phase: MemProcFS, signature search, cross-references
   → slow, broad scanning to find entity manager / player array / view matrix
2. Execution phase: custom app via vmm.dll/LeechCore,
   periodic reads of known offsets at 60–240 Hz
This split is fundamental to detection — behavioral analysis
targets the execution phase's statistical signature.

Stock Firmware Fingerprints

Vanilla pcileech-fpga build exhibits:
- VID/DID 10EE:0666 (Xilinx placeholder)
- Xilinx 7-series PCIe IP signature bytes at characteristic offsets
- DSN Extended Capability absent or default
- No AER, LTR, ARI, ATS, or SR-IOV capabilities
- BAR0 mapped (DMA window); BAR1–5 disabled or all-ones
- BAR reads return zero (zerowrite4k) or echo address (loopaddr)
- MSI capability present but no interrupts ever fire
- Config reads complete in deterministically uniform time
  (BRAM lookup with fixed pipeline depth, near-zero variance)
- LTSSM never leaves L0 after training; no ASPM transitions
- AER correctable-error count stays at zero
- Power management never leaves D0
- Class Code matches donor placeholder but no class-specific behavior

Configuration Space Spoofing

Bridge vs Emulated Firmware

Bridge firmware:
  Patches identity fields via Vivado's PCIe IP Core GUI
  (VID, DID, Subsystem IDs, Class Code, sometimes DSN).
  Fast to produce, but 7-series hard IP generates internal capability
  blocks at characteristic offsets that retain FPGA-specific fingerprints.

Emulated (1:1) firmware:
  Implements complete shadow Configuration Space in BRAM.
  Entire 4 KB extended config space initialized from real donor device hex dump.
  When OS issues CfgRd TLP, firmware responds from BRAM.
  IP Core's default registers never appear on the bus.

  Common bugs in emulated firmware:
  - First 16 bytes still come from IP block (mux priority)
  - Type 1 config reads not intercepted
  - Capability blocks bypassed in GUI still leak defaults

Shadow Configuration Space Implementation

Requirements:
1. Intercept incoming CfgRd0/CfgWr0 TLPs
2. Decode target offset
3. Look up value in BRAM
4. Build Completion TLP with correct Completer ID, status, payload
5. Send Completion through hard IP block

4 KB coverage at 4-byte granularity = 1,024 entries × 4 bytes = 4 KB BRAM.
Well within even T35's resources.

Overlay RAM and Writable Register Emulation

Real devices have writable registers. Firmware that returns correct
values on reads but drops writes creates detectable inconsistency.

Detection probe:
  write Command[BME] = 1 → read Command[BME]
  write Command[BME] = 0 → read Command[BME]
  Real silicon: bit toggles. Naive shadow: bit stays at BRAM init value.

Overlay RAM merges at read time:
  response = (base_value & ~writable_mask) | (overlay_value & writable_mask)

The catch: writable mask is register-specific:
- Command Register: different reserved bits than Device Control
- MSI Address Low: bits [1:0] reserved-zero
- BAR: type bits in [3:0] depend on I/O/memory, prefetchable
- Status Register: W1C bits — writing 1 clears, writing 0 no change
- AER Status: W1C across the board

Naive implementations with single global mask fail because
reserved-bit and W1C behavior diverges. Detection probes
W1C cases: write 0x00000000 to Correctable Error Status,
then write known-1 patterns, verify read-back semantics.

Donor Card Extraction

Every serious emulated firmware starts with a donor — a physical
PCIe card whose complete identity is cloned. Not just VID/DID —
entire 4 KB config space, all capabilities, BAR size masks,
MSI/MSI-X table layouts, all extended capabilities, DSN.

Extraction tools:
- lspci -d [VID:DID] -vvv -xxxx (full ECAM dump)
- setpci -s <BDF> ECAP_AER+0x4.L
- Direct ECAM mapping in kernel-mode tools
- VFIO passthrough + programmatic dump

Donor selection pitfalls:
- Duplicating hardware already in gaming PC → caught instantly
- Must match FPGA's actual PCIe capability (x16 Gen4 on Gen2 x1 fails)
- Silicon generation must align with claimed link speed
- Class-functional A/B testing detects non-functional donors

Firmware Sophistication Tiers

Tier  Description              Detection Difficulty
──────────────────────────────────────────────────────────────────
0     Stock                    Trivial — VID/DID blacklist
      Unmodified upstream;
      10EE:0666 IDs

1     Bridge                   Easy — signature residue,
      .coe replaced with       driverless device, BME clearance
      donor VID/DID only

2     Shadow config            Medium — R/W consistency probe
      Full 4 KB shadow;        catches silent write drops
      no overlay RAM

3     Overlay RAM              Medium-hard — BAR probe still fails;
      Shadow + writable layer  class-functional A/B fails
      with per-register masks

4     BAR MMIO + MSI           Hard — interrupt distribution analysis;
      Donor-class BAR memory   BAR-region content baselining
      responder + MSI generator

5     Behavioral emulation     Very hard — multi-session statistical
      Latency jitter, ASPM,    analysis required
      AER counters, donor-
      class-specific behavior

6     Private + randomized     Currently undefeated by hardware-layer
      Per-customer layout,     signatures alone
      capability shuffling,
      custom hard-IP integration

Each tier transition corresponds to a defender technique
that closed the prior tier's escape hatch.
Cost-to-implement is nonlinear: 0–2 are public/trivial,
3 needs moderate Verilog, 4–5 need deep PCIe knowledge,
6 is sustained engineering.

Donor Exhaustion

Each detected donor class becomes nonviable. Remaining viable donors
trend toward obscure industrial cards — which themselves become
a behavioral signal on consumer gaming PCs.

Donor Class            Detection Status
─────────────────────────────────────────────────────────
Wi-Fi adapters         Heavily detected; class-spoof checks ubiquitous
Wired NICs             "NIC with loaded driver but zero packets" test
NVMe SSDs              Harder; detected via missing namespace activity
Audio codecs           Lower bandwidth fits FPGA; class checks present
USB host controllers   Child-device enumeration check breaks naive
Capture cards          Harder (genuinely idle when no source)
Industrial / OEM SKUs  Increasingly only viable; demographic signal
Server-class accel.    Physically implausible on consumer boards

Detection at the PCIe Layer

Configuration Integrity

- VID/DID/SVID/SDID against known-real-silicon list
- Capability-chain walk: DWord-aligned Next pointers, no overlaps, no cycles
- Signature-residue scanning: Xilinx 7-series default byte patterns at
  known relative offsets (Device Capabilities field bits, reserved bits,
  VSEC vendor IDs)
- Capability presence consistency: donor model's known caps must all be present
- BAR mask verification: write 0xFFFFFFFF, compare size mask against donor

BAR Memory Read Probing

Send Memory Read TLPs to BAR ranges, validate responses by donor class:

NIC donor BAR0: register layout with receive/transmit ring descriptors,
  interrupt mask, link status. Offset 0x00 returns specific bit pattern.

NVMe donor BAR0: NVMe controller registers — CAP (MQES, DSTRD,
  MPSMIN/MPSMAX), VS, CC, CSTS, AQA, ASQ/ACQ, doorbells at 0x1000.

USB XHCI donor BAR0: Capability Registers (CAPLENGTH, HCSPARAMS, HCCPARAMS).

zerowrite4k returns all-zeros; loopaddr echoes address. Both are
trivially distinguishable from real content.
Tier-4 firmwares implement donor-class responders but usually only
cover registers checked at probe time, leaving others divergent.

R/W Consistency Probing

- Command Register: toggle Memory Space, I/O Space, Bus Master Enable
- Device Control: change MPS, MRRS, Error Enables
- MSI Control: toggle Enable, change Multiple Message Enable
- Walk every W1C bit (Status, AER Status): write 1s, confirm clear
- Walk reserved bits: write 1s, confirm read-back as 0
- Per-register writable masks must match donor

Tier-2 (no overlay) fails immediately.
Tier-3 (single global mask) fails on W1C and reserved-bit cases.

LTSSM and Link-State Validation

Sample PCIe Express Capability Link Status over time:
- Negotiated Width (Link Status[9:4]): consistent with donor deployment
  and FPGA hard block capability
- Current Link Speed (Link Status[3:0]): track slot's actual speed
- Gen4 x8 capability but Gen2 x1 Link Status = contradiction in one read
- DLL Active (Link Status[13]): should be 1 during operation
- Slot Clock Config (Link Status[12]): match real common-clock state

ASPM Behavioral Validation

Real devices claiming ASPM exhibit characteristic L0 ↔ L1 transitions.

Spoofed device anomalies:
- Claims ASPM capability but never transitions out of L0
- Transitions with exit latency inconsistent with claimed value
- Never reaches L1.1 / L1.2 when donor and platform both support

Sample Link Status "DLL Active" bit over time + PMC counters.

AER Baselining

- Departure from donor baseline: per-silicon correctable-error footprint
  should be stable. Implausibly clean (zero correctables when donor
  normally produces Bad TLP / Replay Timer Timeout) is anomalous.
- Implausible Header Log content (default/zeroed values)
- Inconsistent UR/CA responses to probes of unimplemented offsets

Completion Latency Fingerprinting

Real silicon: completion latency shaped by DRAM contention,
internal arbiters, PCIe pipeline depth → heavy-tailed distributions.

BRAM-backed emulators: fixed FPGA clock cycles + PCIe transit
→ much lower variance, even if mean is similar.

Detection signal is distribution shape, not absolute mean.

Statistical methods:
- Kolmogorov–Smirnov test: compare empirical CDFs
- Hill estimator: estimate tail index (real silicon has non-trivial tail;
  emulated firmware without stochastic jitter has no tail)
- Anderson-Darling test: sensitive to tail differences

Collect N latency samples (Memory Reads to BAR), compare against
per-donor reference distribution, flag devices deviating
beyond per-test-statistic threshold.

Tier-5 firmwares add LFSR-based jitter generators, but matching
real distribution shape (mean, variance, tail index, mode count)
requires modeling donor's DRAM access pattern.

MSI/MSI-X Behavioral Validation

A device with MSI Enable, Address/Data programmed, and attached driver
should produce interrupts:

- Zero interrupts when driver should exercise device = anomalous
- Implausibly uniform arrival times (exact 60 Hz heartbeat)
  = timer-driven generator, not event-driven
- Implausibly bursty patterns not matching donor class

Monitor via OS interrupt accounting, ETW/performance telemetry,
driver counters, kernel instrumentation.

Cheat-Phase Access Pattern Recognition

Two distinct patterns:

Development phase:
  Slow, broad scanning, signature search, MemProcFS walking.
  Rare during live competitive play.

Execution phase:
  Narrow, periodic reads (60–240 Hz) of small offset set
  (player positions, entity arrays, view matrices).

Execution phase statistical signature:
  High temporal periodicity, low address-space breadth,
  alignment to game-frame intervals.

Distinguishing features:
- Fano factor
- Autocorrelation at frame intervals
- Address-space coverage entropy

Honeypot regions complement this when combined with:
  IOMMU denial/fault logging, hypervisor-managed protected pages,
  device-domain sandboxing, decoy IOVA mappings, or server-side
  behavioral traps tied to fake game objects.

Hot-Plug and Link Disruption Events

Firmware swaps and donor reconfigurations require link renegotiation.
Three observable signals:

1. AER Surprise Down — uncorrectable fatal error logged when link
   drops unexpectedly mid-session.

2. Slot Status hot-plug events — Presence Detect Changed,
   Data Link Layer State Changed, MRL Sensor Changed.
   Register via IoRegisterPlugPlayNotification with
   EventCategoryTargetDeviceChange or EventCategoryDeviceInterfaceChange.

3. LTSSM re-training cycles — Link Training bit toggling,
   transient Recovery state.

A device that surprise-downs then reappears with subtly different
Config Space (adjusted MSI layout, different latency profile,
different VID/DID) = fingerprint of mid-session firmware reload.

Detection at the IOMMU Layer

Fault-Rate Monitoring

Sample per-device fault counters from IOMMU fault-recording structure
(VT-d Fault Recording Registers, AMD-Vi Event Log) or from WHEA.

Pipeline:
1. Snapshot baseline at session start
2. Sample at intervals; compute per-device fault rate
3. Threshold-trigger additional PCIe probing on devices exceeding baseline
4. Aggregate evidence across signals before action

Domain Assignment Audit

Walk IOMMU domain assignments for anomalies:
- Devices on passthrough/identity domains when strict mode is active
- Devices in unexpectedly large IOMMU groups (poor ACS topology)
- Multiple devices sharing Domain ID when they shouldn't

ACS Topology Verification

Walk PCIe bridge topology between every endpoint and root complex.
For each bridge with ACS Capability:
- Verify Source Validation (SV) enabled
- Verify Translation Blocking (TB) enabled
- Verify P2P Request Redirect (RR) and Completion Redirect (CR) enabled

Bridges without ACS at all = isolation holes by topology.
Bridges with ACS Capability but Control bits not set = misconfiguration.

IOMMU as Containment Primitive

Active containment when suspect device is identified:

1. IOMMU domain re-remapping:
   Reprogram device's domain to sandbox memory instead of revoking access.
   Cheat keeps "reading" but receives garbage data.

2. Bus Master Enable clearance:
   Toggle Command[2] to 0. Effective for tier-0 through tier-3.
   Cheats monitoring BME can race; may need repeated clearance.

3. Downstream Port Containment (DPC):
   When DPC is enabled on root port (Extended Cap ID 0x001D),
   triggers cause port to enter Contained state — all TLPs dropped,
   completions blocked, link logically isolated.
   Enforced at upstream port, no race against firmware-side BME restore.
   Not universal on all chipsets.

4. Anti-cheat-owned device domain:
   For device owned by AC driver, allocate and map only sandbox IOVAs,
   never expose game memory.

5. Hypervisor-integrated enforcement:
   Enforce policy above guest kernel by trapping IOMMU MMIO programming.
   Requires privileged platform integration.

Hypervisor-Level Defense

EPT-Based Memory Protection

EPT translates Guest Physical Address (GPA) to Host Physical Address (HPA).
A hypervisor owning the EPT can:

- Mark game memory as read-execute-only in EPT, even if guest OS marks
  read-write. Writes cause EPT violations the hypervisor traps.
- Hide pages by clearing EPT mappings.
- Implement watchpoints on specific GPA ranges.

IOMMU blocks DMA at device-to-memory boundary;
EPT blocks CPU access at guest-to-host boundary.
A cheat combining DMA card with kernel-mode payload faces both.

VBS, HVCI, and VTL Split

VBS creates Secure Kernel (VTL 1) alongside regular kernel (VTL 0)
in a Hyper-V partition. HVCI uses VTL 1 to enforce no executable page
in VTL 0 is simultaneously writable.

Anti-cheat interaction:
- Register VTL 1 callouts to validate guest state
- Attest against System Guard Secure Launch (DRTM) measurements
- Rely on HVCI to block BYOVD patterns

Combined VBS+HVCI+TPM+SecureBoot is assumed baseline for
serious anti-cheat threat models.

SMM Considerations

System Management Mode (Ring -2) runs in SMRAM, isolated from
OS and hypervisor. SMM handlers can read all physical memory
and are exempt from IOMMU enforcement.

A vulnerable SMI handler = path to arbitrary memory access
without IOMMU mediation.

Mitigations:
- Intel Boot Guard / AMD Platform Secure Boot (firmware signatures)
- SMI Transfer Monitor (STM): hypervisor-resident, treats SMM as
  constrained guest. Rarely implemented by board vendors.
- Runtime verification of SMM lockdown registers

PCIe IDE (Integrity and Data Encryption)

IDE adds link-level TLP protection: integrity (MAC-based, required)
and confidentiality (encryption, optional).
Incorporated into PCIe 6.0 base specification.

Valuable against: physical link interposers, malicious retimers/switches,
traffic tampering.

NOT a DMA-cheat silver bullet: cheat installed as the endpoint
still originates legitimate IDE-protected TLPs after key establishment.
IDE raises the bar for passive bus sniffing but endpoint identity,
IOMMU policy, ACS topology, ATS policy, and attestation remain required.

External Trust Anchors

TPM 2.0

Hardware (or firmware-isolated) cryptoprocessor with:
- PCRs: extend-only registers, PCR[n] = SHA256(PCR[n] || new_value)
- Persistent keys: EK (manufacturer), SRK (provisioned), user-defined
- Hierarchy: Endorsement, Storage, Platform, Null

PCR Allocation (Measured Boot)

PCR   Measured Content
0     SRTM / Core Root of Trust — UEFI firmware code
1     Platform configuration data — firmware variables
2     Option ROM code — third-party UEFI drivers
3     Option ROM configuration and data
4     IPL / boot manager binary (e.g., bootmgfw.efi)
5     IPL configuration — GPT/partition table, boot config
6     Manufacturer-specific / state-transition events
7     Secure Boot policy (PK, KEK, db, dbx)
8–15  OS-defined (BitLocker binds to PCR[11])
16    Debug
17–22 DRTM measurements (Secure Launch)
23    Application-defined

Remote Attestation Cryptography

Trust property: compromised local kernel cannot forge PCR values.

Flow:
1. Server sends nonce
2. Client calls TPM2_Quote(AIK, PCR_selection, nonce)
   TPM computes PCR composite, builds TPMS_ATTEST, signs with AIK
3. Client sends Quote + AIK certificate chain
4. Verifier checks:
   - AIK signature valid
   - AIK certificate chains to trusted TPM manufacturer root
   - EK on known-EK list (binds AIK to real TPM)
   - Nonce matches (freshness, replay protection)
   - PCR composite matches known-good value

A rootkit loading after measured boot cannot alter PCRs.
A software simulator cannot produce valid Quote without TPM private key.

DRTM and Secure Launch

Dynamic Root of Trust for Measurement allows "late launch" —
trusted execution environment established after OS boot,
measurement captured into PCR[17].

Intel: GETSEC[SENTER] (TXT)
AMD: SKINIT (SVM extension)

CPU enters measured execution state, Secure Loader Block (SLB)
loaded and hashed into PCR[17], control transfers to
Measured Launch Environment (MLE).

Microsoft System Guard Secure Launch uses this to load HVCI's
hypervisor into measured state independent of SRTM chain.
Defender requests Quote including PCR[17] and matches against
known-good MLE measurement.

UEFI Pre-Boot DMA Integrity

Pre-Boot DMA Protection: firmware must isolate DMA-capable devices'
I/O buffers before ExitBootServices().

ACPI indicators:
- Intel: DMA_CTRL_PLATFORM_OPT_IN_FLAG in DMAR table flags
- AMD: DMA remap support bit in IVRS IVinfo field

Windows PCR[7] event: firmware extends EV_EFI_ACTION with
"DMA Protection Disabled" when IOMMU/Kernel DMA Protection
is disabled, providing attestation hook.

Combined picture:
PCR[0]/PCR[7] anchor firmware and DMA-protection policy,
ACPI tables describe runtime IOMMU config,
documented DMA interfaces show what OS actually remaps,
attestation ties local claims to remote-verified known-good policy.

Layered Detection Pipeline

Pre-Game Environmental Verification

- IOMMU active and applied to DMA-capable PCIe paths
- Interrupt Remapping enabled
- Secure Boot enabled
- VBS/HVCI active
- TPM 2.0 present and provisioned
- Attestation Quote validates against expected policy
- BIOS/UEFI version not in known vulnerable pre-boot DMA list
- ACS topology walk: all relevant bridges enforce SV, TB, RR, CR

PCIe Inventory Pass

- Enumerate all PCIe devices via PnP tree
- Full 4 KB config-space dump for each
- Check device problem codes (DEVPKEY_Device_ProblemCode)
- Cross-reference SMBIOS slot inventory with populated devices

Configuration Integrity Per Device

- VID/DID/SVID/SDID against known-good list
- Capability-chain walk and validation
- Signature-residue scan
- BAR mask verification
- R/W consistency probing
- Compare against per-donor reference database

Behavioral Sampling During Play

- Periodic Link Status reads (LTSSM, ASPM transitions)
- AER counter snapshots
- Per-device interrupt rate and distribution
- Per-device IOMMU fault rate
- BAR-region content sampling for class consistency

Statistical Analysis Over Session

- Latency distribution comparison (KS test, Hill estimator)
- Interrupt arrival distribution
- ASPM transition rate

Cheat-Phase Detection

- Honeypot region access
- Memory access frequency / locality classifiers

Containment Before Verdict

Each detection produces evidence, not a verdict.
Verdict informed by:
- Multi-signal correlation (single signals can false-positive;
  combinations rarely do)
- Server-side aggregation across sessions
- Behavioral verification (input timing, gameplay statistics)

While verdict accumulates, containment protects the live match:
IOMMU re-remapping to sandbox, BME clearance, or EPT-level
game-process protection degrades cheat effectiveness in real time.

Realistic Limits

A firmware that:
- Clones donor byte-for-byte (full 4 KB config + all capabilities)
- Implements donor-class BAR MMIO, MSI generation, overlay RAM
- Adds completion-latency jitter matching donor distribution
- Generates plausible AER correctable-error rates
- Transitions through ASPM states like the donor
- Uses donor not present in gaming PC and not on blacklists
- Operates only within driver-mapped IOMMU domains (legitimate-path exfil)
- Avoids honeypot regions through gameplay-aware address whitelisting

...can defeat every PCIe-layer and IOMMU-layer signature in isolation.

This is why external trust anchors are required:
TPM attestation, measured boot, and server-side correlation operate
outside the "spoof a PCIe endpoint" problem.

A perfectly emulated DMA card cannot forge a TPM Quote.
But the verifier must bind Quote to allowlist/blocklist of BIOS versions,
DMA-protection events, Secure Boot state, VBS/HVCI, and IOMMU policy.

The cost of defeating all four layers simultaneously
(PCIe + IOMMU + hypervisor + attestation) exceeds typical cheat value.

Forensic Evidence Capture

What to Capture

Artifact                     Source                          Purpose
──────────────────────────────────────────────────────────────────────────────
Full 4 KB config dump        Bus interface / ECAM            Donor ID post-hoc
Capability chain walk        Parsed from config              Capability presence
PCIe link state history      Link Status over session        LTSSM anomaly proof
MSI/MSI-X arrival timeline   OS interrupt telemetry          Rate claim refutation
AER correctable counts       AER capability registers        Baseline outlier proof
IOMMU fault log entries      WHEA/ETW, Driver Verifier       DMA-violation proof
IOMMU domain assignments     IOMMU manager state walk        Passthrough anomaly
ACS bridge state             Bridge enumeration              Isolation proof
Honeypot access record       Hypervisor EPT trap log         Unauthorized read evidence
TPM PCR snapshot             TPM Quote API                   Boot-chain attestation
MCFG / DMAR / IVRS tables   ACPI subsystem                  Platform config baseline
SMBIOS slot inventory        DMI subsystem                   Slot-population audit
BIOS version + patch level   SMBIOS                          Pre-Boot DMA fix verify
Latency-distribution hists   Per-session sampling            Statistical fingerprint

Multi-Signal Correlation

Strongest evidence packages combine:
1. Hardware-layer signal (config space, BAR, link state)
2. Behavioral-layer signal (interrupt distribution, IOMMU fault rate, honeypot)
3. Temporal correlation (hardware signal preceded behavioral by plausible interval)

Three independent signals push false-positive rates below threshold
where appeals become a practical workload.

PCIe Protocol Captures

A PCIe protocol analyzer (interposer) produces the strongest forensic evidence:
full TLP-level captures with byte-exact accuracy and nanosecond timestamps.

Commercial analyzers capture every TLP, DLLP, and physical-layer ordered set.
Traces can be replayed to confirm fingerprinting findings.

Cost (tens to hundreds of thousands USD) limits routine use, but for
high-profile cases (competitive integrity, tournament, prosecution),
protocol-level captures by independent labs are the unambiguous reference.

Thunderbolt / USB4 DMA

Attack Surface

- Thunderbolt 1-4 / USB4 provide direct PCIe tunneling
- Hot-plug capable: device can be attached at runtime
- Pre-boot DMA: device has memory access before OS loads
- Thunderbolt Security Levels:
  - SL0 (None): no security, legacy mode
  - SL1 (User Auth): user must approve new devices
  - SL2 (Secure Connect): device must match previously approved UUID
  - SL3 (No PCIe tunneling): completely disables DMA

Thunderbolt-Specific Attacks

- Thunderclap: malicious Thunderbolt peripherals bypass IOMMU
- Device re-identification: change UUID to bypass SL2
- OS-level Thunderbolt driver vulnerabilities
- PCIe tunneling through USB4 hubs

Defensive Measures

- Kernel DMA Protection (Windows 10 1803+): automatic IOMMU for hot-plug
- Thunderbolt firmware verification
- Platform-level: BIOS setting to disable Thunderbolt PCIe tunneling
- macOS: T2 chip enforces DMA restrictions on Thunderbolt ports

Shadow CR3 / Split TLB

Page Table Manipulation

- Maintain two sets of page tables (two CR3 values):
  - "Clean" CR3: legitimate page tables visible to anti-cheat
  - "Shadow" CR3: modified page tables with cheat-accessible mappings
- Swap CR3 before/after anti-cheat inspection windows
- Combine with EPT manipulation for hypervisor-level split

Split TLB Techniques

- Desync instruction TLB (iTLB) and data TLB (dTLB):
  - Execute code from one physical page
  - Read data from another physical page at same virtual address
- Requires precise TLB invalidation control
- Hypervisor can create EPT-based split: execute on page A,
  read on page B, at same GPA
- Anti-cheat mitigation: TLB flush + re-walk, serializing instructions

Memory Access Techniques

Physical Memory Reading

// Typical pcileech API usage
HANDLE hDevice;
BYTE buffer[0x1000];
pcileech_read_phys(hDevice, physAddr, buffer, sizeof(buffer));

Virtual Address Translation

// Walk page tables: PML4 → PDPT → PD → PT → Physical
PHYSICAL_ADDRESS TranslateVA(UINT64 cr3, UINT64 virtualAddr) {
    UINT64 pml4e = ReadPhys(cr3 + PML4_INDEX(virtualAddr) * 8);
    UINT64 pdpte = ReadPhys(PFN(pml4e) + PDPT_INDEX(virtualAddr) * 8);
    UINT64 pde = ReadPhys(PFN(pdpte) + PD_INDEX(virtualAddr) * 8);
    UINT64 pte = ReadPhys(PFN(pde) + PT_INDEX(virtualAddr) * 8);
    return PFN(pte) + PAGE_OFFSET(virtualAddr);
}

DTB (Directory Table Base) Finding

- Scan physical memory for valid CR3 values
- Look for kernel structures
- Use signature scanning
- Validate page table entries

Security Considerations

Ethical Use

- Security research only
- Authorized testing environments
- Responsible disclosure
- Legal compliance

Risk Awareness

- Physical hardware access required
- Potential system instability
- Detection by advanced anti-cheat
- Legal implications

Resource Organization

The README contains:

  • pcileech and derivatives
  • FPGA firmware projects
  • DMA libraries
  • Integration tools
  • Device emulation firmware
  • Anti-detection implementations

Data Source

Important: This skill provides conceptual guidance and overview information. For detailed information use the following sources:

1. Project Overview & Resource Index

Fetch the main README for the full curated list of repositories, tools, and descriptions:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/README.md

The main README contains thousands of curated links organized by category. When users ask for specific tools, projects, or implementations, retrieve and reference the appropriate sections from this source.

2. Repository Code Details (Archive)

For detailed repository information (file structure, source code, implementation details), the project maintains a local archive. If a repository has been archived, always prefer fetching from the archive over cloning or browsing GitHub directly.

Archive URL format:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/archive/{owner}/{repo}.txt

Examples:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/archive/ufrisk/pcileech.txt
https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/archive/000-aki-000/GameDebugMenu.txt

How to use:

  1. Identify the GitHub repository the user is asking about (owner and repo name from the URL).
  2. Construct the archive URL: replace {owner} with the GitHub username/org and {repo} with the repository name (no .git suffix).
  3. Fetch the archive file — it contains a full code snapshot with file trees and source code generated by code2prompt.
  4. If the fetch returns a 404, the repository has not been archived yet; fall back to the README or direct GitHub browsing.

3. Repository Descriptions

For a concise English summary of what a repository does, the project maintains auto-generated description files.

Description URL format:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/description/{owner}/{repo}/description_en.txt

Examples:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/description/00christian00/UnityDecompiled/description_en.txt
https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/description/ufrisk/pcileech/description_en.txt

How to use:

  1. Identify the GitHub repository the user is asking about (owner and repo name from the URL).
  2. Construct the description URL: replace {owner} with the GitHub username/org and {repo} with the repository name.
  3. Fetch the description file — it contains a short, human-readable summary of the repository's purpose and contents.
  4. If the fetch returns a 404, the description has not been generated yet; fall back to the README entry or the archive.

Priority order when answering questions about a specific repository:

  1. Description (quick summary) — fetch first for concise context
  2. Archive (full code snapshot) — fetch when deeper implementation details are needed
  3. README entry — fallback when neither description nor archive is available
提供游戏引擎(如Unreal、Unity、Godot)开发、逆向工程及反作弊研究的资源指南。涵盖源码分析、插件开发、SDK生成及安全防护模式,适用于模组制作与安全研究。
游戏引擎内部机制查询 引擎源码与插件研究 反作弊与逆向工程分析 SDK代码生成工作流
.claude/skills/game-engine/SKILL.md
npx skills add gmh5225/awesome-game-security --skill game-engine-resources -g -y
SKILL.md
Frontmatter
{
    "name": "game-engine-resources",
    "description": "Guide for game-engine internals, source trees, plugins, and engine-specific security research. Use this skill when researching Unreal, Unity, Source, Godot, custom engines, engine detectors, engine explorers, or engine protection patterns relevant to modding, reverse engineering, and anti-cheat."
}

Game Engine Development Resources

Overview

This skill covers game engine development resources from the awesome-game-security collection, including both commercial (Unreal, Unity) and open-source engines.

README Coverage

  • Game Engine > Guide
  • Game Engine > Source
  • Game Engine Plugins:Unreal
  • Game Engine Plugins:Unity
  • Game Engine Plugins:Godot
  • Game Engine Plugins:Lumix
  • Game Engine Detector
  • Cheat > SDK CodeGen
  • Cheat > Game Engine Explorer:Unreal
  • Cheat > Game Engine Explorer:Unity
  • Cheat > Game Engine Explorer:Source
  • Anti Cheat > Game Engine Protection:Unreal
  • Anti Cheat > Game Engine Protection:Unity
  • Anti Cheat > Game Engine Protection:Source
  • Game Develop > MCP server

Major Engine Categories

Unreal Engine

  • Official documentation and forums
  • Source code access (requires Epic Games account)
  • Community guides and tutorials
  • Plugin development references

Unity Engine

  • C# reference source code
  • Asset store resources
  • Unity-specific design patterns
  • VR/AR development guides

Open Source Engines

  • Godot: Free and open-source, supports GDScript and C#
  • Cocos2d-x: Cross-platform 2D game framework
  • CRYENGINE: High-fidelity graphics engine
  • Source Engine: Valve's game engine (various versions)

Custom/Educational Engines

  • Hazel Engine (TheCherno's educational series)
  • Bevy (Rust-based data-driven engine)
  • Fyrox (Rust game engine)

Key Technical Areas

Rendering

  • Software renderers for learning
  • Ray tracing implementations
  • Shader development tutorials
  • Post-processing effects

Mathematics

  • Linear algebra libraries (GLM, DirectXMath)
  • Physics simulation (PhysX, Bullet)
  • Collision detection algorithms

Networking

  • Client-server architectures
  • KCP reliable UDP protocol
  • Steam networking integration
  • MMORPG server implementations

Resource Categories

Documentation & Guides

- Learning resources and tutorials
- Architecture documentation
- Best practices and style guides

Source Code

- Complete engine implementations
- Subsystem references (renderer, physics, audio)
- Plugin and extension examples

Plugins & Extensions

- ImGui integration for debug UIs
- Scripting language bindings (Lua, .NET)
- Editor tool plugins

Engine Selection Criteria

When researching engines for security analysis or development:

  1. Target Platform: PC, mobile, console compatibility
  2. Source Access: Open source vs proprietary
  3. Language: C++, C#, Rust, or scripting
  4. Graphics API: DirectX, OpenGL, Vulkan, Metal
  5. Community: Documentation and support quality

SDK Generation Workflows

Unreal Engine (Dumper-7)

1. Identify UE version from binary signatures
2. Inject Dumper-7 into running game process
3. SDK output: C++ headers with UObject hierarchy
4. Key structures: UObject, FName, UClass, UFunction, UProperty
5. Generated SDK enables: property access, function calls, blueprint hooks
6. Alternative tools: UnrealDumper, UE4SS (live scripting + SDK dump)

Unity (IL2CPPDumper)

1. Locate global-metadata.dat + GameAssembly.dll (or libil2cpp.so)
2. Run IL2CPPDumper → outputs: dump.cs, il2cpp.h, script.json
3. Load generated headers into IDA/Ghidra for symbol recovery
4. Key structures: Il2CppClass, MethodInfo, FieldInfo, Il2CppType
5. For Mono builds: directly decompile Assembly-CSharp.dll with dnSpy

Source Engine (NetVar Parsing)

1. Walk ClientClass linked list from CHLClient
2. For each class, enumerate RecvTable → RecvProp entries
3. Build offset map: class name → property name → offset
4. Example: CCSPlayer → m_iHealth → 0x100
5. Tools: hazedumper, source2gen (Source 2)

Engine Object Models

Unreal Engine

Core hierarchy:
  UObject → UField → UStruct → UClass
  UObject → AActor → APawn → ACharacter → APlayerCharacter

Key globals:
  GObjects (TUObjectArray): all live UObject instances
  GNames (TNameEntryArray): FName string pool
  GWorld (UWorld*): current world context
  GEngine (UEngine*): engine singleton

Memory layout:
  UObject header: VTable, ObjectFlags, InternalIndex, ClassPrivate, NamePrivate, OuterPrivate
  Properties follow at offsets defined in UClass::PropertySize

Unity (IL2CPP)

Core structures:
  Il2CppDomain → Il2CppAssembly → Il2CppImage → Il2CppClass
  Il2CppClass: fields, methods, vtable, static_fields pointer

Key patterns:
  il2cpp_domain_get() → domain singleton
  il2cpp_class_from_name() → class lookup by namespace + name
  il2cpp_runtime_invoke() → call managed methods from native

Metadata:
  global-metadata.dat contains string pool, type definitions, method signatures
  Encrypted metadata in some protected games (requires custom decryptor)

Source Engine

Core systems:
  Entity list: IClientEntityList → GetClientEntity(index)
  ConVar system: ICvar → FindVar("sv_cheats")
  NetVars: RecvTable hierarchy for network-replicated properties

Key interfaces (accessed via CreateInterface export):
  IVEngineClient, IClientEntityList, IEngineTrace
  ISurface, IPanel (for overlay rendering in Source)

MCP Servers for Game Development

The README's > MCP server subcategory includes servers relevant
to game engine workflows:

- Unreal Engine MCP: AI agent controls UE editor (spawn actors, modify properties, blueprints)
- Unity MCP: AI agent interacts with Unity editor and C# scripting
- Godot MCP: AI agent controls Godot editor and GDScript

These complement the RE-focused MCP tools (see reverse-engineering skill)
by enabling AI-assisted game development and rapid prototyping.

Security Research Focus

For game security research, understanding engine internals helps with:

  • Memory layout and object structures
  • Rendering pipeline hooks
  • Network protocol analysis
  • Anti-cheat integration points

Data Source

Important: This skill provides conceptual guidance and overview information. For detailed information use the following sources:

1. Project Overview & Resource Index

Fetch the main README for the full curated list of repositories, tools, and descriptions:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/README.md

The main README contains thousands of curated links organized by category. When users ask for specific tools, projects, or implementations, retrieve and reference the appropriate sections from this source.

2. Repository Code Details (Archive)

For detailed repository information (file structure, source code, implementation details), the project maintains a local archive. If a repository has been archived, always prefer fetching from the archive over cloning or browsing GitHub directly.

Archive URL format:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/archive/{owner}/{repo}.txt

Examples:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/archive/ufrisk/pcileech.txt
https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/archive/000-aki-000/GameDebugMenu.txt

How to use:

  1. Identify the GitHub repository the user is asking about (owner and repo name from the URL).
  2. Construct the archive URL: replace {owner} with the GitHub username/org and {repo} with the repository name (no .git suffix).
  3. Fetch the archive file — it contains a full code snapshot with file trees and source code generated by code2prompt.
  4. If the fetch returns a 404, the repository has not been archived yet; fall back to the README or direct GitHub browsing.

3. Repository Descriptions

For a concise English summary of what a repository does, the project maintains auto-generated description files.

Description URL format:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/description/{owner}/{repo}/description_en.txt

Examples:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/description/00christian00/UnityDecompiled/description_en.txt
https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/description/ufrisk/pcileech/description_en.txt

How to use:

  1. Identify the GitHub repository the user is asking about (owner and repo name from the URL).
  2. Construct the description URL: replace {owner} with the GitHub username/org and {repo} with the repository name.
  3. Fetch the description file — it contains a short, human-readable summary of the repository's purpose and contents.
  4. If the fetch returns a 404, the description has not been generated yet; fall back to the README entry or the archive.

Priority order when answering questions about a specific repository:

  1. Description (quick summary) — fetch first for concise context
  2. Archive (full code snapshot) — fetch when deeper implementation details are needed
  3. README entry — fallback when neither description nor archive is available
提供游戏黑客技术分类与威胁建模指南,涵盖内存操作、代码注入、挂钩及视觉/辅助作弊。解析从用户态到内核、超虚拟化及DMA的攻击升级路径,用于理解反作弊系统的防御面。
研究游戏安全与反作弊机制 分析游戏作弊技术实现原理 了解内存读写与进程注入技术 评估游戏引擎或系统的安全漏洞
.claude/skills/game-hacking/SKILL.md
npx skills add gmh5225/awesome-game-security --skill game-hacking-techniques -g -y
SKILL.md
Frontmatter
{
    "name": "game-hacking-techniques",
    "description": "Guide for game-hacking technique taxonomy and threat modeling relevant to game security. Use this skill when researching memory access, code injection, overlays, input simulation, engine-specific attack surfaces, or how modern anti-cheat systems constrain user-mode, kernel-mode, hypervisor, and DMA-based cheat implementations."
}

Game Hacking Techniques

Overview

This skill covers game-hacking techniques documented in the awesome-game-security collection, with emphasis on how cheats move from user mode to kernel mode, hypervisors, and DMA when defenders raise the bar. It is best used to understand the offensive side of the threat model that anti-cheat systems are designed to detect.

README Coverage

  • Cheat > Debugging
  • Cheat > Packet Sniffer&Filter
  • Cheat > Packet Capture&Parse
  • Cheat > SpeedHack
  • Cheat > Injection:Windows
  • Cheat > Injection:Linux
  • Cheat > Injection:Android
  • Cheat > Injection:IOS
  • Cheat > Injection:PlayStation
  • Cheat > DLL Hijack
  • Cheat > Hook
  • Cheat > Anti Signature Scanning
  • Cheat > RPM
  • Cheat > DMA
  • Cheat > W2S
  • Cheat > Overlay
  • Cheat > Render/Draw
  • Cheat > UI Interface
  • Cheat > Vulnerable Driver
  • Cheat > Driver Communication
  • Cheat > EFI Driver
  • Cheat > QEMU/KVM/PVE/VBOX
  • Cheat > Wine
  • Cheat > Anti Screenshot
  • Cheat > Spoof Stack
  • Cheat > Hide
  • Cheat > Anti Forensics
  • Cheat > Triggerbot & Aimbot
  • Cheat > WallHack
  • Cheat > HWID
  • Cheat > Bypass Page Protection
  • Cheat > SDK CodeGen
  • Cheat > Game Engine Explorer:*
  • Cheat > Explore UWP
  • Cheat > Explore AntiCheat System:*
  • Cheat > Game:*
  • Cheat > Launcher Abuser
  • Cheat > Linux Kernel Explorer
  • Cheat > Cheat Engine Plugins
  • Some Tricks > Windows Ring0
  • Some Tricks > Windows Ring3
  • Some Tricks > Linux
  • Some Tricks > Android

Escalation Model

User-Mode

  • Read and write process memory
  • Inject DLLs or shellcode
  • Hook graphics or input APIs

Kernel-Mode

  • Use signed or vulnerable drivers for direct memory access
  • Bypass handle-based protections and inspect protected processes
  • Interact with callbacks, page tables, or kernel objects directly

Below the OS

  • Virtualize the system with a hypervisor
  • Read memory through PCIe DMA hardware
  • Move logic to external devices or secondary machines

Core Concepts

Memory Manipulation

  • Read Process Memory (RPM)
  • Write Process Memory (WPM)
  • Pattern scanning
  • Pointer chains
  • Structure reconstruction

Process Injection

  • DLL injection methods
  • Manual mapping
  • Shellcode injection
  • Thread hijacking
  • APC injection

Hooking Techniques

  • Inline hooking (detours)
  • IAT/EAT hooking
  • VTable hooking
  • Hardware breakpoint hooks
  • Syscall hooking

Cheat Categories

Visual Cheats (ESP)

- World-to-Screen transformation
- Player/entity rendering
- Box ESP, skeleton ESP
- Item highlighting
- Radar/minimap hacks

Aim Assistance

- Aimbot algorithms (memory-based and AI visual)
- Triggerbot (auto-fire on crosshair detection)
- No recoil/no spread
- Bullet prediction and lead calculation
- Silent aim (server-side angle manipulation)
- AI visual aimbot (YOLO-based, no memory access required)

AI Visual Cheats (Computer Vision Aimbot)

Architecture overview:
"Zero memory, zero driver injection" paradigm — uses screen capture +
AI object detection + hardware input injection. No process attachment,
no kernel driver, no game memory reading.

Typical setup:
┌─────────────────┐     screen capture      ┌──────────────────┐
│  Gaming PC      │ ───────────────────────▶ │  AI Pipeline     │
│  Game + OBS     │                          │  (same PC, or    │
│                 │ ◀─────────────────────── │   second PC)     │
└─────────────────┘     hardware input       │  YOLO model      │
                        (KMBox / Logitech)   │  TensorRT/CUDA   │
                                             └──────────────────┘

Dual-machine variant (maximum isolation):
- Machine A (game): only runs game + OBS, sends frames via NDI/capture card
- Machine B (cheat): runs AI model, sends mouse commands via USB/network
  to hardware input device on Machine A
- Game machine has zero cheat code/process

Single-machine variant:
- OBS + AI model run on the same PC
- AI implemented as OBS filter plugin (looks like "OBS is running")
- Mouse output via hardware device or driver-level injection

Pipeline stages:

1. Frame Capture:
   - OBS Game Capture (injects graphics hook DLL into game process)
   - OBS Window Capture (no injection, uses DXGI Desktop Duplication)
   - OBS plugin filter form (AI as OBS filter, minimal footprint)
   - Direct framebuffer copy from GPU output layer (60+ FPS)
   - Capture card (for dual-machine: HDMI/DP input on cheat PC)

2. AI Object Detection:
   - Model: YOLOv5 / YOLOv8 / YOLOv10 / YOLO11 (lightweight variants)
   - Training: fine-tuned on game-specific screenshots
     (enemy bodies, heads, torsos as labeled bounding boxes)
   - Input: cropped region around crosshair (320x320 or 640x640)
     to reduce inference cost
   - Output: bounding boxes with class (head/body/enemy) + confidence score
   - Acceleration: TensorRT (NVIDIA), CUDA, DirectML, OpenVINO
   - Target latency: < 20–30 ms per frame for competitive play

3. Coordinate Transform and Aiming Logic:
   - Convert pixel coordinates to mouse movement delta:
     delta_x = (target_x - screen_center_x) * sensitivity
     delta_y = (target_y - screen_center_y) * sensitivity
   - Target selection: closest to crosshair, highest confidence,
     head priority, or combined scoring
   - FOV (Field of View) lock: only engage targets within
     configurable pixel radius from crosshair center

4. Human-like Trajectory Smoothing:
   - Not instant snap — gradual movement with acceleration curve
   - Micro-jitter injection (simulates hand tremor)
   - Bézier curve or cubic interpolation for path
   - End-point correction (overshoot then settle)
   - Random engagement probability (e.g., 85-90% lock rate)
   - Slight intentional offset (not pixel-perfect center-mass)
   - Variable reaction delay (50-200 ms simulated human response)

5. Mouse Movement Execution:
   - Hardware input devices (see Input Simulation section below)
   - Movement commands sent as physical HID reports
   - Game sees genuine hardware mouse input, not API calls

Why OBS specifically:
- Legitimate streaming software, used by millions of streamers
- Anti-cheat cannot ban OBS-related processes without collateral damage
- Game Capture provides fast, low-latency frame access
- Plugin system allows embedding AI as a filter (invisible to AC)
- Supports D3D11, D3D12, Vulkan, OpenGL capture paths

YOLO Model Training Pipeline (for Game AI Aimbot)

End-to-end workflow from raw game screenshots to deployed TensorRT model.

1. Data Collection:
   - Capture game screenshots during actual gameplay (OBS recording or replay)
   - Capture diverse scenarios: different maps, lighting, character skins,
     distances, poses, partial occlusion, smoke/flash effects
   - Aim for 2,000-10,000+ labeled images for robust detection
   - Include negative samples (empty scenes, friendlies, environment objects)

2. Annotation / Labeling:
   - Tools: LabelImg (YOLO format), CVAT (collaborative), Roboflow (cloud),
     Label Studio, makesense.ai (browser-based)
   - YOLO format: one .txt per image, each line:
     <class_id> <center_x> <center_y> <width> <height>
     (all values normalized to 0-1 relative to image dimensions)
   - Class definitions (typical):
     0: enemy_body (full body bounding box)
     1: enemy_head (head-only bounding box, for headshot targeting)
     2: friendly (to avoid shooting teammates)
   - Label head separately from body for head-priority targeting
   - Quality control: consistent label boundaries, no missed instances

3. Data Augmentation:
   - Built-in Ultralytics augmentations (mosaic, mixup, copy-paste)
   - Game-specific augmentations:
     - Brightness/contrast variation (simulate different map lighting)
     - Random crop around crosshair area (match inference ROI)
     - Motion blur (simulate fast movement)
     - Noise injection (simulate compression artifacts)
   - Avoid augmentations that distort aspect ratio
     (characters would look unnatural, hurting accuracy)

4. Training:
   - Framework: Ultralytics YOLOv8/v10/v11/YOLO11
   - Base model: yolov8n.pt or yolov8s.pt (nano/small for speed)
     or yolo11n.pt for latest architecture
   - Training command:
     yolo detect train data=game_dataset.yaml model=yolov8n.pt
       epochs=100 imgsz=640 batch=16 device=0
   - dataset.yaml structure:
     path: /path/to/dataset
     train: images/train
     val: images/val
     names: {0: enemy_body, 1: enemy_head, 2: friendly}
   - Key hyperparameters to tune:
     - imgsz: 320 (fastest) or 640 (more accurate)
     - lr0: initial learning rate (default 0.01)
     - conf: confidence threshold for inference (typically 0.4-0.6)
     - iou: IoU threshold for NMS (typically 0.45-0.7)
   - Training time: 1-4 hours on RTX 3060+ for nano model

5. Validation and Testing:
   - Evaluate mAP@0.5 and mAP@0.5:0.95 on validation set
   - Target: mAP@0.5 > 0.85 for reliable game detection
   - Test inference speed on target hardware
   - Visual inspection on held-out game screenshots

6. Export to TensorRT (deployment):
   - Step 1: Export to ONNX
     yolo export model=best.pt format=onnx simplify=True opset=17
   - Step 2: Convert ONNX to TensorRT engine
     yolo export model=best.pt format=engine half=True device=0
     (half=True enables FP16 precision)
   - Or use trtexec directly:
     trtexec --onnx=best.onnx --saveEngine=best.engine
       --fp16 --workspace=4096
   - FP16 performance: ~17 ms latency, ~57 FPS throughput,
     ~0.9% mAP drop vs FP32 (acceptable trade-off)
   - INT8 quantization: even faster but requires calibration dataset
     and careful accuracy validation

7. Runtime Integration:
   - Load TensorRT engine in C++/Python inference loop
   - Input: preprocessed frame (resize, normalize, HWC→CHW, float32/16)
   - Output: [N, 6] tensor (x1, y1, x2, y2, confidence, class_id)
   - Apply NMS (Non-Maximum Suppression) to deduplicate detections
   - Select target based on: closest to crosshair + highest confidence
   - Convert pixel coordinates to mouse delta

Alternative acceleration backends:
- DirectML (AMD GPUs, Windows native)
- OpenVINO (Intel GPUs/CPUs)
- ONNX Runtime with CUDA EP (cross-platform)
- CoreML (macOS, less common for game cheats)

Movement Cheats

- Speed hacks
- Fly hacks
- No clip
- Teleportation
- Bunny hop automation

Miscellaneous

- Wallhacks
- Skin changers
- Unlock all
- Economy manipulation

Overlay & Rendering

Overlay Methods

  • DirectX Hook: D3D9/11/12 Present hook
  • Vulkan Hook: vkQueuePresentKHR hook
  • OpenGL Hook: wglSwapBuffers hook
  • DWM Overlay: Desktop Window Manager
  • External Window: Transparent overlay window
  • Steam Overlay: Hijacking Steam's overlay
  • NVIDIA Overlay: GeForce Experience hijack

Rendering Libraries

  • Dear ImGui: Immediate mode GUI
  • GDI/GDI+: Windows graphics
  • Direct2D: Hardware-accelerated 2D

Memory Access Methods

User-Mode

- OpenProcess + ReadProcessMemory
- NtReadVirtualMemory
- Memory-mapped files
- Shared memory sections

Kernel-Mode

- Driver-based access
- Physical memory access
- MDL-based copying
- KeStackAttachProcess

Advanced Methods

- DMA (Direct Memory Access)
- EFI runtime services
- Hypervisor-based access
- Hardware-based (FPGA)

EFI/UEFI Cheats

Boot-Time Loading

- EFI manual map: load unsigned driver payload during UEFI boot phase
- ExitBootServices hook: intercept Windows boot to inject kernel code
- Runtime DXE drivers: persist across OS boot via EFI runtime services
- GetVariable/SetVariable: communicate between EFI and OS runtime

EFI-Based Memory Access

- Map physical memory via EFI runtime services
- Bypass DSE entirely (code runs before Windows kernel loads)
- Survive Secure Boot if firmware is compromised or test-signed
- Combine with DMA for maximum stealth

Detection Challenges

- No driver load event (PsSetLoadImageNotifyRoutine never fires)
- Not visible in MmUnloadedDrivers or PiDDBCacheTable
- Secure Boot + TPM attestation is primary defense
- Firmware integrity measurement (UEFI capsule verification)

HWID Spoofing

Targets

- Disk serial: IOCTL_STORAGE_QUERY_PROPERTY, SMART data
- NIC MAC address: NDIS OID_802_3_PERMANENT_ADDRESS
- SMBIOS: motherboard serial, system UUID, BIOS vendor
- GPU serial: registry-based or NVAPI/ADL queries
- Monitor EDID: display serial number
- Volume serial: NtQueryVolumeInformationFile
- TPM EK: Endorsement Key fingerprint

Techniques

- Disk filter driver: intercept IOCTL and replace serial in response
- Registry value spoofing: modify cached hardware IDs
- SMBIOS table patching: modify raw SMBIOS memory region
- NIC driver hook: replace MAC in NDIS miniport response
- Full HWID spoofer: coordinated spoofing across all identifiers

Stack Spoofing

Return Address Spoofing

- Replace return address on stack before API call
- Restore original after call returns
- Evades stack-walk-based detection (RtlWalkFrameChain)
- Techniques: JMP RBX gadget, synthetic frames, fiber-based

Call Stack Reconstruction

- Build fake but plausible call stack frames
- Match expected module return addresses (ntdll, kernel32)
- Evade NtQueryInformationThread stack inspection
- Tools: SpoofCallStack, Vulcan, CallStackSpoofer

Detection & Evasion

- Anti-cheat walks thread stacks looking for non-module returns
- Stack unwinding via .pdata / UNWIND_INFO validation
- Spoofed stacks must pass RtlVirtualUnwind consistency checks

Driver Communication

Full Taxonomy (40+ methods in README)

IOCTL-based:
- Standard DeviceIoControl with custom control codes
- Buffered I/O, Direct I/O, METHOD_NEITHER

Data pointer swaps (abusing legitimate syscalls):
- NtUserGetObjectInformation
- NtConvertBetweenAuxiliaryCounterAndPerformanceCounter
- NtUserRegisterRawInputDevices
- NtGdiGetCOPPCompatibleOPMInformation
- NtDxgkGetTrackedWorkloadStatistics
- NtUserGetPointerInfoList
- NtUserSetInformationThread
- NtDCompositionSetChildRootVisual
- Win32k syscall hooks

Shared memory:
- Named shared sections (ZwCreateSection + ZwMapViewOfSection)
- Physical memory mapping
- Shared event objects for signaling

Callback-based:
- Registry callbacks (CmRegisterCallbackEx)
- Minifilter communication ports (FltCreateCommunicationPort)
- Object callbacks with embedded data

Unconventional channels:
- Named pipes from kernel
- Window messages (NtUserPostMessage)
- ETW provider channels
- Socket from kernel (Winsock Kernel / WSK)
- File system filter callbacks
- Debugging APIs (DbgPrint interception)

World-to-Screen Calculation

Basic Formula

Vector2 WorldToScreen(Vector3 worldPos, Matrix viewMatrix) {
    Vector4 clipCoords;
    clipCoords.x = worldPos.x * viewMatrix[0] + worldPos.y * viewMatrix[4] + 
                   worldPos.z * viewMatrix[8] + viewMatrix[12];
    clipCoords.y = worldPos.x * viewMatrix[1] + worldPos.y * viewMatrix[5] + 
                   worldPos.z * viewMatrix[9] + viewMatrix[13];
    clipCoords.w = worldPos.x * viewMatrix[3] + worldPos.y * viewMatrix[7] + 
                   worldPos.z * viewMatrix[11] + viewMatrix[15];
    
    if (clipCoords.w < 0.1f) return invalid;
    
    Vector2 NDC;
    NDC.x = clipCoords.x / clipCoords.w;
    NDC.y = clipCoords.y / clipCoords.w;
    
    Vector2 screen;
    screen.x = (screenWidth / 2) * (NDC.x + 1);
    screen.y = (screenHeight / 2) * (1 - NDC.y);
    
    return screen;
}

Engine-Specific Techniques

Unity (Mono)

  • Assembly-CSharp.dll analysis
  • Mono JIT hooking
  • Il2CppDumper for IL2CPP builds
  • Method address resolution

Unity (IL2CPP)

  • GameAssembly.dll analysis
  • Metadata recovery
  • Type reconstruction
  • Native hooking

Unreal Engine

  • GObjects/GNames enumeration
  • UWorld traversal
  • SDK generation (Dumper-7)
  • Blueprint hooking

Source Engine

  • Entity list enumeration
  • NetVars parsing
  • ConVar manipulation
  • Signature scanning

Input Simulation

Software Methods

  • SendInput API
  • mouse_event/keybd_event
  • DirectInput hooking
  • Raw input injection
  • Driver-based input (mouclass)

Kernel-Level

  • Mouse class service callback
  • Keyboard filter drivers
  • HID manipulation

Hardware Input Devices (for AI Visual Cheats)

Hardware input devices produce genuine HID reports indistinguishable
from real mouse/keyboard at the USB protocol level. This is the
critical stealth layer for AI visual aimbot setups.

KMBox series (KMBox Net, KMBox B Pro, KMBox B+):
- Standalone hardware device connected via USB or network
- Receives mouse/keyboard commands over TCP/UDP or serial
- Generates real USB HID reports to the gaming PC
- Gaming PC sees a standard USB mouse, not API-injected input
- Network variant enables dual-machine setups
- Supports relative movement, absolute positioning, button events
- API: simple serial/network protocol for move(dx, dy), click, etc.

Arduino / Teensy / STM32 microcontroller:
- Custom firmware emulating USB HID device
- Receives commands from cheat PC via serial/USB CDC
- Generates USB HID mouse reports
- Cheapest hardware option, fully customizable
- Leonardo / Pro Micro (ATmega32U4) most common for native USB HID

Logitech driver exploitation:
- Older versions of G HUB / LGS (Logitech Gaming Software) expose
  internal APIs for mouse movement
- ghub_mouse_move() or lgs_mouse_move() via DLL injection into GHUB
- Logitech devices have driver-level whitelist advantage
- Specific driver versions required (newer versions patched)
- No external hardware needed, but driver-version-dependent

Interception driver (interception.sys):
- Open-source keyboard/mouse filter driver
- Intercepts and injects input at driver level
- Commonly used with AI aimbots for zero-hardware-cost injection
- Detectable by anti-cheat (driver signature known)

HDMI/DP KVM-style middleman:
- Hardware device sitting between mouse and PC
- Intercepts real mouse data, injects AI-calculated deltas
- Transparent to both the mouse and the PC
- Highest stealth but most complex hardware setup

Detection difficulty ranking:
1. Dedicated hardware (KMBox, Arduino HID) — hardest to detect
   (genuine USB HID, no driver anomaly)
2. KVM middleman — very hard (transparent hardware interposer)
3. Logitech driver method — moderate (known driver versions)
4. Interception driver — easier (known driver signature)
5. SendInput / mouse_event — easiest (API-level, trivially detected)

KMBox Protocol Details

KMBox Net (network variant) — UDP-based protocol:

Packet header (16 bytes, Little-Endian):
Offset  Field      Size   Description
0x00    MAC        4 B    Device UUID (unique per device, used for auth)
0x04    RAND       4 B    Random value or parameter
0x08    INDEXPTS   4 B    Incrementing sequence number (replay protection)
0x0C    CMD        4 B    Command code

Key command codes:
Code          Command          Description
0xAF3C2828    connect          Establish connection with device
0xAEDE7345    mouse_move       Direct mouse movement (dx, dy)
0xAEDE7346    mouse_automove   Human-like movement with interpolation
0xA238455A    mouse_beizer     Bézier curve mouse movement
0x9823AE8D    mouse_left       Left button press/release
0x238D8212    mouse_right      Right button press/release
0x97A3AE8D    mouse_middle     Middle button press/release
0xFFEEAD38    mouse_wheel      Scroll wheel
0x123C2C2F    keyboard_all     Keyboard key event

Mouse API functions:
- move(x, y):                 Direct relative movement, no interpolation
- move_auto(x, y, ms):        Human-like movement over ms milliseconds,
                               built-in Bézier curve interpolation
- move_beizer(x, y, ms,       Second-order Bézier curve with custom
    x1, y1, x2, y2):          control points for trajectory shaping

Encrypted variants (enc_*):   Same functions with packet-level encryption
                               to resist network packet analysis

Performance:
- Network (UDP): ~1,000 commands/second
- Serial (KMBox B/B+, 115200 baud): ~300 commands/second
- Network latency: < 2 ms per command (LAN)

KMBox B / B Pro (serial variant):
- USB CDC serial communication (COM port)
- Baud rate: 115200 or higher
- Simpler protocol: ASCII or binary command frames
- move(x, y) over serial: ~3 ms round trip

Physical keyboard/mouse monitoring:
- monitor() function reads real user input from the device
- Enables "pass-through + inject" mode:
  real user input flows through normally,
  AI-calculated deltas are added on top

Arduino / Teensy HID protocol:
- Custom serial command format (typically simple ASCII):
  "M,dx,dy\n"      — mouse move
  "C,button\n"      — click (1=left, 2=right, 3=middle)
  "K,keycode\n"     — keypress
- USB HID report generated by ATmega32U4 (Leonardo)
  or ARM-based Teensy (3.2, 4.0, 4.1)
- HID report descriptor mimics standard mouse:
  buttons (3 bits) + X delta (8-16 bits) + Y delta (8-16 bits)
- No custom driver needed — OS uses generic HID driver

Logitech driver API (exploitable versions):
- G HUB versions prior to certain patches expose internal functions
- Key DLLs: LGS (lcore.dll), G HUB (ghub_mouse.dll or internal APIs)
- ghub_mouse_move(dx, dy) or equivalent internal symbol
- Accessed via DLL injection into GHUB process
  or LoadLibrary + GetProcAddress
- Movement appears as Logitech device input in the HID stack
- Patched in newer G HUB versions; specific version numbers
  circulate in cheat communities

Anti-Detection Techniques

Code Protection

  • Polymorphic code
  • Code virtualization
  • Anti-dump techniques
  • String encryption

Runtime Evasion

  • Stack spoofing
  • Return address manipulation
  • Thread context hiding
  • Module concealment

Development Workflow

External Cheat

1. Pattern scan for signatures
2. Read game memory externally
3. Process data in separate process
4. Render overlay or use input simulation

Internal Cheat

1. Inject into game process
2. Hook rendering functions
3. Access game objects directly
4. Render through game's graphics context

Learning Resources

Communities

  • UnknownCheats
  • GuidedHacking
  • Game Hacking Academy

Practice Targets

  • PWN Adventure (intentionally vulnerable)
  • CTF game challenges
  • Older/unsupported games

Data Source

Important: This skill provides conceptual guidance and overview information. For detailed information use the following sources:

1. Project Overview & Resource Index

Fetch the main README for the full curated list of repositories, tools, and descriptions:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/README.md

The main README contains thousands of curated links organized by category. When users ask for specific tools, projects, or implementations, retrieve and reference the appropriate sections from this source.

2. Repository Code Details (Archive)

For detailed repository information (file structure, source code, implementation details), the project maintains a local archive. If a repository has been archived, always prefer fetching from the archive over cloning or browsing GitHub directly.

Archive URL format:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/archive/{owner}/{repo}.txt

Examples:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/archive/ufrisk/pcileech.txt
https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/archive/000-aki-000/GameDebugMenu.txt

How to use:

  1. Identify the GitHub repository the user is asking about (owner and repo name from the URL).
  2. Construct the archive URL: replace {owner} with the GitHub username/org and {repo} with the repository name (no .git suffix).
  3. Fetch the archive file — it contains a full code snapshot with file trees and source code generated by code2prompt.
  4. If the fetch returns a 404, the repository has not been archived yet; fall back to the README or direct GitHub browsing.

3. Repository Descriptions

For a concise English summary of what a repository does, the project maintains auto-generated description files.

Description URL format:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/description/{owner}/{repo}/description_en.txt

Examples:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/description/00christian00/UnityDecompiled/description_en.txt
https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/description/ufrisk/pcileech/description_en.txt

How to use:

  1. Identify the GitHub repository the user is asking about (owner and repo name from the URL).
  2. Construct the description URL: replace {owner} with the GitHub username/org and {repo} with the repository name.
  3. Fetch the description file — it contains a short, human-readable summary of the repository's purpose and contents.
  4. If the fetch returns a 404, the description has not been generated yet; fall back to the README entry or the archive.

Priority order when answering questions about a specific repository:

  1. Description (quick summary) — fetch first for concise context
  2. Archive (full code snapshot) — fetch when deeper implementation details are needed
  3. README entry — fallback when neither description nor archive is available
提供图形API拦截、覆盖层渲染及渲染管线分析指南,涵盖DirectX、OpenGL和Vulkan。适用于Present/SwapBuffers钩子、交换链处理、着色器/绘制调用拦截、防截图覆盖层及游戏安全研究中的图形调试场景。
需要拦截或挂钩图形API(如DX11 Present, Vulkan vkQueuePresentKHR) 开发跨平台覆盖层或ImGui集成 进行游戏反作弊逆向或截图保护绕过 分析渲染管线或绘制调用
.claude/skills/graphics-api/SKILL.md
npx skills add gmh5225/awesome-game-security --skill graphics-api-hooking -g -y
SKILL.md
Frontmatter
{
    "name": "graphics-api-hooking",
    "description": "Guide for graphics API interception, overlay rendering, and render-pipeline analysis across DirectX, OpenGL, and Vulkan. Use this skill when working with Present or SwapBuffers hooks, DXGI swap chains, shader or draw-call interception, screenshot-sensitive overlays, or graphics debugging in game security research."
}

Graphics API Hooking & Rendering

Overview

This skill covers graphics API resources from the awesome-game-security collection, including DirectX, OpenGL, and Vulkan hooking techniques, overlay rendering, and graphics debugging.

README Coverage

  • DirectX > Guide
  • DirectX > Hook
  • DirectX > Tools
  • DirectX > Emulation
  • DirectX > Compatibility
  • DirectX > Overlay
  • OpenGL > Guide
  • OpenGL > Source
  • OpenGL > Hook
  • Vulkan > Guide
  • Vulkan > API
  • Vulkan > Hook
  • Cheat > Overlay
  • Cheat > Render/Draw
  • Cheat > Anti Screenshot
  • Anti Cheat > Screenshot
  • Anti Cheat > Detection:Overlay

DirectX

DirectX 9

// Key functions to hook
IDirect3DDevice9::EndScene
IDirect3DDevice9::Reset
IDirect3DDevice9::Present

DirectX 11

// Key functions to hook
IDXGISwapChain::Present
ID3D11DeviceContext::DrawIndexed
ID3D11DeviceContext::Draw

DirectX 12

// Key functions to hook
IDXGISwapChain::Present
ID3D12CommandQueue::ExecuteCommandLists

VTable Hooking

// DX11 Example
typedef HRESULT(__stdcall* Present)(IDXGISwapChain*, UINT, UINT);
Present oPresent;

HRESULT __stdcall hkPresent(IDXGISwapChain* swapChain, UINT syncInterval, UINT flags) {
    // Render overlay here
    return oPresent(swapChain, syncInterval, flags);
}

// Hook via vtable
void* swapChainVtable = *(void**)swapChain;
oPresent = (Present)swapChainVtable[8];  // Present is index 8

OpenGL

Key Functions

wglSwapBuffers
glDrawElements
glDrawArrays
glBegin/glEnd (legacy)

Hook Example

typedef BOOL(WINAPI* wglSwapBuffers_t)(HDC);
wglSwapBuffers_t owglSwapBuffers;

BOOL WINAPI hkwglSwapBuffers(HDC hdc) {
    // Render overlay
    return owglSwapBuffers(hdc);
}

Vulkan

Key Functions

vkQueuePresentKHR
vkCreateSwapchainKHR
vkCmdDraw
vkCmdDrawIndexed

Instance/Device Layers

  • Use validation layers for debugging
  • Custom layers for interception
  • Layer manifest configuration

Universal Hook Libraries

Kiero

  • Cross-API hook library
  • Supports DX9/10/11/12, OpenGL, Vulkan
  • Automatic method detection

Universal ImGui Hook

  • Pre-built ImGui integration
  • Multiple API support
  • Easy deployment

ImGui Integration

Setup (DX11)

// In Present hook
ImGui_ImplDX11_Init(device, context);
ImGui_ImplWin32_Init(hwnd);

// Render
ImGui_ImplDX11_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();

// Your rendering code
ImGui::Begin("Overlay");
// ...
ImGui::End();

ImGui::Render();
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());

Window Procedure Hook

// Required for ImGui input
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
    if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam))
        return true;
    return CallWindowProc(oWndProc, hWnd, msg, wParam, lParam);
}

Overlay Techniques

External Overlay

1. Create transparent window
2. Set WS_EX_LAYERED | WS_EX_TRANSPARENT
3. Use SetLayeredWindowAttributes
4. Render with GDI+/D2D
5. Position over game window

DWM Overlay

- Hook Desktop Window Manager
- Render in DWM composition
- Higher privilege requirements
- Better anti-detection

Steam Overlay Hijack

- Hook Steam's overlay functions
- Use existing overlay infrastructure
- Requires Steam running

NVIDIA Overlay Hijack

- Hook GeForce Experience overlay
- Native-looking overlay
- May require specific drivers

Shader Manipulation

Wallhack Implementation

// Disable depth testing
OMSetDepthStencilState(depthDisabledState, 0);

// Or in pixel shader
float4 PSMain(VS_OUTPUT input) : SV_Target {
    // Always pass depth test
    return float4(1, 0, 0, 0.5);  // Red transparent
}

Chams (Character Highlighting)

// Replace model shader
float4 PSChams(VS_OUTPUT input) : SV_Target {
    if (isEnemy) {
        return float4(1, 0, 0, 1);  // Red
    }
    return float4(0, 1, 0, 1);      // Green
}

Rendering Concepts

World-to-Screen

D3DXVECTOR3 WorldToScreen(D3DXVECTOR3 pos, D3DXMATRIX viewProjection) {
    D3DXVECTOR4 clipCoords;
    D3DXVec3Transform(&clipCoords, &pos, &viewProjection);
    
    if (clipCoords.w < 0.1f) return invalid;
    
    D3DXVECTOR3 NDC;
    NDC.x = clipCoords.x / clipCoords.w;
    NDC.y = clipCoords.y / clipCoords.w;
    
    D3DXVECTOR3 screen;
    screen.x = (viewport.Width / 2) * (NDC.x + 1);
    screen.y = (viewport.Height / 2) * (1 - NDC.y);
    
    return screen;
}

View Matrix Extraction

- From device constants
- Pattern scanning
- Engine-specific locations
- Reverse engineered addresses

Debugging Tools

PIX for Windows

  • Frame capture and analysis
  • GPU profiling
  • Shader debugging

RenderDoc

  • Open-source frame debugger
  • Multi-API support
  • Resource inspection

NVIDIA Nsight

  • Performance analysis
  • Shader debugging
  • Frame profiling

Anti-Screenshot Techniques

How Anti-Cheat Captures Screenshots

- BitBlt from game window DC: captures visible content including overlays
- DXGI Desktop Duplication API: captures composited desktop output
- IDXGISwapChain::Present interception: grab backbuffer before present
- PrintWindow: capture specific window contents
- DirectX/Vulkan frame readback: copy render target to CPU-readable buffer
- Scheduled captures: random intervals to catch intermittent overlays

Overlay Evasion Against Screenshot

- Disable overlay rendering during screenshot frame:
  - Detect screenshot by hooking BitBlt/PrintWindow in AC module
  - Suppress ImGui rendering for captured frame
- DWM composition tricks:
  - Render to a separate window that DWM excludes from capture
  - Use WDA_EXCLUDEFROMCAPTURE (SetWindowDisplayAffinity) on overlay window
- Hardware overlay planes:
  - Use IDXGIOutput::FindClosestMatchingMode + hardware overlay
  - Content on hardware overlay plane may not appear in software capture
- External rendering:
  - Render on secondary display or capture card output
  - OBS virtual camera trick: render to virtual camera feed

Cheat-Side Anti-Screenshot (README > Anti Screenshot)

- Projects that detect and evade AC screenshot capture
- Techniques: hook Present to suppress overlay on screenshot frames
- DWM-based overlays that survive PrintWindow but not BitBlt
- Kernel-level: suppress screenshot by blocking DC access

OBS Capture Pipeline and AI Visual Cheat Surface

OBS Frame Capture Modes

OBS (Open Broadcaster Software) is the primary frame source for
AI visual cheats. Its capture modes have distinct detection profiles:

Game Capture (most common for cheats):
- Injects obs-graphics-hook64.dll into game process
- Hooks IDXGISwapChain::Present (D3D11/12) or SwapBuffers (OpenGL)
  or vkQueuePresentKHR (Vulkan) inside the game process
- Copies backbuffer to shared texture/memory each frame
- Lowest latency, highest quality (pre-composition, native resolution)
- Detection: DLL appears in game process module list;
  shared texture handle creation visible to kernel callbacks

Window Capture:
- Uses DXGI Desktop Duplication API (no injection into game)
- Captures composited window output from DWM
- Slightly higher latency (post-composition)
- Detection: IDXGIOutputDuplication usage from non-game process

Display Capture:
- Captures entire monitor output
- Highest latency, captures everything including overlays
- No per-process interaction

OBS Virtual Camera:
- Outputs captured frames as a virtual camera device
- Can feed AI model running in separate process or machine
- Detectable via virtual camera driver enumeration

Frame Pipeline for AI Aimbot

Capture path (latency-critical):
  Game render → Present hook copies backbuffer
  → Shared GPU texture (ID3D11Texture2D, GPU-side)
  → GPU→CPU readback (staging texture + Map/Unmap)
  → CPU-side frame buffer (system memory)
  → Crop to ROI (Region of Interest, e.g., 640x640 around crosshair)
  → AI inference input (CUDA/TensorRT/DirectML)

OBS plugin form factor:
  AI model implemented as OBS video filter plugin
  → Receives frames through obs_source_frame callback
  → Runs inference in-process
  → Outputs mouse commands to hardware device
  → Appears as "OBS running a filter" to the system

Dual-machine pipeline:
  Game PC OBS → NDI (Network Device Interface) or capture card
  → Cheat PC receives video stream
  → AI inference on cheat PC GPU
  → Mouse commands sent via network to KMBox on game PC
  Latency: +5-15 ms for NDI, +2-5 ms for hardware capture card

Performance targets:
  Capture: < 5 ms (GPU shared texture copy)
  Crop + preprocess: < 2 ms
  YOLO inference: 5-15 ms (TensorRT FP16 on RTX 3060+)
  Coordinate calc + smoothing: < 1 ms
  Hardware input transmission: < 2 ms (USB) or < 5 ms (network)
  Total pipeline: 15-40 ms end-to-end

Detection-Relevant Graphics Signals

- obs-graphics-hook64.dll in game process module list
- IDXGISwapChain::Present hook or detour in game process
- Staging texture creation at frame rate (ID3D11Texture2D with
  D3D11_USAGE_STAGING + CPU_ACCESS_READ created per frame)
- GPU-to-CPU memory copy bandwidth anomaly (Map/Unmap calls
  at 60+ FPS on backbuffer-sized resources)
- DXGI shared handle creation from game process to external process
- NDI SDK DLLs loaded (Processing.NDI.Lib.*.dll)
- Virtual camera driver (obs-virtualcam) registered

Anti-Detection Considerations

Present Hook Detection

- VTable integrity checks
- Code section verification
- Call stack analysis
- Module list scanning for known capture DLLs

Evasion Techniques

- Trampoline hooks
- Hardware breakpoints
- Timing obfuscation

Performance Optimization

Best Practices

1. Minimize state changes
2. Batch draw calls
3. Use instancing
4. Cache resources
5. Profile regularly

Common Issues

- Flickering: Double buffer sync
- Artifacts: Clear state properly
- Performance: Reduce overdraw

Resource Organization

The README contains:

  • DirectX 9/11/12 hook implementations
  • OpenGL hook libraries
  • Vulkan interception tools
  • ImGui integration examples
  • Overlay frameworks
  • Shader modification tools

Data Source

Important: This skill provides conceptual guidance and overview information. For detailed information use the following sources:

1. Project Overview & Resource Index

Fetch the main README for the full curated list of repositories, tools, and descriptions:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/README.md

The main README contains thousands of curated links organized by category. When users ask for specific tools, projects, or implementations, retrieve and reference the appropriate sections from this source.

2. Repository Code Details (Archive)

For detailed repository information (file structure, source code, implementation details), the project maintains a local archive. If a repository has been archived, always prefer fetching from the archive over cloning or browsing GitHub directly.

Archive URL format:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/archive/{owner}/{repo}.txt

Examples:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/archive/ufrisk/pcileech.txt
https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/archive/000-aki-000/GameDebugMenu.txt

How to use:

  1. Identify the GitHub repository the user is asking about (owner and repo name from the URL).
  2. Construct the archive URL: replace {owner} with the GitHub username/org and {repo} with the repository name (no .git suffix).
  3. Fetch the archive file — it contains a full code snapshot with file trees and source code generated by code2prompt.
  4. If the fetch returns a 404, the repository has not been archived yet; fall back to the README or direct GitHub browsing.

3. Repository Descriptions

For a concise English summary of what a repository does, the project maintains auto-generated description files.

Description URL format:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/description/{owner}/{repo}/description_en.txt

Examples:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/description/00christian00/UnityDecompiled/description_en.txt
https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/description/ufrisk/pcileech/description_en.txt

How to use:

  1. Identify the GitHub repository the user is asking about (owner and repo name from the URL).
  2. Construct the description URL: replace {owner} with the GitHub username/org and {repo} with the repository name.
  3. Fetch the description file — it contains a short, human-readable summary of the repository's purpose and contents.
  4. If the fetch returns a 404, the description has not been generated yet; fall back to the README entry or the archive.

Priority order when answering questions about a specific repository:

  1. Description (quick summary) — fetch first for concise context
  2. Archive (full code snapshot) — fetch when deeper implementation details are needed
  3. README entry — fallback when neither description nor archive is available
提供Android/iOS游戏安全、逆向工程及反作弊研究指南。涵盖APK/IPA分析、IL2CPP处理、Frida/Zygisk使用、Root越狱绕过、内核模块及模拟器检测等场景。
Android或iOS游戏逆向分析 APK或IPA文件解包与反编译 使用Frida进行动态插桩和Hook Root或越狱检测绕过 移动设备内存修改与调试 Unity IL2CPP库分析与还原
.claude/skills/mobile-security/SKILL.md
npx skills add gmh5225/awesome-game-security --skill mobile-security -g -y
SKILL.md
Frontmatter
{
    "name": "mobile-security",
    "description": "Guide for Android and iOS game security, reversing, and anti-cheat-adjacent platform research. Use this skill when working with APK or IPA analysis, IL2CPP mobile titles, Frida, Zygisk or Magisk, jailbreak or root detection bypass, Android kernel modules, emulator detection, or mobile anti-cheat systems."
}

Mobile Game Security

Overview

This skill covers mobile security resources from the awesome-game-security collection, focusing on Android and iOS game security research, reverse engineering, and protection bypass techniques.

README Coverage

  • Cheat > Magisk
  • Cheat > Xposed
  • Cheat > Frida
  • Cheat > Hook ART(android)
  • Cheat > Hook syscall(android)
  • Cheat > Android Terminal Emulator
  • Cheat > Android File Explorer
  • Cheat > Android Memory Explorer
  • Cheat > Android Application CVE
  • Cheat > Android Kernel CVE
  • Cheat > Android Bootloader Bypass
  • Cheat > IoT / Smart devices
  • Cheat > Android ROM
  • Cheat > Android Device Trees
  • Cheat > Android Kernel Source
  • Cheat > Android Root
  • Cheat > Android Kernel driver development
  • Cheat > Android Kernel Explorer
  • Cheat > Android Kernel Driver
  • Cheat > Android Network Explorer
  • Cheat > Android memory loading
  • Cheat > IOS jailbreak
  • Cheat > IOS Memory Explorer
  • Cheat > IOS File Explorer
  • Cheat > IOS App Packaging
  • Cheat > Injection:Android
  • Cheat > Injection:IOS
  • Anti Cheat > Detection:Android root
  • Anti Cheat > Detection:Magisk
  • Anti Cheat > Detection:Frida
  • Some Tricks > Android
  • Android Emulator
  • IOS Emulator

Android Security

APK Analysis

Tools

  • apktool: Decompile/recompile APKs
  • jadx: DEX to Java decompiler
  • APKiD: Identify packers/protectors
  • Frida: Dynamic instrumentation
  • APKLab: VS Code integration

Workflow

# Decompile APK
apktool d game.apk

# Analyze DEX files
jadx -d output game.apk

# Identify protection
apkid game.apk

Native Library Analysis

IL2CPP Games (Unity)

1. Extract libil2cpp.so from APK
2. Use IL2CPP Dumper to generate headers
3. Analyze with IDA/Ghidra
4. Hook using Frida or native hooks

Native Games

1. Identify target libraries (.so files)
2. Analyze with reverse engineering tools
3. Pattern scan for functions
4. Apply hooks/patches

Memory Manipulation

Tools

  • GameGuardian: Memory editor
  • Cheat Engine (ceserver): Remote debugging
  • Custom memory tools: Direct /proc/pid/mem access

Access Methods

// Via /proc filesystem
int fd = open("/proc/pid/mem", O_RDWR);
pread64(fd, buffer, size, address);
pwrite64(fd, buffer, size, address);

Hooking Frameworks

Frida

// Basic function hook
Interceptor.attach(Module.findExportByName("libgame.so", "function_name"), {
    onEnter: function(args) {
        console.log("Called with: " + args[0]);
    },
    onLeave: function(retval) {
        retval.replace(0);
    }
});

Native Hooks

  • Substrate: Inline hooking framework
  • And64InlineHook: ARM64 inline hooks
  • xHook: PLT hook library
  • Dobby: Multi-platform hook framework

Modern Root Solutions

KernelSU

- Kernel-based root solution, works at kernel level (no /system modification)
- Module system compatible with Magisk modules via KSU module API
- Stealth advantage: no su binary on filesystem, harder to detect
- Requires custom kernel or GKI (Generic Kernel Image) patching
- APatch: newer alternative, patches boot.img with KernelPatch

APatch

- Patches Android kernel at boot via KernelPatch
- No need for custom kernel source (works on stock GKI kernels)
- Module support similar to Magisk/KernelSU
- Root process runs within kernel context

Root Solution Comparison

| Solution  | Level       | Stealth | GKI Support | Module System |
|-----------|-------------|---------|-------------|---------------|
| Magisk    | User/Init   | Medium  | Yes         | Mature        |
| KernelSU  | Kernel      | High    | Yes         | Growing       |
| APatch    | Kernel      | High    | Yes         | Growing       |

Managed Dynamic Instrumentation on Rooted Android

Methodology (KSU/Magisk module + single binary engine):
- Package injector + loader + agent into one ARM64 binary
  to reduce footprint and version mismatch risk
- Expose a local HTTP RPC control plane (127.0.0.1:<port>) for
  low-latency script management, session listing, and function calls
- Keep boot path safe: do NOT start instrumentation engine in
  post-fs-data/service early stage; use delayed manual start after
  boot_completed to avoid zygote/module startup contention

Injection modes:
- Attach: ptrace into running process, inject bootstrap shellcode,
  resolve libc symbols, dlopen agent, then run JS
- Spawn: zygote-hijack path to pause child at fork and inject before
  app initialization (covers Application.onCreate / class init)
- Watch-SO: eBPF-based dlopen monitor that triggers injection when
  target native library is loaded

Stealth tiers:
- NORMAL: direct RWX patching (fastest, easiest to detect)
- WXSHADOW: shadow-page patching to reduce /proc memory visibility
- RECOMP: function recompile/relocation with minimal inline patch

Operational pattern:
- Lifecycle commands: start/stop/restart/status
- Analysis mode: temporarily disable conflicting zygisk modules,
  reboot, instrument, then restore and reboot back to normal mode
- Troubleshooting-first logging: keep manager and engine logs separate

Root Detection Bypass

Common Checks

- /system/bin/su existence
- /system/xbin/su existence  
- Build.TAGS contains "test-keys"
- ro.build.selinux property
- Magisk files/folders
- Package manager checks

Bypass Methods

  • Magisk DenyList / Shamiko: Modern root hiding (replaces MagiskHide)
  • LSPosed/EdXposed: Xposed framework hooks
  • Frida scripts: Hook detection functions
  • APK patching: Remove detection code
  • KernelSU SU isolation: Process-level root visibility control

Zygisk Modules

// Zygisk module structure
class Module : public zygisk::ModuleBase {
    void onLoad(zygisk::Api *api, JNIEnv *env) override {
        this->api = api;
        this->env = env;
    }
    
    void preAppSpecialize(zygisk::AppSpecializeArgs *args) override {
        // Before app loads
    }
    
    void postAppSpecialize(const zygisk::AppSpecializeArgs *args) override {
        // After app loads - inject here
    }
};

Android Protections

Common Protectors

  • Tencent ACE: Chinese market protection
  • AppSealing: Commercial protection
  • DexGuard/ProGuard: Obfuscation
  • Arxan: Enterprise protection

iOS Security

Analysis Tools

  • Hopper: Disassembler
  • IDA Pro: Industry standard
  • class-dump: Objective-C header extraction
  • Frida: Dynamic instrumentation
  • Clutch/dumpdecrypted: App decryption

Jailbreak Tools

  • H5GG: iOS cheat engine
  • Flex: Runtime patching
  • Cycript: Runtime manipulation
  • ceserver-ios: Cheat Engine for iOS

Hooking (Jailbroken)

// Using Logos (Theos)
%hook TargetClass
- (int)targetMethod:(int)arg {
    int result = %orig;
    return result * 2;  // Modify return
}
%end

Non-Jailbreak Techniques

  • Sideloading: Modified IPAs
  • Enterprise certificates: Custom signing
  • AltStore: Self-signing tool

Unity Mobile Games

IL2CPP Analysis

1. Locate libil2cpp.so (Android) or UnityFramework (iOS)
2. Find global-metadata.dat
3. Run IL2CPPDumper
4. Generate SDK/headers
5. Hook target functions

Mono Analysis

1. Extract managed DLLs
2. Decompile with dnSpy/ILSpy
3. Modify and repackage
4. Or hook at runtime

Common Targets

- Currency/coins values
- Player stats (health, damage)
- Inventory manipulation
- Premium unlocks
- Ad removal

Unreal Mobile Games

Analysis Approach

1. Identify UE version
2. Dump SDK using appropriate tool
3. Locate GObjects, GNames
4. Find target functionality
5. Apply memory patches or hooks

Overlay Rendering (Android)

Surface-Based

// Native surface overlay
ANativeWindow* window = ANativeWindow_fromSurface(env, surface);
// Render using OpenGL ES or Vulkan

ImGui Integration

  • Zygisk + ImGui modules
  • Surface hijacking
  • Direct framebuffer access

Network Analysis

Tools

  • mitmproxy: MITM proxy
  • Charles Proxy: Traffic analysis
  • Frida SSL bypass: Certificate pinning bypass

Certificate Pinning Bypass

// Frida universal SSL bypass
Java.perform(function() {
    var TrustManager = Java.registerClass({
        implements: [X509TrustManager],
        methods: {
            checkClientTrusted: function() {},
            checkServerTrusted: function() {},
            getAcceptedIssuers: function() { return []; }
        }
    });
    // Install custom TrustManager
});

Anti-Cheat on Mobile

Common Systems

  • Tencent ACE: Chinese games
  • NetEase Protection: NetEase games
  • Custom solutions: Per-game implementations

Detection Methods

- Root/jailbreak detection
- Frida detection
- Emulator detection
- Integrity checks
- Debugger detection
- Hook detection

Bypass Strategies

1. Static analysis of detection code
2. Hook detection functions
3. Hide injection footprint
4. Timing attack consideration
5. Clean environment emulation

eBPF-Based Tools

Tracing & Hooking

- stackplz: eBPF-based stack trace tool for Android
- eDBG: eBPF-powered debugger for Android processes
- tracee: Aqua Security's eBPF runtime security tool (Linux/Android)
- eBPF hooking: attach to tracepoints, kprobes, uprobes without kernel module

Advantages Over Traditional Approaches

- No kernel module compilation required (runs in eBPF VM)
- Works on stock GKI kernels with BTF support
- Lower detection surface than kernel driver injection
- CO-RE (Compile Once, Run Everywhere) portability
- Safe: eBPF verifier prevents kernel crashes

Android Kernel Driver Development

Development Patterns

- Loadable kernel module (LKM) for older kernels
- GKI-compatible modules via vendor_dlkm partition
- Kernel build scripts: build from AOSP source or vendor BSP
- Device Trees: hardware description for board-specific drivers

Common Use Cases in Game Security

- Process memory access: /dev/custom_mem → read/write target process
- Syscall hooking: __NR_read, __NR_write interception
- Binder hooking: intercept IPC transactions
- GPU memory inspection: access GPU buffers directly

Android Kernel Source

- AOSP Common Kernel (ACK): google/common branch
- GKI: Generic Kernel Image for Android 12+
- Vendor-specific: Qualcomm (CodeAurora), MediaTek, Samsung Exynos
- Build system: build/build.sh or Bazel-based (newer)

HarmonyOS / OpenHarmony

- HarmonyOS (Huawei): abc file format for compiled apps
- arkdecompiler: decompile HarmonyOS abc bytecode
- OpenHarmony: open-source base, growing ecosystem
- Security model differs from Android: distributed capabilities
- Reverse engineering challenges: new bytecode VM, different IPC

Android CVE Research

Application-Level CVEs

- WebView RCE (CVE-based exploit chains)
- Intent redirection / deep link abuse
- Content provider data leaks
- Serialization vulnerabilities (Parcel, Bundle)

Kernel-Level CVEs

- Use-after-free in Binder driver
- Privilege escalation via ion/DMA-BUF
- GPU driver vulnerabilities (Adreno, Mali, PowerVR)
- SELinux policy bypass chains
- Reference: Android Security Bulletins (monthly)

Emulator Considerations

Android Emulators

  • LDPlayer: Gaming focused
  • BlueStacks: Popular emulator
  • NoxPlayer: Game optimization
  • MEmu: Android gaming

Emulator Detection

- Build.FINGERPRINT checks
- Hardware sensor verification
- File system characteristics
- Performance timing

Resource Organization

The README contains:

  • Android hooking frameworks
  • iOS jailbreak tools
  • Memory manipulation utilities
  • Root/jailbreak bypass tools
  • Mobile anti-cheat research
  • Emulator resources

Data Source

Important: This skill provides conceptual guidance and overview information. For detailed information use the following sources:

1. Project Overview & Resource Index

Fetch the main README for the full curated list of repositories, tools, and descriptions:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/README.md

The main README contains thousands of curated links organized by category. When users ask for specific tools, projects, or implementations, retrieve and reference the appropriate sections from this source.

2. Repository Code Details (Archive)

For detailed repository information (file structure, source code, implementation details), the project maintains a local archive. If a repository has been archived, always prefer fetching from the archive over cloning or browsing GitHub directly.

Archive URL format:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/archive/{owner}/{repo}.txt

Examples:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/archive/ufrisk/pcileech.txt
https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/archive/000-aki-000/GameDebugMenu.txt

How to use:

  1. Identify the GitHub repository the user is asking about (owner and repo name from the URL).
  2. Construct the archive URL: replace {owner} with the GitHub username/org and {repo} with the repository name (no .git suffix).
  3. Fetch the archive file — it contains a full code snapshot with file trees and source code generated by code2prompt.
  4. If the fetch returns a 404, the repository has not been archived yet; fall back to the README or direct GitHub browsing.

3. Repository Descriptions

For a concise English summary of what a repository does, the project maintains auto-generated description files.

Description URL format:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/description/{owner}/{repo}/description_en.txt

Examples:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/description/00christian00/UnityDecompiled/description_en.txt
https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/description/ufrisk/pcileech/description_en.txt

How to use:

  1. Identify the GitHub repository the user is asking about (owner and repo name from the URL).
  2. Construct the description URL: replace {owner} with the GitHub username/org and {repo} with the repository name.
  3. Fetch the description file — it contains a short, human-readable summary of the repository's purpose and contents.
  4. If the fetch returns a 404, the description has not been generated yet; fall back to the README entry or the archive.

Priority order when answering questions about a specific repository:

  1. Description (quick summary) — fetch first for concise context
  2. Archive (full code snapshot) — fetch when deeper implementation details are needed
  3. README entry — fallback when neither description nor archive is available
指导维护awesome-game-security资源库,涵盖反作弊、DMA、逆向工程等领域。用于添加资源、分类整理、映射主题及保持README格式规范。
添加游戏安全相关资源链接 整理或创建新的资源分类 检查并统一README.md的Markdown格式 生成或更新目录结构
.claude/skills/overview/SKILL.md
npx skills add gmh5225/awesome-game-security --skill awesome-game-security-overview -g -y
SKILL.md
Frontmatter
{
    "name": "awesome-game-security-overview",
    "description": "Guide for understanding and contributing to the awesome-game-security curated resource list. Use this skill when adding new resources, organizing categories, mapping topics across anti-cheat, Windows kernel, DMA, reverse engineering, and game-engine research, or maintaining README.md format consistency."
}

Awesome Game Security - Project Overview

Purpose

This is a curated collection of resources related to game security, covering both offensive (game hacking, cheating) and defensive (anti-cheat) aspects. The project serves as a comprehensive reference for security researchers, game developers, and enthusiasts, especially where Windows internals, driver trust, reverse engineering, DMA, and modern anti-cheat defenses intersect.

README Coverage

  • Top-level engines and rendering: Game Engine, Renderer, DirectX, OpenGL, Vulkan
  • Offensive research: Cheat
  • Defensive research: Anti Cheat
  • Platform hardening: Windows Security Features
  • Platform-specific ecosystems: Android Emulator, IOS Emulator, Windows Emulator, Linux Emulator
  • Supporting infrastructure: Mathematics, 3D Graphics, AI, Image Codec, Wavefront Obj, Task Scheduler, Game Network, PhysX SDK, Game Develop, Game Assets, Game Hot Patch, Game Testing, Game Tools, Game Manager, Game CI
  • Platform subsystems: WSL, WSA
  • Console emulation: Game Boy, Nintendo Switch, Xbox, PlayStation
  • Tips and tricks: Some Tricks

Project Structure

awesome-game-security/
├── README.md           # Main resource list
├── LICENSE             # MIT License
├── awesome-image.webp  # Project banner
└── scripts/
    ├── generate-toc.py  # Generate table of contents
    └── remove-forks.py  # Clean up forked repos

README.md Format Convention

Category Structure

Each category follows this format:

## Category Name
> Subcategory (optional)
- https://github.com/user/repo [Brief description]
- https://github.com/user/repo [Another description]

Link Format

  • Always use full GitHub URLs for repositories
  • Non-GitHub links are also supported (blog posts, articles, documentation sites)
  • Add brief descriptions in square brackets [description]
  • Use consistent spacing and formatting
  • Group related resources under subcategories with >

Example Entry

## Game Engine
> Guide
- https://github.com/example/guide [Comprehensive game dev guide]

> Source
- https://github.com/example/engine [Open source game engine]

Skill Routing Guide

When an AI agent receives a query, use this table to select the best skill:

Query topic Primary skill Related skills
EAC, BattlEye, Vanguard, detection, heartbeat, screenshot anti-cheat windows-kernel
pcileech, FPGA, DMA, IOMMU, Thunderbolt dma-attack anti-cheat
Unreal SDK, Unity IL2CPP, engine structs, Godot, Lumix game-engine game-hacking
Memory hacking, injection, overlays, driver comm, HWID spoof game-hacking graphics-api
D3D/Vulkan/OpenGL hooks, Present hook, shader interception graphics-api game-hacking
Android root, Frida, iOS jailbreak, KernelSU, APatch mobile-security game-hacking
IDA, Ghidra, DBI, deobfuscation, binary diffing, MCP RE tools, trap-and-emulate CFT, WHP tracing reverse-engineering anti-cheat, windows-kernel
Drivers, callbacks, PatchGuard, HVCI, ETW, pool forensics, WHP API windows-kernel anti-cheat, reverse-engineering
Adding resources, README format, link validation overview (any)

Main Categories

All 27 top-level ## sections in README.md:

  1. Game Engine: Engines, source code, plugins (Unreal/Unity/Godot/Lumix), detectors
  2. Mathematics: Linear algebra, physics libraries
  3. Renderer: Software renderers, ray tracing
  4. 3D Graphics: 3D modeling and graphics resources
  5. AI: Machine learning for games
  6. Image Codec: Image processing libraries
  7. Wavefront Obj: OBJ file parsers
  8. Task Scheduler: Job/task scheduling systems
  9. Game Network: Networking, KCP, JWT, geolocation
  10. PhysX SDK: NVIDIA PhysX resources
  11. Game Develop: Development guides, source code, MCP servers, AI agents
  12. Game Assets / Hot Patch / Testing / Tools / Manager / CI: Supporting infrastructure
  13. DirectX: Guides, hooks, tools, emulation, overlays
  14. OpenGL: Guides, source, hooks
  15. Vulkan: API, guides, hooks
  16. Cheat: Offensive research (debugging, injection, hooking, DMA, overlays, driver comm, EFI, anti-forensics, game-specific)
  17. Anti Cheat: Defensive research (protection, detection, callbacks, forensics, signature scanning)
  18. Some Tricks: Ring0/Ring3/Linux/Android tricks and techniques
  19. Windows Security Features: DSE, PatchGuard, VBS, HVCI, Secure Boot
  20. WSL / WSA: Windows Subsystem for Linux/Android
  21. Windows / Linux / Android / IOS Emulator: Platform emulators
  22. Game Boy / Nintendo Switch / Xbox / PlayStation: Console emulators and research

Contributing Guidelines

  1. Check for duplicates before adding new resources
  2. Verify links are working and point to original repos
  3. Add descriptions that clearly explain the resource's purpose
  4. Place in correct category based on primary functionality
  5. Follow existing format for consistency

Quality Criteria

  • Resource should be actively maintained or historically significant
  • Should provide unique value not covered by existing entries
  • Prefer original repos over forks unless fork adds significant value
  • Include language/platform tags when helpful (e.g., [Rust], [Unity])

Scripts Usage

Generate Table of Contents

python scripts/generate-toc.py

Remove Fork References

python scripts/remove-forks.py

Data Source

Important: This skill provides conceptual guidance and overview information. For detailed information use the following sources:

1. Project Overview & Resource Index

Fetch the main README for the full curated list of repositories, tools, and descriptions:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/README.md

The main README contains thousands of curated links organized by category. When users ask for specific tools, projects, or implementations, retrieve and reference the appropriate sections from this source.

2. Repository Code Details (Archive)

For detailed repository information (file structure, source code, implementation details), the project maintains a local archive. If a repository has been archived, always prefer fetching from the archive over cloning or browsing GitHub directly.

Archive URL format:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/archive/{owner}/{repo}.txt

Examples:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/archive/ufrisk/pcileech.txt
https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/archive/000-aki-000/GameDebugMenu.txt

How to use:

  1. Identify the GitHub repository the user is asking about (owner and repo name from the URL).
  2. Construct the archive URL: replace {owner} with the GitHub username/org and {repo} with the repository name (no .git suffix).
  3. Fetch the archive file — it contains a full code snapshot with file trees and source code generated by code2prompt.
  4. If the fetch returns a 404, the repository has not been archived yet; fall back to the README or direct GitHub browsing.

3. Repository Descriptions

For a concise English summary of what a repository does, the project maintains auto-generated description files.

Description URL format:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/description/{owner}/{repo}/description_en.txt

Examples:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/description/00christian00/UnityDecompiled/description_en.txt
https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/description/ufrisk/pcileech/description_en.txt

How to use:

  1. Identify the GitHub repository the user is asking about (owner and repo name from the URL).
  2. Construct the description URL: replace {owner} with the GitHub username/org and {repo} with the repository name.
  3. Fetch the description file — it contains a short, human-readable summary of the repository's purpose and contents.
  4. If the fetch returns a 404, the description has not been generated yet; fall back to the README entry or the archive.

Priority order when answering questions about a specific repository:

  1. Description (quick summary) — fetch first for concise context
  2. Archive (full code snapshot) — fetch when deeper implementation details are needed
  3. README entry — fallback when neither description nor archive is available
指导逆向工程受保护的游戏及反作弊组件,涵盖用户态、内核态及虚拟机环境。提供调试工具、反汇编、内存分析及动态二进制插桩技术,用于分析驱动、IOCTL协议及注入代码等安全敏感组件。
分析游戏反作弊驱动或内核模块 调试受保护的Unity/.NET游戏应用 研究动态二进制插桩与API钩子技术 逆向分析混淆或加壳的二进制文件
.claude/skills/reverse-engineering/SKILL.md
npx skills add gmh5225/awesome-game-security --skill reverse-engineering-tools -g -y
SKILL.md
Frontmatter
{
    "name": "reverse-engineering-tools",
    "description": "Guide for reverse engineering protected games and anti-cheat components across user mode, kernel mode, and hypervisor-aware environments. Use this skill when analyzing drivers, IOCTL protocols, callback registration, injected-code artifacts, integrity checks, protected binaries, or debugging security-sensitive game components."
}

Reverse Engineering Tools & Techniques

Overview

This skill covers reverse engineering workflows for game security research, including protected game clients, anti-cheat user-mode modules, kernel drivers, memory artifacts, and debugging environments that must survive anti-analysis checks.

README Coverage

  • Cheat > Debugging
  • Cheat > RE Tools
  • Cheat > Mixed boolean-arithmetic
  • Cheat > Dynamic Binary Instrumentation
  • Cheat > Fix VMP
  • Cheat > Fix Themida
  • Cheat > Fix OLLVM
  • Cheat > Virtual Environments
  • Cheat > Decompiler
  • Cheat > IDA themes
  • Cheat > IDA Plugins
  • Cheat > IDA Signature Database
  • Cheat > Binary Ninja Plugins
  • Cheat > Ghidra Plugins
  • Cheat > Radare Plugins
  • Cheat > Windbg Plugins
  • Cheat > X64DBG Plugins
  • Cheat > Cheat Engine Plugins
  • Cheat > ROP Finder
  • Cheat > ROP Generation
  • Anti Cheat > Anti Debugging
  • Anti Cheat > Anti Disassembly
  • Anti Cheat > Dump Fix
  • Anti Cheat > Sample Unpacker
  • Anti Cheat > Obfuscation Engine
  • Anti Cheat > Winows User Dump Analysis
  • Anti Cheat > Winows Kernel Dump Analysis

Debugging Tools

Windows Debuggers

  • Cheat Engine: Memory scanner and debugger for games
  • x64dbg: Open-source x86/x64 debugger
  • WinDbg: Microsoft's kernel/user-mode debugger
  • ReClass.NET: Memory structure reconstruction
  • HyperDbg: Hypervisor-based debugger

Specialized Debuggers

  • CE Mono Helper: Unity/Mono game debugging
  • dnSpy: .NET assembly debugger/decompiler
  • ILSpy: .NET decompiler
  • frida: Dynamic instrumentation toolkit

Platform-Specific

  • edb-debugger: Linux debugger
  • PINCE: Linux game hacking tool
  • H5GG: iOS cheat engine
  • Hardware Breakpoint Tools: HWBP implementations

Disassembly & Decompilation

Multi-Platform

  • IDA Pro: Industry standard disassembler
  • Ghidra: NSA's reverse engineering framework
  • Binary Ninja: Modern RE platform
  • Cutter: Radare2 GUI

Specialized Tools

  • IL2CPP Dumper: Unity IL2CPP analysis
  • dnSpy: .NET/Unity decompilation
  • jadx: Android DEX decompiler
  • Recaf: Java bytecode editor

Memory Analysis

Memory Scanners

- Cheat Engine: Pattern scanning, value searching
- ReClass.NET: Structure reconstruction
- Process Hacker: System analysis

Dump Tools

- KsDumper: Kernel-space process dumping
- PE-bear: PE file analysis
- ImHex: Hex editor for RE

Dynamic Binary Instrumentation (DBI)

Frameworks

  • Frida: Cross-platform DBI
  • DynamoRIO: Runtime code manipulation
  • Pin: Intel's DBI framework
  • TinyInst: Lightweight instrumentation
  • QBDI: QuarkslaB DBI

Use Cases

  1. API hooking and tracing
  2. Code coverage analysis
  3. Fuzzing harness creation
  4. Behavioral analysis
  5. Driver IOCTL and callback tracing

Exception-Driven Lightweight DBI (Trap-and-Emulate)

Concept:
- Replace branch instructions with fault-generating sentinel opcodes
- Catch the resulting exception → emulate the original branch → log → resume
- Full cycle: patch → fault → capture → emulate → record → restore → continue

Sentinel Selection:
- HLT (0xF4) for ret → triggers STATUS_PRIVILEGED_INSTRUCTION
- SALC (0xD6) for jmp/jcc/call → triggers STATUS_ILLEGAL_INSTRUCTION
- Avoids INT3 (0xCC) which anti-debug/integrity checks commonly scan for
- Different sentinels can multiplex branch types

Exception Capture:
- Hook KiUserExceptionDispatcher (not VEH/SEH) for lowest-latency interception
- Assembly stub tail-calls into RtlDispatchException
- Handler dispatches by exception code to custom emulation logic

Branch Emulation Engine:
- Disassemble original (pre-patch) instruction at fault RIP
- jcc: 16-condition lookup table (ZF, SF, CF, OF, PF combinations)
- Direct call: push return address, update RIP
- Indirect branch: resolve effective address (register, memory, SIB, RIP-relative)
- ret: pop return address from stack, handle ret imm16 (extra pop)
- loop/jrcxz: decrement RCX, conditional branch

Instrumentation Strategies:
- Bounded Bulk Patching: scan a window from seed address, patch all branches
  → Simple but detectable by integrity checks
- Branch Chasing: patch only current branch, re-instrument at target on fault
  → Minimal memory footprint, highest stealth, best for unknown binaries
- CFG-Guided Patching: recursive-descent static CFG + chasing for unreached edges
  → Best coverage/safety balance

Integrity Check Evasion:
- PAGE_GUARD + Trap Flag (single-step) instead of direct code patching
- Trigger guard page exception → set TF → single-step through original instruction
- Avoids modifying .text section (defeats hash-based integrity checks)

Control Flow Tracing (CFT) Applications

- Runtime call graph generation with register context at each edge
- Divergence testing: compare traces across different inputs/environments
  → Quickly locates input validation, anti-debug, anti-tamper trigger points
- Deobfuscation: resolve all indirect branches in virtualized code
- Hot path analysis, branch coverage measurement
- Performance: ~600x slowdown (exception per branch), not suitable for
  timing-sensitive targets (rdtsc checks, session timeouts)
- Portable to other architectures: ARM (UDF), RISC-V (illegal instruction)

User-Mode Hypervisor-Assisted Tracing

Concept:
- Use Windows Hypervisor Platform (WHP) API to run guest code in user mode
- No kernel driver required — standard user-mode process hosts the hypervisor
- Map host memory pages into guest address space
- Configure page-level traps (read/write/execute permissions per page)
- Guest execution triggers VM exits on configured events

Trap-Driven Execution:
- Page fault traps: set per-page R/W/X permissions via EPT-equivalent API
  → Execute fault = code coverage, Write fault = memory write monitoring
  → Read fault = data access tracking
- CPUID interception: guest executes CPUID → VM exit → host decides response
  → Useful for fingerprinting guest environment queries
- Syscall interception: guest executes syscall → VM exit → host emulates
  → Controlled experiments without real kernel interaction

Workflow:
1. Prepare initial CPU state (registers, segments, control registers)
2. Map target code + data pages with desired permissions
3. Enter guest execution loop
4. On VM exit: inspect reason, handle trap, optionally modify state
5. Resume or terminate guest

Advantages:
- Pure user-mode: no driver signing, no PatchGuard concerns
- Deterministic: full control over guest memory and execution
- Composable: combine with disassemblers/emulators for hybrid analysis
- Debuggable: host process can be debugged normally

Limitations:
- Requires hardware virtualization support (VT-x/AMD-V)
- Windows-specific (WHP API is Windows 10+)
- Cannot run full OS — suited for code snippets and function-level analysis
- Nested virtualization considerations when host is already a VM

Anti-Analysis Bypass

Techniques

  • Anti-debug detection bypass
  • VM/Sandbox evasion
  • Timing attack mitigation
  • PatchGuard circumvention

Tools

  • TitanHide: Anti-debug hiding
  • HyperHide: Hypervisor-based hiding
  • ScyllaHide: Anti-anti-debug plugin

Game-Specific Analysis

Unity Games

  1. Locate GameAssembly.dll (IL2CPP) or managed DLLs
  2. Use IL2CPP Dumper for structure recovery
  3. Apply dnSpy for Mono games
  4. Hook via Unity-specific frameworks

Unreal Engine Games

  1. Identify UE version from signatures
  2. Use SDK generators (Dumper-7)
  3. Analyze Blueprint bytecode
  4. Hook UObject/UFunction systems

Native Games

  1. Standard PE analysis
  2. Import/export reconstruction
  3. Pattern scanning for signatures
  4. Runtime memory analysis

Workflow Best Practices

Initial Analysis

1. Identify protections (packer, obfuscator, anti-cheat)
2. Determine game engine and version
3. Collect symbol information if available
4. Map out key modules, callbacks, and trust boundaries

Deep Analysis

1. Locate target functionality
2. Trace execution flow
3. Document structures, memory artifacts, and relationships
4. Correlate IOCTLs, callbacks, and runtime checks

Obfuscation Taxonomy

Mixed Boolean-Arithmetic (MBA)

- Linear MBA: e.g., x + y = (x ^ y) + 2*(x & y)
- Polynomial MBA: higher-degree expressions over boolean/arithmetic mix
- Tools: SSPAM, MBA-Blast, SiMBA for simplification
- Common in: VMProtect, Themida, custom LLVM passes

Control Flow Flattening (CFF)

- OLLVM-style: all basic blocks behind a dispatcher switch
- Recovery: symbolic execution, pattern matching, deobfuscation passes
- Tools: D-810 (IDA), de-ollvm scripts, SATURN
- Variants: nested dispatchers, encrypted state variables

Opaque Predicates

- Invariant conditions injected to confuse static analysis
- Number-theoretic (x² mod 4 ∈ {0,1}), pointer-aliasing based
- Detection: abstract interpretation, SMT solvers (Z3)

Virtualization-Based Obfuscation

VMProtect / Themida / Code Virtualizer:
- Custom bytecode VM with randomized opcode set per build
- Handler table dispatch loop: fetch → decode → execute
- Devirtualization approaches:
  - Trace-based: record handler execution, lift to IR
  - Pattern-based: identify handler semantics by structure
  - Symbolic: concolic execution through VM dispatch
- Tools: VMPAttack, NoVmp, Oreans UnVirtualizer, vtil

Binary Lifting

- Lift machine code to compiler IR (LLVM IR, VEX, ESIL)
- Enables compiler-level optimization passes for deobfuscation
- Tools: McSema, remill, RetDec, Binary Ninja MLIL/HLIL

Disassembler Plugin Ecosystem

IDA Pro Plugins

Categories found in README (> IDA Plugins, 150+ entries):
- Decompiler enhancers: HexRaysPyTools, HRDevHelper
- Type recovery: ClassInformer, auto_struct
- Signature: FLIRT, Lumina, IDA Signature Database
- Scripting: IDAPython, IDC, LazyIDA
- Visualization: IDAGraph, Lighthouse (coverage)
- Anti-obfuscation: D-810 (MBA), de-ollvm, Patfinder
- Game-specific: SDK loaders, structure importers

Binary Ninja Plugins

- Sidekick, snippets, type libraries
- HLIL-based analysis scripts
- Custom architectures and loaders
- Headless analysis for batch processing

Ghidra Plugins

- GhidraScript (Java/Python), Ghidra extensions
- Ghidraaas (Ghidra-as-a-Service)
- Type importers, signature matchers
- Firmware analysis (SVD loader, embedded)

Radare2 / iaito Plugins

- r2pipe scripting (Python, JS, Rust)
- iaito: official radare2 Qt GUI
- r2ghidra: Ghidra decompiler integration
- r2dec: lightweight decompiler

WinDbg Plugins

- SwishDbgExt, WinDbgX
- Time Travel Debugging (TTD) extensions
- !analyze extensions, custom formatters
- Kernel debugging helpers

x64dbg Plugins

- ScyllaHide (anti-anti-debug)
- TitanEngine, x64dbgpy
- Trace plugins, pattern scanners
- Conditional breakpoint scripts

Cheat Engine Plugins

- Mono/IL2CPP helpers
- Auto-assembler templates
- Structure dissectors
- Pointer scanner extensions

MCP-Based RE Tools

The README's MCP server section and RE tool ecosystem now include
AI-assisted reverse engineering through Model Context Protocol:

- IDA MCP: AI agent controls IDA Pro (rename, annotate, navigate)
- Ghidra MCP: AI agent queries Ghidra decompilation and PCODE
- Binary Ninja MCP: AI agent interacts with Binary Ninja API
- radare2 MCP: AI agent drives r2 sessions via r2pipe
- x64dbg MCP: AI agent controls live debugging sessions

Workflow: LLM ↔ MCP server ↔ RE tool, enabling natural-language
queries like "find all functions calling CreateRemoteThread" or
"rename this function based on its decompiled logic"

Binary Diffing

Tools for comparing binary versions (patch analysis, vulnerability research):
- BinDiff (Google): graph-based structural comparison
- Diaphora: IDA plugin, best open-source binary diff
- ghidriff: Ghidra-based diffing, command-line and scriptable
- DarunGrim: patch analysis focused differ
- turbodiff: lightweight IDA diffing plugin

Use cases in game security:
- Tracking anti-cheat driver updates between versions
- Identifying patched vulnerabilities in game clients
- Comparing obfuscated builds to isolate logic changes

Anti-Debug Techniques Catalog

User-Mode Anti-Debug

- IsDebuggerPresent / CheckRemoteDebuggerPresent
- NtQueryInformationProcess (ProcessDebugPort, ProcessDebugFlags, ProcessDebugObjectHandle)
- NtSetInformationThread (ThreadHideFromDebugger)
- PEB.BeingDebugged, PEB.NtGlobalFlag, heap flags
- INT 2D, INT 3 scanning, OutputDebugString tricks
- Timing checks: rdtsc, QueryPerformanceCounter, GetTickCount64
- TLS callbacks for early detection
- Exception-based: unhandled exception filter, VEH chain inspection
- Parent process checks (csrss.exe verification)
- Self-debugging: NtCreateDebugObject

Kernel-Mode Anti-Debug

- KdDebuggerEnabled / KdDebuggerNotPresent
- Debug register (DR0-DR7) monitoring and clearing
- KPROCESS.DebugPort zeroing
- NMI callbacks for debugger detection
- Hardware breakpoint detection via context inspection

Anti-Debug Bypass Tools

- ScyllaHide: comprehensive anti-anti-debug (x64dbg/IDA/standalone)
- TitanHide: kernel-mode debugger hiding
- HyperHide: hypervisor-based anti-debug bypass
- SharpOD: OllyDbg anti-anti-debug plugin

VMProtect/Themida Analysis

Resources

  • Devirtualization tools
  • Control flow recovery
  • Handler analysis techniques
  • Unpacking methodologies

ROP/Exploit Development

Tools

  • ROPgadget: Gadget finder
  • rp++: Fast ROP gadget finder
  • angrop: Automated ROP chain generation

Data Source

Important: This skill provides conceptual guidance and overview information. For detailed information use the following sources:

1. Project Overview & Resource Index

Fetch the main README for the full curated list of repositories, tools, and descriptions:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/README.md

The main README contains thousands of curated links organized by category. When users ask for specific tools, projects, or implementations, retrieve and reference the appropriate sections from this source.

2. Repository Code Details (Archive)

For detailed repository information (file structure, source code, implementation details), the project maintains a local archive. If a repository has been archived, always prefer fetching from the archive over cloning or browsing GitHub directly.

Archive URL format:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/archive/{owner}/{repo}.txt

Examples:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/archive/ufrisk/pcileech.txt
https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/archive/000-aki-000/GameDebugMenu.txt

How to use:

  1. Identify the GitHub repository the user is asking about (owner and repo name from the URL).
  2. Construct the archive URL: replace {owner} with the GitHub username/org and {repo} with the repository name (no .git suffix).
  3. Fetch the archive file — it contains a full code snapshot with file trees and source code generated by code2prompt.
  4. If the fetch returns a 404, the repository has not been archived yet; fall back to the README or direct GitHub browsing.

3. Repository Descriptions

For a concise English summary of what a repository does, the project maintains auto-generated description files.

Description URL format:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/description/{owner}/{repo}/description_en.txt

Examples:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/description/00christian00/UnityDecompiled/description_en.txt
https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/description/ufrisk/pcileech/description_en.txt

How to use:

  1. Identify the GitHub repository the user is asking about (owner and repo name from the URL).
  2. Construct the description URL: replace {owner} with the GitHub username/org and {repo} with the repository name.
  3. Fetch the description file — it contains a short, human-readable summary of the repository's purpose and contents.
  4. If the fetch returns a 404, the description has not been generated yet; fall back to the README entry or the archive.

Priority order when answering questions about a specific repository:

  1. Description (quick summary) — fetch first for concise context
  2. Archive (full code snapshot) — fetch when deeper implementation details are needed
  3. README entry — fallback when neither description nor archive is available
指导Windows内核安全研究,涵盖驱动开发、PatchGuard、DSE及内存检查。用于游戏保护分析和底层安全机制研究,提供结构体解析与符号行走方法。
分析Windows内核结构如EPROCESS或MMVAD 研究反作弊检测机制如PatchGuard或DSE 进行驱动加载与安全策略相关开发 执行内核内存检查或IRQL敏感回调分析
.claude/skills/windows-kernel/SKILL.md
npx skills add gmh5225/awesome-game-security --skill windows-kernel-security -g -y
SKILL.md
Frontmatter
{
    "name": "windows-kernel-security",
    "description": "Guide for Windows kernel internals and security mechanisms used in game protection and low-level research. Use this skill when working with drivers, IRQL-sensitive callbacks, EPROCESS, ETHREAD, MMVAD internals, IOCTL paths, DSE, PatchGuard, HVCI, PiDDBCache, MmUnloadedDrivers, or kernel memory inspection."
}

Windows Kernel Security

Overview

This skill covers Windows kernel internals that matter for game security research: object callbacks, process and image notifications, APC behavior, driver loading, trust enforcement, memory manager structures, and the bookkeeping anti-cheats inspect to detect hostile drivers or hidden executable code.

README Coverage

  • Cheat > PatchGuard-related
  • Cheat > Driver Signature enforcement
  • Cheat > Windows Kernel Explorer
  • Cheat > EFI Driver (cross-reference with game-hacking skill)
  • Cheat > Vulnerable Driver
  • Anti Cheat > Detection:Attach
  • Anti Cheat > Detection:Hide
  • Anti Cheat > Detection:Vulnerable Driver
  • Anti Cheat > Detection:Spoof Stack
  • Anti Cheat > Windows Ring3 Callback
  • Anti Cheat > Windows Ring0 Callback
  • Anti Cheat > Information System & Forensics
  • Some Tricks > Windows Ring0
  • Windows Security Features

Core Kernel Concepts

Important Structures

  • EPROCESS / ETHREAD
  • KTHREAD / KAPC / KAPC_STATE
  • MMVAD / VAD tree nodes
  • PEB / TEB
  • DRIVER_OBJECT
  • DEVICE_OBJECT
  • IRP (I/O Request Packet)

Key Tables

  • SSDT (System Service Descriptor Table)
  • IDT (Interrupt Descriptor Table)
  • GDT (Global Descriptor Table)
  • PspCidTable (Process/Thread handle table)
  • PiDDBCacheTable / MmUnloadedDrivers / PoolBigPageTable

User-Mode Kernel Symbol Walking

Methodology

- Load local ntoskrnl image (typically C:\Windows\System32\ntoskrnl.exe)
- Use dbghelp + symbol server path (srv*cache*https://msdl.microsoft.com/download/symbols)
  to resolve exported symbol RVAs and type information
- Build structure-aware field lookup:
  - Query field offset directly (e.g., _EPROCESS.Token)
  - Enumerate all members of a target struct (_TOKEN, _EPROCESS, etc.)
  - Search a field name across all known structs (useful when parent type is unknown)
- Keep symbol path configurable for offline/private symbol repositories

Why It Matters in Game Security

- Reduces hardcoded-offset fragility across Windows builds
- Helps map kernel object layouts used by anti-cheat and drivers
- Supports rapid adaptation when anti-cheat-relevant fields shift
  (EPROCESS, ETHREAD, token/handle/security-related members)

Gadget Scanning Workflow

- Map executable sections of ntoskrnl image in user mode
- Scan for short control-flow gadgets (e.g., pop rcx ; ret, jmp rax)
- Use as a research primitive for:
  - ROP chain feasibility analysis
  - Kernel exploit mitigation evaluation
  - Anti-cheat hardening review against gadget-dependent attack paths

Security Features

PatchGuard (Kernel Patch Protection)

- Protects critical kernel structures
- Periodic verification checks
- BSOD on tampering detection
- Multiple trigger mechanisms

Driver Signature Enforcement (DSE)

- Requires signed drivers
- CI.dll verification
- Test signing mode
- WHQL certification

Virtualization-Based Security (VBS)

Architecture:
- Uses the Windows hypervisor to create an isolated execution environment
- Splits the system into Virtual Trust Levels (VTLs)
  - VTL0: Normal world — standard Windows kernel and user-mode processes
  - VTL1: Secure world — Secure Kernel, security policy enforcement
- Even if VTL0 kernel is fully compromised, VTL1 remains isolated
- Three main buckets:
  - Memory-protection features (HVCI)
  - Virtual Trust Levels (VTL0/VTL1 separation)
  - VBS enclaves (isolated execution for selected workloads)

Hypervisor-Enforced Code Integrity (HVCI)

- Also known as Memory Integrity
- Ensures only trusted, validated code executes in kernel mode
- Combines Windows hypervisor + Secure Kernel (VTL1) for enforcement
- Key mechanism: W→X transition restriction
  - Executable kernel pages cannot become writable
  - Writable pages cannot become executable without re-validation
- Enforcement pipeline:
  - Code integrity policy defines what is trusted
  - Hypervisor memory enforcement via second-stage address translation (EPT/SLAT)
  - Once a kernel page is validated, strict execution rules are enforced
- Driver compatibility requirements: drivers must be HVCI-compatible

Secure Boot

- UEFI-based boot verification
- Boot loader chain validation
- Kernel signature checks
- DBX (forbidden signatures)
- Foundation for attestation and DMA-hardening assumptions

Kernel Callbacks

Process Callbacks

PsSetCreateProcessNotifyRoutine
PsSetCreateProcessNotifyRoutineEx
PsSetCreateProcessNotifyRoutineEx2

Thread Callbacks

PsSetCreateThreadNotifyRoutine
PsSetCreateThreadNotifyRoutineEx

Image Load Callbacks

PsSetLoadImageNotifyRoutine
PsSetLoadImageNotifyRoutineEx

Object Callbacks

ObRegisterCallbacks
// OB_OPERATION_HANDLE_CREATE
// OB_OPERATION_HANDLE_DUPLICATE

APC / Execution Context

KeInitializeApc
KeInsertQueueApc
KeStackAttachProcess
RtlWalkFrameChain

Registry Callbacks

CmRegisterCallback
CmRegisterCallbackEx

Minifilter Callbacks

FltRegisterFilter
// IRP_MJ_CREATE, IRP_MJ_READ, etc.

Driver Development

Basic Structure

NTSTATUS DriverEntry(
    PDRIVER_OBJECT DriverObject,
    PUNICODE_STRING RegistryPath
) {
    DriverObject->DriverUnload = DriverUnload;
    DriverObject->MajorFunction[IRP_MJ_CREATE] = DispatchCreate;
    DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = DispatchIoctl;
    // Create device, symbolic link...
    return STATUS_SUCCESS;
}

Communication Methods

  • IOCTL (DeviceIoControl)
  • Direct I/O
  • Buffered I/O
  • Shared memory

Vulnerable Driver Exploitation

Common Vulnerability Types

  • Arbitrary read/write primitives
  • IOCTL handler vulnerabilities
  • Pool overflow
  • Use-after-free

Notable Vulnerable Drivers

- gdrv.sys (Gigabyte)
- iqvw64e.sys (Intel)
- MsIo64.sys
- Mhyprot2.sys (Genshin Impact)
- dbutil_2_3.sys (Dell)
- RTCore64.sys (MSI)
- Capcom.sys

Exploitation Steps

  1. Load vulnerable signed driver
  2. Trigger vulnerability
  3. Achieve kernel read/write
  4. Disable DSE or load unsigned driver
  5. Execute arbitrary kernel code

PatchGuard Bypass Techniques

Timing-Based

  • Predict PG timer
  • Modify between checks

Context Manipulation

  • Exception handling
  • DPC manipulation
  • Thread context tampering

Hypervisor-Based

  • EPT manipulation
  • Memory virtualization
  • Intercept PG checks

Kernel Hooking

ETW (Event Tracing for Windows)

- InfinityHook technique
- HalPrivateDispatchTable
- System call tracing

ETW Internals

Provider / Consumer Model

Architecture:
- Providers: kernel or user-mode components that emit events
  - Manifest-based providers (registered via wevtutil)
  - TraceLogging providers (self-describing, no manifest)
  - MOF providers (legacy WMI-based)
- Consumers: tools that subscribe to and process events
  - Real-time consumers (ETW sessions)
  - Log file consumers (.etl files)
- Controllers: manage sessions (xperf, tracelog, logman)

Key kernel providers:
  Microsoft-Windows-Kernel-Process (process/thread lifecycle)
  Microsoft-Windows-Kernel-File (file I/O)
  Microsoft-Windows-Kernel-Audit-API-Calls (security-sensitive APIs)

ThreatIntel ETW Provider

- Microsoft-Windows-Threat-Intelligence
- Available to PPL (Protected Process Light) and above
- Events: NtReadVirtualMemory, NtWriteVirtualMemory, NtMapViewOfSection on protected processes
- Used by EDR and anti-cheat for detecting memory access to protected processes
- Attackers target: patch EtwThreatIntProvRegHandle or EtwpEventWriteFull

Common ETW Bypass Patterns

- Patch EtwEventWrite in ntdll.dll (user-mode ETW silencing)
- Patch nt!EtwpEventWriteFull in kernel (kernel-mode ETW silencing)
- NtSetInformationThread(ThreadHideFromDebugger) — hides thread from ETW
- Remove provider registration by walking EtwRegistration list
- EPT-based protection can defend ETW structures from tampering

Kernel Segment Heap Architecture

Timeline

Windows NT ~ 1809   : Legacy NT Pool Manager (ExAllocatePoolWithTag)
Windows 10 19H1     : Kernel Segment Heap introduced (March 2019, build 1903)
                      └─ User-mode Segment Heap ported to the kernel
Windows 10 2004     : ExAllocatePool2 / ExAllocatePool3 added
                      └─ ExAllocatePoolWithTag officially deprecated
Windows 10 20H2~    : Dynamic KDP (Kernel Data Protection) stabilized
Windows 11          : VBS/HVCI enabled by default; Secure Pool usage expanded

Common misconception: Many sources claim "the Segment Heap was introduced
in Windows 10 2004," but the kernel segment heap was actually introduced
in 19H1 (1903). Windows 10 2004 added the new Pool APIs built on top of it.

Legacy NT Pool Structure (_POOL_HEADER, pre-19H1)

_POOL_HEADER (16 bytes, x64):
Offset  Field           Size   Description
0x00    PoolIndex        1 B    Pool descriptor index
0x01    PreviousSize     1 B    Previous chunk size
0x02    PoolType         1 B    Pool type (Paged, NonPaged, etc.)
0x03    BlockSize        1 B    Current chunk size (>> 4)
0x04    PoolTag          4 B    4-byte ASCII tag
0x08    ProcessBilled    8 B    KPROCESS pointer (valid only with PoolQuota)

Memory layout:
[POOL_HEADER 16B][user data ...][POOL_HEADER 16B][user data ...]
      ↑ plaintext, predictable        ↑ adjacent → overwritable

Security weaknesses:
- Pool Walking: traverse chunks linearly via BlockSize
- Pool Overflow: corrupt adjacent header for arbitrary write on free
- PoolIndex Overwrite: OOB dereference into pool descriptor array
- ProcessBilled Overwrite: arbitrary address dereference on free path

Windows 8 partial mitigation:
  ProcessBilled = KPROCESS_PTR ^ ExpPoolQuotaCookie ^ CHUNK_ADDR
  But plaintext _POOL_HEADER remained until 19H1.

_SEGMENT_HEAP Core Structure

Each pool type is managed by its own independent _SEGMENT_HEAP instance.

_SEGMENT_HEAP (kernel offsets, based on 20H2):
0x000   EnvHandle (10 B)     — heap environment handle
0x010   Signature (4 B)      — always 0xDDEEDDEE
0x028   UserContext (8 B)
0x048   AllocatedBase (8 B)  — LFH structure allocation base
0x058   SegContexts[2] (0x180 B) — segment context array
0x100   VsContext (0xC0 B)   — VS allocator context
0x280   LfhContext (0x4C0 B) — LFH allocator context
higher  LargeAllocMetadata   — large allocation metadata
higher  LargeReservedPages / LargeCommittedPages

Per pool type instances (nt!PoolVector / HEAP_POOL_NODES):
├── NonPagedPool (NP)       → _SEGMENT_HEAP instance #1
├── NonPagedPoolNx (NPNx)   → _SEGMENT_HEAP instance #2  ← primary target
├── PagedPool (PP)          → _SEGMENT_HEAP instance #3
├── PagedPoolSession        → _SEGMENT_HEAP stored in current thread
└── (other special pools)

Allocation Routing Flow

ExAllocatePoolWithTag / ExAllocatePool2 / ExAllocatePool3
        │
        ▼
  ExAllocateHeapPool (internal)
        │
        ├─ size ≤ 0x200 AND LFH activated  ──▶  kLFH
        │   └─ RtlpHpLfhContextAllocate
        │
        ├─ 0x1e1 ≤ size ≤ 0xfe0            ──▶  VS Allocator
        │   └─ RtlpHpVsContextAllocateInternal
        │
        ├─ page-aligned (0x20000~0x7f0000)  ──▶  Segment Allocator
        │   └─ RtlpHpSegAlloc
        │
        └─ large (> 0x7f0000)              ──▶  Large Allocator
            └─ RtlpHpLargeAlloc

kLFH (Low Fragmentation Heap)

Size range:       ≤ 0x200 bytes (512 B), when LFH activated for that size class
Activation:       After 18 consecutive allocations of the same size
Key function:     RtlpHpLfhContextAllocate
Chunk header:     _POOL_HEADER (16 B, still present)
Metadata:         _HEAP_LFH_SUBSEGMENT (isolated, not inline)
Bucket count:     129 (Buckets[129])

Bucket structure:
_HEAP_LFH_CONTEXT
└── Buckets[129]
     ├── Bucket #0:   size 1~8 B
     ├── Bucket #1:   size 9~16 B
     ├── ...
     └── Bucket #128: size ~0x1FF B
         (each bucket has AffinitySlots → _HEAP_LFH_SUBSEGMENT)

Security properties:
- Block placement within subsegment is randomized
- Next allocation position managed through FreeHint, encoded with LfhKey
- Adjacent chunk overflow cannot directly corrupt management structure

VS Allocator (Variable Size)

Size range:       (a) ≤ 0x1e0 && LFH inactive; (b) 0x1e1~0xfe0;
                  (c) 0x1001~0xffff && non-page-aligned
Key function:     RtlpHpVsContextAllocateInternal
Chunk header:     _HEAP_VS_CHUNK_HEADER (16 B, HeapKey XOR encoded)
Free management:  Red-Black Tree (FreeChunkTree)
Algorithm:        Best-fit

_HEAP_VS_CHUNK_HEADER (allocated state):
┌──────────────────────────────────────────────────────────┐
│  Sizes (8 B) — XOR encoded: HeaderBits ^ self_addr ^ HeapKey
│    ├─ UnsafeSize      : chunk size / 16
│    ├─ UnsafePrevSize  : previous chunk size / 16
│    ├─ MemoryCost      : pages occupied
│    └─ UnusedBytes     : whether unused bytes exist
│  EncodedSegmentPageOffset (1 B)
│    — (self_addr ^ self ^ HeapKey) & 0xFF
│    — page distance to VS subsegment start
└──────────────────────────────────────────────────────────┘

Memory layout:
[_HEAP_VS_CHUNK_HEADER 16B][_POOL_HEADER 16B][user data ...]
       ↑ HeapKey XOR             ↑ PoolTag etc. still present

VS subsegment structure (_HEAP_VS_SUBSEGMENT):
├── ListEntry      — subsegment linked list
├── CommitBitmap   — page commit state bitmap
├── CommitLock     — lock used during commit
├── Size (2 B)     — subsegment size (>> 4)
└── Signature (15 bit) + FullCommit (1 bit) — integrity check

Segment Allocator (Backend)

Size range #1:    0x20000 < size ≤ 0x7f000 (128 KB ~ 508 KB)
Size range #2:    0x7f000 < size ≤ 0x7f0000 (508 KB ~ ~7 MB)
Core structure:   _HEAP_PAGE_SEGMENT + 256 page descriptors
Segment mask:     0xFFFFFFFFFFF00000

The kernel uses two independent SegContexts (unlike user-mode's single context).

Page segment signature encoding:
check = page_segment ^ page_segment->Signature
      ^ 0xA2E64EADA2E64EAD ^ RtlpHpHeapGlobals.HeapKey

Large Allocator

Size range:       > 0x7f0000 (typically page-aligned)
Key function:     RtlpHpLargeAlloc
Metadata:         _SEGMENT_HEAP.LargeAllocMetadata
Tracking:         BigPagePoolTable (PoolTrackTable)
No inline header; metadata recorded externally.

Header Layout Per Allocation Path

Path          Memory layout (chunk start → user data)
────────────────────────────────────────────────────────────────
kLFH          [_POOL_HEADER 16B] [data]
VS            [_HEAP_VS_CHUNK_HEADER 16B] [_POOL_HEADER 16B] [data]
Segment       [_HEAP_PAGE_SEGMENT header] ... [page descriptors]
Large         Metadata in BigPagePoolTable; no inline header
CacheAligned  [_POOL_HEADER #1] ... [_POOL_HEADER #2 (CacheAligned)] [data]

Residual _POOL_HEADER Under Segment Heap

_POOL_HEADER was not fully removed. Remaining usage:

Field           Status under Segment Heap
PoolTag         Still recorded (for debugging/tracing)
PoolType        Recorded, not used for allocator selection on free
BlockSize       Unused in VS path; still present in kLFH
PreviousSize    Unused, set to 0
PoolIndex       Unused, set to 0
ProcessBilled   Valid only with PoolQuota flag (encoded with ExpPoolQuotaCookie)

Pointer Encoding Mechanisms

Global key structure: _RTLP_HP_HEAP_GLOBALS (nt!RtlpHpHeapGlobals)
Generated randomly at boot time; global in ntoskrnl.

{
    UINT64 HeapKey;   // VS Allocator + Segment Allocator header encoding
    UINT64 LfhKey;    // LFH callback pointer encoding
}

Encoding formulas:

VS chunk header — Sizes field:
  encoded = (real Sizes) ^ (address of vs_chunk_header) ^ HeapKey

VS chunk — EncodedSegmentPageOffset:
  encoded = ((real page distance) ^ vs_chunk_header ^ HeapKey) & 0xFF

Segment context signature:
  check = page_segment ^ page_segment->Signature
        ^ 0xA2E64EADA2E64EAD ^ HeapKey

LFH callback function pointer:
  encoded = real function address ^ HeapKey ^ address of LfhContext

ProcessBilled (POOL_HEADER, Windows 8+):
  encoded = KPROCESS_PTR ^ ExpPoolQuotaCookie ^ CHUNK_ADDR

Implications for attackers:
- Must leak HeapKey and LfhKey from RtlpHpHeapGlobals
- Must know chunk's own virtual address (self-referential XOR)
- Failing encoding validation triggers:
  BugCheck 0x139 (KERNEL_SECURITY_CHECK_FAILURE) or
  BugCheck 0x13A (KERNEL_MODE_HEAP_CORRUPTION)

Dynamic Lookaside and Delay Free

Dynamic Lookaside:
_HEAP_VS_CONTEXT
└── Lookaside buckets (_RTL_DYNAMIC_LOOKASIDE)
     ├── Per-size singly-linked lists
     ├── Depth (2 B)     — current list depth
     └── NextEntry (8 B) — pointer to next cached chunk

Rebalancing (every 3 Balance Set Manager scans):
- alloc count < 25 → Depth decreases by 10
- miss ratio ≥ 0.5% → Depth increases
- miss ratio < 0.5% → Depth decreases by 1
- Range: minimum 4 ~ MaximumDepth

Delay Free (VS Allocator):
- size < 1 KB AND Config.Flags bit 4 == 1:
  → stored in DelayFreeContext list
  → batch freed after 32 entries accumulate
- Otherwise: inserted immediately into FreeChunkTree
- Security: disrupts UAF timing (cannot immediately reuse freed chunk)

New Pool APIs: ExAllocatePool2 / ExAllocatePool3

Evolution:
ExAllocatePool                 (legacy, no tag)
ExAllocatePoolWithTag          (pre-19H1 standard, deprecated in 2004)
ExAllocatePoolWithTagPriority  (priority support)
ExAllocatePoolWithQuotaTag     (quota tracking)
        ↓
ExAllocatePool2                (general case, zero-initialized by default)
ExAllocatePool3                (extended parameters, priority + Secure Pool)

ExAllocatePool2:
  PVOID ExAllocatePool2(POOL_FLAGS Flags, SIZE_T NumberOfBytes, ULONG Tag);
  - Zero-initialized by default (no RtlZeroMemory needed)
  - Returns NULL on failure by default
  - POOL_FLAG_RAISE_ON_FAILURE converts to exception
  - POOL_FLAG_USE_QUOTA integrates legacy PoolQuota

ExAllocatePool3:
  PVOID ExAllocatePool3(POOL_FLAGS Flags, SIZE_T NumberOfBytes, ULONG Tag,
                        PCPOOL_EXTENDED_PARAMETER ExtendedParameters, ULONG Count);
  Extended parameter types:
  - PoolExtendedParameterPriority: allocation priority (e.g., HighPoolPriority)
  - PoolExtendedParameterSecurePool: KDP Secure Pool (VTL0 write-protected)

Down-level compatibility:
  #define POOL_ZERO_DOWN_LEVEL_SUPPORT
  ExInitializeDriverRuntime(DriversRuntimeInitSupportFlags);
  → ExAllocatePool2 internally falls back to alloc + memset on older OS

Kernel Data Protection (KDP) and Secure Pool

KDP leverages Segment Heap's Secure Pool feature to allocate
read-only kernel memory that cannot be modified from VTL0.

Virtual address space layout:
  Dedicated 512 GB Secure Pool region (1 PML4 entry)
  Base address: randomized at boot
  Managed by: Secure Kernel (VTL1)
  VTL0 writes: blocked via NAR (Node Address Range)

Initialization flow:
1. NT Memory Manager boot Phase 1
2. Randomly calculate 512 GB Secure Pool virtual address
3. INITIALIZE_SECURE_POOL Secure Call → Secure Kernel
4. Secure Kernel creates NAR + initializes NTE (Node Table Entry)

Anti-cheat usage:
  // Create Secure Pool context
  ExCreatePool(POOL_FLAG_NON_PAGED, tag, &securePoolHandle);

  // Allocate detection rule table (immutable after init)
  POOL_EXTENDED_PARAMS_SECURE_POOL sp = {
      .Cookie           = MY_COOKIE,
      .SecurePoolHandle = securePoolHandle,
      .Buffer           = &detectionRuleTable,
      .SecurePoolFlags  = SECURE_POOL_FLAGS_FREEABLE
      // MODIFIABLE flag omitted → write-protected after init
  };
  g_DetectionRules = ExAllocatePool3(POOL_FLAG_NON_PAGED,
      sizeof(detectionRuleTable), 'DRul', &extParams, 1);
  // g_DetectionRules is now immutable — no VTL0 code can modify it

Attack Technique Evolution (Segment Heap Era)

Technique comparison:
Technique                    NT Pool (pre-19H1)    Segment Heap (19H1+)
─────────────────────────────────────────────────────────────────────────
Adjacent header overwrite    Easy                  Blocked by encoding
Pool Walking                 Possible              Impossible (metadata isolation)
ProcessBilled overwrite      Requires Win8+ cookie Requires cookie + HeapKey
kLFH pool spray              Predictable           Possible but needs precise control
VS FreeChunkTree corruption  N/A                   Requires HeapKey bypass
Large chunk BigPool tracking PoC exists             PoC exists (PoolTrackTable)

Modern kLFH exploit requirements:
1. Find target object of same size (same kLFH bucket)
2. Target must contain exploitable members (pointer, function table)
3. Target allocation must be triggerable from user mode
4. Vulnerable and target objects must be in same pool type
   (NonPagedPoolNx and PagedPool use separate _SEGMENT_HEAP instances)

VS chunk overflow recovery (must restore to avoid BugCheck):
  ghost_chunk->Sizes.HeaderBits =
      (real_sizes) ^ (ULONG_PTR)ghost_chunk ^ HeapKey;
  ghost_chunk->EncodedSegmentPageOffset =
      ((real_page_offset) ^ (ULONG_PTR)ghost_chunk ^ HeapKey) & 0xFF;
  // Failure → BugCheck 0x13A

Required pre-exploit leak values:
Symbol                          Purpose               Source
nt!RtlpHpHeapGlobals           HeapKey, LfhKey        Pattern scan ExFreePoolWithTag
nt!ExpPoolQuotaCookie           Decode ProcessBilled   Pattern scan ExAllocatePoolWithQuotaTag
nt!PsInitialSystemProcess      EPROCESS chain         ntoskrnl import analysis
Chunk's own virtual address    Self-referential XOR   Requires info-leak primitive

BugCheck Codes (Segment Heap Related)

Code    Name                               Trigger
0x139   KERNEL_SECURITY_CHECK_FAILURE      VS/LFH header integrity check failure
0x13A   KERNEL_MODE_HEAP_CORRUPTION        Heap metadata corruption detected
0xC5    DRIVER_CORRUPTED_EXPOOL            Pool accessed at incorrect IRQL
0x19    BAD_POOL_HEADER                    _POOL_HEADER validation failure (LFH path)

Pool Allocation & Forensics

Pool Forensics Artifacts

PiDDBCacheTable:
- Tracks historically loaded drivers by hash + timestamp
- Anti-cheat inspects this to detect BYOVD or test-signed driver loads
- Attackers attempt to remove entries post-load

MmUnloadedDrivers:
- Circular buffer of recently unloaded drivers (name + address range)
- Cannot be cleared from user mode
- Anti-cheat uses to detect load-unload-reload patterns

PoolBigPageTable:
- Maps large pool allocations (>= PAGE_SIZE) to owning driver tag
- Used for: identifying hidden drivers, finding leaked pool allocations
- Anti-cheat walks this to detect manually mapped driver memory

Pool Tag Forensics

- ExAllocatePoolWithTag / ExAllocatePool2: every allocation carries a 4-byte tag
- Pool tag scanning: identify driver presence by known tags
- Tool: pooltag.txt (Microsoft), PoolMon, WinDbg !poolfind
- Anti-cheat technique: scan pool tags for known cheat driver signatures

Modern Pool Scanning (Segment Heap Era)

Legacy method (pre-19H1) — NO LONGER WORKS:
  Follow BlockSize in inline header to traverse linearly.
  PPOOL_HEADER h = startAddr;
  while (h->BlockSize != 0) {
      if (h->PoolTag == TARGET_TAG) { /* ... */ }
      h += h->BlockSize;  // Invalid under segment heap
  }

Modern alternatives:

BigPool detection (Large Alloc path):
  Reference nt!PoolBigPageTable (or nt!PoolTrackTable)
  └─ Traverse BigPagePoolTable entries
  └─ Find allocations without corresponding driver objects

Small allocation detection:
  _SEGMENT_HEAP → VsContext → SubsegmentList traversal
  _SEGMENT_HEAP → LfhContext → Buckets[] → AffinitySlots → Subsegments

VS Chunk Header decoding (requires HeapKey):
  real_sizes = encoded_header ^ chunk_address ^ HeapKey
  → Decode to determine chunk size, PoolTag, allocation legitimacy

Anti-cheat scanning targets:
- Suspicious PoolTags: cheat drivers use custom/rare tags; maintain blacklist
- Executable permission pages: NonPagedPool chunks with X permission
  from suspicious sources (no corresponding loaded module)
- Shellcode patterns: scan decoded chunk contents for known cheat signatures,
  ROP gadgets, specific syscall sequences
- kLFH allocation pattern anomalies: unusual allocation patterns in
  specific size buckets can indicate pool grooming

WinDbg commands:
  dt nt!_RTLP_HP_HEAP_GLOBALS nt!RtlpHpHeapGlobals  // HeapKey, LfhKey
  dt nt!_SEGMENT_HEAP <address>
  dt nt!_HEAP_VS_CHUNK_HEADER <address>
  dt nt!_HEAP_LFH_CONTEXT <address>
  !pool <address>
  !poolfind <Tag> [pool_type]
  !poolused [flags]                    // stats by PoolTag
  dt nt!_POOL_TRACKER_BIG_PAGES nt!PoolBigPageTable

VS chunk header decode (manual):
  HeaderBits_raw = poi(<chunk_addr>)
  real Sizes = HeaderBits_raw ^ <chunk_addr> ^ HeapKey

Driver Development Migration Checklist

□ ExAllocatePoolWithTag          → ExAllocatePool2
□ ExAllocatePool (without tag)   → Remove or ExAllocatePool2
□ ExAllocatePoolWithTagPriority  → ExAllocatePool3 + Priority param
□ ExAllocatePoolWithQuotaTag     → ExAllocatePool2 + POOL_FLAG_USE_QUOTA
□ RtlZeroMemory after alloc     → Remove (ExAllocatePool2 zero-initializes)
□ Review POOL_FLAG_RAISE_ON_FAILURE (NULL check vs exception)
□ Critical read-only data       → ExAllocatePool3 + Secure Pool

SSDT Hooking (Legacy)

- Modify service table entries
- Requires PG bypass
- High detection risk

IRP Hooking

- Hook driver dispatch routines
- Less monitored than SSDT
- Per-driver targeting

Memory Manipulation

Physical Memory Access

MmMapIoSpace
MmCopyMemory
\\Device\\PhysicalMemory

Virtual Memory

ZwReadVirtualMemory
ZwWriteVirtualMemory
KeStackAttachProcess
MmCopyVirtualMemory

MDL Operations

IoAllocateMdl
MmProbeAndLockPages
MmMapLockedPagesSpecifyCache

Research Tools

Analysis

  • WinDbg / WinDbg Preview
  • Process Hacker / System Informer
  • OpenArk
  • WinArk

Utilities

  • KDU (Kernel Driver Utility)
  • OSR Driver Loader
  • DriverView

Monitoring

  • Process Monitor
  • API Monitor
  • ETW consumers

EFI/Boot-Time Threats

EFI Driver Cross-Reference

The README's > EFI Driver subcategory (under Cheat) contains 30+ projects:
- EFI bootkit frameworks: UEFI DXE drivers that persist across boots
- Boot-time memory mappers: inject code before Windows kernel initializes
- ExitBootServices hooks: intercept Windows boot handoff
- EFI runtime service abuse: GetVariable/SetVariable for kernel ↔ EFI comm

See also: game-hacking skill for EFI cheat workflows

Boot-Time Access

- EFI runtime services persist after ExitBootServices
- DXE (Driver Execution Environment) phase: full hardware access
- Pre-kernel execution: no DSE, no PatchGuard, no HVCI enforcement
- Secure Boot is the primary mitigation (firmware signature verification)

Memory Access

- GetVariable/SetVariable: pass data between EFI and OS runtime
- Runtime memory mapping via EFI memory map
- Physical memory access before Windows memory manager initializes
- ACPI table injection for persistent low-level modifications

Hypervisor Development

Hypervisor Types

Type 1 (bare-metal):
- Runs directly on hardware
- Examples: VMware ESXi, Microsoft Hyper-V, Xen
- Used for VBS, production security enforcement

Type 2 (hosted):
- Runs on top of a host operating system
- Examples: Oracle VirtualBox, VMware Workstation
- Common for research, development, and testing

Hardware Virtualization Platforms

Intel VT-x:
- Introduced 2005, widely supported on modern Intel CPUs
- Foundation for VMCS, EPT, VM exits

AMD-V (SVM):
- AMD's counterpart to VT-x, also introduced 2005
- VMCB structure, NPT (Nested Page Tables)

ARM Virtualization Extensions:
- EL2 (hypervisor mode) and stage-2 memory translation
- Used on ARM platforms for mobile and embedded security

Intel VT-x Core Concepts

VMCS (Virtual Machine Control Structure)

Central data structure for Intel VT-x:
- Describes guest state, host state, and virtualization controls
- Tells the processor:
  - What state to restore on VM entry
  - What state to save on VM exit
  - Which events transfer control back to the hypervisor

Guest/Host State Areas:
- Control registers (CR0, CR3, CR4)
- Segment registers (CS, SS, DS, ES, FS, GS)
- Debug registers (DR7 — hardware breakpoints)
- Descriptor-table registers (GDTR, IDTR)
- Key fields:
  - CR3: root of guest page tables, central to virtual memory
  - GDTR/IDTR: Global/Interrupt Descriptor Tables
  - CS/SS: code and stack segments
  - DR7: hardware breakpoint control

Control Fields:
- Pin-based controls
- Primary processor-based controls
- Secondary processor-based controls
- Events that cause VM exits:
  - CPUID interception
  - INVLPG interception
  - Control-register access
  - EPT violations
  - MSR access

EPT (Extended Page Tables)

Intel's implementation of SLAT (Second-Level Address Translation):
- Gives the hypervisor independent control over guest memory
- Two-stage address translation pipeline:
  1. GVA → GPA: Guest Virtual → Guest Physical (via guest page tables, rooted at CR3)
  2. GPA → HPA: Guest Physical → Host Physical (via EPT, rooted at EPTP in VMCS)
- Guest believes it owns its own memory mappings
- Hypervisor has a second, independent layer controlling:
  - What physical memory is reachable
  - What permissions apply (read/write/execute)

EPT Hierarchy:
- PML4 → PDPT → PD → PT (4-level page table)
- Each entry carries read/write/execute permissions
- EPT violations trigger VM exits when access permissions are violated

Page Table Entries (PTE):
- Maps GVA to GPA
- Carries: read/write, supervisor-only, caching, software-defined bits
- Guest PTEs and EPT serve different roles:
  - Guest PTE: controls guest's view of memory
  - EPT: controls hypervisor's view of the guest

VM Exits & VMCALL

VM Exits:
- Occur when configured events happen in the guest
- Triggers: CPUID, CR access, I/O instructions, EPT violations, MSR access
- On exit: processor saves guest state (per VMCS), restores host state,
  records exit reason for hypervisor handler

VMCALL:
- Guest intentionally transfers control to hypervisor
- Similar in concept to a system call (guest → hypervisor)
- Used for guest-hypervisor communication interfaces

Nested Virtualization

- Running a hypervisor inside a VM managed by another hypervisor
- Useful for research, testing, and development
- Adds complexity: multiple layers participate in the same virtualization flow
- Relevant for testing hypervisor-based defense under VMware/Hyper-V

AMD-V (SVM)

  • VMCB (Virtual Machine Control Block) structure
  • NPT (Nested Page Tables) — AMD's SLAT equivalent
  • SVM operations (VMRUN, VMSAVE, VMLOAD)

Use Cases

  • Memory hiding
  • Syscall interception
  • Security monitoring
  • Anti-cheat evasion
  • EPT-based memory protection and introspection

Windows Hypervisor Platform (WHP) API

User-mode hypervisor interface (Windows 10+):
- WHvCreatePartition / WHvSetupPartition: create VM partition
- WHvCreateVirtualProcessor: add vCPU
- WHvMapGpaRange: map host memory into guest physical address space
- WHvRunVirtualProcessor: enter guest execution, blocks until VM exit
- WHvGetVirtualProcessorRegisters / Set: read/write guest CPU state

Key capability:
- Enables hypervisor-assisted analysis from user mode (no kernel driver)
- Page-level trap handling: set R/W/X permissions per guest page
- VM exit reasons: memory access violation, CPUID, MSR access, I/O port, syscall
- Deterministic execution: host controls all guest state and memory

Prerequisites:
- Enable Windows features: Microsoft-Hyper-V-Hypervisor + HypervisorPlatform
- Hardware: VT-x or AMD-V support
- Note: WHP coexists with Hyper-V but conflicts with some third-party hypervisors

See also: reverse-engineering skill → User-Mode Hypervisor-Assisted Tracing
for analysis workflows built on WHP

Hypervisor-Based Defense

Concept

- Security approach using virtualization primitives to enforce protections
  from a higher privilege level than the guest kernel
- Moves security decisions into an isolated execution environment
  that a compromised kernel cannot easily tamper with
- Present across major OS platforms:
  - Windows: Virtualization-Based Security (VBS)
  - Android: Android Virtualization Framework (AVF)
  - Apple: Secure execution environments, hardware-backed isolation

EPT Hooks as Defensive Primitives

Mechanism:
- Instead of patching the guest kernel, modify EPT permissions
- Specific memory accesses trigger EPT violations → VM exit
- Hypervisor inspects the access and decides: allow, deny, or log

Example: Watching writes to a sensitive region
1. Remove write permission from the EPT entry for target region
2. Guest runs normally until it attempts a write to that region
3. EPT violation → VM exit → hypervisor receives control
4. Hypervisor evaluates context:
   - Which module performed the access
   - What memory was touched
   - Whether the access is authorized
5. Decision: allow write, deny and return, or log and continue

Advantages over traditional kernel hooks:
- Operate outside the guest OS
- Remain effective even if guest kernel is compromised
- Transparent to guest-level detection
- Cannot be removed by kernel-level rootkits

Protectable Assets via EPT

- Executable pages of EPP (Endpoint Protection Platform) drivers
  → Prevents silent patching of security software
- ETW-related structures
  → Unauthorized writes fault into hypervisor
- Callback/callout/routine lists (PsSetCreateProcessNotifyRoutine, etc.)
  → Write authorization moved outside the guest kernel
- Critical kernel data structures
  → PatchGuard-protected regions, SSDT, IDT

Threat Model for Hypervisor Defense

Assumes kernel compromise has already happened:
- Attacker has kernel code execution
- Attacker can load vulnerable drivers (BYOVD)
- Attacker can modify kernel memory
- Traditional kernel-resident protections are untrustworthy

Hypervisor advantage:
- Sits above the guest kernel in privilege hierarchy
- Enforces policies from a higher privilege layer
- Kernel-level rootkits cannot disable hypervisor-level enforcement

Attack Scenario: BYOVD vs EPT Protection

Without hypervisor defense:
1. Attacker loads vulnerable signed driver
2. Gains kernel R/W primitives
3. Patches callback list to remove EPP callbacks
4. EPP is blinded — attacker operates undetected

With EPT-based defense:
1. Attacker loads vulnerable signed driver
2. Gains kernel R/W primitives
3. Attempts to patch callback list
4. EPT violation triggers VM exit
5. Hypervisor catches the write, evaluates context
6. Write is denied — callback list remains intact

Resource Organization

The README contains categorized links for:

  • PatchGuard research and bypasses
  • DSE bypass techniques
  • Vulnerable driver exploits
  • Kernel callback enumeration
  • ETW/PMI/NMI handlers
  • Intel PT integration

Data Source

Important: This skill provides conceptual guidance and overview information. For detailed information use the following sources:

1. Project Overview & Resource Index

Fetch the main README for the full curated list of repositories, tools, and descriptions:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/README.md

The main README contains thousands of curated links organized by category. When users ask for specific tools, projects, or implementations, retrieve and reference the appropriate sections from this source.

2. Repository Code Details (Archive)

For detailed repository information (file structure, source code, implementation details), the project maintains a local archive. If a repository has been archived, always prefer fetching from the archive over cloning or browsing GitHub directly.

Archive URL format:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/archive/{owner}/{repo}.txt

Examples:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/archive/ufrisk/pcileech.txt
https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/archive/000-aki-000/GameDebugMenu.txt

How to use:

  1. Identify the GitHub repository the user is asking about (owner and repo name from the URL).
  2. Construct the archive URL: replace {owner} with the GitHub username/org and {repo} with the repository name (no .git suffix).
  3. Fetch the archive file — it contains a full code snapshot with file trees and source code generated by code2prompt.
  4. If the fetch returns a 404, the repository has not been archived yet; fall back to the README or direct GitHub browsing.

3. Repository Descriptions

For a concise English summary of what a repository does, the project maintains auto-generated description files.

Description URL format:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/description/{owner}/{repo}/description_en.txt

Examples:

https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/description/00christian00/UnityDecompiled/description_en.txt
https://raw.githubusercontent.com/gmh5225/awesome-game-security/refs/heads/main/description/ufrisk/pcileech/description_en.txt

How to use:

  1. Identify the GitHub repository the user is asking about (owner and repo name from the URL).
  2. Construct the description URL: replace {owner} with the GitHub username/org and {repo} with the repository name.
  3. Fetch the description file — it contains a short, human-readable summary of the repository's purpose and contents.
  4. If the fetch returns a 404, the description has not been generated yet; fall back to the README entry or the archive.

Priority order when answering questions about a specific repository:

  1. Description (quick summary) — fetch first for concise context
  2. Archive (full code snapshot) — fetch when deeper implementation details are needed
  3. README entry — fallback when neither description nor archive is available

Accueil - Wiki
Copyright © 2011-2026 iteam. Current version is 2.155.2. UTC+08:00, 2026-07-09 08:31
浙ICP备14020137号-1 $Carte des visiteurs$