Примітиви експлуатації Windows Registry Hive

Tip

Вивчайте та практикуйте AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Вивчайте та практикуйте GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE) Вивчайте та практикуйте Azure Hacking: HackTricks Training Azure Red Team Expert (AzRTE)

Підтримайте HackTricks

Чому пошкодження hive особливе

Windows registry hives — це відображені в пам’ять .regf файли, якими керує власний алокатор (HvAllocateCell, HvReallocateCell, HvFreeCell). Алокатор:

  • Не рандомізує виділення – розміщення клітинок залежить лише від порядку/розміру попередніх викликів API реєстру, тому макети відтворюються на різних хостах.
  • Не має перевірок цілісності – вручну змінені поля заголовка/даних довіряються споживачам ядра (Cmp* routines) та самому процесу Registry.
  • Ділить адресний простір з привілейованими hives – у багатьох випадках hives, контрольовані атакуючим, відображуються в тому ж діапазоні адрес у режимі користувача, що й HKLM/HKU hives, що дозволяє переповнення між hives.

Це робить помилки корупції пам’яті на основі hive (наприклад, CVE-2023-23420 / CVE-2023-23423) винятково надійними для LPE.

Детерміноване формування макету за допомогою API реєстру

Оскільки алокація hive детермінована, ви можете налаштовувати розміщення клітинок виключно через Win32 APIs. Типовий робочий процес:

  1. Скинути цільовий ключ (видалити/створити заново), щоб hive bin містив лише відомі клітинки.
  2. Виділяти передбачувані послідовності клітинок шляхом створення значень з ретельно підібраними розмірами:
  • Клітини метаданих ключів/значень кратні 8 байтам.
  • Запис значень розміром 0x3FD8 байт примушує створити новий 0x4000-байтовий бін (0x3FD8 даних + _HBIN заголовок/відступи), ідеальний для подальшого переплетення бінів.
  1. Використовувати типи, дружні до зміни розміру (наприклад, REG_BINARY), щоб можна було звільняти/розширювати окремі клітини просто викликаючи RegSetValueEx з різними довжинами.
  2. Записувати послідовність операцій (create/delete/resize). Відтворення цієї послідовності відтворює той самий макет на інших системах, тому що алокатор не має випадковості.
Приклад формувача макету (simplified C) ```c void MakeBin(HKEY base, const wchar_t *name, size_t bytes) { std::vector buf(bytes, 0x41); RegSetKeyValueW(base, NULL, name, REG_BINARY, buf.data(), (DWORD)buf.size()); }

void Groom(HKEY hive) { for (int i = 0; i < 0x20; ++i) { wchar_t value[32]; swprintf(value, L“bin_%02d“, i); MakeBin(hive, value, 0x3FD8); RegDeleteKeyValueW(hive, NULL, value); // leaves holes for victim cells } }

</details>

Once a corruption primitive (overwrite/fill) is available, the groom guarantees that the **target cell resides next to the sprayed holes**, enabling precise overwrites without heap spraying.

## API-only access to privileged hives via misconfigured descendants

Windows only evaluates the **ACL on the final component** of a registry path. If any descendant under HKLM/HKU grants KEY_SET_VALUE, KEY_CREATE_SUB_KEY, or WRITE_DAC to low-privileged users, you can reach it even when every parent key is locked down. Project Zero found >1000 such writable keys in HKLM on Windows 11, including long-lived entries like HKLM\SOFTWARE\Microsoft\DRM and several HKLM\SYSTEM branches.

Practical enumeration strategy:

1. From an elevated context, walk \Registry\Machine and \Registry\User, dumping each key’s security descriptor. Store items whose DACL allows unprivileged SIDs.
2. As a normal user, attempt RegOpenKeyEx with KEY_SET_VALUE|KEY_CREATE_SUB_KEY against the recorded paths. Successful opens are viable targets for hive corruption bugs that require attacker-controlled data in system hives.
3. Maintain a cache of open handles to **stable writable locations** so PoCs can directly deploy corrupted metadata.
```powershell
$targets = Get-ChildItem Registry::HKEY_LOCAL_MACHINE -Recurse |
Where-Object { (Get-Acl $_.PsPath).Access.IdentityReference -match 'S-1-5-32-545' } |
Select-Object -ExpandProperty PsPath

foreach ($path in $targets) {
try { Get-Item -Path $path -ErrorAction Stop | Out-Null }
catch {}
}

Once such a path is known, the exploit never needs offline hive tampering—standard registry APIs are enough to stage the corrupt cells inside privileged hives touched by SYSTEM services.

Cross-user hive abuse via HKCU\Software\Microsoft\Input\TypingInsights

Every user hive contains HKCU\Software\Microsoft\Input\TypingInsights, whose ACL grants KEY_ALL_ACCESS to Everyone (S-1-1-0). Until Microsoft tightens it, any user can:

  • Fill another user’s hive up to the 2 GiB limit, causing logon failures or forcing hive truncation (useful to coerce allocator behavior or DoS).
  • Drop corrupted cells into other users’ NTUSER.DAT, setting up lateral exploits that trigger when the victim process reads the compromised key.
  • Modify differencing hives for sandboxed apps that rely on per-user overlay hives, forcing them to consume malicious metadata.

This makes hive corruption vulnerabilities applicable to lateral movement, not just elevation within the same account.

Turning metadata corruption into paged pool overflows

Large registry values are stored in _CM_BIG_DATA records:

  • _CM_KEY_VALUE.DataLength holds the logical size. Its high bit indicates whether the payload lives inside the cell or in big-data storage.
  • _CM_BIG_DATA.Count counts 16 KiB chunks (16384 bytes minus metadata) referenced via a chunk table.

When any component calls CmpGetValueData:

  1. The kernel allocates a paged pool buffer sized strictly from DataLength.
  2. It copies Count * 0x4000 bytes from hive storage into that buffer.

If you can corrupt the cell so DataLength < 16344 * (Count - 1), the copy overruns the destination linearly into adjacent paged-pool objects. A reliable exploit chain is:

  1. Use the deterministic groom to place the vulnerable _CM_KEY_VALUE near controllable metadata.
  2. Flip DataLength to a small number (e.g., 0x100) while leaving _CM_BIG_DATA.Count intact.
  3. Pool-groom from user mode (pipes, ALPC ports, section objects) so a chosen object (like EPROCESS->Token owner or SRVNET_BUFFER) occupies the next chunk after the allocation from step 1.
  4. Trigger a read (e.g., RegQueryValueEx, NtQueryValueKey) so CmpGetValueData copies all chunks and overwrites the neighbor’s fields with attacker-controlled data from the hive.
  5. Use the corrupted kernel object to pivot to arbitrary read/write or direct SYSTEM token theft.

Because the overflow length equals (Count * 0x4000) - DataLength, you get a precise byte budget and full control over the bytes written, outperforming many driver-based pool overflows.

Inter-hive linear overflows via tightly packed HBINs

Hives mounted by the Registry process are mapped in 2 MiB-aligned views with no guard gaps. You can force two different hives to grow in lockstep until their _HBIN ranges touch:

  1. Choose an attacker-writable hive (app hive or user hive) and a privileged target (e.g., HKLM\SOFTWARE).
  2. Continuously create/delete 0x3FD8-byte values in both hives. Each allocation adds a 0x4000-byte bin, so running both writers in parallel interleaves their bins in virtual memory (observed with !process Registry + !vad).
  3. Once the final bin of the attacker hive sits immediately before an HBIN belonging to HKLM, use the hive corruption bug to overflow out of the attacker hive, smashing HBIN headers or cells inside HKLM.
  4. With HKLM metadata under control you can:
  • Stage a big-data inconsistency primitive directly in the privileged hive.
  • Corrupt configuration data consumed by SYSTEM services before it ever leaves the kernel.

The absence of guard pages means a linear overwrite from an unprivileged hive can directly corrupt SYSTEM-owned hive structures, enabling data-only attacks or setting up the pool overflow described above inside HKLM/HKU.

Operational tips

  • Monitor hive placement with !vad (user-mode) and !reg view / !pool (kernel) to confirm adjacency before triggering the overflow.
  • Cache writable HKLM paths discovered during enumeration so corruption primitives can be deployed quickly even after reboots.
  • Combine hive grooming with standard pool feng shui (pipe pair freelists, NtAllocateVirtualMemory on Registry process) to stabilize post-overflow primitives.

References

Tip

Вивчайте та практикуйте AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Вивчайте та практикуйте GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE) Вивчайте та практикуйте Azure Hacking: HackTricks Training Azure Red Team Expert (AzRTE)

Підтримайте HackTricks