🎓 BookMCQ
← Back to 15. Security

📝 Buffer overflow attack in operating system (37 MCQs)

Memory Boundary Violations in Program Execution

A buffer overflow occurs when a program writes more data into a memory buffer than the allocated space can hold. In operating system security, memory corruption may overwrite adjacent variables, control data, or return addresses. Depending on the affected process and available protections, the defect can cause crashes, data corruption, or execution of unauthorised code.

Why Unsafe Memory Operations Create Vulnerabilities

Languages and libraries that permit unchecked memory writes can allow input length to exceed buffer capacity. Incorrect bounds calculations, unsafe copying, and missing validation create the underlying weakness. The risk is especially serious in privileged services because corrupted control data may affect operations performed with elevated authority.

How an Overflow Corrupts Adjacent Memory

A program allocates a buffer of a specified size and receives input. If it fails to verify the input length, excess bytes may overwrite neighbouring memory. The processor does not automatically understand the intended buffer boundary in every programming environment, so compiler, runtime, and hardware protections are used to reduce exploitation.

Example of an Oversized Input String

Consider a program that allocates a 16-byte character buffer but copies a 24-byte input without checking its length. The additional eight bytes exceed the allocated region and may overwrite adjacent data. The actual consequence depends on memory layout and protections; it may cause a crash or corrupt program state.

Memory Safety Controls and Residual Risks

Bounds checking, safer library functions, memory-safe languages, stack canaries, address space layout randomisation, and non-executable memory reduce overflow risks. These controls differ in what they protect and are not individually complete solutions. Correct input validation and secure coding remain essential, especially in operating system components and privileged applications.

Misconceptions About Buffer Overflows

'Every buffer overflow gives an attacker code execution' is false because many cause only crashes or corruption. 'A stack canary prevents every memory error' is incorrect because it detects certain stack overwrites. 'Increasing buffer size eliminates the vulnerability' ignores unbounded input and incorrect length handling.

Exam Focus: Buffer Bounds and Memory Protections

Calculate the difference between an input length and allocated buffer capacity, then explain which memory may be corrupted. Compare stack canaries, ASLR, non-executable memory, and bounds checking. Questions may distinguish denial of service from code execution and ask why secure input handling is the primary preventive measure.

Key Terms of Buffer Overflow Security

  • Buffer - Fixed memory area holding data.
  • Overflow - Write beyond allocated capacity.
  • Stack canary - Value used to detect stack corruption.
  • ASLR - Randomises memory layout locations.
  • Bounds checking - Verifies access remains within limits.
11
Easy
15
Medium
11
Hard

📝 All Buffer overflow attack in operating system MCQs

Q1. What is a buffer overflow in the context of program memory?

A.A condition where a buffer is accessed beyond its allocated size ✅
B.A technique to encrypt data in a buffer
C.A method for optimizing buffer allocation
D.A process that frees memory automatically
💡 Difficulty: easy | ✅ Correct: A

📖 Explanation: A buffer overflow occurs when a program writes more data to a memory buffer than it can hold, overwriting adjacent memory. This can corrupt data, crash the program, or allow an attacker to inject malicious code. Options B, C, and D describe unrelated concepts such as encryption, optimization, and memory deallocation, which do not involve exceeding buffer limits.

Q2. Which security mechanism is designed to detect and abort a program before a stack buffer overflow can overwrite the return address?

A.Address Space Layout Randomization (ASLR)
B.Stack canary (canary value) ✅
C.Data Execution Prevention (DEP)
D.Control Flow Guard (CFG)
💡 Difficulty: easy | ✅ Correct: B

📖 Explanation: A stack canary is a known value placed between a buffer and the control data on the stack; before returning, the program checks if the canary was altered. If it changed, the program aborts, preventing a return‑address overwrite. ASLR randomizes memory locations, DEP marks pages non‑executable, and CFG validates indirect branches, none of which directly check a canary value.

Q3. In a typical 32‑bit system, how many bytes are overwritten if a function copies 260 bytes into a 256‑byte stack buffer and then returns?

A.0 bytes
B.4 bytes ✅
C.8 bytes
D.12 bytes
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: When 260 bytes are copied into a 256‑byte buffer, the excess is 4 bytes. Those extra bytes overwrite the memory immediately following the buffer, which on a 32‑bit stack usually holds the saved frame pointer and return address. Therefore, exactly 4 bytes are overwritten, potentially altering program flow. The other options assume larger overflows that do not match the given data size.

Q4. Which of the following best describes why stack‑based buffer overflows are particularly dangerous for privilege escalation?

A.They allow overwriting global variables
B.They enable modification of the saved return address ✅
C.They corrupt heap metadata structures
D.They cause denial‑of‑service by crashing the program
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: Overwriting the saved return address on the stack lets an attacker redirect execution to attacker‑controlled code, often after gaining elevated privileges. While global variables and heap metadata can be targets, the classic escalation path exploits the return address to execute payloads with higher rights. Denial‑of‑service is a side effect but not the primary escalation mechanism.

Q5. A developer writes a function that copies user input into a local array without bounds checking. Which mitigation technique should be applied at compile time to reduce exploitation risk?

A.Enable stack canaries ✅
B.Use dynamic linking
C.Turn off optimizations
D.Increase buffer size
💡 Difficulty: medium | ✅ Correct: A

📖 Explanation: Enabling stack canaries inserts a known guard value before the return address; the runtime checks it before function exit. If an overflow occurs, the canary changes and the program aborts, reducing the chance of successful exploitation. Dynamic linking, disabling optimizations, or merely enlarging the buffer do not provide the same protective check against overflow.

Q6. Consider the following C code fragment: \n\nc\nvoid foo(char *input) {\n char buf[128];\n strcpy(buf, input);\n}\n\nIf an attacker supplies a string of length 200, which part of the stack is most likely to be compromised first?

A.The saved frame pointer
B.The return address ✅
C.The next function's local variables
D.The global variable table
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: The strcpy call will copy 200 bytes into a 128‑byte buffer, overflowing by 72 bytes. The first overwritten region after the buffer is typically the saved frame pointer, followed by the saved return address. However, most exploit techniques target the return address directly because altering it can redirect execution. The next function's locals and global variables reside elsewhere, making the return address the primary target.

Q7. Which of the following statements about Address Space Layout Randomization (ASLR) is FALSE?

A.It randomizes the base addresses of executable regions
B.It makes buffer overflow exploits harder but not impossible
C.It guarantees that all buffer overflows are prevented ✅
D.It can be bypassed with information leaks
💡 Difficulty: medium | ✅ Correct: C

📖 Explanation: ASLR does not guarantee prevention of buffer overflows; it merely randomizes memory locations, increasing the difficulty of locating useful addresses for an exploit. The other statements are true: ASLR randomizes base addresses, makes exploitation harder, and can be defeated if an attacker can discover memory layout through leaks.

Q8. An embedded device runs code compiled without stack protection. An attacker discovers a buffer overflow that writes 12 bytes past a 64‑byte buffer. Which of the following payload strategies is most likely to succeed?

A.Return‑to‑libc attack using system(\/bin/sh\) ✅
B.Injecting a NOP sled followed by shellcode
C.Overwriting a function pointer in the heap
D.Modifying a global configuration flag
💡 Difficulty: hard | ✅ Correct: A

📖 Explanation: A return‑to‑libc attack reuses existing library code, such as system(), to execute a shell without needing executable stack space, which is often disabled on embedded devices. Injecting a NOP sled requires an executable stack, which may be prevented. Overwriting heap pointers or global flags is less direct and may not lead to code execution.

Q9. Why does the presence of a non‑executable stack (DEP) not fully mitigate stack buffer overflow attacks?

A.Because DEP only protects heap memory
B.Because attackers can still overwrite return addresses to jump to existing code ✅
C.Because DEP disables all memory writes
D.Because DEP encrypts stack contents
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: DEP (Data Execution Prevention) marks the stack as non‑executable, preventing injected shellcode from running there. However, attackers can redirect execution to already‑present code (e.g., return‑to‑libc) without needing to execute code on the stack. DEP does not affect heap protection, nor does it encrypt or block writes.

Q10. A program uses `gets()` to read user input into a 50‑byte array. Which modern C library function should replace `gets()` to avoid buffer overflow risks?

A.scanf() with %s specifier
B.fgets() with size limit ✅
C.gets_s() without size argument
D.strcpy() with manual length check
💡 Difficulty: easy | ✅ Correct: B

📖 Explanation: `fgets()` allows the programmer to specify the maximum number of characters to read, preventing overflow by respecting the buffer size. Using `scanf()` with `%s` still risks overflow, `gets_s()` requires a size argument to be safe, and `strcpy()` does not perform bounds checking.

Q11. In a 64‑bit system, how many bytes are typically needed to overwrite the saved return address after a buffer overflow on the stack?

A.8 bytes ✅
B.16 bytes
C.4 bytes
D.12 bytes
💡 Difficulty: medium | ✅ Correct: A

📖 Explanation: On a 64‑bit architecture, pointers and addresses are 8 bytes long, so the saved return address occupies 8 bytes. Overwriting it therefore requires writing at least 8 bytes beyond the buffer's end. The other options correspond to different pointer sizes or unrelated offsets.

Q12. Which of the following best explains why stack canaries must be unpredictable at runtime?

A.Predictable canaries can be guessed and overwritten by an attacker ✅
B.Unpredictable canaries improve program speed
C.Predictable canaries cause compiler errors
D.Unpredictable canaries reduce memory usage
💡 Difficulty: hard | ✅ Correct: A

📖 Explanation: If a canary value is predictable, an attacker can determine it and craft an overflow that preserves the canary, bypassing the protection. Randomizing the canary each execution makes it infeasible for the attacker to guess the correct value, ensuring the integrity check catches unauthorized overwrites.

Q13. A security analyst observes that a certain application crashes when processing a specially crafted file. Which debugging technique is most appropriate to identify a possible stack overflow?

A.Static code analysis of source files
B.Running the program under a memory sanitizer like Valgrind ✅
C.Checking network traffic logs
D.Reviewing user authentication logs
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: Memory sanitizers monitor heap and stack accesses at runtime, detecting overruns, use‑after‑free, and other memory errors that cause crashes. Static analysis may miss runtime-specific issues, while network logs and authentication logs are unrelated to memory corruption.

Q14. Why might an attacker prefer a stack‑based buffer overflow over a heap‑based one in certain exploit scenarios?

A.Stack buffers are larger than heap buffers
B.Stack memory is less protected by ASLR
C.Stack overflows are easier to trigger with user input ✅
D.Heap overflows cannot alter control flow
💡 Difficulty: easy | ✅ Correct: C

📖 Explanation: User‑controlled inputs, such as command‑line arguments or form fields, are often copied directly into stack buffers, making it straightforward to craft an overflow. While heap buffers can be larger, they often involve more complex allocation patterns. Stack memory may be randomized, but the primary reason is the simplicity of triggering overflows via direct input.

Q15. Which of the following is a common defensive technique that randomizes the location of the stack canary itself?

A.Stack canary rotation
B.Canary re‑randomization per function call ✅
C.Address Space Layout Randomization (ASLR)
D.Control Flow Integrity (CFI)
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: Re‑randomizing the canary value for each function call makes it harder for an attacker to predict or reuse a leaked canary across multiple overflows. This is distinct from simply rotating canary values or using ASLR, which randomizes memory regions, and CFI, which enforces legitimate control‑flow transfers.

Q16. A C program uses `strncpy(dest, src, sizeof(dest))`. Which subtle bug could still lead to a buffer overflow?

A.`strncpy` always null‑terminates the destination
B.If `src` is longer than `dest`, the destination may lack a terminating null
C.`sizeof(dest)` returns the size of the pointer, not the buffer ✅
D.`strncpy` does not copy any bytes if source is empty
💡 Difficulty: medium | ✅ Correct: C

📖 Explanation: When `dest` is a pointer, `sizeof(dest)` yields the size of the pointer (typically 4 or 8 bytes) rather than the actual buffer length, causing `strncpy` to copy too few or too many bytes, potentially leading to overflow. The other statements are either true or unrelated.

Q17. In a return‑to‑libc attack, which library function is most commonly used to spawn a shell?

A.printf()
B.system() ✅
C.malloc()
D.strlen()
💡 Difficulty: easy | ✅ Correct: B

📖 Explanation: `system()` executes a command string via the host's command interpreter, and calling `system(/bin/sh)` spawns a shell. This makes it a popular target for return‑to‑libc attacks. Functions like `printf`, `malloc`, and `strlen` do not directly invoke a shell.

Q18. Why does compiling a program with the `-fstack-protector-strong` flag improve security against buffer overflows?

A.It disables all stack allocations ✅
B.It inserts canaries and performs additional checks on vulnerable functions
C.It encrypts stack memory
D.It removes all recursive functions
💡 Difficulty: medium | ✅ Correct: A

📖 Explanation: The `-fstack-protector-strong` option adds stack canaries to functions that use buffers, protect against stack smashing, and performs checks before returning. It does not disable allocations, encrypt memory, or alter recursion; instead, it adds runtime checks that abort execution if a canary is corrupted.

Q19. A web server processes HTTP headers into a fixed‑size array of 256 bytes. An attacker sends a header of 300 bytes. Which security principle is being violated?

A.Least privilege
B.Defense in depth
C.Fail‑closed
D.Input validation ✅
💡 Difficulty: easy | ✅ Correct: D

📖 Explanation: Input validation requires that all external data be checked for size, type, and format before use. The server accepts a header longer than the buffer, causing overflow. This directly breaches the input‑validation principle. Least privilege, defense in depth, and fail‑closed relate to broader system design, not the immediate overflow.

Q20. Which of the following best describes the role of a shadow stack in modern operating systems?

A.A secondary stack used for storing return addresses securely ✅
B.A stack used only for storing temporary variables
C.A hardware feature that doubles stack size
D.A software library for managing heap allocations
💡 Difficulty: hard | ✅ Correct: A

📖 Explanation: A shadow stack maintains a protected copy of return addresses separate from the main stack, allowing the OS to verify integrity before a function returns. This mitigates attacks that overwrite return addresses. It is not used for temporary variables, does not double stack size, nor manage heap allocations.

Q21. An attacker exploits a stack buffer overflow to overwrite a function pointer stored in a global variable. Which type of vulnerability does this illustrate?

A.Code injection
B.Control‑flow hijacking ✅
C.Information disclosure
D.Resource exhaustion
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: Overwriting a function pointer changes the program's control flow, causing execution to jump to attacker‑chosen code. This is a classic control‑flow hijacking technique. Code injection typically refers to inserting new code, while information disclosure and resource exhaustion involve data leaks or denial‑of‑service, respectively.

Q22. Why might an operating system enforce non‑executable memory for the stack but still allow return‑to‑libc attacks?

A.Because return‑to‑libc uses existing executable code ✅
B.Because non‑executable stacks are only a suggestion
C.Because DEP also disables system libraries
D.Because return‑to‑libc modifies the stack pointer only
💡 Difficulty: hard | ✅ Correct: A

📖 Explanation: DEP prevents execution of code placed on the stack, but return‑to‑libc reuses code already present in linked libraries (e.g., `system`). Thus, the attack bypasses the non‑executable restriction by jumping to legitimate executable regions, illustrating why DEP alone is insufficient.

Q23. A C program declares `char buffer[10];` and then calls `memcpy(buffer, source, 20);`. Which of the following outcomes is most likely?

A.The program will automatically truncate the copy to 10 bytes
B.The copy will overflow and corrupt adjacent memory ✅
C.The compiler will generate an error and refuse to compile
D.The runtime will raise an exception and stop copying
💡 Difficulty: easy | ✅ Correct: B

📖 Explanation: `memcpy` copies the exact number of bytes specified, ignoring the destination size. Copying 20 bytes into a 10‑byte buffer overwrites adjacent stack memory, leading to corruption or crashes. The compiler typically does not detect this, and C has no built‑in runtime bounds checking.

Q24. Which mitigation technique relies on randomizing the location of the stack itself rather than the contents within it?

A.Stack canaries
B.Address Space Layout Randomization (ASLR) ✅
C.Control Flow Guard (CFG)
D.Executable Space Protection (ESP)
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: ASLR randomizes the base address of memory regions, including the stack, making it harder for an attacker to predict where buffers reside. Stack canaries protect the contents, CFG validates indirect branches, and ESP is not a standard term for this purpose.

Q25. A developer writes a function that uses `alloca()` to allocate a large buffer on the stack. Which security risk does this introduce?

A.Heap fragmentation
B.Stack overflow due to dynamic allocation size ✅
C.Race conditions between threads
D.Increased CPU usage
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: `alloca()` allocates memory on the stack at runtime; if the requested size is large, it can exceed the stack's limits, causing a stack overflow. This differs from heap fragmentation (alloca does not use the heap) and does not directly cause race conditions or CPU spikes.

Q26. Why is it advantageous for an attacker to locate a gadgets chain in a binary when performing Return‑Oriented Programming (ROP)?

A.Gadgets provide encrypted payloads
B.Gadgets allow execution without injecting new code ✅
C.Gadgets increase the size of the exploit payload
D.Gadgets enable direct memory writes
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: ROP reuses short instruction sequences (gadgets) already present in the binary to perform arbitrary computation, avoiding the need for executable memory. This bypasses DEP and other protections that rely on preventing new code injection. Gadgets do not encrypt payloads, nor necessarily increase size, nor directly write memory.

Q27. Which of the following best explains why stack buffer overflows are more prevalent in languages like C and C++ compared to Java?

A.Java does not allow functions
B.Java automatically checks array bounds ✅
C.Java uses a different CPU architecture
D.C and C++ lack garbage collection
💡 Difficulty: easy | ✅ Correct: B

📖 Explanation: Java performs automatic bounds checking on arrays and strings, throwing exceptions when an overflow would occur, thus preventing classic stack buffer overflows. C and C++ provide no such checks, allowing unchecked memory writes. The other statements are inaccurate.

Q28. A program compiled with `-fno-stack-protector` is vulnerable. Which compiler flag should be added to re‑enable stack canaries?

A.#NAME?
B.#NAME? ✅
C.#NAME?
D.#NAME?
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: `-fstack-protector-all` forces the compiler to insert stack canaries into every function, protecting against stack smashing. `-fno-omit-frame-pointer` affects debugging, `-O3` is an optimization level, and `-march=native` selects CPU features; none of these directly add canary protection.

Q29. In a buffer overflow that overwrites a function's saved frame pointer, what is the immediate effect on program execution?

A.The program will skip the function entirely
B.The return address may be altered, leading to control‑flow hijack ✅
C.The stack will be deallocated prematurely
D.The heap allocation will fail
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: Overwriting the saved frame pointer can corrupt the saved return address stored just above it, allowing an attacker to redirect execution when the function returns. Skipping the function, premature deallocation, or heap failures are not direct consequences of a frame‑pointer overwrite.

Q30. Which of the following best describes the principle of fail‑closed in the context of buffer overflow defenses?

A.Allowing the program to continue running after an overflow
B.Terminating the program or denying service when a violation is detected ✅
C.Logging the overflow but proceeding normally
D.Automatically fixing the overflow in memory
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: Fail‑closed means the system stops normal operation (e.g., aborts or denies service) when a security violation like a buffer overflow is detected, ensuring that compromised behavior does not continue. Continuing execution, merely logging, or auto‑repairing do not align with the fail‑closed philosophy.

Q31. A security researcher uses a fuzzing tool to generate random inputs for a network service. Which type of bug is the researcher most likely to uncover?

A.SQL injection
B.Stack buffer overflow ✅
C.Cross‑site scripting
D.Privilege escalation
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: Fuzzing supplies unexpected, often oversized, inputs to trigger memory‑corruption bugs such as stack buffer overflows. SQL injection and XSS target input handling in web contexts, while privilege escalation is a higher‑level outcome; fuzzing directly probes for low‑level memory faults.

Q32. Why does the inclusion of a canary value not protect against attacks that only read memory without writing?

A.Canaries only detect write‑based corruption ✅
B.Reading memory automatically updates the canary
C.Canaries are encrypted and unreadable
D.Canaries are only effective on 64‑bit systems
💡 Difficulty: easy | ✅ Correct: A

📖 Explanation: Stack canaries are designed to detect overwrites; they are unchanged by mere reads. Therefore, attacks that only read memory (information disclosure) bypass the canary check. Encryption, automatic updates, or architecture constraints are unrelated to this limitation.

Q33. An attacker wants to exploit a stack overflow but the target binary has no executable stack. Which technique can still achieve code execution?

A.Heap spraying
B.Return‑to‑libc ✅
C.Stack pivoting without code injection
D.Format string exploitation
💡 Difficulty: hard | ✅ Correct: B

📖 Explanation: Return‑to‑libc reuses existing library code (e.g., `system`) to execute a shell, bypassing the need for an executable stack. Heap spraying requires an executable heap, stack pivoting still needs code to execute, and format strings are a different class of vulnerability.

Q34. Which of the following is a direct consequence of overwriting the saved return address on the stack?

A.Corrupting global variables
B.Changing the program's execution flow ✅
C.Increasing CPU clock speed
D.Modifying file permissions
💡 Difficulty: easy | ✅ Correct: B

📖 Explanation: Altering the saved return address causes the program to jump to an attacker‑chosen location when the function returns, directly modifying execution flow. Global variables may be indirectly affected, but the primary effect is control‑flow hijacking. CPU speed and file permissions are unrelated.

Q35. A C function uses `scanf(%s, buffer);` where `buffer` is 32 bytes. Which safer alternative should be used to prevent overflow?

A.scanf(%s, buffer) with no changes
B.scanf(%31s, buffer)
C.gets(buffer)
D.fgets(buffer, sizeof(buffer), stdin) ✅
💡 Difficulty: medium | ✅ Correct: D

📖 Explanation: `fgets` reads up to `sizeof(buffer)-1` characters and always null‑terminates, preventing overflow. Using `scanf(%31s, buffer)` limits input but still leaves room for newline handling issues; `gets` is unsafe, and the original `scanf` without a width specifier is vulnerable.

Q36. Why is it important for developers to understand both stack and heap overflow mechanisms?

A.Because they are the same thing
B.Because mitigations for one automatically protect the other
C.Because different attacks target different memory regions and may require distinct defenses ✅
D.Because modern compilers only protect the heap
💡 Difficulty: medium | ✅ Correct: C

📖 Explanation: Stack and heap overflows affect different memory areas and have unique exploitation paths; defenses like canaries protect the stack, while heap hardening (e.g., safe unlinking) secures the heap. Understanding both allows developers to apply appropriate safeguards. The other statements are inaccurate.

Q37. In the context of a stack buffer overflow, what does the term off‑by‑one refer to?

A.Writing one byte beyond the buffer's end ✅
B.Reading one byte before the buffer's start
C.A buffer that is exactly one byte too small for its intended data
D.A compiler warning about one extra line of code
💡 Difficulty: easy | ✅ Correct: A

📖 Explanation: An off‑by‑one error occurs when a program writes a single byte past the allocated buffer boundary, potentially corrupting adjacent memory such as the saved return address. It is distinct from reading before the buffer, sizing errors, or compiler warnings.

🔗 Related Topics (MCQs)