π‘οΈ Hardware Enforcements, Compiler Shields & Modern Exploit Countermeasures
Early buffer overflows succeeded effortlessly because systems executed code on the stack and kept memory addresses completely static across program runs. To neutralize entire vulnerability classes without requiring complete manual rewrites of legacy C/C++ codebases, operating system architects, CPU designers, and compiler engineers developed systematic Binary Exploit Mitigations. These defenses operate on three coordinated fronts: Hardware Enforcements such as the CPU No-Execute (NX / DEP) bit, which enforces the $W \oplus X$ (Write XOR Execute) memory invariant; Kernel Entropy via Address Space Layout Randomization (ASLR) and Position Independent Executables (PIE), which randomize stack, heap, and library base addresses on every execution; and Compiler-Level Protections like Stack Canaries and RELRO. Understanding how these mitigations interactβand how modern attackers bypass them using Information Leaks and Return-Oriented Programming (ROP)βis essential for engineering robust, resilient low-level software.
EXPLOIT TECHNIQUES VS. DEFENSIVE MITIGATION TOPOGRAPHY:
βββββββββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββ
β ADVERSARY ATTACK PRIMITIVE β DEFENSIVE MITIGATION LAYER β IMPLEMENTATION LEVEL β
βββββββββββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββ€
β 1. Direct Shellcode Execution β Non-Executable Stack (NX / DEP) β Hardware (CPU MMU Page Table Bit 63)β
β (Injecting code onto Stack/Heap) β W ^ X Policy (Write XOR Execute) β Kernel (Virtual Memory Manager) β
βββββββββββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββ€
β 2. Linear Stack Return Address Over- β Stack Smashing Protector (Canary) β Compiler (GCC -fstack-protector) β
β write via strcpy() / gets() β GS Buffer Security Check (/GS) β Thread Control Block (fs:[0x28]) β
βββββββββββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββ€
β 3. Hardcoded Return-to-libc & Gadgets β Address Space Layout Randomization β Kernel (sysctl randomize_va_space) β
β (Jumping to fixed library offsets) β Position Independent Executable (PIE) β Compiler (-fPIE -pie) β
βββββββββββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββ€
β 4. Global Offset Table (GOT) Hijack β Relocation Read-Only (Full RELRO) β Linker (GNU ld -z relro -z now) β
β (Overwriting dynamic function ptr) β Binds all symbols at load time β Memory marked PROT_READ only β
βββββββββββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββ€
β 5. Return-Oriented Programming (ROP) β Control Flow Integrity (CFI / CFG) β Compiler (Clang CFI, MSVC /guard:cf)β
β & Indirect Call/Jump Hijacking β Intel CET (Shadow Stack & IBT) β Hardware (Control-flow Enforcement) β
βββββββββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββ
THE W ^ X (WRITE XOR EXECUTE) HARDWARE MEMORY INVARIANT:
A memory page may be Writable, or Executable, but NEVER BOTH simultaneously!
Permission Mask: Valid States in { [R], [R, W], [R, X] } | BANNED: [R, W, X]
1. HARDWARE LEVEL: CPU PAGE TABLE ENTRY (PTE) BIT 63:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β x86_64 / ARM64 PAGE TABLE ENTRY (64-bit descriptor): β
β β
β [Bit 63: XD/NX] βββΊ [Bits 62..12: Physical Base Address] βββΊ [Bit 2: U/S] βββΊ [Bit 1: R/W] β
β β
β β’ Bit 63 = 0 (Executable): CPU Instruction Fetch unit allows reading opcodes from this page. β
β β’ Bit 63 = 1 (No-Execute): CPU MMU hardware blocks instruction fetches immediately! β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Attempting to execute shellcode on stack)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β HARDWARE FAULT TRAP LIFECYCLE: β
β 1. Attacker overflows stack buffer and overwrites Saved RIP to point to 0x7fffffffe000. β
β 2. Function returns: CPU loads 0x7fffffffe000 into RIP. β
β 3. CPU Instruction Fetch unit consults Translation Lookaside Buffer (TLB) for target page. β
β 4. MMU observes Bit 63 (NX) is set to 1 on the Stack Memory Page! β
β 5. CPU triggers Hardware Page Fault (#PF) with error code 0x11 (Instruction fetch violation). β
β 6. Linux Kernel traps fault, sends signal 11 (SIGSEGV), and immediately terminates process! β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
fs:[0x28]) between local variables and the Saved Return Address, validating integrity prior to returning.
COMPILER STACK CANARY INSERTION & VERIFICATION PIPELINE:
1. FUNCTION PROLOGUE (CANARY INSERTION ON ENTRY):
When compiling with GCC `-fstack-protector-all`:
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β sub rsp, 0x50 ; Allocate 80 bytes of stack space β
β mov rax, QWORD PTR fs:0x28 ; Load master random canary from Thread Control Block β
β mov QWORD PTR [rbp-0x8], rax ; Store canary directly above Saved RBP on the stack β
β xor eax, eax ; Clear rax from registers to prevent leakage β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
2. STACK FRAME ANATOMY WITH ACTIVE CANARY:
Low Memory
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ <-- RSP
β Local Buffer: char buffer[64] β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Compiler Alignment Padding (8 bytes) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β STACK CANARY (__stack_chk_guard) @ [rbp-0x8] (8 bytes) β <-- MUST REMAIN INTACT!
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Saved Frame Pointer (RBP) (8 bytes) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Saved Return Address (RIP) (8 bytes) β <-- Attacker target
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ <-- High Memory
3. FUNCTION EPILOGUE (CANARY VERIFICATION ON EXIT):
Before executing the `ret` instruction:
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β mov rax, QWORD PTR [rbp-0x8] ; Read canary value back from stack frame β
β sub rax, QWORD PTR fs:0x28 ; Compare against original master canary in TCB β
β je clean_exit ; If diff == 0: Canary intact! Safe to return! β
β call __stack_chk_fail ; MISMATCH! Tampering detected! Terminate immediately!β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
TYPES OF STACK CANARIES:
β’ Terminator Canary: Contains NULL (\x00), CR (\x0d), LF (\x0a), and EOF (-1).
Terminates string functions like strcpy() and gets() before the canary can be overwritten!
β’ Random Canary: 8 bytes of cryptographically secure random entropy generated at process startup.
Contains a NULL byte in the lowest byte (e.g., 0x00a7b41299f0e100) to defeat string functions.
/proc/sys/kernel/randomize_va_space, compares standard ASLR against Position Independent Executables (PIE), and writes a Python memory layout inspector.
import subprocess
import re
class AslrEntropyAuditor:
"""
Linux ASLR Kernel Configuration Levels (/proc/sys/kernel/randomize_va_space):
0 = DISABLED : All segments static (Stack, Heap, Libraries fixed).
1 = CONSERVATIVE : Randomizes Stack, VDSO page, and shared mmap libraries. Heap is static.
2 = FULL ASLR (Default): Randomizes Stack, Heap (brk), VDSO, and all mmap allocations.
"""
@staticmethod
def inspect_aslr_kernel_setting() -> str:
try:
with open("/proc/sys/kernel/randomize_va_space", "r") as f:
val = f.read().strip()
modes = {"0": "0 (Disabled)", "1": "1 (Conservative)", "2": "2 (Full ASLR)"}
return modes.get(val, f"Unknown ({val})")
except FileNotFoundError:
return "N/A (Non-Linux Environment)"
@staticmethod
def sample_memory_addresses(binary_path: str = "/bin/ls") -> dict:
"""Runs a binary under gdb/proc mapping to inspect base address changes."""
# Querying memory mapping of /bin/cat through /proc/self/maps
cmd = ["head", "-n", "5", "/proc/self/maps"]
out = subprocess.check_output(cmd, text=True)
# Extract first mapped memory page base
match = re.search(r"^([0-9a-f]+)-", out)
base_addr = match.group(1) if match else "0x0"
return {"first_mapped_base": f"0x{base_addr}"}
if __name__ == "__main__":
print("==========================================================================")
print(" LINUX ASLR & POSITION INDEPENDENT EXECUTION AUDIT")
print("==========================================================================")
current_mode = AslrEntropyAuditor.inspect_aslr_kernel_setting()
print(f"[*] Kernel ASLR Mode (/proc/sys/kernel/randomize_va_space): {current_mode}")
print("\n[*] Sampling Process Base Addresses across consecutive executions:")
for run in range(1, 4):
sample = AslrEntropyAuditor.sample_memory_addresses()
print(f" β’ Execution Run {run} Base Address : {sample['first_mapped_base']}")
print("\n--- POSITION INDEPENDENT EXECUTABLES (PIE) ARCHITECTURE ---")
print("β’ Non-PIE Binary (-no-pie): Code segment (.text) loaded at fixed base: 0x00400000.")
print(" Attackers can still find reliable ROP gadgets even if ASLR is enabled!")
print("β’ PIE Binary (-fPIE -pie): Code segment base is randomized alongside libraries.")
print(" Requires an Information Leak (pointer leak) to calculate the randomized base offset.")
DYNAMIC LINKING: PROCEDURE LINKAGE TABLE (PLT) & GLOBAL OFFSET TABLE (GOT):
How Dynamically Linked Binaries Resolve libc Functions (e.g., printf()):
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 1. Application calls printf@plt. β
β 2. printf@plt jumps to address stored in Global Offset Table: [printf@got.plt]. β
β 3. First execution (Lazy Binding): GOT points back to dynamic linker resolver (ld.so). β
β 4. Linker resolves true address of printf() in libc.so, writes it into printf@got.plt. β
β 5. Subsequent calls: printf@plt jumps directly to resolved libc address without linker delay. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
THE EXPLOITATION VECTOR: GOT OVERWRITE ATTACK:
If the GOT is writable, an attacker with an arbitrary memory write vulnerability
(e.g., Format String attack) overwrites printf@got.plt with the address of system().
The next time the application calls printf("/bin/sh"), it executes system("/bin/sh") instead!
RELRO (RELOCATION READ-ONLY) MITIGATION ARCHITECTURE:
1. NO RELRO (gcc -Wl,-z,norelro):
β’ Internal ELF data structures (.dtors, .got, .dynamic) are completely writable.
2. PARTIAL RELRO (gcc -Wl,-z,relro):
β’ Internal data sections (.init_array, .fini_array) are marked read-only after relocation.
β’ THE GOT REMAINS WRITABLE to permit lazy binding during runtime. Attackers can still overwrite GOT!
3. FULL RELRO (gcc -Wl,-z,relro,-z,now):
β’ Disables Lazy Binding completely via immediate binding (-z now).
β’ The dynamic linker resolves ALL external library symbols at program startup.
β’ The entire Global Offset Table (.got) is remapped as READ-ONLY (PROT_READ) before main() runs!
β’ Any attempt to overwrite a GOT entry raises an uncatchable SIGSEGV segmentation fault!
ret (Gadgets) and chain them together on the stack to prepare system calls.
RETURN-ORIENTED PROGRAMMING (ROP) UNDER DEP/NX:
Core Philosophy: "Execute without injecting new code by stitching together existing snippets!"
A "Gadget" is a short sequence of existing instructions ending with a 'ret' (opcode 0xc3):
Example Gadget 1 : pop rdi ; ret
Example Gadget 2 : pop rsi ; ret
Example Gadget 3 : pop rax ; ret
Example Gadget 4 : syscall
HOW GADGETS CONTROL CPU REGISTERS ON x86_64:
In 64-bit Linux (System V AMD64 ABI), function arguments are passed in registers:
Arg 1 = RDI | Arg 2 = RSI | Arg 3 = RDX | Syscall Number = RAX
CONSTRUCTING A ROP CHAIN TO CALL execve("/bin/sh", 0, 0):
Stack Memory Layout (Crafted by Overwriting Saved RIP):
βββββββββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β STACK ADDRESS / OFFSET β VALUE ON STACK & CPU BEHAVIOR β
βββββββββββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Top of Overwrite (Saved RIP) β [Address of Gadget 1: pop rdi ; ret] β
β Next Stack Slot (RSP + 8) β [Pointer to "/bin/sh\0" string] β
β β (pop rdi pops this pointer into RDI register!) β
βββββββββββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Next Stack Slot (RSP + 16) β [Address of Gadget 2: pop rsi ; ret] β
β Next Stack Slot (RSP + 24) β 0x0000000000000000 (NULL argv array) β
β β (pop rsi pops 0x0 into RSI register!) β
βββββββββββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Next Stack Slot (RSP + 32) β [Address of Gadget 3: pop rax ; ret] β
β Next Stack Slot (RSP + 40) β 59 (Decimal 59 = Syscall 59: sys_execve) β
β β (pop rax pops 59 into RAX register!) β
βββββββββββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Next Stack Slot (RSP + 48) β [Address of Gadget 4: syscall ; ret] β
β β (Executes kernel interrupt: execve("/bin/sh", 0, 0)!) β
βββββββββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
CONTROL FLOW INTEGRITY (CFI) ARCHITECTURAL TAXONOMY:
1. FORWARD-EDGE PROTECTION (INDIRECT CALLS & JUMPS):
β’ Threat: Attacker overwrites function pointers or C++ vtable pointers.
β’ Software Defense: Clang CFI / Windows Control Flow Guard (CFG).
β’ Mechanism: Compilers construct an allowable Call Graph at compile time.
Before any indirect call: call [rax], the compiler inserts a check:
__cfi_check(rax); // Validates target address is a legitimate, designated entry point!
If rax points to a gadget or unapproved function: Process aborts immediately.
2. BACKWARD-EDGE PROTECTION (RETURN ADDRESSES & ROP CHAINS):
β’ Threat: Attacker overwrites Saved Return Address on stack (ROP chains).
β’ Hardware Defense: Intel CET (Control-flow Enforcement Technology) / ARM Pointer Auth (PAC).
INTEL CET SHADOW STACK HARDWARE ARCHITECTURE:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β PRIMARY USER STACK (Writable by Program) SHADOW STACK (Hardware Protected / Read-Only) β
β β
β When 'call' instruction executes: When 'call' instruction executes: β
β Pushes Return Address to User Stack. CPU PUSHES COPIED RETURN ADDR TO SHADOW STACK! β
β (Readable and Writable) (Protected by CPU MMU; completely unwritable!) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Attacker executes buffer overflow)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β OVERFLOW OCCURS ON USER STACK: SHADOW STACK REMAINS UNTOUCHED: β
β User Stack Return Addr: 0x41414141 (Altered!) Shadow Stack Return Addr: 0x00401140 (Original!)β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (When 'ret' instruction executes)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β HARDWARE RETURN CHECK: β
β CPU pops both addresses simultaneously and compares them: β
β IF User_Stack_Return != Shadow_Stack_Return: β
β TRIGGER HARDWARE CONTROL PROTECTION EXCEPTION (#CP)! β
β ROP CHAIN EXECUTION TERMINATED BY CPU HARDWARE AT BYTE ZERO! β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
readelf.
import subprocess
import shutil
class BinaryMitigationAuditor:
def __init__(self, binary_path: str):
self.binary = binary_path
if not shutil.which("readelf"):
raise EnvironmentError("readelf utility is required to inspect ELF headers.")
def run_readelf(self, flag: str) -> str:
try:
return subprocess.check_output(["readelf", flag, self.binary], text=True, stderr=subprocess.DEVNULL)
except subprocess.CalledProcessError:
return ""
def audit_mitigations(self) -> dict:
results = {
"binary": self.binary,
"relro": "NO RELRO",
"canary": "NO CANARY",
"nx": "NX DISABLED",
"pie": "NO PIE"
}
# 1. Audit RELRO (Inspect GNU_RELRO segment and BIND_NOW dynamic flag)
segments = self.run_readelf("-l")
dynamic = self.run_readelf("-d")
if "GNU_RELRO" in segments:
if "BIND_NOW" in dynamic or "FLAGS_1.*NOW" in dynamic:
results["relro"] = "FULL RELRO"
else:
results["relro"] = "PARTIAL RELRO"
# 2. Audit Stack Canary (Check for symbol __stack_chk_fail)
symbols = self.run_readelf("-s")
if "__stack_chk_fail" in symbols:
results["canary"] = "CANARY FOUND"
# 3. Audit NX / DEP (Check GNU_STACK segment flags: RWE vs RW)
for line in segments.splitlines():
if "GNU_STACK" in line:
if "E" in line.split()[-1]: # Look for Execute flag
results["nx"] = "NX DISABLED (Executable Stack)"
else:
results["nx"] = "NX ENABLED"
# 4. Audit PIE (Inspect ELF Header Type: EXEC vs DYN)
header = self.run_readelf("-h")
for line in header.splitlines():
if "Type:" in line:
if "DYN (Shared object file)" in line:
results["pie"] = "PIE ENABLED"
elif "EXEC (Executable file)" in line:
results["pie"] = "NO PIE (Fixed Base)"
return results
if __name__ == "__main__":
# In live audit, pass target compiled executable
target = "/bin/ls"
auditor = BinaryMitigationAuditor(target)
report = auditor.audit_mitigations()
print("==========================================================================")
print(" BINARY EXPLOIT MITIGATION AUDIT (checksec clone)")
print("==========================================================================")
print(f"[*] Target Binary : {report['binary']}")
print(f"[*] RELRO Protection : {report['relro']}")
print(f"[*] Stack Canary : {report['canary']}")
print(f"[*] NX (DEP) Bit : {report['nx']}")
print(f"[*] PIE Execution : {report['pie']}")
score = sum(1 for v in report.values() if "FULL" in v or "FOUND" in v or "ENABLED" in v)
print(f"\n[β] Hardening Score : {score}/4 Mitigations Active")
-z execstack, using static binaries without PIE, and deploying proper GCC/Clang flags in CI/CD pipelines.
COMPILER BUILD SPECIFICATION COMPARISON:
// ==============================================================================
// PITFALL 1: INSECURE BUILD FLAGS (COMMONLY USED IN LEGACY MAKEFILES)
// CFLAGS = -m32 -fno-stack-protector -z execstack -no-pie
// CONSEQUENCE:
// 1. -fno-stack-protector removes all stack canaries (vulnerable to strcpy overflow).
// 2. -z execstack marks stack memory RWX (shellcode executes directly).
// 3. -no-pie pins code to fixed addresses (ROP gadgets never move).
// RESULT: Exploitable with high reliability via basic stack smashing!
// ==============================================================================
// ==============================================================================
// PRODUCTION HARDENED BUILD SPECIFICATION (GCC & CLANG):
// CFLAGS = -O2 \
// -Wall -Wextra -Werror \
// -fstack-protector-strong \
// -D_FORTIFY_SOURCE=2 \
// -fPIE \
// -fstack-clash-protection \
// -fcf-protection=full
// LDFLAGS = -Wl,-z,relro,-z,now -Wl,-z,noexecstack -pie
// ==============================================================================
DETAILED EXPLANATION OF PRODUCTION FLAGS:
β’ -fstack-protector-strong: Places canaries on functions with arrays, pointer references,
or local frame allocations, balancing security with low CPU overhead.
β’ -D_FORTIFY_SOURCE=2: Replaces dangerous functions (strcpy, sprintf) with bounds-checked
in-line wrappers (__strcpy_chk) that verify buffer sizes at compile and runtime.
β’ -fPIE -pie: Compiles the binary as a Position Independent Executable, allowing full ASLR.
β’ -Wl,-z,relro,-z,now: Enforces Full RELRO, remapping the Global Offset Table as read-only.
β’ -Wl,-z,noexecstack: Explicitly commands the linker to mark the stack segment non-executable.
β’ -fcf-protection=full: Emits Intel CET control-flow enforcement instructions (ENDBRANCH).
BINARY EXPLOIT MITIGATION SPECIFICATION MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β MITIGATION NAME β HARDWARE / COMPILER FLAG β TARGET DEFENDED β COMMON BYPASS TECHNIQUE β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β Non-Executable Stack β CPU Page Table Bit 63 (NX/XD)β Stack/Heap β Return-to-libc (ret2libc) & β
β (DEP / NX / W^X) β gcc -Wl,-z,noexecstack β Code Injection β Return-Oriented Prog (ROP) β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β Stack Canaries β gcc -fstack-protector-strong β Saved Return β Information Leak (reading β
β (StackGuard) β Master canary at fs:[0x28] β Address (RIP/EIP)β canary byte-by-byte via fork) β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β ASLR (Full Kernel) β /proc/sys/kernel/ β Base Memory β Information Leak (pointer leakβ
β β randomize_va_space = 2 β Address Guessing β to calculate randomized base) β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β Position Independent β gcc -fPIE -pie β Binary Code β Relative ROP gadgets inside β
β Executable (PIE) β β Segment (.text) β leaked module offsets β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β Full RELRO β gcc -Wl,-z,relro,-z,now β Global Offset β Target writable memory outsideβ
β (Relocation Read-Only) β β Table (GOT) β GOT (e.g. malloc hooks / TLS) β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β FORTIFY_SOURCE β gcc -D_FORTIFY_SOURCE=2 β Unsafe string β Vulnerabilities in unchecked β
β β (Bounds-checked wrappers) β functions β dynamic length computations β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β Control Flow Integrity β Clang -fsanitize=cfi β Indirect Jumps β Advanced ROP gadget execution β
β (CFI / Intel CET) β Intel CET Shadow Stack β & Return Addrs β within allowable call graphs β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ€
β TOP 5 BINARY HARDENING BEST PRACTICES: β
β 1. Always enforce Full RELRO: Combine -z relro and -z now to make the GOT read-only. β
β 2. Enable Stack Protection in CI: Compile with -fstack-protector-strong on all release builds. β
β 3. Never allow RWX segments: Enforce the W ^ X rule; ensure stacks and heaps are non-executable. β
β 4. Build with PIE enabled: Allow the operating system kernel to randomize code addresses via ASLR. β
β 5. Audit release binaries with checksec: Verify compiler flags are applied to all output binaries. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ