Primitivas de Exploração de Hive do Windows Registry

Tip

Aprenda e pratique Hacking AWS:HackTricks Training AWS Red Team Expert (ARTE)
Aprenda e pratique Hacking GCP: HackTricks Training GCP Red Team Expert (GRTE) Aprenda e pratique Hacking Azure: HackTricks Training Azure Red Team Expert (AzRTE)

Supporte o HackTricks

Por que a corrupção de hive é especial

Os hives do Windows Registry são arquivos .regf mapeados em memória gerenciados por um alocador personalizado (HvAllocateCell, HvReallocateCell, HvFreeCell). O alocador:

  • Não randomiza as alocações – o posicionamento das cells depende apenas da ordem/tamanho de chamadas prévias às APIs do registry, então os layouts são reprodutíveis entre hosts.
  • Não possui verificações de integridade – campos de header/dados alterados manualmente são confiados pelos consumidores do kernel (rotinas Cmp*) e pelo processo Registry em si.
  • Compartilha o espaço de endereçamento com hives privilegiados – em muitos casos hives controlados pelo atacante são mapeados na mesma faixa de endereços user-mode que HKLM/HKU hives, permitindo overflows entre hives.

Isso torna bugs de corrupção de memória baseados em hive (por exemplo, CVE-2023-23420 / CVE-2023-23423) singularmente confiáveis para LPE.

Grooming determinístico do layout com as APIs do Registry

Como a alocação de hive é determinística, você pode ajustar o posicionamento das cells puramente via Win32 APIs. Um fluxo de trabalho típico é:

  1. Resetar a chave alvo (deletar/recriar) de modo que o hive bin contenha apenas cells conhecidas.
  2. Alocar sequências previsíveis de cells criando values com tamanhos cuidadosamente selecionados:
  • Cells de metadados de chave/value são múltiplos de 8 bytes.
  • Escrever valores de tamanho 0x3FD8 força um bin novo de 0x4000 bytes (0x3FD8 de dados + header/padding _HBIN), ideal para intercalar bins mais tarde.
  1. Usar tipos que permitam redimensionamento (ex.: REG_BINARY) para que você possa liberar/estender cells individuais apenas chamando RegSetValueEx com comprimentos diferentes.
  2. Registrar a sequência de operações (create/delete/resize). Reproduzi-la gera o mesmo layout em outros sistemas porque o alocador não possui aleatoriedade.
Exemplo de modelador de layout (C simplificado) ```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>

Uma vez que um corruption primitive (overwrite/fill) esteja disponível, o groom garante que a **a célula alvo esteja ao lado dos sprayed holes**, possibilitando overwrites precisos sem heap spraying.

## Acesso apenas por API a hives privilegiadas via descendentes mal configurados

O Windows avalia apenas a **ACL no componente final** de um caminho de registro. Se qualquer descendente sob HKLM/HKU conceder `KEY_SET_VALUE`, `KEY_CREATE_SUB_KEY` ou `WRITE_DAC` a usuários de baixo privilégio, você pode alcançá-lo mesmo quando todas as chaves pai estiverem bloqueadas. Project Zero encontrou **>1000 chaves graváveis desse tipo em HKLM no Windows 11**, incluindo entradas de longa duração como `HKLM\SOFTWARE\Microsoft\DRM` e vários ramos de `HKLM\SYSTEM`.

Estratégia prática de enumeração:

1. A partir de um contexto elevado, percorra `\Registry\Machine` e `\Registry\User`, despejando o security descriptor de cada chave. Armazene itens cuja DACL permite SIDs não privilegiados.
2. Como um usuário normal, tente `RegOpenKeyEx` com `KEY_SET_VALUE|KEY_CREATE_SUB_KEY` contra os caminhos registrados. Aberturas bem-sucedidas são alvos viáveis para bugs de corrupção de hive que requerem dados controlados pelo atacante em system hives.
3. Mantenha um cache de handles abertos para localizações graváveis estáveis para que PoCs possam implantar diretamente metadados corrompidos.
```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.

Abuso de hive entre usuários 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:

  • Preencher o hive de outro usuário até o limite de 2 GiB, causando falhas de logon ou forçando truncamento do hive (útil para coagir o comportamento do allocator ou DoS).
  • Inserir células corrompidas em NTUSER.DAT de outros usuários, preparando lateral exploits que disparam quando o processo vítima lê a chave comprometida.
  • Modificar differencing hives para apps sandboxed que dependem de per-user overlay hives, forçando-os a consumir metadata maliciosa.

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

Transformando corrupção de metadata em 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. Defina DataLength para um número pequeno (e.g., 0x100) enquanto mantém _CM_BIG_DATA.Count intacto.
  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.

Dicas operacionais

  • 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

Aprenda e pratique Hacking AWS:HackTricks Training AWS Red Team Expert (ARTE)
Aprenda e pratique Hacking GCP: HackTricks Training GCP Red Team Expert (GRTE) Aprenda e pratique Hacking Azure: HackTricks Training Azure Red Team Expert (AzRTE)

Supporte o HackTricks