Adreno A7xx SDS->RB privilege bypass (GPU SMMU takeover to Kernel R/W)

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

Esta página abstrai um bug de lógica em microcode Adreno A7xx observado na prática (CVE-2025-21479) em técnicas de exploração reprodutíveis: abusar do masking ao nível IB em Set Draw State (SDS) para executar CP packets privilegiados a partir de uma app não privilegiada, pivotando para takeover da GPU SMMU e depois para um R/W de kernel rápido e estável via um truque de dirty pagetable.

  • Affected: Qualcomm Adreno A7xx GPU firmware prior to a microcode fix that changed masking of register $12 from 0x3 to 0x7.
  • Primitive: Execute privileged CP packets (e.g., CP_SMMU_TABLE_UPDATE) from SDS, which is user-controlled.
  • Outcome: Arbitrary physical/virtual kernel memory R/W, SELinux disable, root.
  • Prereq: Ability to create a KGSL GPU context and submit command buffers that enter SDS (normal app capability).

Background: IB levels, SDS and the $12 mask

  • O kernel mantém um ringbuffer (RB=IB0). O espaço do usuário submete IB1 via CP_INDIRECT_BUFFER, encadeando para IB2/IB3.
  • SDS é um fluxo de comandos especial acessado via CP_SET_DRAW_STATE:
  • A6xx: SDS é tratado como IB3
  • A7xx: SDS movido para IB4
  • O microcode rastreia o nível IB atual no registador $12 e filtra packets privilegiados para que só sejam aceitos quando o nível efetivo corresponder a IB0 (kernel RB).
  • Bug: O microcode A7xx manteve o masking de $12 com 0x3 (2 bits) em vez de 0x7 (3 bits). Como IB4 & 0x3 == 0, SDS foi identificado erroneamente como IB0, permitindo packets privilegiados a partir de SDS controlado pelo usuário.

Why it matters:

A6XX                | A7XX
RB  & 3       == 0  |  RB  & 3       == 0
IB1 & 3       == 1  |  IB1 & 3       == 1
IB2 & 3       == 2  |  IB2 & 3       == 2
IB3 (SDS) & 3 == 3  |  IB3 & 3       == 3
|  IB4 (SDS) & 3 == 0   <-- misread as IB0 if mask is 0x3

Exemplo de diff de microcódigo (o patch alterou a máscara para 0x7):

@@ CP_SMMU_TABLE_UPDATE
- and $02, $12, 0x3
+ and $02, $12, 0x7
@@ CP_FIXED_STRIDE_DRAW_TABLE
- and $02, $12, 0x3
+ and $02, $12, 0x7

Visão geral da exploração

Goal: From SDS (misread as IB0) issue privileged CP packets to re-point the GPU SMMU to attacker-crafted page tables, then use GPU copy/write packets for arbitrary physical R/W. Finally, pivot to a fast CPU-side R/W via dirty pagetable.

High-level chain

  • Criar uma tabela de páginas GPU falsa na memória compartilhada
  • Entrar em SDS e executar:
  • CP_SMMU_TABLE_UPDATE -> mudar para a tabela de páginas falsa
  • CP_MEM_WRITE / CP_MEM_TO_MEM -> implementar primitivos de escrita/leitura
  • CP_SET_DRAW_STATE with run-now flags (dispatch immediately)

GPU R/W primitives via fake pagetable

  • Escrita: CP_MEM_WRITE para um GPU VA escolhido pelo atacante cujos PTEs você mapeia para um PA escolhido -> escrita física arbitrária
  • Leitura: CP_MEM_TO_MEM copia 4/8 bytes do PA alvo para um buffer compartilhado no userspace (batch para leituras maiores)

Notas

  • Cada processo Android recebe um contexto KGSL (IOCTL_KGSL_GPU_CONTEXT_CREATE). Mudar contextos normalmente atualiza tabelas SMMU no RB; o bug permite fazê-lo em SDS.
  • Tráfego excessivo da GPU pode causar apagões na UI e reboots; leituras são pequenas (4/8B) e sync é lento por padrão.

Construindo a sequência de comandos SDS

  • Spray uma tabela de páginas GPU falsa na memória compartilhada de modo que pelo menos uma instância fique em um endereço físico conhecido (por ex., via allocator grooming e repetição).
  • Construa um buffer SDS contendo, na ordem:
  1. CP_SMMU_TABLE_UPDATE para o endereço físico da tabela de páginas falsa
  2. One or more CP_MEM_WRITE and/or CP_MEM_TO_MEM packets to implement R/W using your new translations
  3. CP_SET_DRAW_STATE com flags para run-now

The exact packet encodings vary by firmware; use freedreno’s afuc/packet docs to assemble the words, and ensure the SDS submission path is taken by the driver.

Encontrando o physbase do kernel Samsung sob KASLR físico

Samsung randomizes the kernel physical base within a known region on Snapdragon devices. Brute-force the expected range and look for the first 16 bytes of _stext.

Representative loop

while (!ctx->kernel.pbase) {
offset += 0x8000;
uint64_t d1 = kernel_physread_u64(ctx, base + offset);
if (d1 != 0xd10203ffd503233f) continue;   // first 8 bytes of _stext
uint64_t d2 = kernel_physread_u64(ctx, base + offset + 8);
if (d2 == 0x910083fda9027bfd) {           // second 8 bytes of _stext
ctx->kernel.pbase = base + offset - 0x10000;
break;
}
}

Uma vez que physbase seja conhecido, calcule o endereço virtual do kernel com o mapa linear:

_stext = 0xffffffc008000000 + (Kernel Code & ~0xa8000000)

Estabilizando para R/W rápido e confiável do kernel pelo lado da CPU (dirty pagetable)

GPU R/W é lento e de granularidade pequena. Faça pivot para um primitivo rápido/estável corrompendo os PTEs do seu próprio processo (“dirty pagetable”):

Passos

  • Localize o task_struct atual -> mm_struct -> mm_struct->pgd usando os primitivos lentos de GPU R/W
  • mmap duas páginas adjacentes no userspace A e B (por exemplo, em 0x1000)
  • Percorra PGD->PMD->PTE para resolver os endereços físicos dos PTEs de A/B (helpers: get_pgd_offset, get_pmd_offset, get_pte_offset)
  • Sobrescreva o PTE de B para apontar para a tabela de páginas de último nível que gerencia A/B com atributos RW (phys_to_readwrite_pte)
  • Escreva via VA de B para mutar o PTE de A para mapear PFNs alvo; leia/escreva memória do kernel via VA de A, esvaziando o TLB até que um sentinel mude
Exemplo de trecho de pivot dirty-pagetable ```c uint64_t *map = mmap((void*)0x1000, PAGE_SIZE*2, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, 0, 0); uint64_t *page_map = (void*)((uint64_t)map + PAGE_SIZE); page_map[0] = 0x4242424242424242;

uint64_t tsk = get_curr_task_struct(ctx); uint64_t mm = kernel_vread_u64(ctx, tsk + OFFSETOF_TASK_STRUCT_MM); uint64_t mm_pgd = kernel_vread_u64(ctx, mm + OFFSETOF_MM_PGD);

uint64_t pgd_off = get_pgd_offset((uint64_t)map); uint64_t phys_pmd = kernel_vread_u64(ctx, mm_pgd + pgd_off) & ~((1<<12)-1); uint64_t pmd_off = get_pmd_offset((uint64_t)map); uint64_t phys_pte = kernel_pread_u64(ctx, phys_pmd + pmd_off) & ~((1<<12)-1); uint64_t pte_off = get_pte_offset((uint64_t)map); uint64_t pte_addr = phys_pte + pte_off; uint64_t new_pte = phys_to_readwrite_pte(pte_addr); kernel_write_u64(ctx, pte_addr + 8, new_pte, false); while (page_map[0] == 0x4242424242424242) flush_tlb();

</details>

## Detecção

- Telemetria: alertar se CP_SMMU_TABLE_UPDATE (ou opcodes privilegiados similares) aparecer fora de RB/IB0, especialmente em SDS; monitorar rajadas anômalas de 4/8 bytes de CP_MEM_TO_MEM e padrões excessivos de TLB flush

## Impacto

Um aplicativo local com acesso à GPU pode executar privileged GPU packets, sequestrar o GPU SMMU, alcançar R/W físico/virtual arbitrário do kernel, desabilitar o SELinux e obter root em dispositivos Snapdragon A7xx afetados (por exemplo, Samsung S23). Gravidade: Alta (comprometimento do kernel).

### Veja também

<a class="content_ref" href="pixel-bigwave-bigo-job-timeout-uaf-kernel-write.md"><span class="content_ref_label">Pixel Bigwave Bigo Job Timeout Uaf Kernel Write</span></a>

## Referências

- [CVE-2025-21479: Adreno A7xx SDS->RB privilege bypass to kernel R/W (Samsung S23)](https://xploitbengineer.github.io/CVE-2025-21479)
- [Mesa freedreno afuc disassembler README (microcode + packets)](https://gitlab.freedesktop.org/mesa/mesa/-/blob/c0f56fc64cad946d5c4fda509ef3056994c183d9/src/freedreno/afuc/README.rst)
- [Google Project Zero: Attacking Qualcomm Adreno GPU (SMMU takeover via CP packets)](https://googleprojectzero.blogspot.com/2020/09/attacking-qualcomm-adreno-gpu.html)
- [Dirty pagetable (archive)](https://web.archive.org/web/20240425043203/https://yanglingxi1993.github.io/dirty_pagetable/dirty_pagetable.html)

> [!TIP]
> Aprenda e pratique Hacking AWS:<img src="../../../../../images/arte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../../images/arte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">\
> Aprenda e pratique Hacking GCP: <img src="../../../../../images/grte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte)<img src="../../../../../images/grte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">
> Aprenda e pratique Hacking Azure: <img src="../../../../../images/azrte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">[**HackTricks Training Azure Red Team Expert (AzRTE)**](https://training.hacktricks.xyz/courses/azrte)<img src="../../../../../images/azrte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">
>
> <details>
>
> <summary>Supporte o HackTricks</summary>
>
> - Confira os [**planos de assinatura**](https://github.com/sponsors/carlospolop)!
> - **Junte-se ao** 💬 [**grupo do Discord**](https://discord.gg/hRep4RUj7f) ou ao [**grupo do telegram**](https://t.me/peass) ou **siga**-nos no **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.**
> - **Compartilhe truques de hacking enviando PRs para o** [**HackTricks**](https://github.com/carlospolop/hacktricks) e [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) repositórios do github.
>
> </details>