int greet() { char buf[48]; // [rsp+0h] [rbp-30h] BYREF printf("Input your name:"); read(0, buf, 0x100uLL); return printf("Hello, %s!\n", buf); }
Buffer Overflow Vulnerability in greet()
Function
The provided C code contains a critical stack-based buffer overflow vulnerability due to unsafe use of the read()
function. Here's a breakdown:
Vulnerability Details:
-
Buffer Declaration:
char buf[48];
allocates a 48-byte buffer on the stack.
Stack layout (x86-64):buf
starts at[rbp - 0x30]
(48 bytes below base pointer).- Saved
rbp
is at[rbp + 0x0]
(8 bytes). - Return address is at
[rbp + 0x8]
(8 bytes afterrbp
).
-
Unsafe
read()
Call:read(0, buf, 0x100uLL); // Reads 256 bytes from stdin
This allows writing 256 bytes into a 48-byte buffer, overflowing adjacent stack data.
-
Overflow Offset Calculation:
- Bytes to overflow
buf
: 48 bytes - Bytes to overwrite saved
rbp
: 8 bytes - Total bytes to reach return address:
48 + 8 = 56 bytes
- Return address position: Bytes 57–64 of input control program flow.
- Bytes to overflow
Exploitation Steps (Attack Scenario):
-
Craft Malicious Input:
payload = ( b"A" * 56 + # Padding to reach return address p64(0x401212) + # Overwrite return address (e.g., target function) b"\x00" * (256 - 64) # Optional trailing padding )
-
Hijack Control Flow:
- Overwrite return address with:
- Shellcode address (if executable stack).
system()
address + arguments (Ret2Libc).- ROP gadgets (bypassing DEP/ASLR).
- Overwrite return address with:
-
Execute Arbitrary Code:
- Spawn shell, read files, or escalate privileges.
Mitigation Strategies:
-
Bounds Checking:
Replaceread(0, buf, 0x100uLL)
with:fgets(buf, sizeof(buf), stdin); // Limits input to buffer size
-
Compiler Protections:
Enable stack canaries (-fstack-protector
), DEP (-z noexecstack
), and ASLR. -
Safer Functions:
Usesnprintf()
instead ofprintf()
to prevent format string vulnerabilities.
Key Risks:
- Remote Code Execution (RCE): Full system compromise.
- Denial-of-Service (DoS): Crash via corrupted stack.
- ASLR Bypass: Possible with info leaks + ROP chains.
Critical Severity: Always validate input sizes when using low-level I/O functions.