Skip to content

Commit 26da920

Browse files
committed
ensure no one tries to hash things before the random seed is found
1 parent b69fa1f commit 26da920

4 files changed

Lines changed: 14 additions & 4 deletions

File tree

‎Include/object.h‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -512,6 +512,10 @@ typedef struct {
512512
} _Py_HashSecret_t;
513513
PyAPI_DATA(_Py_HashSecret_t) _Py_HashSecret;
514514

515+
#ifdef Py_DEBUG
516+
PyAPI_DATA(int) _Py_HashSecret_Initialized;
517+
#endif
518+
515519
/* Helper for passing objects to printf and the like */
516520
#define PyObject_REPR(obj) PyString_AS_STRING(PyObject_Repr(obj))
517521

‎Objects/stringobject.c‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1209,6 +1209,7 @@ string_hash(PyStringObject *a)
12091209
register unsigned char *p;
12101210
register long x;
12111211

1212+
assert(_Py_HashSecret_Initialized);
12121213
if (a->ob_shash != -1)
12131214
return a->ob_shash;
12141215
len = Py_SIZE(a);

‎Objects/unicodeobject.c‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6692,6 +6692,7 @@ unicode_hash(PyUnicodeObject *self)
66926692
register Py_UNICODE *p;
66936693
register long x;
66946694

6695+
assert(_Py_HashSecret_Initialized);
66956696
if (self->hash != -1)
66966697
return self->hash;
66976698
len = PyUnicode_GET_SIZE(self);

‎Python/random.c‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,11 @@
55
#include <fcntl.h>
66
#endif
77

8-
static int random_initialized = 0;
8+
#ifdef Py_DEBUG
9+
int _Py_HashSecret_Initialized = 0;
10+
#else
11+
static int _Py_HashSecret_Initialized = 0;
12+
#endif
913

1014
#ifdef MS_WINDOWS
1115
typedef BOOL (WINAPI *CRYPTACQUIRECONTEXTA)(HCRYPTPROV *phProv,\
@@ -246,11 +250,11 @@ _PyRandom_Init(void)
246250
{
247251
char *env;
248252
void *secret = &_Py_HashSecret;
249-
Py_ssize_t secret_size = sizeof(_Py_HashSecret);
253+
Py_ssize_t secret_size = sizeof(_Py_HashSecret_t);
250254

251-
if (random_initialized)
255+
if (_Py_HashSecret_Initialized)
252256
return;
253-
random_initialized = 1;
257+
_Py_HashSecret_Initialized = 1;
254258

255259
/*
256260
By default, hash randomization is disabled, and only

0 commit comments

Comments
 (0)