Blame SOURCES/00146-hashlib-fips.patch

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