# potential memory corruption in or/buffers.c (particularly on 32 bit)

preferred_chunk_size in Tor's or/buffers.c shifts size_t until it wraps to 0 on 32-bit, causing tor_realloc(0) then heap writes in chunk_grow.

- Payout: hidden
- Severity: low
- Program: Tor
- Found by: guido
- Disclosed: 2017-10-19
- Write-up quality: 6/10
- Original: https://hackerone.com/reports/163459
- Library page: https://bugbountylibrary.com/r/h1%3A163459
- Tags: area:oss domain:oss impact:dos kind:bounty platform:hackerone sev:low tech:linux technique:source-review vuln:dos vuln:memory-corruption

**Target:** or/buffers.c buffer chunk allocation (32-bit builds)
**Root cause:** preferred_chunk_size doubles sz in a loop until CHUNK_SIZE_WITH_ALLOC(sz) >= target; for large target on 32-bit, sz <<= 1 wraps to 0, so the function returns 0 and callers pass it to tor_malloc/tor_realloc.
**Steps:**
1. Compile the provided repro with `-m32` defining DEBUG_CHUNK_ALLOC and FLEXIBLE_ARRAY_MEMBER.
2. Observe preferred_chunk_size(0x80000000) returns 0x00000000 due to sz <<= 1 overflow.
3. Build a buf via buf_new(), write 507904 chunks of 0x1000 bytes, then `write_to_buf(string, 0x3FFFFFA, buf)`.
4. Call `buf_pullup(buf, 0x90000000)` so buf_pullup computes `newsize = CHUNK_SIZE_WITH_ALLOC(preferred_chunk_size(capacity))` and calls chunk_grow.
5. chunk_grow calls `tor_realloc(chunk, CHUNK_ALLOC_SIZE(sz))` with sz=0, then writes `chunk->memlen = sz; chunk->data = chunk->mem + offset;` into the zero-sized allocation.
**How found:** Code reading of preferred_chunk_size's shift loop; noticed sz <<= 1 can wrap to 0 for large size_t targets, then traced all callers (buf_pullup, buf_new_with_capacity, buf_add_chunk_with_capacity) to see the return value feeds tor_malloc/tor_realloc, and wrote a -m32 harness to confirm the wrap.
**Insight:** Audit size-computation helpers that loop with `sz <<= 1` for wraparound to 0; a zero return silently becomes a zero-byte allocation whose subsequent header writes corrupt the heap. Trace every caller of such helpers, not just the obvious one.

