Buffer Overflow
What is a Buffer Overflow?
A buffer overflow occurs when a program writes data beyond the boundaries of a pre-allocated fixed-length buffer. This can corrupt adjacent memory, crash the program, or allow an attacker to inject and execute arbitrary code.
How Does it Work?
When a function copies data into a buffer without checking the size (e.g., using strcpy instead of strncpy in C), excess data overwrites adjacent memory. In stack-based overflows, this can overwrite the return address, redirecting execution to attacker-controlled code. In heap-based overflows, it corrupts heap metadata.
Stack-Based Buffer Overflow
// VULNERABLE: strcpy doesn't check destination bounds
void process_input(char *user_input) {
char buffer[128];
strcpy(buffer, user_input); // Overflows if input > 128 bytes
// Attacker overwrites return address on the stack
}
// SECURE: Use strncpy with explicit bounds
void process_input_safe(char *user_input) {
char buffer[128];
strncpy(buffer, user_input, sizeof(buffer) - 1);
buffer[sizeof(buffer) - 1] = '\0'; // Ensure null termination
}
Heap-Based Buffer Overflow
// VULNERABLE: No bounds check on heap allocation
char *buf = (char *)malloc(256);
// If attacker controls 'size', they can write beyond 256 bytes
memcpy(buf, source, attacker_controlled_size);
Real-World Examples
EternalBlue (CVE-2017-0144) exploited a buffer overflow in Windows SMBv1 to power WannaCry and NotPetya. Heartbleed (CVE-2014-0160) was a buffer over-read in OpenSSL. The Morris Worm (1988) — the first major internet worm — used a buffer overflow in fingerd.
Security Impact
Buffer overflows enable arbitrary code execution, denial of service, and privilege escalation. In firmware and embedded systems, they can cause physical harm — a buffer overflow in a medical device or automotive ECU firmware could have life-safety consequences.
Prevention & Mitigation
Use memory-safe languages (Rust, Go, Java) where possible. Enable compiler protections (stack canaries, ASLR, DEP/NX). Use safe string functions (strncpy, snprintf). Perform bounds checking on all buffer operations.
How Precogs AI Stops Buffer Overflow
Precogs AI Binary SAST detects buffer overflow patterns in compiled C/C++ binaries, firmware, and embedded systems — including stack-based, heap-based, and integer overflow-triggered buffer overflows — without requiring source code access.