Blame SOURCES/00146-hashlib-fips.patch

8ee724
From ece76465680b0df5b3fce7bf8ff1ff0253933889 Mon Sep 17 00:00:00 2001
8ee724
From: Petr Viktorin <pviktori@redhat.com>
8ee724
Date: Mon, 2 Sep 2019 17:33:29 +0200
8ee724
Subject: [PATCH 01/11] Remove HASH_OBJ_CONSTRUCTOR
8ee724
8ee724
See https://github.com/python/cpython/commit/c7e219132aff1e21cb9ccb0a9b570dc6c750039b
8ee724
---
8ee724
 Modules/_hashopenssl.c | 59 ------------------------------------------
8ee724
 1 file changed, 59 deletions(-)
8ee724
8ee724
diff --git a/Modules/_hashopenssl.c b/Modules/_hashopenssl.c
8ee724
index 78445ebabdd3..cb81e9765251 100644
8ee724
--- a/Modules/_hashopenssl.c
8ee724
+++ b/Modules/_hashopenssl.c
8ee724
@@ -48,10 +48,6 @@
8ee724
  * to allow the user to optimize based on the platform they're using. */
8ee724
 #define HASHLIB_GIL_MINSIZE 2048
8ee724
 
8ee724
-#ifndef HASH_OBJ_CONSTRUCTOR
8ee724
-#define HASH_OBJ_CONSTRUCTOR 0
8ee724
-#endif
8ee724
-
8ee724
 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER >= 0x00908000)
8ee724
 #define _OPENSSL_SUPPORTS_SHA2
8ee724
 #endif
8ee724
@@ -384,53 +380,6 @@ EVP_repr(PyObject *self)
8ee724
     return PyString_FromString(buf);
8ee724
 }
72be67
 
8ee724
-#if HASH_OBJ_CONSTRUCTOR
8ee724
-static int
8ee724
-EVP_tp_init(EVPobject *self, PyObject *args, PyObject *kwds)
8ee724
-{
8ee724
-    static char *kwlist[] = {"name", "string", NULL};
8ee724
-    PyObject *name_obj = NULL;
8ee724
-    Py_buffer view = { 0 };
8ee724
-    char *nameStr;
8ee724
-    const EVP_MD *digest;
8ee724
-
8ee724
-    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|s*:HASH", kwlist,
8ee724
-                                     &name_obj, &view)) {
8ee724
-        return -1;
8ee724
-    }
8ee724
-
8ee724
-    if (!PyArg_Parse(name_obj, "s", &nameStr)) {
8ee724
-        PyErr_SetString(PyExc_TypeError, "name must be a string");
8ee724
-        PyBuffer_Release(&view);
8ee724
-        return -1;
8ee724
-    }
8ee724
-
8ee724
-    digest = EVP_get_digestbyname(nameStr);
8ee724
-    if (!digest) {
8ee724
-        PyErr_SetString(PyExc_ValueError, "unknown hash function");
8ee724
-        PyBuffer_Release(&view);
8ee724
-        return -1;
8ee724
-    }
8ee724
-    EVP_DigestInit(self->ctx, digest);
8ee724
-
8ee724
-    self->name = name_obj;
8ee724
-    Py_INCREF(self->name);
8ee724
-
8ee724
-    if (view.obj) {
8ee724
-        if (view.len >= HASHLIB_GIL_MINSIZE) {
8ee724
-            Py_BEGIN_ALLOW_THREADS
8ee724
-            EVP_hash(self, view.buf, view.len);
8ee724
-            Py_END_ALLOW_THREADS
8ee724
-        } else {
8ee724
-            EVP_hash(self, view.buf, view.len);
8ee724
-        }
8ee724
-        PyBuffer_Release(&view);
8ee724
-    }
8ee724
-
8ee724
-    return 0;
8ee724
-}
8ee724
-#endif
8ee724
-
72be67
 
8ee724
 PyDoc_STRVAR(hashtype_doc,
8ee724
 "A hash represents the object used to calculate a checksum of a\n\
8ee724
@@ -487,9 +436,6 @@ static PyTypeObject EVPtype = {
8ee724
     0,                  /* tp_descr_set */
8ee724
     0,                  /* tp_dictoffset */
8ee724
 #endif
8ee724
-#if HASH_OBJ_CONSTRUCTOR
8ee724
-    (initproc)EVP_tp_init, /* tp_init */
8ee724
-#endif
8ee724
 };
72be67
 
8ee724
 static PyObject *
8ee724
@@ -928,11 +874,6 @@ init_hashlib(void)
8ee724
         return;
8ee724
     }
72be67
 
8ee724
-#if HASH_OBJ_CONSTRUCTOR
8ee724
-    Py_INCREF(&EVPtype);
8ee724
-    PyModule_AddObject(m, "HASH", (PyObject *)&EVPtype);
8ee724
-#endif
8ee724
-
8ee724
     /* these constants are used by the convenience constructors */
8ee724
     INIT_CONSTRUCTOR_CONSTANTS(md5);
8ee724
     INIT_CONSTRUCTOR_CONSTANTS(sha1);
8ee724
8ee724
From d7339af75678c760f6d6c0eb455b0eb889c22574 Mon Sep 17 00:00:00 2001
8ee724
From: Petr Viktorin <pviktori@redhat.com>
8ee724
Date: Mon, 2 Sep 2019 18:02:25 +0200
8ee724
Subject: [PATCH 02/11] Add the usedforsecurity argument to _hashopenssl
8ee724
8ee724
---
8ee724
 Modules/_hashopenssl.c | 63 ++++++++++++++++++++++++++++++++----------
8ee724
 1 file changed, 48 insertions(+), 15 deletions(-)
8ee724
8ee724
diff --git a/Modules/_hashopenssl.c b/Modules/_hashopenssl.c
8ee724
index cb81e9765251..f2dbc095cc66 100644
8ee724
--- a/Modules/_hashopenssl.c
8ee724
+++ b/Modules/_hashopenssl.c
8ee724
@@ -441,7 +441,7 @@ static PyTypeObject EVPtype = {
8ee724
 static PyObject *
8ee724
 EVPnew(PyObject *name_obj,
8ee724
        const EVP_MD *digest, const EVP_MD_CTX *initial_ctx,
8ee724
-       const unsigned char *cp, Py_ssize_t len)
8ee724
+       const unsigned char *cp, Py_ssize_t len, int usedforsecurity)
8ee724
 {
8ee724
     EVPobject *self;
8ee724
 
8ee724
@@ -456,7 +456,23 @@ EVPnew(PyObject *name_obj,
8ee724
     if (initial_ctx) {
8ee724
         EVP_MD_CTX_copy(self->ctx, initial_ctx);
8ee724
     } else {
8ee724
-        EVP_DigestInit(self->ctx, digest);
8ee724
+        EVP_MD_CTX_init(self->ctx);
72be67
+
8ee724
+        /*
8ee724
+        If the user has declared that this digest is being used in a
8ee724
+        non-security role (e.g. indexing into a data structure), set
8ee724
+        the exception flag for openssl to allow it
8ee724
+        */
8ee724
+        if (!usedforsecurity) {
8ee724
+#ifdef EVP_MD_CTX_FLAG_NON_FIPS_ALLOW
8ee724
+            EVP_MD_CTX_set_flags(self->ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
8ee724
+#endif
8ee724
+        }
8ee724
+        if (!EVP_DigestInit_ex(self->ctx, digest, NULL)) {
8ee724
+            _setException(PyExc_ValueError);
8ee724
+            Py_DECREF(self);
8ee724
+            return NULL;
8ee724
+        }
8ee724
     }
8ee724
 
8ee724
     if (cp && len) {
8ee724
@@ -485,15 +501,16 @@ The MD5 and SHA1 algorithms are always supported.\n");
8ee724
 static PyObject *
8ee724
 EVP_new(PyObject *self, PyObject *args, PyObject *kwdict)
8ee724
 {
8ee724
-    static char *kwlist[] = {"name", "string", NULL};
8ee724
+    static char *kwlist[] = {"name", "string", "usedforsecurity", NULL};
8ee724
     PyObject *name_obj = NULL;
8ee724
     Py_buffer view = { 0 };
8ee724
     PyObject *ret_obj;
8ee724
     char *name;
8ee724
     const EVP_MD *digest;
8ee724
+    int usedforsecurity = 1;
8ee724
 
8ee724
-    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "O|s*:new", kwlist,
8ee724
-                                     &name_obj, &view)) {
8ee724
+    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "O|s*i:new", kwlist,
8ee724
+                                     &name_obj, &view, &usedforsecurity)) {
8ee724
         return NULL;
8ee724
     }
8ee724
 
8ee724
@@ -506,7 +523,7 @@ EVP_new(PyObject *self, PyObject *args, PyObject *kwdict)
8ee724
     digest = EVP_get_digestbyname(name);
8ee724
 
8ee724
     ret_obj = EVPnew(name_obj, digest, NULL, (unsigned char*)view.buf,
8ee724
-                     view.len);
8ee724
+                     view.len, usedforsecurity);
8ee724
     PyBuffer_Release(&view);
8ee724
 
8ee724
     return ret_obj;
8ee724
@@ -771,30 +788,46 @@ generate_hash_name_list(void)
8ee724
  *  the generic one passing it a python string and are noticeably
8ee724
  *  faster than calling a python new() wrapper.  Thats important for
8ee724
  *  code that wants to make hashes of a bunch of small strings.
8ee724
+ *
8ee724
+ *  For usedforsecurity=False, the optimization is not used.
8ee724
  */
8ee724
 #define GEN_CONSTRUCTOR(NAME)  \
8ee724
     static PyObject * \
8ee724
-    EVP_new_ ## NAME (PyObject *self, PyObject *args) \
8ee724
+    EVP_new_ ## NAME (PyObject *self, PyObject *args, PyObject *kwdict) \
8ee724
     { \
8ee724
+        static char *kwlist[] = {"string", "usedforsecurity", NULL}; \
8ee724
         Py_buffer view = { 0 }; \
8ee724
         PyObject *ret_obj; \
8ee724
+        int usedforsecurity=1; \
8ee724
      \
8ee724
-        if (!PyArg_ParseTuple(args, "|s*:" #NAME , &view)) { \
8ee724
+        if (!PyArg_ParseTupleAndKeywords( \
8ee724
+            args, kwdict, "|s*i:" #NAME, kwlist, \
8ee724
+            &view, &usedforsecurity \
8ee724
+        )) { \
8ee724
             return NULL; \
8ee724
         } \
8ee724
-     \
8ee724
-        ret_obj = EVPnew( \
8ee724
-                    CONST_ ## NAME ## _name_obj, \
8ee724
-                    NULL, \
8ee724
-                    CONST_new_ ## NAME ## _ctx_p, \
8ee724
-                    (unsigned char*)view.buf, view.len); \
8ee724
+        if (usedforsecurity == 0) { \
8ee724
+            ret_obj = EVPnew( \
8ee724
+                        CONST_ ## NAME ## _name_obj, \
8ee724
+                        EVP_get_digestbyname(#NAME), \
8ee724
+                        NULL, \
8ee724
+                        (unsigned char*)view.buf, view.len, \
8ee724
+                        usedforsecurity); \
8ee724
+        } else { \
8ee724
+            ret_obj = EVPnew( \
8ee724
+                        CONST_ ## NAME ## _name_obj, \
8ee724
+                        NULL, \
8ee724
+                        CONST_new_ ## NAME ## _ctx_p, \
8ee724
+                        (unsigned char*)view.buf, view.len, \
8ee724
+                        usedforsecurity); \
8ee724
+        } \
8ee724
         PyBuffer_Release(&view); \
8ee724
         return ret_obj; \
8ee724
     }
8ee724
 
8ee724
 /* a PyMethodDef structure for the constructor */
8ee724
 #define CONSTRUCTOR_METH_DEF(NAME)  \
8ee724
-    {"openssl_" #NAME, (PyCFunction)EVP_new_ ## NAME, METH_VARARGS, \
8ee724
+    {"openssl_" #NAME, (PyCFunction)EVP_new_ ## NAME, METH_VARARGS|METH_KEYWORDS, \
8ee724
         PyDoc_STR("Returns a " #NAME \
8ee724
                   " hash object; optionally initialized with a string") \
8ee724
     }
8ee724
8ee724
From c8102e61fb3ade364d4bb7f2fe3f3452e2018ecd Mon Sep 17 00:00:00 2001
8ee724
From: David Malcolm <dmalcolm@redhat.com>
8ee724
Date: Mon, 2 Sep 2019 17:59:53 +0200
8ee724
Subject: [PATCH 03/11] hashlib.py: Avoid the builtin constructor
8ee724
8ee724
---
8ee724
 Lib/hashlib.py | 58 +++++++++++++-------------------------------------
8ee724
 1 file changed, 15 insertions(+), 43 deletions(-)
8ee724
8ee724
diff --git a/Lib/hashlib.py b/Lib/hashlib.py
8ee724
index bbd06b9996ee..404ed6891fb9 100644
8ee724
--- a/Lib/hashlib.py
8ee724
+++ b/Lib/hashlib.py
8ee724
@@ -69,65 +69,37 @@
72be67
                                 'pbkdf2_hmac')
72be67
 
72be67
 
72be67
-def __get_builtin_constructor(name):
72be67
-    try:
72be67
-        if name in ('SHA1', 'sha1'):
72be67
-            import _sha
72be67
-            return _sha.new
72be67
-        elif name in ('MD5', 'md5'):
72be67
-            import _md5
72be67
-            return _md5.new
72be67
-        elif name in ('SHA256', 'sha256', 'SHA224', 'sha224'):
72be67
-            import _sha256
72be67
-            bs = name[3:]
72be67
-            if bs == '256':
72be67
-                return _sha256.sha256
72be67
-            elif bs == '224':
72be67
-                return _sha256.sha224
72be67
-        elif name in ('SHA512', 'sha512', 'SHA384', 'sha384'):
72be67
-            import _sha512
72be67
-            bs = name[3:]
72be67
-            if bs == '512':
72be67
-                return _sha512.sha512
72be67
-            elif bs == '384':
72be67
-                return _sha512.sha384
72be67
-    except ImportError:
72be67
-        pass  # no extension module, this hash is unsupported.
72be67
-
72be67
-    raise ValueError('unsupported hash type ' + name)
72be67
-
72be67
-
72be67
 def __get_openssl_constructor(name):
72be67
     try:
72be67
         f = getattr(_hashlib, 'openssl_' + name)
72be67
         # Allow the C module to raise ValueError.  The function will be
72be67
         # defined but the hash not actually available thanks to OpenSSL.
72be67
-        f()
72be67
+        #
72be67
+        # We pass "usedforsecurity=False" to disable FIPS-based restrictions:
72be67
+        # at this stage we're merely seeing if the function is callable,
72be67
+        # rather than using it for actual work.
72be67
+        f(usedforsecurity=False)
72be67
         # Use the C function directly (very fast)
72be67
         return f
72be67
     except (AttributeError, ValueError):
72be67
-        return __get_builtin_constructor(name)
8ee724
-
72be67
-
72be67
-def __py_new(name, string=''):
72be67
-    """new(name, string='') - Return a new hashing object using the named algorithm;
72be67
-    optionally initialized with a string.
72be67
-    """
72be67
-    return __get_builtin_constructor(name)(string)
8ee724
+        raise
8ee724
 
8ee724
 
72be67
-def __hash_new(name, string=''):
8ee724
-    """new(name, string='') - Return a new hashing object using the named algorithm;
8ee724
-    optionally initialized with a string.
72be67
+def __hash_new(name, string='', usedforsecurity=True):
8ee724
+    """new(name, string='', usedforsecurity=True) - Return a new hashing object
8ee724
+    using the named algorithm; optionally initialized with a string.
8ee724
+    
72be67
+    Override 'usedforsecurity' to False when using for non-security purposes in
72be67
+    a FIPS environment
72be67
     """
72be67
     try:
72be67
-        return _hashlib.new(name, string)
72be67
+        return _hashlib.new(name, string, usedforsecurity)
72be67
     except ValueError:
8ee724
         # If the _hashlib module (OpenSSL) doesn't support the named
8ee724
         # hash, try using our builtin implementations.
8ee724
         # This allows for SHA224/256 and SHA384/512 support even though
8ee724
         # the OpenSSL library prior to 0.9.8 doesn't provide them.
72be67
-        return __get_builtin_constructor(name)(string)
72be67
+        raise
72be67
 
8ee724
 
72be67
 try:
8ee724
@@ -218,4 +190,4 @@ def prf(msg, inner=inner, outer=outer):
72be67
 
72be67
 # Cleanup locals()
72be67
 del __always_supported, __func_name, __get_hash
72be67
-del __py_new, __hash_new, __get_openssl_constructor
72be67
+del __hash_new, __get_openssl_constructor
8ee724
8ee724
From 2ade3e5a6c5732c0692c4cc2235a2bbe0948f50b Mon Sep 17 00:00:00 2001
8ee724
From: David Malcolm <dmalcolm@redhat.com>
8ee724
Date: Mon, 2 Sep 2019 17:56:46 +0200
8ee724
Subject: [PATCH 04/11] Adjust docstrings & comments
8ee724
8ee724
---
8ee724
 Lib/hashlib.py         | 29 ++++++++++++++++++++++-------
8ee724
 Modules/_hashopenssl.c |  9 ++++++++-
8ee724
 2 files changed, 30 insertions(+), 8 deletions(-)
8ee724
8ee724
diff --git a/Lib/hashlib.py b/Lib/hashlib.py
8ee724
index 404ed6891fb9..46d0b470ab4a 100644
8ee724
--- a/Lib/hashlib.py
8ee724
+++ b/Lib/hashlib.py
8ee724
@@ -6,9 +6,12 @@
8ee724
 
8ee724
 __doc__ = """hashlib module - A common interface to many hash functions.
8ee724
 
8ee724
-new(name, string='') - returns a new hash object implementing the
8ee724
-                       given hash function; initializing the hash
8ee724
-                       using the given string data.
8ee724
+new(name, string='', usedforsecurity=True)
8ee724
+     - returns a new hash object implementing the given hash function;
8ee724
+       initializing the hash using the given string data.
8ee724
+
8ee724
+       "usedforsecurity" is a non-standard extension for better supporting
8ee724
+       FIPS-compliant environments (see below)
8ee724
 
8ee724
 Named constructor functions are also available, these are much faster
8ee724
 than using new():
8ee724
@@ -25,6 +28,20 @@
8ee724
 Choose your hash function wisely.  Some have known collision weaknesses.
8ee724
 sha384 and sha512 will be slow on 32 bit platforms.
8ee724
 
8ee724
+Our implementation of hashlib uses OpenSSL.
8ee724
+
8ee724
+OpenSSL has a "FIPS mode", which, if enabled, may restrict the available hashes
8ee724
+to only those that are compliant with FIPS regulations.  For example, it may
8ee724
+deny the use of MD5, on the grounds that this is not secure for uses such as
8ee724
+authentication, system integrity checking, or digital signatures.
8ee724
+
8ee724
+If you need to use such a hash for non-security purposes (such as indexing into
8ee724
+a data structure for speed), you can override the keyword argument
8ee724
+"usedforsecurity" from True to False to signify that your code is not relying
8ee724
+on the hash for security purposes, and this will allow the hash to be usable
8ee724
+even in FIPS mode.  This is not a standard feature of Python 2.7's hashlib, and
8ee724
+is included here to better support FIPS mode.
8ee724
+
8ee724
 Hash objects have these methods:
8ee724
  - update(arg): Update the hash object with the string arg. Repeated calls
8ee724
                 are equivalent to a single call with the concatenation of all
8ee724
@@ -82,6 +99,7 @@ def __get_openssl_constructor(name):
8ee724
         # Use the C function directly (very fast)
8ee724
         return f
8ee724
     except (AttributeError, ValueError):
8ee724
+        # RHEL only: Fallbacks removed; we always use OpenSSL for hashes.
8ee724
         raise
8ee724
 
8ee724
 
8ee724
@@ -95,10 +113,7 @@ def __hash_new(name, string='', usedforsecurity=True):
8ee724
     try:
8ee724
         return _hashlib.new(name, string, usedforsecurity)
8ee724
     except ValueError:
8ee724
-        # If the _hashlib module (OpenSSL) doesn't support the named
8ee724
-        # hash, try using our builtin implementations.
8ee724
-        # This allows for SHA224/256 and SHA384/512 support even though
8ee724
-        # the OpenSSL library prior to 0.9.8 doesn't provide them.
8ee724
+        # RHEL only: Fallbacks removed; we always use OpenSSL for hashes.
8ee724
         raise
8ee724
 
8ee724
 
8ee724
diff --git a/Modules/_hashopenssl.c b/Modules/_hashopenssl.c
8ee724
index f2dbc095cc66..d24432e048bf 100644
8ee724
--- a/Modules/_hashopenssl.c
8ee724
+++ b/Modules/_hashopenssl.c
8ee724
@@ -496,7 +496,14 @@ PyDoc_STRVAR(EVP_new__doc__,
8ee724
 An optional string argument may be provided and will be\n\
8ee724
 automatically hashed.\n\
8ee724
 \n\
8ee724
-The MD5 and SHA1 algorithms are always supported.\n");
8ee724
+The MD5 and SHA1 algorithms are always supported.\n \
8ee724
+\n\
8ee724
+An optional \"usedforsecurity=True\" keyword argument is provided for use in\n\
8ee724
+environments that enforce FIPS-based restrictions.  Some implementations of\n\
8ee724
+OpenSSL can be configured to prevent the usage of non-secure algorithms (such\n\
8ee724
+as MD5).  If you have a non-security use for these algorithms (e.g. a hash\n\
8ee724
+table), you can override this argument by marking the callsite as\n\
8ee724
+\"usedforsecurity=False\".");
8ee724
 
8ee724
 static PyObject *
8ee724
 EVP_new(PyObject *self, PyObject *args, PyObject *kwdict)
8ee724
8ee724
From 6698e1d84c3f19bbb4438b2b2c78a5ef8bd5ad42 Mon Sep 17 00:00:00 2001
8ee724
From: Petr Viktorin <pviktori@redhat.com>
8ee724
Date: Thu, 29 Aug 2019 10:25:28 +0200
8ee724
Subject: [PATCH 05/11] Expose OpenSSL FIPS_mode as _hashlib.get_fips_mode
8ee724
8ee724
---
8ee724
 Modules/_hashopenssl.c | 22 ++++++++++++++++++++++
8ee724
 1 file changed, 22 insertions(+)
8ee724
8ee724
diff --git a/Modules/_hashopenssl.c b/Modules/_hashopenssl.c
8ee724
index d24432e048bf..74f9ab9ec150 100644
8ee724
--- a/Modules/_hashopenssl.c
8ee724
+++ b/Modules/_hashopenssl.c
8ee724
@@ -860,10 +860,32 @@ GEN_CONSTRUCTOR(sha384)
8ee724
 GEN_CONSTRUCTOR(sha512)
8ee724
 #endif
8ee724
 
8ee724
+static PyObject *
8ee724
+_hashlib_get_fips_mode(PyObject *module, PyObject *unused)
8ee724
+{
8ee724
+    // XXX: This function skips error checking.
8ee724
+    // This is only appropriate for RHEL.
8ee724
+
8ee724
+    // From the OpenSSL docs:
8ee724
+    // "If the library was built without support of the FIPS Object Module,
8ee724
+    // then the function will return 0 with an error code of
8ee724
+    // CRYPTO_R_FIPS_MODE_NOT_SUPPORTED (0x0f06d065)."
8ee724
+    // In RHEL:
8ee724
+    // * we do build with FIPS, so the function always succeeds
8ee724
+    // * even if it didn't, people seem used to errors being left on the
8ee724
+    //   OpenSSL error stack.
8ee724
+
8ee724
+    // For more info, see:
8ee724
+    //  https://bugzilla.redhat.com/show_bug.cgi?id=1745499
8ee724
+
8ee724
+    return PyInt_FromLong(FIPS_mode());
8ee724
+}
8ee724
+
8ee724
 /* List of functions exported by this module */
8ee724
 
8ee724
 static struct PyMethodDef EVP_functions[] = {
8ee724
     {"new", (PyCFunction)EVP_new, METH_VARARGS|METH_KEYWORDS, EVP_new__doc__},
8ee724
+    {"get_fips_mode", (PyCFunction)_hashlib_get_fips_mode, METH_NOARGS, NULL},
8ee724
     CONSTRUCTOR_METH_DEF(md5),
8ee724
     CONSTRUCTOR_METH_DEF(sha1),
8ee724
 #ifdef _OPENSSL_SUPPORTS_SHA2
8ee724
8ee724
From 9a8833619658c6be5ca72c60189a64da05536d85 Mon Sep 17 00:00:00 2001
8ee724
From: David Malcolm <dmalcolm@redhat.com>
8ee724
Date: Mon, 2 Sep 2019 18:00:26 +0200
8ee724
Subject: [PATCH 06/11] Adjust tests
8ee724
8ee724
---
8ee724
 Lib/test/test_hashlib.py | 118 ++++++++++++++++++++++++---------------
8ee724
 1 file changed, 74 insertions(+), 44 deletions(-)
8ee724
8ee724
diff --git a/Lib/test/test_hashlib.py b/Lib/test/test_hashlib.py
8ee724
index b8d6388feaf9..b03fc84f82b4 100644
8ee724
--- a/Lib/test/test_hashlib.py
8ee724
+++ b/Lib/test/test_hashlib.py
8ee724
@@ -34,6 +34,8 @@ def hexstr(s):
72be67
         r = r + h[(i >> 4) & 0xF] + h[i & 0xF]
72be67
     return r
72be67
 
8ee724
+from _hashlib import get_fips_mode
8ee724
+
72be67
 
72be67
 class HashLibTestCase(unittest.TestCase):
72be67
     supported_hash_names = ( 'md5', 'MD5', 'sha1', 'SHA1',
8ee724
@@ -63,10 +65,10 @@ def __init__(self, *args, **kwargs):
72be67
         # of hashlib.new given the algorithm name.
72be67
         for algorithm, constructors in self.constructors_to_test.items():
72be67
             constructors.add(getattr(hashlib, algorithm))
72be67
-            def _test_algorithm_via_hashlib_new(data=None, _alg=algorithm):
72be67
+            def _test_algorithm_via_hashlib_new(data=None, _alg=algorithm, usedforsecurity=True):
72be67
                 if data is None:
72be67
-                    return hashlib.new(_alg)
72be67
-                return hashlib.new(_alg, data)
72be67
+                    return hashlib.new(_alg, usedforsecurity=usedforsecurity)
72be67
+                return hashlib.new(_alg, data, usedforsecurity=usedforsecurity)
72be67
             constructors.add(_test_algorithm_via_hashlib_new)
72be67
 
72be67
         _hashlib = self._conditional_import_module('_hashlib')
8ee724
@@ -80,28 +82,13 @@ def _test_algorithm_via_hashlib_new(data=None, _alg=algorithm):
72be67
                 if constructor:
72be67
                     constructors.add(constructor)
72be67
 
72be67
-        _md5 = self._conditional_import_module('_md5')
72be67
-        if _md5:
72be67
-            self.constructors_to_test['md5'].add(_md5.new)
72be67
-        _sha = self._conditional_import_module('_sha')
72be67
-        if _sha:
72be67
-            self.constructors_to_test['sha1'].add(_sha.new)
72be67
-        _sha256 = self._conditional_import_module('_sha256')
72be67
-        if _sha256:
72be67
-            self.constructors_to_test['sha224'].add(_sha256.sha224)
72be67
-            self.constructors_to_test['sha256'].add(_sha256.sha256)
72be67
-        _sha512 = self._conditional_import_module('_sha512')
72be67
-        if _sha512:
72be67
-            self.constructors_to_test['sha384'].add(_sha512.sha384)
72be67
-            self.constructors_to_test['sha512'].add(_sha512.sha512)
72be67
-
72be67
         super(HashLibTestCase, self).__init__(*args, **kwargs)
72be67
 
72be67
     def test_hash_array(self):
72be67
         a = array.array("b", range(10))
72be67
         constructors = self.constructors_to_test.itervalues()
72be67
         for cons in itertools.chain.from_iterable(constructors):
72be67
-            c = cons(a)
72be67
+            c = cons(a, usedforsecurity=False)
72be67
             c.hexdigest()
72be67
 
72be67
     def test_algorithms_attribute(self):
8ee724
@@ -122,28 +109,9 @@ def test_unknown_hash(self):
72be67
         self.assertRaises(ValueError, hashlib.new, 'spam spam spam spam spam')
72be67
         self.assertRaises(TypeError, hashlib.new, 1)
72be67
 
72be67
-    def test_get_builtin_constructor(self):
72be67
-        get_builtin_constructor = hashlib.__dict__[
72be67
-                '__get_builtin_constructor']
72be67
-        self.assertRaises(ValueError, get_builtin_constructor, 'test')
72be67
-        try:
72be67
-            import _md5
72be67
-        except ImportError:
72be67
-            pass
72be67
-        # This forces an ImportError for "import _md5" statements
72be67
-        sys.modules['_md5'] = None
72be67
-        try:
72be67
-            self.assertRaises(ValueError, get_builtin_constructor, 'md5')
72be67
-        finally:
72be67
-            if '_md5' in locals():
72be67
-                sys.modules['_md5'] = _md5
72be67
-            else:
72be67
-                del sys.modules['_md5']
72be67
-        self.assertRaises(TypeError, get_builtin_constructor, 3)
72be67
-
72be67
     def test_hexdigest(self):
72be67
         for name in self.supported_hash_names:
72be67
-            h = hashlib.new(name)
72be67
+            h = hashlib.new(name, usedforsecurity=False)
72be67
             self.assertTrue(hexstr(h.digest()) == h.hexdigest())
72be67
 
72be67
     def test_large_update(self):
8ee724
@@ -153,16 +121,16 @@ def test_large_update(self):
72be67
         abcs = aas + bees + cees
72be67
 
72be67
         for name in self.supported_hash_names:
72be67
-            m1 = hashlib.new(name)
72be67
+            m1 = hashlib.new(name, usedforsecurity=False)
72be67
             m1.update(aas)
72be67
             m1.update(bees)
72be67
             m1.update(cees)
72be67
 
72be67
-            m2 = hashlib.new(name)
72be67
+            m2 = hashlib.new(name, usedforsecurity=False)
72be67
             m2.update(abcs)
72be67
             self.assertEqual(m1.digest(), m2.digest(), name+' update problem.')
72be67
 
72be67
-            m3 = hashlib.new(name, abcs)
72be67
+            m3 = hashlib.new(name, abcs, usedforsecurity=False)
72be67
             self.assertEqual(m1.digest(), m3.digest(), name+' new problem.')
72be67
 
72be67
     def check(self, name, data, digest):
8ee724
@@ -170,7 +138,7 @@ def check(self, name, data, digest):
72be67
         # 2 is for hashlib.name(...) and hashlib.new(name, ...)
72be67
         self.assertGreaterEqual(len(constructors), 2)
72be67
         for hash_object_constructor in constructors:
72be67
-            computed = hash_object_constructor(data).hexdigest()
72be67
+            computed = hash_object_constructor(data, usedforsecurity=False).hexdigest()
72be67
             self.assertEqual(
72be67
                     computed, digest,
72be67
                     "Hash algorithm %s constructed using %s returned hexdigest"
8ee724
@@ -195,7 +163,7 @@ def check_update(self, name, data, digest):
72be67
 
72be67
     def check_unicode(self, algorithm_name):
72be67
         # Unicode objects are not allowed as input.
72be67
-        expected = hashlib.new(algorithm_name, str(u'spam')).hexdigest()
8ee724
+        expected = hashlib.new(algorithm_name, str(u'spam'), usedforsecurity=False).hexdigest()
72be67
         self.check(algorithm_name, u'spam', expected)
72be67
 
72be67
     def test_unicode(self):
8ee724
@@ -393,6 +361,68 @@ def hash_in_chunks(chunk_size):
72be67
 
8ee724
         self.assertEqual(expected_hash, hasher.hexdigest())
72be67
 
72be67
+    def test_issue9146(self):
72be67
+        # Ensure that various ways to use "MD5" from "hashlib" don't segfault:
72be67
+        m = hashlib.md5(usedforsecurity=False)
72be67
+        m.update(b'abc\n')
72be67
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
8ee724
+
72be67
+        m = hashlib.new('md5', usedforsecurity=False)
72be67
+        m.update(b'abc\n')
72be67
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
8ee724
+
72be67
+        m = hashlib.md5(b'abc\n', usedforsecurity=False)
72be67
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
8ee724
+
72be67
+        m = hashlib.new('md5', b'abc\n', usedforsecurity=False)
72be67
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
72be67
+
8ee724
+    def assertRaisesDisabledForFIPS(self, callable_obj=None, *args, **kwargs):
72be67
+        try:
72be67
+            callable_obj(*args, **kwargs)
72be67
+        except ValueError, e:
8ee724
+            if not e.args[0].endswith('disabled for FIPS'):
72be67
+                self.fail('Incorrect exception raised')
72be67
+        else:
72be67
+            self.fail('Exception was not raised')
72be67
+
8ee724
+    @unittest.skipUnless(get_fips_mode(),
72be67
+                         'FIPS enforcement required for this test.')
8ee724
+    def test_hashlib_fips_mode(self):
72be67
+        # Ensure that we raise a ValueError on vanilla attempts to use MD5
72be67
+        # in hashlib in a FIPS-enforced setting:
8ee724
+        self.assertRaisesDisabledForFIPS(hashlib.md5)
8ee724
+        self.assertRaisesDisabledForFIPS(hashlib.new, 'md5')
72be67
+
8ee724
+    @unittest.skipUnless(get_fips_mode(),
72be67
+                         'FIPS enforcement required for this test.')
72be67
+    def test_hashopenssl_fips_mode(self):
72be67
+        # Verify the _hashlib module's handling of md5:
72be67
+        import _hashlib
72be67
+
72be67
+        assert hasattr(_hashlib, 'openssl_md5')
72be67
+
72be67
+        # Ensure that _hashlib raises a ValueError on vanilla attempts to
72be67
+        # use MD5 in a FIPS-enforced setting:
8ee724
+        self.assertRaisesDisabledForFIPS(_hashlib.openssl_md5)
8ee724
+        self.assertRaisesDisabledForFIPS(_hashlib.new, 'md5')
72be67
+
72be67
+        # Ensure that in such a setting we can whitelist a callsite with
72be67
+        # usedforsecurity=False and have it succeed:
72be67
+        m = _hashlib.openssl_md5(usedforsecurity=False)
72be67
+        m.update('abc\n')
72be67
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
8ee724
+
72be67
+        m = _hashlib.new('md5', usedforsecurity=False)
72be67
+        m.update('abc\n')
72be67
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
8ee724
+
72be67
+        m = _hashlib.openssl_md5('abc\n', usedforsecurity=False)
72be67
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
8ee724
+
72be67
+        m = _hashlib.new('md5', 'abc\n', usedforsecurity=False)
72be67
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
72be67
+
8ee724
 
72be67
 class KDFTests(unittest.TestCase):
72be67
     pbkdf2_test_vectors = [
8ee724
8ee724
From 31e527aa4f57845dfb0c3dd4f0e9192af5a5b4e2 Mon Sep 17 00:00:00 2001
8ee724
From: David Malcolm <dmalcolm@redhat.com>
8ee724
Date: Mon, 2 Sep 2019 18:00:47 +0200
8ee724
Subject: [PATCH 07/11] Don't build non-OpenSSL hash implementations
8ee724
8ee724
---
8ee724
 setup.py | 15 ---------------
8ee724
 1 file changed, 15 deletions(-)
8ee724
8ee724
diff --git a/setup.py b/setup.py
8ee724
index 33cecc687573..272d2f1b5bb8 100644
8ee724
--- a/setup.py
8ee724
+++ b/setup.py
8ee724
@@ -874,21 +874,6 @@ def detect_modules(self):
72be67
                 print ("warning: openssl 0x%08x is too old for _hashlib" %
72be67
                        openssl_ver)
72be67
                 missing.append('_hashlib')
72be67
-        if COMPILED_WITH_PYDEBUG or not have_usable_openssl:
72be67
-            # The _sha module implements the SHA1 hash algorithm.
72be67
-            exts.append( Extension('_sha', ['shamodule.c']) )
72be67
-            # The _md5 module implements the RSA Data Security, Inc. MD5
72be67
-            # Message-Digest Algorithm, described in RFC 1321.  The
72be67
-            # necessary files md5.c and md5.h are included here.
72be67
-            exts.append( Extension('_md5',
72be67
-                            sources = ['md5module.c', 'md5.c'],
72be67
-                            depends = ['md5.h']) )
72be67
-
72be67
-        min_sha2_openssl_ver = 0x00908000
72be67
-        if COMPILED_WITH_PYDEBUG or openssl_ver < min_sha2_openssl_ver:
72be67
-            # OpenSSL doesn't do these until 0.9.8 so we'll bring our own hash
72be67
-            exts.append( Extension('_sha256', ['sha256module.c']) )
72be67
-            exts.append( Extension('_sha512', ['sha512module.c']) )
72be67
 
72be67
         # Modules that provide persistent dictionary-like semantics.  You will
72be67
         # probably want to arrange for at least one of them to be available on
8ee724
8ee724
From e9cd6a63ce17a0120b1d017bf08f05f3ed223bb1 Mon Sep 17 00:00:00 2001
8ee724
From: Petr Viktorin <pviktori@redhat.com>
8ee724
Date: Mon, 2 Sep 2019 18:33:22 +0200
8ee724
Subject: [PATCH 08/11] Allow for errros in pre-created context creation
8ee724
8ee724
---
8ee724
 Modules/_hashopenssl.c | 6 ++++--
8ee724
 1 file changed, 4 insertions(+), 2 deletions(-)
8ee724
8ee724
diff --git a/Modules/_hashopenssl.c b/Modules/_hashopenssl.c
8ee724
index 74f9ab9ec150..7609e9e490f0 100644
8ee724
--- a/Modules/_hashopenssl.c
8ee724
+++ b/Modules/_hashopenssl.c
8ee724
@@ -813,7 +813,7 @@ generate_hash_name_list(void)
8ee724
         )) { \
8ee724
             return NULL; \
8ee724
         } \
8ee724
-        if (usedforsecurity == 0) { \
8ee724
+        if (usedforsecurity == 0 || CONST_new_ ## NAME ## _ctx_p == NULL) { \
8ee724
             ret_obj = EVPnew( \
8ee724
                         CONST_ ## NAME ## _name_obj, \
8ee724
                         EVP_get_digestbyname(#NAME), \
8ee724
@@ -846,7 +846,9 @@ generate_hash_name_list(void)
8ee724
     CONST_ ## NAME ## _name_obj = PyString_FromString(#NAME); \
8ee724
         if (EVP_get_digestbyname(#NAME)) { \
8ee724
             CONST_new_ ## NAME ## _ctx_p = EVP_MD_CTX_new(); \
72be67
-            EVP_DigestInit(CONST_new_ ## NAME ## _ctx_p, EVP_get_digestbyname(#NAME)); \
8ee724
+            if (!EVP_DigestInit(CONST_new_ ## NAME ## _ctx_p, EVP_get_digestbyname(#NAME))) { \
8ee724
+                CONST_new_ ## NAME ## _ctx_p = NULL; \
8ee724
+            } \
8ee724
         } \
8ee724
     } \
72be67
 } while (0);
8ee724
8ee724
From d0465ea1c07f24067b4d6f60f73a29c82f2ad03f Mon Sep 17 00:00:00 2001
8ee724
From: David Malcolm <dmalcolm@redhat.com>
8ee724
Date: Mon, 2 Sep 2019 18:40:08 +0200
8ee724
Subject: [PATCH 09/11] use SHA-256 rather than MD5 in
8ee724
 multiprocessing.connection (patch 169; rhbz#879695)
8ee724
8ee724
---
8ee724
 Lib/multiprocessing/connection.py | 12 ++++++++++--
8ee724
 1 file changed, 10 insertions(+), 2 deletions(-)
8ee724
8ee724
diff --git a/Lib/multiprocessing/connection.py b/Lib/multiprocessing/connection.py
8ee724
index 645a26f069ea..d4dc6ac19d53 100644
8ee724
--- a/Lib/multiprocessing/connection.py
8ee724
+++ b/Lib/multiprocessing/connection.py
8ee724
@@ -56,6 +56,10 @@
8ee724
 # A very generous timeout when it comes to local connections...
8ee724
 CONNECTION_TIMEOUT = 20.
8ee724
 
8ee724
+# The hmac module implicitly defaults to using MD5.
8ee724
+# Support using a stronger algorithm for the challenge/response code:
8ee724
+HMAC_DIGEST_NAME='sha256'
72be67
+
8ee724
 _mmap_counter = itertools.count()
72be67
 
8ee724
 default_family = 'AF_INET'
8ee724
@@ -413,12 +417,16 @@ def PipeClient(address):
8ee724
 WELCOME = b'#WELCOME#'
8ee724
 FAILURE = b'#FAILURE#'
72be67
 
8ee724
+def get_digestmod_for_hmac():
8ee724
+    import hashlib
8ee724
+    return getattr(hashlib, HMAC_DIGEST_NAME)
8ee724
+
8ee724
 def deliver_challenge(connection, authkey):
8ee724
     import hmac
8ee724
     assert isinstance(authkey, bytes)
8ee724
     message = os.urandom(MESSAGE_LENGTH)
8ee724
     connection.send_bytes(CHALLENGE + message)
8ee724
-    digest = hmac.new(authkey, message).digest()
8ee724
+    digest = hmac.new(authkey, message, get_digestmod_for_hmac()).digest()
8ee724
     response = connection.recv_bytes(256)        # reject large message
8ee724
     if response == digest:
8ee724
         connection.send_bytes(WELCOME)
8ee724
@@ -432,7 +440,7 @@ def answer_challenge(connection, authkey):
8ee724
     message = connection.recv_bytes(256)         # reject large message
8ee724
     assert message[:len(CHALLENGE)] == CHALLENGE, 'message = %r' % message
8ee724
     message = message[len(CHALLENGE):]
8ee724
-    digest = hmac.new(authkey, message).digest()
8ee724
+    digest = hmac.new(authkey, message, get_digestmod_for_hmac()).digest()
8ee724
     connection.send_bytes(digest)
8ee724
     response = connection.recv_bytes(256)        # reject large message
8ee724
     if response != WELCOME:
8ee724
8ee724
From 82b181a2c55be0f0766fdf1f0a3e950d22fe0602 Mon Sep 17 00:00:00 2001
8ee724
From: Petr Viktorin <pviktori@redhat.com>
8ee724
Date: Mon, 19 Aug 2019 13:59:40 +0200
8ee724
Subject: [PATCH 10/11] Make uuid.uuid3 work (using libuuid via ctypes)
8ee724
8ee724
---
8ee724
 Lib/uuid.py | 8 ++++++++
8ee724
 1 file changed, 8 insertions(+)
8ee724
8ee724
diff --git a/Lib/uuid.py b/Lib/uuid.py
8ee724
index 80d33c0bd83f..bfb7477b5f58 100644
8ee724
--- a/Lib/uuid.py
8ee724
+++ b/Lib/uuid.py
8ee724
@@ -455,6 +455,7 @@ def _netbios_getnode():
8ee724
 
8ee724
 # If ctypes is available, use it to find system routines for UUID generation.
8ee724
 _uuid_generate_time = _UuidCreate = None
8ee724
+_uuid_generate_md5 = None
8ee724
 try:
8ee724
     import ctypes, ctypes.util
8ee724
     import sys
8ee724
@@ -471,6 +472,8 @@ def _netbios_getnode():
8ee724
             continue
8ee724
         if hasattr(lib, 'uuid_generate_time'):
8ee724
             _uuid_generate_time = lib.uuid_generate_time
8ee724
+            # The library that has uuid_generate_time should have md5 too.
8ee724
+            _uuid_generate_md5 = getattr(lib, 'uuid_generate_md5')
8ee724
             break
8ee724
     del _libnames
8ee724
 
8ee724
@@ -595,6 +598,11 @@ def uuid1(node=None, clock_seq=None):
8ee724
 
8ee724
 def uuid3(namespace, name):
8ee724
     """Generate a UUID from the MD5 hash of a namespace UUID and a name."""
8ee724
+    if _uuid_generate_md5:
8ee724
+        _buffer = ctypes.create_string_buffer(16)
8ee724
+        _uuid_generate_md5(_buffer, namespace.bytes, name, len(name))
8ee724
+        return UUID(bytes=_buffer.raw)
8ee724
+
8ee724
     from hashlib import md5
8ee724
     hash = md5(namespace.bytes + name).digest()
8ee724
     return UUID(bytes=hash[:16], version=3)
8ee724