Protections Libc

Tip

Apprenez et pratiquez le hacking AWS :HackTricks Training AWS Red Team Expert (ARTE)
Apprenez et pratiquez le hacking GCP : HackTricks Training GCP Red Team Expert (GRTE) Apprenez et pratiquez le hacking Azure : HackTricks Training Azure Red Team Expert (AzRTE)

Soutenir HackTricks

Application de l’alignement des chunks

Malloc alloue la mémoire en groupes de 8 octets (32-bit) ou 16 octets (64-bit). Cela signifie que la fin des chunks sur les systèmes 32-bit doit être alignée sur 0x8, et sur les systèmes 64-bit sur 0x0. La fonctionnalité de sécurité vérifie que chaque chunk est correctement aligné à ces emplacements spécifiques avant d’utiliser un pointeur issu d’un bin.

Avantages de sécurité

L’application de l’alignement des chunks sur les systèmes 64-bit améliore significativement la sécurité de Malloc en limitant le placement des fake chunks à seulement 1 adresse sur 16. Cela complique les tentatives d’exploitation, surtout dans les scénarios où l’attaquant dispose d’un contrôle limité sur les valeurs d’entrée, rendant les attaques plus complexes et plus difficiles à exécuter avec succès.

  • Fastbin Attack on __malloc_hook

Les nouvelles règles d’alignement dans Malloc contrecarrent également une attaque classique impliquant __malloc_hook. Auparavant, un attaquant pouvait manipuler les tailles des chunks pour écraser ce pointeur de fonction et obtenir une exécution de code. Désormais, l’exigence stricte d’alignement rend ces manipulations non viables, fermant une voie d’exploitation courante et renforçant la sécurité globale.

Note : Depuis glibc 2.34 les hooks legacy (__malloc_hook, __free_hook, etc.) ont été retirés de l’ABI exportée. Les exploits modernes ciblent maintenant d’autres pointeurs de fonction modifiables (par ex. tcache per-thread struct, vtable-style callbacks) ou s’appuient sur setcontext, _IO_list_all primitives, etc.

Pointer Mangling on fastbins and tcache

Pointer Mangling est une amélioration de sécurité utilisée pour protéger les fastbin et tcache Fd pointers dans les opérations de gestion mémoire. Cette technique aide à empêcher certains types de tactiques d’exploitation mémoire, spécifiquement celles qui ne nécessitent pas d’information leaked ou qui manipulent des emplacements mémoire directement par rapport à des positions connues (relative overwrites).

Le cœur de cette technique est une formule d’obfuscation :

New_Ptr = (L >> 12) XOR P

  • L est la Storage Location du pointeur.
  • P est le réel fastbin/tcache Fd Pointer.

La raison du décalage logique de la Storage Location (L) de 12 bits vers la droite avant l’opération XOR est cruciale. Cette manipulation corrige une vulnérabilité inhérente à la nature déterministe des 12 bits de poids faible des adresses mémoire, qui sont typiquement prévisibles à cause des contraintes d’architecture du système. En décalant ces bits, la portion prévisible est retirée de l’équation, augmentant l’aléa du nouveau pointeur obfusqué et protégeant ainsi contre les exploits qui se basent sur la prévisibilité de ces bits.

Ce pointeur manglé exploite l’aléa existant fourni par Address Space Layout Randomization (ASLR), qui randomise les adresses utilisées par les programmes pour rendre difficile la prédiction de la disposition mémoire d’un processus.

La démangling du pointeur pour récupérer l’adresse originale implique l’utilisation du même XOR. Ici, le pointeur manglé est traité comme P dans la formule, et lorsqu’il est XORé avec la Storage Location L inchangée, il révèle le pointeur original. Cette symétrie entre mangling et demangling permet au système d’encoder et décoder efficacement les pointeurs sans surcharge significative, tout en augmentant substantiellement la sécurité contre les attaques qui manipulent des pointeurs mémoire.

Avantages de sécurité

Pointer mangling vise à prévenir les overwrites partielles et complètes de pointeurs dans la gestion du heap, une amélioration de sécurité significative. Cette fonctionnalité impacte les techniques d’exploitation de plusieurs manières :

  1. Prévention des Bye Byte Relative Overwrites : auparavant, un attaquant pouvait modifier une partie d’un pointeur pour rediriger des chunks du heap vers d’autres emplacements sans connaître les adresses exactes, une technique visible dans l’exploit leakless House of Roman. Avec le pointer mangling, de tels overwrites relatifs sans un heap leak exigent maintenant du brute forcing, réduisant drastiquement leur probabilité de succès.
  2. Augmentation de la difficulté des attaques sur les tcache bin/fastbin : les attaques courantes qui écrasent des pointeurs de fonction (comme __malloc_hook) en manipulant les entrées fastbin ou tcache sont entravées. Par exemple, une attaque peut consister à leak une adresse LibC, libérer un chunk dans le tcache bin, puis écraser le Fd pour le rediriger vers __malloc_hook pour une exécution arbitraire. Avec le pointer mangling, ces pointeurs doivent être correctement manglés, nécessitant un heap leak pour une manipulation précise, élevant ainsi la barrière d’exploitation.
  3. Exigence de heap leaks pour les emplacements non-heap : créer un fake chunk dans des zones non-heap (comme la stack, la section .bss, ou PLT/GOT) nécessite désormais aussi un heap leak en raison du besoin de pointer mangling. Cela étend la complexité de l’exploitation de ces zones, similaire à l’exigence pour manipuler des adresses LibC.
  4. Rendre les leaks d’adresses heap plus difficiles : le pointer mangling limite l’utilité des Fd pointers dans les fastbin et tcache bins comme sources de heap address leaks. Cependant, les pointeurs dans les unsorted, small, et large bins restent non manglés, et donc toujours utilisables pour leak des adresses. Ce changement pousse les attaquants à explorer ces bins pour trouver des informations exploitables, bien que certaines techniques puissent encore permettre de démangler des pointeurs avant un leak, avec des contraintes.

Safe-Linking Bypass (page-aligned leak scenario)

Même avec safe-linking activé (glibc ≥ 2.32), si vous pouvez leak le pointeur manglé et que le chunk corrompu et le chunk victime partagent la même page de 4KB, le pointeur original peut être récupéré avec juste l’offset de page :

// leaked_fd is the mangled Fd read from the chunk on the same page
uintptr_t l = (uintptr_t)&chunk->fd;           // storage location
uintptr_t original = (leaked_fd ^ (l >> 12));  // demangle

This restores the Fd and permits classic tcache/fastbin poisoning. If the chunks sit on different pages, brute-forcing the 12-bit page offset (0x1000 possibilities) is often feasible when allocation patterns are deterministic or when crashes are acceptable (e.g., CTF-style exploits).

Demangling Pointers with a Heap leak

Caution

Pour une meilleure explication du processus consultez le post original ici.

Algorithm Overview

The formula used for mangling and demangling pointers is:

New_Ptr = (L >> 12) XOR P

Where L is the storage location and P is the Fd pointer. When L is shifted right by 12 bits, it exposes the most significant bits of P, due to the nature of XOR, which outputs 0 when bits are XORed with themselves.

Key Steps in the Algorithm:

  1. Initial Leak of the Most Significant Bits: By XORing the shifted L with P, you effectively get the top 12 bits of P because the shifted portion of L will be zero, leaving P’s corresponding bits unchanged.
  2. Recovery of Pointer Bits: Since XOR is reversible, knowing the result and one of the operands allows you to compute the other operand. This property is used to deduce the entire set of bits for P by successively XORing known sets of bits with parts of the mangled pointer.
  3. Iterative Demangling: The process is repeated, each time using the newly discovered bits of P from the previous step to decode the next segment of the mangled pointer, until all bits are recovered.
  4. Handling Deterministic Bits: The final 12 bits of L are lost due to the shift, but they are deterministic and can be reconstructed post-process.

You can find an implementation of this algorithm here: https://github.com/mdulin2/mangle

Pointer Guard

Pointer Guard is an exploit mitigation technique used in glibc to protect stored function pointers, particularly those registered by library calls such as atexit(). This protection involves scrambling the pointers by XORing them with a secret stored in the thread data (fs:0x30) and applying a bitwise rotation. This mechanism aims to prevent attackers from hijacking control flow by overwriting function pointers.

Bypassing Pointer Guard with a leak

  1. Understanding Pointer Guard Operations: The scrambling (mangling) of pointers is done using the PTR_MANGLE macro which XORs the pointer with a 64-bit secret and then performs a left rotation of 0x11 bits. The reverse operation for recovering the original pointer is handled by PTR_DEMANGLE.
  2. Attack Strategy: The attack is based on a known-plaintext approach, where the attacker needs to know both the original and the mangled versions of a pointer to deduce the secret used for mangling.
  3. Exploiting Known Plaintexts:
  • Identifying Fixed Function Pointers: By examining glibc source code or initialized function pointer tables (like __libc_pthread_functions), an attacker can find predictable function pointers.
  • Computing the Secret: Using a known function pointer such as __pthread_attr_destroy and its mangled version from the function pointer table, the secret can be calculated by reverse rotating (right rotation) the mangled pointer and then XORing it with the address of the function.
  1. Alternative Plaintexts: The attacker can also experiment with mangling pointers with known values like 0 or -1 to see if these produce identifiable patterns in memory, potentially revealing the secret when these patterns are found in memory dumps.
  2. Practical Application: After computing the secret, an attacker can manipulate pointers in a controlled manner, essentially bypassing the Pointer Guard protection in a multithreaded application with knowledge of the libc base address and an ability to read arbitrary memory locations.

GLIBC Tunables & Recent Loader Bugs

The dynamic loader parses GLIBC_TUNABLES before program startup. Mis-parsing bugs here directly affect libc before most mitigations kick in. The 2023 “Looney Tunables” bug (CVE-2023-4911) is an example: an overlong GLIBC_TUNABLES value overflows internal buffers in ld.so, enabling privilege escalation on many distros when combined with SUID binaries. Exploitation requires only crafting the environment and repeatedly invoking the target binary; pointer guard or safe-linking do not prevent it because corruption happens in the loader prior to heap setup.

References

Tip

Apprenez et pratiquez le hacking AWS :HackTricks Training AWS Red Team Expert (ARTE)
Apprenez et pratiquez le hacking GCP : HackTricks Training GCP Red Team Expert (GRTE) Apprenez et pratiquez le hacking Azure : HackTricks Training Azure Red Team Expert (AzRTE)

Soutenir HackTricks