diff -r fcf4d547bed8 Doc/using/cmdline.rst --- a/Doc/using/cmdline.rst Sat Jan 21 20:27:59 2012 +0100 +++ b/Doc/using/cmdline.rst Mon Jan 23 16:29:26 2012 -0500 @@ -522,6 +522,34 @@ .. versionadded:: 2.6 +.. envvar:: PYTHONHASHRANDOMIZATION + + If this is set to a non-empty string, the hash() values of str, unicode + and buffer objects are randomized. Although they remain constant within + an individual Python process, they are not predictable between repeated + invocations of Python. + + This is intended to provide protection against a denial-of-service + caused by carefully-chosen inputs that exploit the worst case performance + of a dict lookup, O(n^2) complexity. See: + + http://www.ocert.org/advisories/ocert-2011-003.html + + for details. + + Changing hash values affects the order in which keys are retrieved from + a dict. Although Python has never made guarantees about this ordering + (and it typically varies between 32-bit and 64-bit builds), enough + real-world code implicitly relies on this non-guaranteed behavior that + the randomization is disabled by default. + +.. envvar:: PYTHONHASHSEED + + If this is set, it is used as a fixed seed for generating the hash() of + the types covererd by PYTHONHASHRANDOMIZATION. It should be a number in + the range [0; 4294967295]. The value 0 overrides the other variable and + disables the hash randomization. + .. envvar:: PYTHONIOENCODING Overrides the encoding used for stdin/stdout/stderr, in the syntax diff -r fcf4d547bed8 Include/object.h --- a/Include/object.h Sat Jan 21 20:27:59 2012 +0100 +++ b/Include/object.h Mon Jan 23 16:29:26 2012 -0500 @@ -517,6 +517,13 @@ PyAPI_FUNC(long) _Py_HashDouble(double); PyAPI_FUNC(long) _Py_HashPointer(void*); +typedef struct { + long prefix; + long suffix; +} _Py_HashSecret_t; +PyAPI_DATA(_Py_HashSecret_t) _Py_HashSecret; + + /* Helper for passing objects to printf and the like */ #define PyObject_REPR(obj) PyString_AS_STRING(PyObject_Repr(obj)) diff -r fcf4d547bed8 Include/pythonrun.h --- a/Include/pythonrun.h Sat Jan 21 20:27:59 2012 +0100 +++ b/Include/pythonrun.h Mon Jan 23 16:29:26 2012 -0500 @@ -171,6 +171,8 @@ PyAPI_FUNC(PyOS_sighandler_t) PyOS_getsig(int); PyAPI_FUNC(PyOS_sighandler_t) PyOS_setsig(int, PyOS_sighandler_t); +/* Random */ +PyAPI_FUNC(int) _PyOS_URandom (void *buffer, Py_ssize_t size); #ifdef __cplusplus } diff -r fcf4d547bed8 Lib/lib-tk/test/test_ttk/test_functions.py --- a/Lib/lib-tk/test/test_ttk/test_functions.py Sat Jan 21 20:27:59 2012 +0100 +++ b/Lib/lib-tk/test/test_ttk/test_functions.py Mon Jan 23 16:29:26 2012 -0500 @@ -144,7 +144,7 @@ ('a', 'b', 'c')), ("test {a b} c", ())) # state spec and options self.assertEqual(ttk._format_elemcreate('image', False, 'test', - ('a', 'b'), a='x', b='y'), ("test a b", ("-a", "x", "-b", "y"))) + ('a', 'b'), a='x'), ("test a b", ("-a", "x"))) # format returned values as a tcl script # state spec with multiple states and an option with a multivalue self.assertEqual(ttk._format_elemcreate('image', True, 'test', diff -r fcf4d547bed8 Lib/os.py --- a/Lib/os.py Sat Jan 21 20:27:59 2012 +0100 +++ b/Lib/os.py Mon Jan 23 16:29:26 2012 -0500 @@ -738,22 +738,3 @@ _make_statvfs_result) except NameError: # statvfs_result may not exist pass - -if not _exists("urandom"): - def urandom(n): - """urandom(n) -> str - - Return a string of n random bytes suitable for cryptographic use. - - """ - try: - _urandomfd = open("/dev/urandom", O_RDONLY) - except (OSError, IOError): - raise NotImplementedError("/dev/urandom (or equivalent) not found") - try: - bs = b"" - while n > len(bs): - bs += read(_urandomfd, n - len(bs)) - finally: - close(_urandomfd) - return bs diff -r fcf4d547bed8 Lib/test/mapping_tests.py --- a/Lib/test/mapping_tests.py Sat Jan 21 20:27:59 2012 +0100 +++ b/Lib/test/mapping_tests.py Mon Jan 23 16:29:26 2012 -0500 @@ -15,7 +15,7 @@ def _reference(self): """Return a dictionary of values which are invariant by storage in the object under test.""" - return {1:2, "key1":"value1", "key2":(1,2,3)} + return {"1": "2", "key1":"value1", "key2":(1,2,3)} def _empty_mapping(self): """Return an empty mapping object""" return self.type2test() diff -r fcf4d547bed8 Lib/test/regrtest.py --- a/Lib/test/regrtest.py Sat Jan 21 20:27:59 2012 +0100 +++ b/Lib/test/regrtest.py Mon Jan 23 16:29:26 2012 -0500 @@ -438,6 +438,11 @@ except IndexError: next_single_test = None if randomize: + hashseed = os.getenv('PYTHONHASHSEED') + if not hashseed: + os.environ['PYTHONHASHSEED'] = str(random_seed) + os.execv(sys.executable, [sys.executable] + sys.argv) + return random.seed(random_seed) print "Using random seed", random_seed random.shuffle(selected) diff -r fcf4d547bed8 Lib/test/test_gdb.py --- a/Lib/test/test_gdb.py Sat Jan 21 20:27:59 2012 +0100 +++ b/Lib/test/test_gdb.py Mon Jan 23 16:29:26 2012 -0500 @@ -58,13 +58,15 @@ """Test that the debugger can debug Python.""" - def run_gdb(self, *args): + def run_gdb(self, *args, **env): """Runs gdb with the command line given by *args. Returns its stdout, stderr """ + if not env: + env = None out, err = subprocess.Popen( - args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, ).communicate() return out, err @@ -124,7 +126,7 @@ # print ' '.join(args) # Use "args" to invoke gdb, capturing stdout, stderr: - out, err = self.run_gdb(*args) + out, err = self.run_gdb(*args, PYTHONHASHSEED='0') # Ignore some noise on stderr due to the pending breakpoint: err = err.replace('Function "%s" not defined.\n' % breakpoint, '') @@ -181,11 +183,13 @@ gdb_output = self.get_stack_trace('print 42') self.assertTrue('PyObject_Print' in gdb_output) - def assertGdbRepr(self, val, cmds_after_breakpoint=None): + def assertGdbRepr(self, val, exp_repr=None, cmds_after_breakpoint=None): # Ensure that gdb's rendering of the value in a debugged process # matches repr(value) in this process: gdb_repr, gdb_output = self.get_gdb_repr('print ' + repr(val), cmds_after_breakpoint) + if not exp_repr: + exp_repr = repr(val) self.assertEqual(gdb_repr, repr(val), gdb_output) def test_int(self): @@ -213,7 +217,8 @@ 'Verify the pretty-printing of dictionaries' self.assertGdbRepr({}) self.assertGdbRepr({'foo': 'bar'}) - self.assertGdbRepr({'foo': 'bar', 'douglas':42}) + self.assertGdbRepr({'foo': 'bar', 'douglas': 42}, + "{'foo': 'bar', 'douglas': 42}") def test_lists(self): 'Verify the pretty-printing of lists' diff -r fcf4d547bed8 Lib/test/test_inspect.py --- a/Lib/test/test_inspect.py Sat Jan 21 20:27:59 2012 +0100 +++ b/Lib/test/test_inspect.py Mon Jan 23 16:29:26 2012 -0500 @@ -771,7 +771,6 @@ self.assertEqualException(f, '2, 3, 4') self.assertEqualException(f, '1, 2, 3, a=1') self.assertEqualException(f, '2, 3, 4, c=5') - self.assertEqualException(f, '2, 3, 4, a=1, c=5') # f got an unexpected keyword argument self.assertEqualException(f, 'c=2') self.assertEqualException(f, '2, c=3') diff -r fcf4d547bed8 Lib/test/test_os.py --- a/Lib/test/test_os.py Sat Jan 21 20:27:59 2012 +0100 +++ b/Lib/test/test_os.py Mon Jan 23 16:29:26 2012 -0500 @@ -11,6 +11,7 @@ import subprocess import time from test import test_support +from test.script_helper import assert_python_ok import mmap import uuid @@ -527,17 +528,41 @@ class URandomTests (unittest.TestCase): def test_urandom(self): - try: - self.assertEqual(len(os.urandom(1)), 1) - self.assertEqual(len(os.urandom(10)), 10) - self.assertEqual(len(os.urandom(100)), 100) - self.assertEqual(len(os.urandom(1000)), 1000) - # see http://bugs.python.org/issue3708 - self.assertRaises(TypeError, os.urandom, 0.9) - self.assertRaises(TypeError, os.urandom, 1.1) - self.assertRaises(TypeError, os.urandom, 2.0) - except NotImplementedError: - pass + self.assertEqual(len(os.urandom(1)), 1) + self.assertEqual(len(os.urandom(10)), 10) + self.assertEqual(len(os.urandom(100)), 100) + self.assertEqual(len(os.urandom(1000)), 1000) + # see http://bugs.python.org/issue3708 + self.assertRaises(TypeError, os.urandom, 0.9) + self.assertRaises(TypeError, os.urandom, 1.1) + self.assertRaises(TypeError, os.urandom, 2.0) + + def test_urandom_length(self): + self.assertEqual(len(os.urandom(1)), 1) + self.assertEqual(len(os.urandom(10)), 10) + self.assertEqual(len(os.urandom(100)), 100) + self.assertEqual(len(os.urandom(1000)), 1000) + + def test_urandom_value(self): + data1 = os.urandom(16) + data2 = os.urandom(16) + self.assertNotEqual(data1, data2) + + def get_urandom_subprocess(self, count): + code = '\n'.join(( + 'import os, sys', + 'data = os.urandom(%s)' % count, + 'sys.stdout.write(data)', + 'sys.stdout.flush()')) + out = assert_python_ok('-c', code) + stdout = out[1] + self.assertEqual(len(stdout), 16) + return stdout + + def test_urandom_subprocess(self): + data1 = self.get_urandom_subprocess(16) + data2 = self.get_urandom_subprocess(16) + self.assertNotEqual(data1, data2) def test_execvpe_with_bad_arglist(self): self.assertRaises(ValueError, os.execvpe, 'notepad', [], None) diff -r fcf4d547bed8 Lib/test/test_unicode.py --- a/Lib/test/test_unicode.py Sat Jan 21 20:27:59 2012 +0100 +++ b/Lib/test/test_unicode.py Mon Jan 23 16:29:26 2012 -0500 @@ -9,8 +9,11 @@ import struct import codecs import unittest +from test.script_helper import assert_python_ok from test import test_support, string_tests +IS_64BIT = (struct.calcsize('l') == 8) + # decorator to skip tests on narrow builds requires_wide_build = unittest.skipIf(sys.maxunicode == 65535, 'requires wide build') @@ -1631,6 +1634,58 @@ self.assertEqual(unicode_encodedecimal(u"123\u20ac\u0660", "replace"), b'123?0') +# Examples of the various types having randomized hash: +test_reprs = [repr('abc'), repr(u'abc'), "buffer('abc')"] + +class HashTest(unittest.TestCase): + def get_hash(self, _repr, randomization=None, seed=None): + env = {} + if randomization is not None: + env['PYTHONHASHRANDOMIZATION'] = str(randomization) + if seed is not None: + env['PYTHONHASHSEED'] = str(seed) + out = assert_python_ok( + '-c', 'print(hash(%s))' % _repr, + **env) + stdout = out[1].strip() + return int(stdout) + + def test_empty_string(self): + self.assertEqual(hash(""), 0) + self.assertEqual(hash(u""), 0) + self.assertEqual(hash(buffer("")), 0) + + def test_null_hash(self): + # PYTHONHASHSEED=0 disables the randomized hash + if IS_64BIT: + known_hash_of_obj = 1453079729188098211 + else: + known_hash_of_obj = -1600925533 + for t in test_reprs: + # Randomization is disabled by default: + self.assertEqual(self.get_hash(t), known_hash_of_obj) + + # If enabled, it can still be disabled by setting the seed to 0: + self.assertEqual(self.get_hash(t, randomization=1, seed=0), + known_hash_of_obj) + + def test_fixed_hash(self): + # test a fixed seed for the randomized hash + # Note that all types share the same values: + if IS_64BIT: + h = -4410911502303878509 + else: + h = -206076799 + for obj in test_reprs: + self.assertEqual(self.get_hash(obj, randomization=1, seed=42), + h) + + def test_randomized_hash(self): + # two runs should return different hashes + for obj in test_reprs: + run1 = self.get_hash(obj, randomization=1) + run2 = self.get_hash(obj, randomization=1) + self.assertNotEqual(run1, run2) def test_main(): test_support.run_unittest(__name__) diff -r fcf4d547bed8 Makefile.pre.in --- a/Makefile.pre.in Sat Jan 21 20:27:59 2012 +0100 +++ b/Makefile.pre.in Mon Jan 23 16:29:26 2012 -0500 @@ -290,6 +290,7 @@ Python/pymath.o \ Python/pystate.o \ Python/pythonrun.o \ + Python/random.o \ Python/structmember.o \ Python/symtable.o \ Python/sysmodule.o \ diff -r fcf4d547bed8 Misc/python.man --- a/Misc/python.man Sat Jan 21 20:27:59 2012 +0100 +++ b/Misc/python.man Mon Jan 23 16:29:26 2012 -0500 @@ -423,6 +423,28 @@ .IP PYTHONWARNINGS If this is set to a comma-separated string it is equivalent to specifying the \fB\-W\fP option for each separate value. +.IP PYTHONHASHRANDOMIZATION +If this is set to a non-empty string, the hash() values of str, unicode and +buffer objects are randomized. Although they remain constant within an +individual Python process, they are not predictable between repeated +invocations of Python. +.IP +This is intended to provide protection against a denial of service +caused by carefully-chosen inputs that exploit the worst case performance +of a dict lookup, O(n^2) complexity. See +http://www.ocert.org/advisories/ocert-2011-003.html +for details. +.IP +Changing hash values affects the order in which keys are retrieved from +a dict. Although Python has never made guarantees about this ordering +(and it typically varies between 32-bit and 64-bit builds), enough +real-world code implicitly relies on this non-guaranteed behavior that +the randomization is disabled by default. +.IP PYTHONHASHSEED +If this is set, it is used as a fixed seed for generating the hash() of +the types covererd by PYTHONHASHRANDOMIZATION. It should be a number in +the range [0; 4294967295]. The value 0 overrides the other variable and +disables the hash randomization. .SH AUTHOR The Python Software Foundation: http://www.python.org/psf .SH INTERNET RESOURCES diff -r fcf4d547bed8 Modules/posixmodule.c --- a/Modules/posixmodule.c Sat Jan 21 20:27:59 2012 +0100 +++ b/Modules/posixmodule.c Mon Jan 23 16:29:26 2012 -0500 @@ -8538,117 +8538,36 @@ } #endif -#ifdef MS_WINDOWS - -PyDoc_STRVAR(win32_urandom__doc__, +PyDoc_STRVAR(posix_urandom__doc__, "urandom(n) -> str\n\n\ -Return a string of n random bytes suitable for cryptographic use."); - -typedef BOOL (WINAPI *CRYPTACQUIRECONTEXTA)(HCRYPTPROV *phProv,\ - LPCSTR pszContainer, LPCSTR pszProvider, DWORD dwProvType,\ - DWORD dwFlags ); -typedef BOOL (WINAPI *CRYPTGENRANDOM)(HCRYPTPROV hProv, DWORD dwLen,\ - BYTE *pbBuffer ); - -static CRYPTGENRANDOM pCryptGenRandom = NULL; -/* This handle is never explicitly released. Instead, the operating - system will release it when the process terminates. */ -static HCRYPTPROV hCryptProv = 0; +Return n pseudo-random bytes."); static PyObject* -win32_urandom(PyObject *self, PyObject *args) -{ - int howMany; - PyObject* result; +posix_urandom(PyObject *self, PyObject *args) +{ + Py_ssize_t size; + PyObject *result; + int ret; /* Read arguments */ - if (! PyArg_ParseTuple(args, "i:urandom", &howMany)) - return NULL; - if (howMany < 0) + if (!PyArg_ParseTuple(args, "n:urandom", &size)) + return NULL; + if (size < 0) return PyErr_Format(PyExc_ValueError, "negative argument not allowed"); - if (hCryptProv == 0) { - HINSTANCE hAdvAPI32 = NULL; - CRYPTACQUIRECONTEXTA pCryptAcquireContext = NULL; - - /* Obtain handle to the DLL containing CryptoAPI - This should not fail */ - hAdvAPI32 = GetModuleHandle("advapi32.dll"); - if(hAdvAPI32 == NULL) - return win32_error("GetModuleHandle", NULL); - - /* Obtain pointers to the CryptoAPI functions - This will fail on some early versions of Win95 */ - pCryptAcquireContext = (CRYPTACQUIRECONTEXTA)GetProcAddress( - hAdvAPI32, - "CryptAcquireContextA"); - if (pCryptAcquireContext == NULL) - return PyErr_Format(PyExc_NotImplementedError, - "CryptAcquireContextA not found"); - - pCryptGenRandom = (CRYPTGENRANDOM)GetProcAddress( - hAdvAPI32, "CryptGenRandom"); - if (pCryptGenRandom == NULL) - return PyErr_Format(PyExc_NotImplementedError, - "CryptGenRandom not found"); - - /* Acquire context */ - if (! pCryptAcquireContext(&hCryptProv, NULL, NULL, - PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) - return win32_error("CryptAcquireContext", NULL); - } - - /* Allocate bytes */ - result = PyString_FromStringAndSize(NULL, howMany); - if (result != NULL) { - /* Get random data */ - memset(PyString_AS_STRING(result), 0, howMany); /* zero seed */ - if (! pCryptGenRandom(hCryptProv, howMany, (unsigned char*) - PyString_AS_STRING(result))) { - Py_DECREF(result); - return win32_error("CryptGenRandom", NULL); - } + result = PyBytes_FromStringAndSize(NULL, size); + if (result == NULL) + return NULL; + + ret = _PyOS_URandom(PyBytes_AS_STRING(result), + PyBytes_GET_SIZE(result)); + if (ret == -1) { + Py_DECREF(result); + return NULL; } return result; } -#endif - -#ifdef __VMS -/* Use openssl random routine */ -#include -PyDoc_STRVAR(vms_urandom__doc__, -"urandom(n) -> str\n\n\ -Return a string of n random bytes suitable for cryptographic use."); - -static PyObject* -vms_urandom(PyObject *self, PyObject *args) -{ - int howMany; - PyObject* result; - - /* Read arguments */ - if (! PyArg_ParseTuple(args, "i:urandom", &howMany)) - return NULL; - if (howMany < 0) - return PyErr_Format(PyExc_ValueError, - "negative argument not allowed"); - - /* Allocate bytes */ - result = PyString_FromStringAndSize(NULL, howMany); - if (result != NULL) { - /* Get random data */ - if (RAND_pseudo_bytes((unsigned char*) - PyString_AS_STRING(result), - howMany) < 0) { - Py_DECREF(result); - return PyErr_Format(PyExc_ValueError, - "RAND_pseudo_bytes"); - } - } - return result; -} -#endif #ifdef HAVE_SETRESUID PyDoc_STRVAR(posix_setresuid__doc__, @@ -9035,12 +8954,7 @@ #ifdef HAVE_GETLOADAVG {"getloadavg", posix_getloadavg, METH_NOARGS, posix_getloadavg__doc__}, #endif - #ifdef MS_WINDOWS - {"urandom", win32_urandom, METH_VARARGS, win32_urandom__doc__}, - #endif - #ifdef __VMS - {"urandom", vms_urandom, METH_VARARGS, vms_urandom__doc__}, - #endif + {"urandom", posix_urandom, METH_VARARGS, posix_urandom__doc__}, #ifdef HAVE_SETRESUID {"setresuid", posix_setresuid, METH_VARARGS, posix_setresuid__doc__}, #endif diff -r fcf4d547bed8 Objects/bufferobject.c --- a/Objects/bufferobject.c Sat Jan 21 20:27:59 2012 +0100 +++ b/Objects/bufferobject.c Mon Jan 23 16:29:26 2012 -0500 @@ -334,10 +334,16 @@ return -1; p = (unsigned char *) ptr; len = size; - x = *p << 7; + if (len == 0) { + self->b_hash = 0; + return 0; + } + x = _Py_HashSecret.prefix; + x ^= *p << 7; while (--len >= 0) x = (1000003*x) ^ *p++; x ^= size; + x ^= _Py_HashSecret.suffix; if (x == -1) x = -2; self->b_hash = x; diff -r fcf4d547bed8 Objects/object.c --- a/Objects/object.c Sat Jan 21 20:27:59 2012 +0100 +++ b/Objects/object.c Mon Jan 23 16:29:26 2012 -0500 @@ -1094,6 +1094,8 @@ return -1; } +_Py_HashSecret_t _Py_HashSecret; + long PyObject_Hash(PyObject *v) { diff -r fcf4d547bed8 Objects/stringobject.c --- a/Objects/stringobject.c Sat Jan 21 20:27:59 2012 +0100 +++ b/Objects/stringobject.c Mon Jan 23 16:29:26 2012 -0500 @@ -1265,11 +1265,17 @@ if (a->ob_shash != -1) return a->ob_shash; len = Py_SIZE(a); + if (len == 0) { + a->ob_shash = 0; + return 0; + } + x = _Py_HashSecret.prefix; p = (unsigned char *) a->ob_sval; - x = *p << 7; + x ^= *p << 7; while (--len >= 0) x = (1000003*x) ^ *p++; x ^= Py_SIZE(a); + x ^= _Py_HashSecret.suffix; if (x == -1) x = -2; a->ob_shash = x; diff -r fcf4d547bed8 Objects/unicodeobject.c --- a/Objects/unicodeobject.c Sat Jan 21 20:27:59 2012 +0100 +++ b/Objects/unicodeobject.c Mon Jan 23 16:29:26 2012 -0500 @@ -6541,11 +6541,26 @@ if (self->hash != -1) return self->hash; len = PyUnicode_GET_SIZE(self); + if (len == 0) { + self->hash = 0; + return 0; + } + + /* Issue #13703: add 2 x sizeof(Py_hash_t) random bytes (prefix and suffix) + to the output of hash(unicode) to protect Python against the hash collision + attack on dictionary. Without these random bytes, an attacker can + computes N strings with the same hash value to exploit to worst case of + a dict lookup, O(n^2) complexity, to cause a denial of service. See + oCERT advisory for the details: + http://www.ocert.org/advisories/ocert-2011-003.html */ + x = _Py_HashSecret.prefix; + p = PyUnicode_AS_UNICODE(self); - x = *p << 7; + x ^= *p << 7; while (--len >= 0) x = (1000003*x) ^ *p++; x ^= PyUnicode_GET_SIZE(self); + x ^= _Py_HashSecret.suffix; if (x == -1) x = -2; self->hash = x; diff -r fcf4d547bed8 PCbuild/pythoncore.vcproj --- a/PCbuild/pythoncore.vcproj Sat Jan 21 20:27:59 2012 +0100 +++ b/PCbuild/pythoncore.vcproj Mon Jan 23 16:29:26 2012 -0500 @@ -1834,6 +1834,10 @@ RelativePath="..\Python\pythonrun.c" > + + diff -r fcf4d547bed8 Python/pythonrun.c --- a/Python/pythonrun.c Sat Jan 21 20:27:59 2012 +0100 +++ b/Python/pythonrun.c Mon Jan 23 16:29:26 2012 -0500 @@ -167,6 +167,8 @@ if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0') Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p); + _PyRandom_Init(); + interp = PyInterpreterState_New(); if (interp == NULL) Py_FatalError("Py_Initialize: can't make first interpreter"); diff -r fcf4d547bed8 Python/random.c --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Python/random.c Mon Jan 23 16:29:26 2012 -0500 @@ -0,0 +1,284 @@ +#include "Python.h" +#ifdef MS_WINDOWS +#include +#else +#include +#endif + +static int random_initialized = 0; + +#ifdef MS_WINDOWS +typedef BOOL (WINAPI *CRYPTACQUIRECONTEXTA)(HCRYPTPROV *phProv,\ + LPCSTR pszContainer, LPCSTR pszProvider, DWORD dwProvType,\ + DWORD dwFlags ); +typedef BOOL (WINAPI *CRYPTGENRANDOM)(HCRYPTPROV hProv, DWORD dwLen,\ + BYTE *pbBuffer ); + +static CRYPTGENRANDOM pCryptGenRandom = NULL; +/* This handle is never explicitly released. Instead, the operating + system will release it when the process terminates. */ +static HCRYPTPROV hCryptProv = 0; + +static int +win32_urandom_init(int raise) +{ + HINSTANCE hAdvAPI32 = NULL; + CRYPTACQUIRECONTEXTA pCryptAcquireContext = NULL; + + /* Obtain handle to the DLL containing CryptoAPI. This should not fail. */ + hAdvAPI32 = GetModuleHandle("advapi32.dll"); + if(hAdvAPI32 == NULL) + goto error; + + /* Obtain pointers to the CryptoAPI functions. This will fail on some early + versions of Win95. */ + pCryptAcquireContext = (CRYPTACQUIRECONTEXTA)GetProcAddress( + hAdvAPI32, "CryptAcquireContextA"); + if (pCryptAcquireContext == NULL) + goto error; + + pCryptGenRandom = (CRYPTGENRANDOM)GetProcAddress(hAdvAPI32, + "CryptGenRandom"); + if (pCryptGenRandom == NULL) + goto error; + + /* Acquire context */ + if (! pCryptAcquireContext(&hCryptProv, NULL, NULL, + PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) + goto error; + + return 0; + +error: + if (raise) + PyErr_SetFromWindowsErr(0); + else + Py_FatalError("Fail to initialize Windows random API (CryptoGen)"); + return -1; +} + +/* Fill buffer with size pseudo-random bytes generated by the Windows CryptoGen + API. Return 0 on success, or -1 on error. */ +static int +win32_urandom(unsigned char *buffer, Py_ssize_t size, int raise) +{ + Py_ssize_t orig_size = size; + Py_ssize_t chunk; + + if (hCryptProv == 0) + { + if (win32_urandom_init(raise) == -1) + return -1; + } + + while (size > 0) + { + chunk = Py_MIN(size, INT_MAX); + if (!pCryptGenRandom(hCryptProv, chunk, buffer)) + { + /* CryptGenRandom() failed */ + if (raise) + PyErr_SetFromWindowsErr(0); + else + Py_FatalError("Fail to initialized the randomized hash " + "secret using CryptoGen)"); + return -1; + } + buffer += chunk; + size -= chunk; + } + return 0; +} + +#else + +/* Read size bytes from /dev/urandom into buffer. + Call Py_FatalError() on error. */ +static void +dev_urandom_noraise(char *buffer, Py_ssize_t size) +{ + int fd; + Py_ssize_t n; + + assert (0 < size); + + fd = open("/dev/urandom", O_RDONLY); + if (fd < 0) + Py_FatalError("Fail to open /dev/urandom"); + + while (0 < size) + { + do { + n = read(fd, buffer, (size_t)size); + } while (n < 0 && errno == EINTR); + if (n <= 0) + { + /* stop on error or if read(size) returned 0 */ + Py_FatalError("Fail to read bytes from /dev/urandom"); + break; + } + buffer += n; + size -= (Py_ssize_t)n; + } + close(fd); +} + +/* Read size bytes from /dev/urandom into buffer. + Return 0 on success, raise an exception and return -1 on error. */ +static int +dev_urandom_python(char *buffer, Py_ssize_t size) +{ + int fd; + Py_ssize_t n; + + if (size <= 0) + return 0; + + Py_BEGIN_ALLOW_THREADS + fd = open("/dev/urandom", O_RDONLY); + Py_END_ALLOW_THREADS + if (fd < 0) + { + PyErr_SetFromErrnoWithFilename(PyExc_OSError, "/dev/urandom"); + return -1; + } + + Py_BEGIN_ALLOW_THREADS + do { + do { + n = read(fd, buffer, (size_t)size); + } while (n < 0 && errno == EINTR); + if (n <= 0) + break; + buffer += n; + size -= (Py_ssize_t)n; + } while (0 < size); + Py_END_ALLOW_THREADS + + if (n <= 0) + { + /* stop on error or if read(size) returned 0 */ + if (n < 0) + PyErr_SetFromErrno(PyExc_OSError); + else + PyErr_Format(PyExc_RuntimeError, + "Fail to read %zi bytes from /dev/urandom", + size); + close(fd); + return -1; + } + close(fd); + return 0; +} +#endif + +/* Fill buffer with pseudo-random bytes generated by a linear congruent + generator (LCG): + + x(n+1) = (x(n) * 214013 + 2531011) % 2^32 + + Use bits 23..16 of x(n) to generate a byte. */ +static void +lcg_urandom(unsigned int x0, unsigned char *buffer, size_t size) +{ + size_t index; + unsigned int x; + + x = x0; + for (index=0; index < size; index++) { + x *= 214013; + x += 2531011; + /* modulo 2 ^ (8 * sizeof(int)) */ + buffer[index] = (x >> 16) & 0xff; + } +} + +/* Fill buffer with size pseudo-random bytes, not suitable for cryptographic + use, from the operating random number generator (RNG). + + Return 0 on success, raise an exception and return -1 on error. */ +int +_PyOS_URandom(void *buffer, Py_ssize_t size) +{ + if (size < 0) { + PyErr_Format(PyExc_ValueError, + "negative argument not allowed"); + return -1; + } + if (size == 0) + return 0; + +#ifdef MS_WINDOWS + return win32_urandom((unsigned char *)buffer, size, 1); +#else + return dev_urandom_python((char*)buffer, size); +#endif +} + +void +_PyRandom_Init(void) +{ + char *env; + void *secret = &_Py_HashSecret; + Py_ssize_t secret_size = sizeof(_Py_HashSecret); + + if (random_initialized) + return; + random_initialized = 1; + + /* + By default, hash randomization is disabled, and only + enabled if PYTHONHASHRANDOMIZATION is set + */ + env = Py_GETENV("PYTHONHASHRANDOMIZATION"); + if (!env || *env == '\0') { + /* Not found: disable the randomized hash: */ + memset(secret, 0, secret_size); + return; + } + + /* + PYTHONHASHRANDOMIZATION was found; generate a per-process secret, + using PYTHONHASHSEED if provided. + */ + + env = Py_GETENV("PYTHONHASHSEED"); + if (env && *env != '\0') { + char *endptr = env; + unsigned long seed; + seed = strtoul(env, &endptr, 10); + if (*endptr != '\0' + || seed > 4294967295UL + || (errno == ERANGE && seed == ULONG_MAX)) + { + Py_FatalError("PYTHONHASHSEED must be an integer " + "in range [0; 4294967295]"); + } + if (seed == 0) { + /* disable the randomized hash */ + memset(secret, 0, secret_size); + } + else { + lcg_urandom(seed, (unsigned char*)secret, secret_size); + } + } + else { +#ifdef MS_WINDOWS +#if 1 + (void)win32_urandom((unsigned char *)secret, secret_size, 0); +#else + /* fast but weak RNG (fast initialization, weak seed) */ + _PyTime_timeval t; + unsigned int seed; + _PyTime_gettimeofday(&t); + seed = (unsigned int)t.tv_sec; + seed ^= t.tv_usec; + seed ^= getpid(); + lcg_urandom(seed, (unsigned char*)secret, secret_size); +#endif +#else /* #ifdef MS_WINDOWS */ + dev_urandom_noraise((char*)secret, secret_size); +#endif + } +} +