Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions Lib/test/test_winreg.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import gc
import os, sys, errno
import itertools
import threading
import unittest
from platform import machine, win32_edition
Expand Down Expand Up @@ -318,6 +319,37 @@ def run(self):
DeleteKey(HKEY_CURRENT_USER, test_key_name+'\\changing_value')
DeleteKey(HKEY_CURRENT_USER, test_key_name)

def test_queryvalueex_race_condition(self):
# gh-142282: QueryValueEx could read garbage buffer under race
# condition when another thread changes the value size
done = False
ready = threading.Event()
values = [b'ham', b'spam']

class WriterThread(threading.Thread):
def run(self):
with CreateKey(HKEY_CURRENT_USER, test_key_name) as key:
values_iter = itertools.cycle(values)
while not done:
val = next(values_iter)
SetValueEx(key, 'test_value', 0, REG_BINARY, val)
ready.set()

thread = WriterThread()
thread.start()
try:
ready.wait()
with CreateKey(HKEY_CURRENT_USER, test_key_name) as key:
for _ in range(1000):
result, typ = QueryValueEx(key, 'test_value')
# The result must be one of the written values,
# not garbage data from uninitialized buffer
self.assertIn(result, values)
finally:
done = True
thread.join()
DeleteKey(HKEY_CURRENT_USER, test_key_name)

def test_long_key(self):
# Issue2810, in 2.6 and 3.1 when the key name was exactly 256
# characters, EnumKey raised "WindowsError: More data is
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix :func:`winreg.QueryValueEx` to not accidentally read garbage buffer under race condition.
2 changes: 1 addition & 1 deletion PC/winreg.c
Original file line number Diff line number Diff line change
Expand Up @@ -1651,7 +1651,7 @@ winreg_QueryValueEx_impl(PyObject *module, HKEY key, const wchar_t *name)
return PyErr_SetFromWindowsErrWithFunction(rc,
"RegQueryValueEx");
}
obData = Reg2Py(retBuf, bufSize, typ);
obData = Reg2Py(retBuf, retSize, typ);
PyMem_Free(retBuf);
if (obData == NULL)
return NULL;
Expand Down
Loading