> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# What Is a Buffer Overflow Attack

> Explains buffer overflow attacks, how they overwrite memory to hijack execution, common exploitation techniques, and mitigations like canaries, NX, ASLR, safer APIs and compiler hardening

A buffer overflow attack occurs when a program writes more data into a fixed-size memory region (a buffer) than that region can hold. This extra data overwrites adjacent memory and can corrupt program state, crash the program, or allow an attacker to change execution flow.

Why this matters: on many systems buffers for local variables live on the stack next to control data such as the saved return address. Overwriting that return address lets an attacker redirect execution to code of their choosing (often injected into the overflowed buffer as "shellcode") or to existing code gadgets (return-oriented programming, ROP).

Example (C):

```c theme={null}
void f(char *input) {
    char name[16];
    strcpy(name, input); // unsafe: strcpy does not check bounds
}
```

`strcpy` copies bytes from `input` into `name` without bounds checking. If `input` is longer than 16 bytes, the copy continues past the end of `name`, overwriting adjacent stack memory. If the saved return address is overwritten, the function may return to an attacker-controlled address.

When data written past the buffer overwrites neighboring memory, we call that a buffer overflow.

![A stylized diagram of a program stack showing a buffer of machine instructions on the left and the return address region on the right being overwritten with repeated "A" bytes. The image illustrates a buffer overflow where the buffer's contents grow into and replace the return address.](https://mintcdn.com/kodekloud-c4ac6d9a/IK4ISE2GFis3psR1/images/DevOps-Interview-Questions-and-Answers-Scenario-Based-Prep/Security/What-Is-a-Buffer-Overflow-Attack/buffer-overflow-return-address-overwritten.jpg?fit=max\&auto=format\&n=IK4ISE2GFis3psR1\&q=85\&s=d829ddb5ef76d17341b3dcc061b3741c)

Exploitation overview

* Overwrite a saved return address to redirect execution.
* Inject shellcode into the overflowed buffer and point the return address at it (classic technique).
* Use ROP to chain together small existing code snippets when the stack is non-executable.
* If the new address is invalid, the program usually crashes — if valid and attacker-controlled, arbitrary code execution is possible.

Defenses and mitigations

1. Stack canaries (Stack Smashing Protector)
   * Compilers can insert a small, unpredictable value (a canary) between the buffer and the saved return address. Before returning from a function, the runtime checks whether the canary was modified. If it was, the program aborts instead of returning to a potentially attacker-supplied address.
   * Example compiler options: `-fstack-protector`, `-fstack-protector-strong`.
   * Canaries are effective at detecting contiguous buffer overruns that would corrupt the return address, but they are not a silver bullet (non-contiguous corruptions or info leaks can bypass them).

2. Non-executable stack (DEP / NX)
   * Operating systems can mark stack pages non-executable so injected shellcode on the stack cannot be executed.
   * Limitations: attackers can still use return-oriented programming (ROP) or other control-flow hijacking techniques to reuse existing executable code.

![A colorful diagram of a program stack layout showing a buffer of machine instruction bytes on the left, a highlighted stack canary in the middle, and a series of overwritten return address bytes (many "A"s) on the right. The diagram is labeled with sections like "STACK", "BUFFER", "STACK CANARY", "RETURN ADDRESS", and "NON-EXECUTABLE."](https://mintcdn.com/kodekloud-c4ac6d9a/IK4ISE2GFis3psR1/images/DevOps-Interview-Questions-and-Answers-Scenario-Based-Prep/Security/What-Is-a-Buffer-Overflow-Attack/stack-canary-buffer-overflow-diagram.jpg?fit=max\&auto=format\&n=IK4ISE2GFis3psR1\&q=85\&s=0678e9c366bb137f58566879ad5a9a12)

Additional mitigations (summary table)

| Mitigation | Purpose | Notes / Examples |
| - | - | - |
| Address Space Layout Randomization (ASLR) | Randomize memory layout to make it harder to predict addresses to jump to | Increases difficulty of reliably jumping to injected shellcode or known library addresses |
| Control-Flow Integrity (CFI) / compiler & hardware protections | Restrict valid control-flow transfers to legitimate targets | Makes it harder for attackers to hijack execution without detection |
| Safer APIs and language/runtime choices | Eliminate whole classes of bounds errors | Prefer bounds-checked APIs and modern languages that perform automatic bounds checking. Use `strlcpy` or `strncpy_s` where available; avoid `strcpy`. Note: `strncpy` alone does not guarantee NUL-termination if source is longer than destination. |

Practical recommendations

* Avoid unsafe string and memory functions like `strcpy`, `strcat`, `gets`, and unbounded `memcpy` with untrusted sizes.
* Use platform-provided secure APIs (`strlcpy`, `strncpy_s`) or safe libraries that centralize bounds checks.
* Compile with available hardening flags (`-fstack-protector`, `-D_FORTIFY_SOURCE=2`) and enable OS mitigations (ASLR, NX).
* Consider safer languages (Rust, Go, managed runtimes) for new development where appropriate.
* Combine mitigations: multiple layers (compiler, OS, safe code) significantly reduce risk.

Links and references

* OWASP — Buffer Overflow: [https://owasp.org](https://owasp.org)
* Return-Oriented Programming (ROP): [https://en.wikipedia.org/wiki/Return-oriented\_programming](https://en.wikipedia.org/wiki/Return-oriented_programming)
* Address Space Layout Randomization (ASLR): [https://en.wikipedia.org/wiki/Address\_space\_layout\_randomization](https://en.wikipedia.org/wiki/Address_space_layout_randomization)

Defensive best practice: Write bounds-checked code, compile with stack protections and hardening flags, and enable OS mitigations like NX/DEP and ASLR. Layered defenses (safe APIs + compiler and OS protections) provide the best protection against buffer overflow exploits.

> [card] [Watch Video](https://learn.kodekloud.com/user/courses/devops-interview-prep/module/6ea54e9c-4935-4be4-8955-674e08d91cc7/lesson/7ada5405-437b-453b-9302-d996b942d017)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.