# chain.__setstate__ Type Confusion

itertools.chain.__setstate__ accepted non-iterator objects, so chain_next passed them to PyIter_Next causing a NULL-pointer type confusion and DEP access violation in CPython 3.5.2.

- Payout: $1,000
- Severity: medium
- Program: Internet Bug Bounty
- Credited: johnleitch
- Disclosed: 2016-12-05
- Write-up quality: 7/10
- Original: https://hackerone.com/reports/175091
- Library page: https://bugbountylibrary.com/r/h1%3A175091
- Tags: domain:oss impact:dos kind:bounty platform:hackerone sev:medium tech:python technique:source-review vuln:deserialization vuln:memory-corruption

**Target:** itertools.chain.__setstate__ in CPython C module
**Root cause:** chain_setstate() parsed the state tuple with PyArg_ParseTuple but never validated that source/active were iterator objects before storing them; chain_next later calls PyIter_Next on the unvalidated object, dereferencing a bogus tp_iternext pointer.
**Steps:**
1. Build CPython 3.5.2 (itertoolsmodule.c chain_setstate).
2. Create a chain object and call its __setstate__ with a non-iterator object as source, e.g. `it.__setstate__((object(),))`.
3. Call next() on the chain so chain_next invokes PyIter_Next on the non-iterator.
4. Observe access violation c0000005 at eip=00000000 with stack PyIter_Next -> chain_next -> wrap_next.
**How found:** Code review of chain_setstate() noting missing PyIter_Check compared to other itertools setstate functions, then crafting a non-iterator argument to trigger the crash under a debugger.
**Exploitation:** Attacker-controlled Python code (e.g. sandboxed/untrusted input) supplies a crafted object to chain.__setstate__, causing PyIter_Next to call through an invalid tp_iternext pointer; report notes possible code execution but only a crash is demonstrated.
**Insight:** When auditing C-extension setstate/deserialization paths, compare argument validation against sibling types; missing PyIter_Check/PyObject_TypeCheck before storing into struct fields that later get called through function pointers yields type confusion.
