# smartlist_add, smartlist_insert (may) cause heap corruption as a result of inadequate checks in smartlist_ensure_capacity

Signed 32-bit overflow in Tor's smartlist_ensure_capacity lets num_used wrap negative, causing out-of-bounds heap write in smartlist_add/insert.

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

**Target:** smartlist_t dynamic array in Tor core library
**Root cause:** smartlist_ensure_capacity takes an int size; when num_used is INT_MAX, num_used+1 overflows to negative, the `size > sl->capacity` check is false, and no reallocation occurs before indexing with a negative value.
**Steps:**
1. Fill a smartlist via smartlist_add until sl->num_used == 0x7FFFFFFF (INT_MAX).
2. Call smartlist_add(sl, element) again: sl->num_used+1 overflows to -2147483648.
3. smartlist_ensure_capacity(sl, -2147483648) sees size > capacity false, skips realloc.
4. sl->list[sl->num_used++] writes at negative index, corrupting heap / segfaulting.
**How found:** Code review of smartlist_ensure_capacity: noticed size is int and MAX_CAPACITY is INT_MAX, so num_used+1 at INT_MAX wraps negative and bypasses the size > capacity guard.
**Exploitation:** Requires a code path invoking smartlist_add/insert on the same list at attacker behest and ~16GB (8GB with smaller element) of allocatable memory; then the negative index yields an out-of-bounds heap write.
**Insight:** When a capacity check takes a signed int computed as count+1, test the INT_MAX boundary: the increment wraps negative and the guard silently passes, so audit every `ensure_capacity(x+1)` pattern for signed overflow.

