Libc Protections

Tip

AWS Hacking’i öğrenin ve pratik yapın:HackTricks Training AWS Red Team Expert (ARTE)
GCP Hacking’i öğrenin ve pratik yapın: HackTricks Training GCP Red Team Expert (GRTE) Azure Hacking’i öğrenin ve pratik yapın: HackTricks Training Azure Red Team Expert (AzRTE)

HackTricks'i Destekleyin

Chunk Alignment Enforcement

Malloc bellek tahsisini 8-byte (32-bit) veya 16-byte (64-bit) gruplar halinde yapar. Bu, 32-bit sistemlerde chunk sonlarının 0x8 ile, 64-bit sistemlerde ise 0x0 ile hizalanması gerektiği anlamına gelir. Güvenlik özelliği, bir bin’den alınan bir işaretçi kullanılmadan önce her chunk’ın bu özel konumlarda doğru hizalandığını doğrular.

Güvenlik Faydaları

64-bit sistemlerde chunk hizalama zorlaması, Malloc’un güvenliğini önemli ölçüde artırır; çünkü sahte chunk’ların yerleştirilebileceği adresleri her 16 adresten yalnızca 1 ile sınırlar. Bu, özellikle kullanıcı girdileri üzerinde sınırlı kontrole sahip senaryolarda istismar çabalarını karmaşıklaştırır ve saldırıların başarılı olmasını zorlaştırır.

  • Fastbin Attack on __malloc_hook

Malloc’taki yeni hizalama kuralları, __malloc_hook ile ilgili klasik bir saldırıyı da engeller. Önceden, saldırganlar chunk boyutlarını manipüle ederek bu fonksiyon işaretçisini overwrite edip code execution elde edebiliyordu. Artık katı hizalama gereksinimi, bu tür manipülasyonları geçersiz kılarak yaygın bir sömürü yolunu kapatır ve genel güvenliği artırır.

Not: glibc 2.34’ten itibaren legacy hooks (__malloc_hook, __free_hook, vb.) exported ABI’den kaldırıldı. Modern exploit’ler artık diğer yazılabilir fonksiyon işaretçilerini (ör. tcache per-thread struct, vtable-style callbacks) hedefliyor veya setcontext, _IO_list_all primitives, vb. gibi mekanizmalara dayanıyor.

Pointer Mangling on fastbins and tcache

Pointer Mangling, bellek yönetimi işlemlerinde fastbin ve tcache Fd işaretçilerini korumak için kullanılan bir güvenlik geliştirmesidir. Bu teknik, özellikle leak gerektirmeyen veya bellek konumlarını bilinen yerlere göre doğrudan manipüle eden (relative overwrites) bazı bellek istismarı taktiklerini engellemeye yardımcı olur.

Tekniğin özü bir obfuscation formülüdür:

New_Ptr = (L >> 12) XOR P

  • L işaretçinin Storage Location’ıdır.
  • P gerçek fastbin/tcache Fd Pointer’ıdır.

Storage location (L) değerinin 12 bit sağa kaydırılmasının ve ardından XOR işlemine sokulmasının nedeni kritiktir. Bu işlem, mimari kısıtlamalar nedeniyle genellikle tahmin edilebilir olan adreslerin en düşük 12 bitinin deterministik doğasından kaynaklanan bir zayıflığı giderir. Bitlerin kaydırılmasıyla, tahmin edilebilir kısım denklemden çıkarılır, böylece yeni, mangled işaretçinin rastgeleliği artar ve bu da bu bitlerin tahmin edilebilirliğine dayanan istismarları zorlaştırır.

Bu mangled işaretçi, programlar tarafından kullanılan adresleri rastgeleleştiren Address Space Layout Randomization (ASLR) tarafından sağlanan mevcut rastgelelikten yararlanır; bu da bir saldırganın bir işlemin bellek düzenini tahmin etmesini zorlaştırır.

Bir işaretçiyi orijinal adresine döndürmek (demangling) aynı XOR işlemi kullanılarak yapılır. Burada mangled işaretçi formülde P olarak ele alınır ve değişmemiş storage location (L) ile XORlandığında orijinal işaretçi ortaya çıkar. Pointer mangling ve demangling arasındaki bu simetri, sistemi önemli bir yük getirmeden işaretçileri verimli şekilde kodlayıp çözmesini sağlar ve bellek işaretçilerini manipüle eden saldırılara karşı güvenliği ciddi şekilde artırır.

Güvenlik Faydaları

Pointer mangling, heap yönetiminde kısmi ve tam işaretçi overwriteleri önlemeyi amaçlar ve bu, güvenlik açısından büyük bir geliştirmedir. Bu özellik, exploit tekniklerini birkaç şekilde etkiler:

  1. Bye Byte Relative Overwrites’in Önlenmesi: Önceden saldırganlar, bir işaretçinin bir kısmını değiştirerek exact adresler bilinmeden heap chunk’ları farklı yerlere yönlendirebiliyordu; leakless House of Roman istismarında görüldüğü gibi. Pointer mangling ile, leak olmadan yapılan bu tür relative overwrite’lar artık brute force gerektirebilir; böylece başarı olasılığı ciddi şekilde azalır.
  2. Tcache Bin/Fastbin Saldırılarının Zorluk Seviyesinin Artması: Fastbin veya tcache girişlerini manipüle ederek fonksiyon işaretçilerini (ör. __malloc_hook) overwrite etmeye dayalı yaygın saldırılar zorlaşır. Örneğin, bir saldırı LibC adresi leak edip bir chunk’ı tcache içine free’leyip sonra Fd işaretçisini __malloc_hook’a yönlendirerek arbitrary code execution elde etmeyi hedefleyebilir. Pointer mangling ile bu işaretçilerin doğru şekilde mangled olması gerekir; bu da doğru manipülasyon için bir heap leak gerektirir ve istismarın eşiğini yükseltir.
  3. Non-Heap Konumlarında Fake Chunk Oluşturmanın Heap Leak Gerektirmesi: Stack, .bss veya PLT/GOT gibi non-heap alanlarda sahte chunk oluşturmak artık pointer mangling nedeniyle heap leak gerektirir. Bu, bu alanları istismar etme karmaşıklığını artırır; tıpkı LibC adreslerini manipüle etme gerekliliği gibi.
  4. Heap Adreslerini Leak Etmenin Daha Zor Hale Gelmesi: Pointer mangling, fastbin ve tcache bin’deki Fd işaretçilerini heap adresi leak kaynağı olarak kullanılmasını sınırlar. Ancak unsorted, small ve large bin’lerdeki işaretçiler mangled değildir; bu yüzden halen adres leak için kullanılabilirler. Bu durum saldırganları bu bin’lerde kullanılabilir bilgi aramaya iter, bazı teknikler yine mangled işaretçileri bir leak öncesinde demangle etmeye izin verebilir ancak bunlar sınırlamalarla karşılaşır.

Safe-Linking Bypass (page-aligned leak scenario)

Safe-linking etkin olsa bile (glibc ≥ 2.32), eğer mangled işaretçiyi leak edebiliyorsanız ve hem corrupted chunk hem de victim chunk aynı 4KB sayfayı paylaşıyorsa, orijinal işaretçi yalnızca sayfa offset’iyle geri elde edilebilir:

// 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

For a better explanation of the process check the original post from here.

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

AWS Hacking’i öğrenin ve pratik yapın:HackTricks Training AWS Red Team Expert (ARTE)
GCP Hacking’i öğrenin ve pratik yapın: HackTricks Training GCP Red Team Expert (GRTE) Azure Hacking’i öğrenin ve pratik yapın: HackTricks Training Azure Red Team Expert (AzRTE)

HackTricks'i Destekleyin