Skip to content

gh-156939: Fix struct.pack('0p', bytes) - #157071

Open
vstinner wants to merge 1 commit into
python:mainfrom
vstinner:struct_empty_pascal
Open

gh-156939: Fix struct.pack('0p', bytes)#157071
vstinner wants to merge 1 commit into
python:mainfrom
vstinner:struct_empty_pascal

Conversation

@vstinner

@vstinner vstinner commented Sep 7, 2026

Copy link
Copy Markdown
Member

If the Pascal string is empty (size=0), do not write the size prefix. Previously, a NUL byte was written outsize the buffer (buffer overflow).

If the Pascal string is empty (size=0), do not write the size prefix.
Previously, a NUL byte was written outsize the buffer (buffer
overflow).
@vstinner vstinner added needs backport to 3.13 bugs and security fixes needs backport to 3.14 bugs and security fixes needs backport to 3.15 pre-release feature fixes, bugs and security fixes labels Sep 7, 2026
@vstinner vstinner changed the title gh-156943: Fix struct.pack('0p', bytes) gh-156939: Fix struct.pack('0p', bytes) Sep 7, 2026
@vstinner

vstinner commented Sep 7, 2026

Copy link
Copy Markdown
Member Author

In Python 3.14 and older, struct.pack('0p', b'abc') writes a NUL byte after the bytes contents. But bytes objects allocates an extra byte for a trailing NUL byte, so the buffer overflow doesn't write arbitrary memory. It's just a silent write which doesn't corrupt anything.

On Python 3.15, struct.pack() uses PyBytesWriter which doesn't allocate an extra trailing NUL byte for small strings (up to 256 bytes). And so a buffer overflow can write outsize PyBytesWriter.small_buffer. In practice, it should write a NUL byte in ``PyBytesWriter.objwhich is aNULL` pointer, so it should not corrupt arbitrary memory.

Well, it's better to avoid a buffer overflow anyway :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting core review needs backport to 3.13 bugs and security fixes needs backport to 3.14 bugs and security fixes needs backport to 3.15 pre-release feature fixes, bugs and security fixes skip news

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant