Skip to content

Serialize access to Blake2State in the generichash bindings - #979

Open
iefa-m wants to merge 1 commit into
pyca:mainfrom
iefa-m:blake2-state-lock
Open

iefa-m wants to merge 1 commit into
pyca:mainfrom
iefa-m:blake2-state-lock

Conversation

@iefa-m

@iefa-m iefa-m commented Nov 6, 2026

Copy link
Copy Markdown

generichash_blake2b_update, generichash_blake2b_final and Blake2State.copy pass the shared state buffer to libsodium without any locking, and cffi releases the GIL for the call. When several threads call update() on one nacl.hashlib.blake2b object they race on S->buflen inside blake2b_update, and once it goes past 256 the next memcpy(S->buf + left, in, inlen) writes beyond the end of the state buffer. Eight threads each feeding 100 KB chunks into one shared object segfault CPython 3.13 on every run, while stdlib hashlib.blake2b returns the correct digest for the same workload because it locks each hash object. Free-threaded 3.14t is affected the same way.

The fix adds a per-state threading.Lock to Blake2State and holds it around the update, final and copy calls, so nacl.hashlib.blake2b and direct users of the bindings are both covered. The new test hashes from 8 threads and compares the result with hashlib. It crashes on main and passes with the fix on 3.13 and 3.14t.

libsodium is called with the GIL released, so concurrent update() calls
on a shared blake2b state race on its buffer length inside
blake2b_update and can write past the end of the state buffer. Hold a
per-state lock around update, final and copy, as hashlib does.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant