# WWW2Exec - atexit(), Armazenamento TLS & Outros Ponteiros Emaranhados {{#include ../../banners/hacktricks-training.md}} ## **\_\_atexit Estruturas** > [!CAUTION] > Hoje em dia é muito **estranho explorar isso!** **`atexit()`** é uma função à qual **outras funções são passadas como parâmetros.** Essas **funções** serão **executadas** ao executar um **`exit()`** ou o **retorno** do **main**.\ Se você puder **modificar** o **endereço** de qualquer uma dessas **funções** para apontar para um shellcode, por exemplo, você **ganhará controle** do **processo**, mas isso é atualmente mais complicado.\ Atualmente, os **endereços das funções** a serem executadas estão **ocultos** atrás de várias estruturas e, finalmente, o endereço para o qual aponta não é o endereço das funções, mas está **criptografado com XOR** e deslocamentos com uma **chave aleatória**. Portanto, atualmente, esse vetor de ataque **não é muito útil, pelo menos em x86** e **x64_86**.\ A **função de criptografia** é **`PTR_MANGLE`**. **Outras arquiteturas** como m68k, mips32, mips64, aarch64, arm, hppa... **não implementam a função de criptografia** porque ela **retorna o mesmo** que recebeu como entrada. Portanto, essas arquiteturas seriam atacáveis por esse vetor. Você pode encontrar uma explicação detalhada sobre como isso funciona em [https://m101.github.io/binholic/2017/05/20/notes-on-abusing-exit-handlers.html](https://m101.github.io/binholic/2017/05/20/notes-on-abusing-exit-handlers.html) ## link_map Como explicado [**neste post**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#2---targetting-ldso-link_map-structure), se o programa sair usando `return` ou `exit()`, ele executará `__run_exit_handlers()` que chamará os destrutores registrados. > [!CAUTION] > Se o programa sair pela função **`_exit()`**, ele chamará a **`exit` syscall** e os manipuladores de saída não serão executados. Portanto, para confirmar que `__run_exit_handlers()` é executado, você pode definir um ponto de interrupção nele. O código importante é ([source](https://elixir.bootlin.com/glibc/glibc-2.32/source/elf/dl-fini.c#L131)): ```c ElfW(Dyn) *fini_array = map->l_info[DT_FINI_ARRAY]; if (fini_array != NULL) { ElfW(Addr) *array = (ElfW(Addr) *) (map->l_addr + fini_array->d_un.d_ptr); size_t sz = (map->l_info[DT_FINI_ARRAYSZ]->d_un.d_val / sizeof (ElfW(Addr))); while (sz-- > 0) ((fini_t) array[sz]) (); } [...] // This is the d_un structure ptype l->l_info[DT_FINI_ARRAY]->d_un type = union { Elf64_Xword d_val; // address of function that will be called, we put our onegadget here Elf64_Addr d_ptr; // offset from l->l_addr of our structure } ``` Note como `map -> l_addr + fini_array -> d_un.d_ptr` é usado para **calcular** a posição do **array de funções a serem chamadas**. Existem **algumas opções**: - Sobrescrever o valor de `map->l_addr` para fazê-lo apontar para um **falso `fini_array`** com instruções para executar código arbitrário. - Sobrescrever as entradas `l_info[DT_FINI_ARRAY]` e `l_info[DT_FINI_ARRAYSZ]` (que são mais ou menos consecutivas na memória), para fazê-las **apontar para uma estrutura `Elf64_Dyn` forjada** que fará novamente **`array` apontar para uma zona de memória** controlada pelo atacante. - [**Este writeup**](https://github.com/nobodyisnobody/write-ups/tree/main/DanteCTF.2023/pwn/Sentence.To.Hell) sobrescreve `l_info[DT_FINI_ARRAY]` com o endereço de uma memória controlada em `.bss` contendo um falso `fini_array`. Este array falso contém **primeiro um** [**one gadget**](../rop-return-oriented-programing/ret2lib/one-gadget.md) **endereço** que será executado e então a **diferença** entre o endereço deste **array falso** e o **valor de `map->l_addr`** para que `*array` aponte para o array falso. - De acordo com o post principal desta técnica e [**este writeup**](https://activities.tjhsst.edu/csc/writeups/angstromctf-2021-wallstreet), ld.so deixa um ponteiro na pilha que aponta para o `link_map` binário em ld.so. Com uma escrita arbitrária, é possível sobrescrevê-lo e fazê-lo apontar para um falso `fini_array` controlado pelo atacante com o endereço de um [**one gadget**](../rop-return-oriented-programing/ret2lib/one-gadget.md), por exemplo. Seguindo o código anterior, você pode encontrar outra seção interessante com o código: ```c /* Next try the old-style destructor. */ ElfW(Dyn) *fini = map->l_info[DT_FINI]; if (fini != NULL) DL_CALL_DT_FINI (map, ((void *) map->l_addr + fini->d_un.d_ptr)); } ``` Neste caso, seria possível sobrescrever o valor de `map->l_info[DT_FINI]` apontando para uma estrutura `ElfW(Dyn)` forjada. Encontre [**mais informações aqui**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#2---targetting-ldso-link_map-structure). ## Sobrescrita de dtor_list de TLS-Storage em **`__run_exit_handlers`** Como [**explicado aqui**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#5---code-execution-via-tls-storage-dtor_list-overwrite), se um programa sair via `return` ou `exit()`, ele executará **`__run_exit_handlers()`**, que chamará qualquer função de destrutor registrada. Código de `_run_exit_handlers()`: ```c /* Call all functions registered with `atexit' and `on_exit', in the reverse of the order in which they were registered perform stdio cleanup, and terminate program execution with STATUS. */ void attribute_hidden __run_exit_handlers (int status, struct exit_function_list **listp, bool run_list_atexit, bool run_dtors) { /* First, call the TLS destructors. */ #ifndef SHARED if (&__call_tls_dtors != NULL) #endif if (run_dtors) __call_tls_dtors (); ``` Código de **`__call_tls_dtors()`**: ```c typedef void (*dtor_func) (void *); struct dtor_list //struct added { dtor_func func; void *obj; struct link_map *map; struct dtor_list *next; }; [...] /* Call the destructors. This is called either when a thread returns from the initial function or when the process exits via the exit function. */ void __call_tls_dtors (void) { while (tls_dtor_list) // parse the dtor_list chained structures { struct dtor_list *cur = tls_dtor_list; // cur point to tls-storage dtor_list dtor_func func = cur->func; PTR_DEMANGLE (func); // demangle the function ptr tls_dtor_list = tls_dtor_list->next; // next dtor_list structure func (cur->obj); [...] } } ``` Para cada função registrada em **`tls_dtor_list`**, ele irá desmanglar o ponteiro de **`cur->func`** e chamá-lo com o argumento **`cur->obj`**. Usando a função **`tls`** deste [**fork do GEF**](https://github.com/bata24/gef), é possível ver que na verdade o **`dtor_list`** está muito **perto** do **stack canary** e do **PTR_MANGLE cookie**. Assim, com um overflow nele, seria possível **sobrescrever** o **cookie** e o **stack canary**.\ Sobrescrevendo o PTR_MANGLE cookie, seria possível **burlar a função `PTR_DEMANLE`** configurando-o para 0x00, o que significa que o **`xor`** usado para obter o endereço real é apenas o endereço configurado. Então, ao escrever no **`dtor_list`**, é possível **encadear várias funções** com o **endereço** da função e seu **argumento**. Finalmente, note que o ponteiro armazenado não será apenas xored com o cookie, mas também rotacionado 17 bits: ```armasm 0x00007fc390444dd4 <+36>: mov rax,QWORD PTR [rbx] --> mangled ptr 0x00007fc390444dd7 <+39>: ror rax,0x11 --> rotate of 17 bits 0x00007fc390444ddb <+43>: xor rax,QWORD PTR fs:0x30 --> xor with PTR_MANGLE ``` Então você precisa levar isso em consideração antes de adicionar um novo endereço. Encontre um exemplo na [**postagem original**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#5---code-execution-via-tls-storage-dtor_list-overwrite). ## Outros ponteiros corrompidos em **`__run_exit_handlers`** Esta técnica é [**explicada aqui**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#5---code-execution-via-tls-storage-dtor_list-overwrite) e depende novamente do programa **sair chamando `return` ou `exit()`** para que **`__run_exit_handlers()`** seja chamado. Vamos verificar mais código desta função: ```c while (true) { struct exit_function_list *cur; restart: cur = *listp; if (cur == NULL) { /* Exit processing complete. We will not allow any more atexit/on_exit registrations. */ __exit_funcs_done = true; break; } while (cur->idx > 0) { struct exit_function *const f = &cur->fns[--cur->idx]; const uint64_t new_exitfn_called = __new_exitfn_called; switch (f->flavor) { void (*atfct) (void); void (*onfct) (int status, void *arg); void (*cxafct) (void *arg, int status); void *arg; case ef_free: case ef_us: break; case ef_on: onfct = f->func.on.fn; arg = f->func.on.arg; PTR_DEMANGLE (onfct); /* Unlock the list while we call a foreign function. */ __libc_lock_unlock (__exit_funcs_lock); onfct (status, arg); __libc_lock_lock (__exit_funcs_lock); break; case ef_at: atfct = f->func.at; PTR_DEMANGLE (atfct); /* Unlock the list while we call a foreign function. */ __libc_lock_unlock (__exit_funcs_lock); atfct (); __libc_lock_lock (__exit_funcs_lock); break; case ef_cxa: /* To avoid dlclose/exit race calling cxafct twice (BZ 22180), we must mark this function as ef_free. */ f->flavor = ef_free; cxafct = f->func.cxa.fn; arg = f->func.cxa.arg; PTR_DEMANGLE (cxafct); /* Unlock the list while we call a foreign function. */ __libc_lock_unlock (__exit_funcs_lock); cxafct (arg, status); __libc_lock_lock (__exit_funcs_lock); break; } if (__glibc_unlikely (new_exitfn_called != __new_exitfn_called)) /* The last exit function, or another thread, has registered more exit functions. Start the loop over. */ goto restart; } *listp = cur->next; if (*listp != NULL) /* Don't free the last element in the chain, this is the statically allocate element. */ free (cur); } __libc_lock_unlock (__exit_funcs_lock); ``` A variável `f` aponta para a estrutura **`initial`** e, dependendo do valor de `f->flavor`, diferentes funções serão chamadas.\ Dependendo do valor, o endereço da função a ser chamada estará em um lugar diferente, mas sempre estará **demangled**. Além disso, nas opções **`ef_on`** e **`ef_cxa`**, também é possível controlar um **argumento**. É possível verificar a **estrutura `initial`** em uma sessão de depuração com o GEF executando **`gef> p initial`**. Para abusar disso, você precisa **vazar ou apagar o `PTR_MANGLE`cookie** e então sobrescrever uma entrada `cxa` em initial com `system('/bin/sh')`.\ Você pode encontrar um exemplo disso no [**post original do blog sobre a técnica**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#6---code-execution-via-other-mangled-pointers-in-initial-structure). {{#include ../../banners/hacktricks-training.md}}