Blame SOURCES/00329-fips.patch

93c559
From 0d4515001c99025c024d773f34d3eb97833d0b5d Mon Sep 17 00:00:00 2001
93c559
From: Charalampos Stratakis <cstratak@redhat.com>
93c559
Date: Fri, 29 Jan 2021 14:16:21 +0100
93c559
Subject: [PATCH 01/13] Use python's fall backs for the crypto it implements
93c559
 only if we are not in FIPS mode
93c559
93c559
---
93c559
 Lib/hashlib.py           | 194 +++++++++++++++------------------------
93c559
 Lib/test/test_hashlib.py |   1 +
93c559
 2 files changed, 76 insertions(+), 119 deletions(-)
93c559
93c559
diff --git a/Lib/hashlib.py b/Lib/hashlib.py
93c559
index 58c340d56e3..1fd80c7d4fd 100644
93c559
--- a/Lib/hashlib.py
93c559
+++ b/Lib/hashlib.py
93c559
@@ -68,8 +68,6 @@ __all__ = __always_supported + ('new', 'algorithms_guaranteed',
93c559
                                 'algorithms_available', 'pbkdf2_hmac')
93c559
 
93c559
 
93c559
-__builtin_constructor_cache = {}
93c559
-
93c559
 # Prefer our blake2 implementation
93c559
 # OpenSSL 1.1.0 comes with a limited implementation of blake2b/s. The OpenSSL
93c559
 # implementations neither support keyed blake2 (blake2 MAC) nor advanced
93c559
@@ -79,54 +77,64 @@ __block_openssl_constructor = {
93c559
     'blake2b', 'blake2s',
93c559
 }
93c559
 
93c559
-def __get_builtin_constructor(name):
93c559
-    cache = __builtin_constructor_cache
93c559
-    constructor = cache.get(name)
93c559
-    if constructor is not None:
93c559
-        return constructor
93c559
-    try:
93c559
-        if name in {'SHA1', 'sha1'}:
93c559
-            import _sha1
93c559
-            cache['SHA1'] = cache['sha1'] = _sha1.sha1
93c559
-        elif name in {'MD5', 'md5'}:
93c559
-            import _md5
93c559
-            cache['MD5'] = cache['md5'] = _md5.md5
93c559
-        elif name in {'SHA256', 'sha256', 'SHA224', 'sha224'}:
93c559
-            import _sha256
93c559
-            cache['SHA224'] = cache['sha224'] = _sha256.sha224
93c559
-            cache['SHA256'] = cache['sha256'] = _sha256.sha256
93c559
-        elif name in {'SHA512', 'sha512', 'SHA384', 'sha384'}:
93c559
-            import _sha512
93c559
-            cache['SHA384'] = cache['sha384'] = _sha512.sha384
93c559
-            cache['SHA512'] = cache['sha512'] = _sha512.sha512
93c559
-        elif name in {'blake2b', 'blake2s'}:
93c559
-            import _blake2
93c559
-            cache['blake2b'] = _blake2.blake2b
93c559
-            cache['blake2s'] = _blake2.blake2s
93c559
-        elif name in {'sha3_224', 'sha3_256', 'sha3_384', 'sha3_512'}:
93c559
-            import _sha3
93c559
-            cache['sha3_224'] = _sha3.sha3_224
93c559
-            cache['sha3_256'] = _sha3.sha3_256
93c559
-            cache['sha3_384'] = _sha3.sha3_384
93c559
-            cache['sha3_512'] = _sha3.sha3_512
93c559
-        elif name in {'shake_128', 'shake_256'}:
93c559
-            import _sha3
93c559
-            cache['shake_128'] = _sha3.shake_128
93c559
-            cache['shake_256'] = _sha3.shake_256
93c559
-    except ImportError:
93c559
-        pass  # no extension module, this hash is unsupported.
93c559
-
93c559
-    constructor = cache.get(name)
93c559
-    if constructor is not None:
93c559
-        return constructor
93c559
-
93c559
-    raise ValueError('unsupported hash type ' + name)
93c559
+try:
93c559
+    from _hashlib import get_fips_mode
93c559
+except ImportError:
93c559
+    def get_fips_mode():
93c559
+        return 0
93c559
+
93c559
+if not get_fips_mode():
93c559
+    __builtin_constructor_cache = {}
93c559
+
93c559
+    def __get_builtin_constructor(name):
93c559
+        cache = __builtin_constructor_cache
93c559
+        constructor = cache.get(name)
93c559
+        if constructor is not None:
93c559
+            return constructor
93c559
+        try:
93c559
+            if name in {'SHA1', 'sha1'}:
93c559
+                import _sha1
93c559
+                cache['SHA1'] = cache['sha1'] = _sha1.sha1
93c559
+            elif name in {'MD5', 'md5'}:
93c559
+                import _md5
93c559
+                cache['MD5'] = cache['md5'] = _md5.md5
93c559
+            elif name in {'SHA256', 'sha256', 'SHA224', 'sha224'}:
93c559
+                import _sha256
93c559
+                cache['SHA224'] = cache['sha224'] = _sha256.sha224
93c559
+                cache['SHA256'] = cache['sha256'] = _sha256.sha256
93c559
+            elif name in {'SHA512', 'sha512', 'SHA384', 'sha384'}:
93c559
+                import _sha512
93c559
+                cache['SHA384'] = cache['sha384'] = _sha512.sha384
93c559
+                cache['SHA512'] = cache['sha512'] = _sha512.sha512
93c559
+            elif name in {'blake2b', 'blake2s'}:
93c559
+                import _blake2
93c559
+                cache['blake2b'] = _blake2.blake2b
93c559
+                cache['blake2s'] = _blake2.blake2s
93c559
+            elif name in {'sha3_224', 'sha3_256', 'sha3_384', 'sha3_512'}:
93c559
+                import _sha3
93c559
+                cache['sha3_224'] = _sha3.sha3_224
93c559
+                cache['sha3_256'] = _sha3.sha3_256
93c559
+                cache['sha3_384'] = _sha3.sha3_384
93c559
+                cache['sha3_512'] = _sha3.sha3_512
93c559
+            elif name in {'shake_128', 'shake_256'}:
93c559
+                import _sha3
93c559
+                cache['shake_128'] = _sha3.shake_128
93c559
+                cache['shake_256'] = _sha3.shake_256
93c559
+        except ImportError:
93c559
+            pass  # no extension module, this hash is unsupported.
93c559
+
93c559
+        constructor = cache.get(name)
93c559
+        if constructor is not None:
93c559
+            return constructor
93c559
+
93c559
+        raise ValueError('unsupported hash type ' + name)
93c559
 
93c559
 
93c559
 def __get_openssl_constructor(name):
93c559
-    if name in __block_openssl_constructor:
93c559
-        # Prefer our builtin blake2 implementation.
93c559
-        return __get_builtin_constructor(name)
93c559
+    if not get_fips_mode():
93c559
+        if name in __block_openssl_constructor:
93c559
+            # Prefer our builtin blake2 implementation.
93c559
+            return __get_builtin_constructor(name)
93c559
     try:
93c559
         # MD5, SHA1, and SHA2 are in all supported OpenSSL versions
93c559
         # SHA3/shake are available in OpenSSL 1.1.1+
93c559
@@ -141,21 +149,23 @@ def __get_openssl_constructor(name):
93c559
         return __get_builtin_constructor(name)
93c559
 
93c559
 
93c559
-def __py_new(name, data=b'', **kwargs):
93c559
-    """new(name, data=b'', **kwargs) - Return a new hashing object using the
93c559
-    named algorithm; optionally initialized with data (which must be
93c559
-    a bytes-like object).
93c559
-    """
93c559
-    return __get_builtin_constructor(name)(data, **kwargs)
93c559
+if not get_fips_mode():
93c559
+    def __py_new(name, data=b'', **kwargs):
93c559
+        """new(name, data=b'', **kwargs) - Return a new hashing object using the
93c559
+        named algorithm; optionally initialized with data (which must be
93c559
+        a bytes-like object).
93c559
+        """
93c559
+        return __get_builtin_constructor(name)(data, **kwargs)
93c559
 
93c559
 
93c559
 def __hash_new(name, data=b'', **kwargs):
93c559
     """new(name, data=b'') - Return a new hashing object using the named algorithm;
93c559
     optionally initialized with data (which must be a bytes-like object).
93c559
     """
93c559
-    if name in __block_openssl_constructor:
93c559
-        # Prefer our builtin blake2 implementation.
93c559
-        return __get_builtin_constructor(name)(data, **kwargs)
93c559
+    if not get_fips_mode():
93c559
+        if name in __block_openssl_constructor:
93c559
+            # Prefer our builtin blake2 implementation.
93c559
+            return __get_builtin_constructor(name)(data, **kwargs)
93c559
     try:
93c559
         return _hashlib.new(name, data, **kwargs)
93c559
     except ValueError:
93c559
@@ -163,6 +173,8 @@ def __hash_new(name, data=b'', **kwargs):
93c559
         # hash, try using our builtin implementations.
93c559
         # This allows for SHA224/256 and SHA384/512 support even though
93c559
         # the OpenSSL library prior to 0.9.8 doesn't provide them.
93c559
+        if get_fips_mode():
93c559
+            raise
93c559
         return __get_builtin_constructor(name)(data)
93c559
 
93c559
 
93c559
@@ -173,72 +185,14 @@ try:
93c559
     algorithms_available = algorithms_available.union(
93c559
             _hashlib.openssl_md_meth_names)
93c559
 except ImportError:
93c559
+    if get_fips_mode:
93c559
+        raise
93c559
     new = __py_new
93c559
     __get_hash = __get_builtin_constructor
93c559
 
93c559
-try:
93c559
-    # OpenSSL's PKCS5_PBKDF2_HMAC requires OpenSSL 1.0+ with HMAC and SHA
93c559
-    from _hashlib import pbkdf2_hmac
93c559
-except ImportError:
93c559
-    _trans_5C = bytes((x ^ 0x5C) for x in range(256))
93c559
-    _trans_36 = bytes((x ^ 0x36) for x in range(256))
93c559
-
93c559
-    def pbkdf2_hmac(hash_name, password, salt, iterations, dklen=None):
93c559
-        """Password based key derivation function 2 (PKCS #5 v2.0)
93c559
 
93c559
-        This Python implementations based on the hmac module about as fast
93c559
-        as OpenSSL's PKCS5_PBKDF2_HMAC for short passwords and much faster
93c559
-        for long passwords.
93c559
-        """
93c559
-        if not isinstance(hash_name, str):
93c559
-            raise TypeError(hash_name)
93c559
-
93c559
-        if not isinstance(password, (bytes, bytearray)):
93c559
-            password = bytes(memoryview(password))
93c559
-        if not isinstance(salt, (bytes, bytearray)):
93c559
-            salt = bytes(memoryview(salt))
93c559
-
93c559
-        # Fast inline HMAC implementation
93c559
-        inner = new(hash_name)
93c559
-        outer = new(hash_name)
93c559
-        blocksize = getattr(inner, 'block_size', 64)
93c559
-        if len(password) > blocksize:
93c559
-            password = new(hash_name, password).digest()
93c559
-        password = password + b'\x00' * (blocksize - len(password))
93c559
-        inner.update(password.translate(_trans_36))
93c559
-        outer.update(password.translate(_trans_5C))
93c559
-
93c559
-        def prf(msg, inner=inner, outer=outer):
93c559
-            # PBKDF2_HMAC uses the password as key. We can re-use the same
93c559
-            # digest objects and just update copies to skip initialization.
93c559
-            icpy = inner.copy()
93c559
-            ocpy = outer.copy()
93c559
-            icpy.update(msg)
93c559
-            ocpy.update(icpy.digest())
93c559
-            return ocpy.digest()
93c559
-
93c559
-        if iterations < 1:
93c559
-            raise ValueError(iterations)
93c559
-        if dklen is None:
93c559
-            dklen = outer.digest_size
93c559
-        if dklen < 1:
93c559
-            raise ValueError(dklen)
93c559
-
93c559
-        dkey = b''
93c559
-        loop = 1
93c559
-        from_bytes = int.from_bytes
93c559
-        while len(dkey) < dklen:
93c559
-            prev = prf(salt + loop.to_bytes(4, 'big'))
93c559
-            # endianness doesn't matter here as long to / from use the same
93c559
-            rkey = int.from_bytes(prev, 'big')
93c559
-            for i in range(iterations - 1):
93c559
-                prev = prf(prev)
93c559
-                # rkey = rkey ^ prev
93c559
-                rkey ^= from_bytes(prev, 'big')
93c559
-            loop += 1
93c559
-            dkey += rkey.to_bytes(inner.digest_size, 'big')
93c559
-
93c559
-        return dkey[:dklen]
93c559
+# OpenSSL's PKCS5_PBKDF2_HMAC requires OpenSSL 1.0+ with HMAC and SHA
93c559
+from _hashlib import pbkdf2_hmac
93c559
 
93c559
 try:
93c559
     # OpenSSL's scrypt requires OpenSSL 1.1+
93c559
@@ -259,4 +213,6 @@ for __func_name in __always_supported:
93c559
 
93c559
 # Cleanup locals()
93c559
 del __always_supported, __func_name, __get_hash
93c559
-del __py_new, __hash_new, __get_openssl_constructor
93c559
+del __hash_new, __get_openssl_constructor
93c559
+if not get_fips_mode():
93c559
+    del __py_new
93c559
diff --git a/Lib/test/test_hashlib.py b/Lib/test/test_hashlib.py
93c559
index 86f31a55878..8235505092b 100644
93c559
--- a/Lib/test/test_hashlib.py
93c559
+++ b/Lib/test/test_hashlib.py
93c559
@@ -1039,6 +1039,7 @@ class KDFTests(unittest.TestCase):
93c559
                 iterations=1, dklen=None)
93c559
             self.assertEqual(out, self.pbkdf2_results['sha1'][0][0])
93c559
 
93c559
+    @unittest.skip("The python implementation of pbkdf2_hmac has been removed")
93c559
     @unittest.skipIf(builtin_hashlib is None, "test requires builtin_hashlib")
93c559
     def test_pbkdf2_hmac_py(self):
93c559
         self._test_pbkdf2_hmac(builtin_hashlib.pbkdf2_hmac, builtin_hashes)
93c559
-- 
93c559
2.26.2
93c559
93c559
93c559
From 8a174c9a8d4180a5a7b19f4419b98c63b91b13ab Mon Sep 17 00:00:00 2001
93c559
From: Petr Viktorin <pviktori@redhat.com>
93c559
Date: Thu, 25 Jul 2019 17:19:06 +0200
93c559
Subject: [PATCH 02/13] Disable Python's hash implementations in FIPS mode,
93c559
 forcing OpenSSL
93c559
93c559
---
93c559
 Include/_hashopenssl.h         | 66 ++++++++++++++++++++++++++++++++++
93c559
 Modules/_blake2/blake2b_impl.c |  5 +++
93c559
 Modules/_blake2/blake2module.c |  3 ++
93c559
 Modules/_blake2/blake2s_impl.c |  5 +++
93c559
 Modules/_hashopenssl.c         | 35 +-----------------
93c559
 setup.py                       | 28 ++++++++++-----
93c559
 6 files changed, 99 insertions(+), 43 deletions(-)
93c559
 create mode 100644 Include/_hashopenssl.h
93c559
93c559
diff --git a/Include/_hashopenssl.h b/Include/_hashopenssl.h
93c559
new file mode 100644
93c559
index 00000000000..a726c0d3fbf
93c559
--- /dev/null
93c559
+++ b/Include/_hashopenssl.h
93c559
@@ -0,0 +1,66 @@
93c559
+#ifndef Py_HASHOPENSSL_H
93c559
+#define Py_HASHOPENSSL_H
93c559
+
93c559
+#include "Python.h"
93c559
+#include <openssl/crypto.h>
93c559
+#include <openssl/err.h>
93c559
+
93c559
+/* LCOV_EXCL_START */
93c559
+static PyObject *
93c559
+_setException(PyObject *exc)
93c559
+{
93c559
+    unsigned long errcode;
93c559
+    const char *lib, *func, *reason;
93c559
+
93c559
+    errcode = ERR_peek_last_error();
93c559
+    if (!errcode) {
93c559
+        PyErr_SetString(exc, "unknown reasons");
93c559
+        return NULL;
93c559
+    }
93c559
+    ERR_clear_error();
93c559
+
93c559
+    lib = ERR_lib_error_string(errcode);
93c559
+    func = ERR_func_error_string(errcode);
93c559
+    reason = ERR_reason_error_string(errcode);
93c559
+
93c559
+    if (lib && func) {
93c559
+        PyErr_Format(exc, "[%s: %s] %s", lib, func, reason);
93c559
+    }
93c559
+    else if (lib) {
93c559
+        PyErr_Format(exc, "[%s] %s", lib, reason);
93c559
+    }
93c559
+    else {
93c559
+        PyErr_SetString(exc, reason);
93c559
+    }
93c559
+    return NULL;
93c559
+}
93c559
+/* LCOV_EXCL_STOP */
93c559
+
93c559
+
93c559
+__attribute__((__unused__))
93c559
+static int
93c559
+_Py_hashlib_fips_error(char *name) {
93c559
+    int result = FIPS_mode();
93c559
+    if (result == 0) {
93c559
+        // "If the library was built without support of the FIPS Object Module,
93c559
+        // then the function will return 0 with an error code of
93c559
+        // CRYPTO_R_FIPS_MODE_NOT_SUPPORTED (0x0f06d065)."
93c559
+        // But 0 is also a valid result value.
93c559
+
93c559
+        unsigned long errcode = ERR_peek_last_error();
93c559
+        if (errcode) {
93c559
+            _setException(PyExc_ValueError);
93c559
+            return 1;
93c559
+        }
93c559
+        return 0;
93c559
+    }
93c559
+    PyErr_Format(PyExc_ValueError, "%s is not available in FIPS mode",
93c559
+                 name);
93c559
+    return 1;
93c559
+}
93c559
+
93c559
+#define FAIL_RETURN_IN_FIPS_MODE(name) do { \
93c559
+    if (_Py_hashlib_fips_error(name)) return NULL; \
93c559
+} while (0)
93c559
+
93c559
+#endif  // !Py_HASHOPENSSL_H
93c559
diff --git a/Modules/_blake2/blake2b_impl.c b/Modules/_blake2/blake2b_impl.c
93c559
index 7fb1296f8b2..67620afcad2 100644
93c559
--- a/Modules/_blake2/blake2b_impl.c
93c559
+++ b/Modules/_blake2/blake2b_impl.c
93c559
@@ -14,6 +14,7 @@
93c559
  */
93c559
 
93c559
 #include "Python.h"
93c559
+#include "_hashopenssl.h"
93c559
 #include "pystrhex.h"
93c559
 
93c559
 #include "../hashlib.h"
93c559
@@ -96,6 +97,8 @@ py_blake2b_new_impl(PyTypeObject *type, PyObject *data, int digest_size,
93c559
     BLAKE2bObject *self = NULL;
93c559
     Py_buffer buf;
93c559
 
93c559
+    FAIL_RETURN_IN_FIPS_MODE("_blake2");
93c559
+
93c559
     self = new_BLAKE2bObject(type);
93c559
     if (self == NULL) {
93c559
         goto error;
93c559
@@ -274,6 +277,8 @@ _blake2_blake2b_update(BLAKE2bObject *self, PyObject *data)
93c559
 {
93c559
     Py_buffer buf;
93c559
 
93c559
+    FAIL_RETURN_IN_FIPS_MODE("_blake2");
93c559
+
93c559
     GET_BUFFER_VIEW_OR_ERROUT(data, &buf;;
93c559
 
93c559
     if (self->lock == NULL && buf.len >= HASHLIB_GIL_MINSIZE)
93c559
diff --git a/Modules/_blake2/blake2module.c b/Modules/_blake2/blake2module.c
93c559
index ff142c9f3ed..bc67529cb5e 100644
93c559
--- a/Modules/_blake2/blake2module.c
93c559
+++ b/Modules/_blake2/blake2module.c
93c559
@@ -9,6 +9,7 @@
93c559
  */
93c559
 
93c559
 #include "Python.h"
93c559
+#include "_hashopenssl.h"
93c559
 
93c559
 #include "impl/blake2.h"
93c559
 
93c559
@@ -57,6 +58,8 @@ PyInit__blake2(void)
93c559
     PyObject *m;
93c559
     PyObject *d;
93c559
 
93c559
+    FAIL_RETURN_IN_FIPS_MODE("blake2");
93c559
+
93c559
     m = PyModule_Create(&blake2_module);
93c559
     if (m == NULL)
93c559
         return NULL;
93c559
diff --git a/Modules/_blake2/blake2s_impl.c b/Modules/_blake2/blake2s_impl.c
93c559
index e3e90d0587b..57c0f3fcbd7 100644
93c559
--- a/Modules/_blake2/blake2s_impl.c
93c559
+++ b/Modules/_blake2/blake2s_impl.c
93c559
@@ -14,6 +14,7 @@
93c559
  */
93c559
 
93c559
 #include "Python.h"
93c559
+#include "_hashopenssl.h"
93c559
 #include "pystrhex.h"
93c559
 
93c559
 #include "../hashlib.h"
93c559
@@ -96,6 +97,8 @@ py_blake2s_new_impl(PyTypeObject *type, PyObject *data, int digest_size,
93c559
     BLAKE2sObject *self = NULL;
93c559
     Py_buffer buf;
93c559
 
93c559
+    FAIL_RETURN_IN_FIPS_MODE("_blake2");
93c559
+
93c559
     self = new_BLAKE2sObject(type);
93c559
     if (self == NULL) {
93c559
         goto error;
93c559
@@ -274,6 +277,8 @@ _blake2_blake2s_update(BLAKE2sObject *self, PyObject *data)
93c559
 {
93c559
     Py_buffer buf;
93c559
 
93c559
+    FAIL_RETURN_IN_FIPS_MODE("_blake2");
93c559
+
93c559
     GET_BUFFER_VIEW_OR_ERROUT(data, &buf;;
93c559
 
93c559
     if (self->lock == NULL && buf.len >= HASHLIB_GIL_MINSIZE)
93c559
diff --git a/Modules/_hashopenssl.c b/Modules/_hashopenssl.c
93c559
index adc86537732..deecc077ef8 100644
93c559
--- a/Modules/_hashopenssl.c
93c559
+++ b/Modules/_hashopenssl.c
93c559
@@ -16,6 +16,7 @@
93c559
 #include "Python.h"
93c559
 #include "hashlib.h"
93c559
 #include "pystrhex.h"
93c559
+#include "_hashopenssl.h"
93c559
 
93c559
 
93c559
 /* EVP is the preferred interface to hashing in OpenSSL */
93c559
@@ -24,9 +25,6 @@
93c559
 #include <openssl/crypto.h>
93c559
 /* We use the object interface to discover what hashes OpenSSL supports. */
93c559
 #include <openssl/objects.h>
93c559
-#include "openssl/err.h"
93c559
-
93c559
-#include <openssl/crypto.h>       // FIPS_mode()
93c559
 
93c559
 #ifndef OPENSSL_THREADS
93c559
 #  error "OPENSSL_THREADS is not defined, Python requires thread-safe OpenSSL"
93c559
@@ -118,37 +116,6 @@ class _hashlib.HMAC "HMACobject *" "((_hashlibstate *)PyModule_GetState(module))
93c559
 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=7df1bcf6f75cb8ef]*/
93c559
 
93c559
 
93c559
-/* LCOV_EXCL_START */
93c559
-static PyObject *
93c559
-_setException(PyObject *exc)
93c559
-{
93c559
-    unsigned long errcode;
93c559
-    const char *lib, *func, *reason;
93c559
-
93c559
-    errcode = ERR_peek_last_error();
93c559
-    if (!errcode) {
93c559
-        PyErr_SetString(exc, "unknown reasons");
93c559
-        return NULL;
93c559
-    }
93c559
-    ERR_clear_error();
93c559
-
93c559
-    lib = ERR_lib_error_string(errcode);
93c559
-    func = ERR_func_error_string(errcode);
93c559
-    reason = ERR_reason_error_string(errcode);
93c559
-
93c559
-    if (lib && func) {
93c559
-        PyErr_Format(exc, "[%s: %s] %s", lib, func, reason);
93c559
-    }
93c559
-    else if (lib) {
93c559
-        PyErr_Format(exc, "[%s] %s", lib, reason);
93c559
-    }
93c559
-    else {
93c559
-        PyErr_SetString(exc, reason);
93c559
-    }
93c559
-    return NULL;
93c559
-}
93c559
-/* LCOV_EXCL_STOP */
93c559
-
93c559
 /* {Py_tp_new, NULL} doesn't block __new__ */
93c559
 static PyObject *
93c559
 _disabled_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
93c559
diff --git a/setup.py b/setup.py
93c559
index bd5f7369244..89edbb627fa 100644
93c559
--- a/setup.py
93c559
+++ b/setup.py
93c559
@@ -2306,7 +2306,7 @@ class PyBuildExt(build_ext):
93c559
                            sources=sources,
93c559
                            depends=depends))
93c559
 
93c559
-    def detect_openssl_hashlib(self):
93c559
+    def detect_openssl_args(self):
93c559
         # Detect SSL support for the socket module (via _ssl)
93c559
         config_vars = sysconfig.get_config_vars()
93c559
 
93c559
@@ -2327,7 +2327,7 @@ class PyBuildExt(build_ext):
93c559
         if not openssl_libs:
93c559
             # libssl and libcrypto not found
93c559
             self.missing.extend(['_ssl', '_hashlib'])
93c559
-            return None, None
93c559
+            raise ValueError('Cannot build for RHEL without OpenSSL')
93c559
 
93c559
         # Find OpenSSL includes
93c559
         ssl_incs = find_file(
93c559
@@ -2335,7 +2335,7 @@ class PyBuildExt(build_ext):
93c559
         )
93c559
         if ssl_incs is None:
93c559
             self.missing.extend(['_ssl', '_hashlib'])
93c559
-            return None, None
93c559
+            raise ValueError('Cannot build for RHEL without OpenSSL')
93c559
 
93c559
         # OpenSSL 1.0.2 uses Kerberos for KRB5 ciphers
93c559
         krb5_h = find_file(
93c559
@@ -2345,12 +2345,23 @@ class PyBuildExt(build_ext):
93c559
         if krb5_h:
93c559
             ssl_incs.extend(krb5_h)
93c559
 
93c559
+
93c559
+        ssl_args = {
93c559
+            'include_dirs': openssl_includes,
93c559
+            'library_dirs': openssl_libdirs,
93c559
+            'libraries': ['ssl', 'crypto'],
93c559
+        }
93c559
+
93c559
+        return ssl_args
93c559
+
93c559
+    def detect_openssl_hashlib(self):
93c559
+
93c559
+        config_vars = sysconfig.get_config_vars()
93c559
+
93c559
         if config_vars.get("HAVE_X509_VERIFY_PARAM_SET1_HOST"):
93c559
             self.add(Extension(
93c559
                 '_ssl', ['_ssl.c'],
93c559
-                include_dirs=openssl_includes,
93c559
-                library_dirs=openssl_libdirs,
93c559
-                libraries=openssl_libs,
93c559
+                **self.detect_openssl_args(),
93c559
                 depends=['socketmodule.h', '_ssl/debughelpers.c'])
93c559
             )
93c559
         else:
93c559
@@ -2358,9 +2369,7 @@ class PyBuildExt(build_ext):
93c559
 
93c559
         self.add(Extension('_hashlib', ['_hashopenssl.c'],
93c559
                            depends=['hashlib.h'],
93c559
-                           include_dirs=openssl_includes,
93c559
-                           library_dirs=openssl_libdirs,
93c559
-                           libraries=openssl_libs))
93c559
+                           **self.detect_openssl_args()) )
93c559
 
93c559
     def detect_hash_builtins(self):
93c559
         # By default we always compile these even when OpenSSL is available
93c559
@@ -2417,6 +2426,7 @@ class PyBuildExt(build_ext):
93c559
                     '_blake2/blake2b_impl.c',
93c559
                     '_blake2/blake2s_impl.c'
93c559
                 ],
93c559
+                **self.detect_openssl_args(),
93c559
                 depends=blake2_deps
93c559
             ))
93c559
 
93c559
-- 
93c559
2.26.2
93c559
93c559
93c559
From 56171083467bd5798adcb1946cfc0b1d68403755 Mon Sep 17 00:00:00 2001
93c559
From: Charalampos Stratakis <cstratak@redhat.com>
93c559
Date: Thu, 12 Dec 2019 16:58:31 +0100
93c559
Subject: [PATCH 03/13] Expose all hashes available to OpenSSL
93c559
93c559
---
93c559
 Include/_hashopenssl.h          |  11 ++--
93c559
 Modules/_blake2/blake2b_impl.c  |   4 +-
93c559
 Modules/_blake2/blake2module.c  |   2 +-
93c559
 Modules/_blake2/blake2s_impl.c  |   4 +-
93c559
 Modules/_hashopenssl.c          |  43 +++++++++++++
93c559
 Modules/clinic/_hashopenssl.c.h | 106 +++++++++++++++++++++++++++++++-
93c559
 6 files changed, 158 insertions(+), 12 deletions(-)
93c559
93c559
diff --git a/Include/_hashopenssl.h b/Include/_hashopenssl.h
93c559
index a726c0d3fbf..47ed0030422 100644
93c559
--- a/Include/_hashopenssl.h
93c559
+++ b/Include/_hashopenssl.h
93c559
@@ -39,7 +39,7 @@ _setException(PyObject *exc)
93c559
 
93c559
 __attribute__((__unused__))
93c559
 static int
93c559
-_Py_hashlib_fips_error(char *name) {
93c559
+_Py_hashlib_fips_error(PyObject *exc, char *name) {
93c559
     int result = FIPS_mode();
93c559
     if (result == 0) {
93c559
         // "If the library was built without support of the FIPS Object Module,
93c559
@@ -49,18 +49,17 @@ _Py_hashlib_fips_error(char *name) {
93c559
 
93c559
         unsigned long errcode = ERR_peek_last_error();
93c559
         if (errcode) {
93c559
-            _setException(PyExc_ValueError);
93c559
+            _setException(exc);
93c559
             return 1;
93c559
         }
93c559
         return 0;
93c559
     }
93c559
-    PyErr_Format(PyExc_ValueError, "%s is not available in FIPS mode",
93c559
-                 name);
93c559
+    PyErr_Format(exc, "%s is not available in FIPS mode", name);
93c559
     return 1;
93c559
 }
93c559
 
93c559
-#define FAIL_RETURN_IN_FIPS_MODE(name) do { \
93c559
-    if (_Py_hashlib_fips_error(name)) return NULL; \
93c559
+#define FAIL_RETURN_IN_FIPS_MODE(exc, name) do { \
93c559
+    if (_Py_hashlib_fips_error(exc, name)) return NULL; \
93c559
 } while (0)
93c559
 
93c559
 #endif  // !Py_HASHOPENSSL_H
93c559
diff --git a/Modules/_blake2/blake2b_impl.c b/Modules/_blake2/blake2b_impl.c
93c559
index 67620afcad2..9e125dcbf43 100644
93c559
--- a/Modules/_blake2/blake2b_impl.c
93c559
+++ b/Modules/_blake2/blake2b_impl.c
93c559
@@ -97,7 +97,7 @@ py_blake2b_new_impl(PyTypeObject *type, PyObject *data, int digest_size,
93c559
     BLAKE2bObject *self = NULL;
93c559
     Py_buffer buf;
93c559
 
93c559
-    FAIL_RETURN_IN_FIPS_MODE("_blake2");
93c559
+    FAIL_RETURN_IN_FIPS_MODE(PyExc_ValueError, "_blake2");
93c559
 
93c559
     self = new_BLAKE2bObject(type);
93c559
     if (self == NULL) {
93c559
@@ -277,7 +277,7 @@ _blake2_blake2b_update(BLAKE2bObject *self, PyObject *data)
93c559
 {
93c559
     Py_buffer buf;
93c559
 
93c559
-    FAIL_RETURN_IN_FIPS_MODE("_blake2");
93c559
+    FAIL_RETURN_IN_FIPS_MODE(PyExc_ValueError, "_blake2");
93c559
 
93c559
     GET_BUFFER_VIEW_OR_ERROUT(data, &buf;;
93c559
 
93c559
diff --git a/Modules/_blake2/blake2module.c b/Modules/_blake2/blake2module.c
93c559
index bc67529cb5e..79a9eed5c13 100644
93c559
--- a/Modules/_blake2/blake2module.c
93c559
+++ b/Modules/_blake2/blake2module.c
93c559
@@ -58,7 +58,7 @@ PyInit__blake2(void)
93c559
     PyObject *m;
93c559
     PyObject *d;
93c559
 
93c559
-    FAIL_RETURN_IN_FIPS_MODE("blake2");
93c559
+    FAIL_RETURN_IN_FIPS_MODE(PyExc_ImportError, "blake2");
93c559
 
93c559
     m = PyModule_Create(&blake2_module);
93c559
     if (m == NULL)
93c559
diff --git a/Modules/_blake2/blake2s_impl.c b/Modules/_blake2/blake2s_impl.c
93c559
index 57c0f3fcbd7..b59624d7d98 100644
93c559
--- a/Modules/_blake2/blake2s_impl.c
93c559
+++ b/Modules/_blake2/blake2s_impl.c
93c559
@@ -97,7 +97,7 @@ py_blake2s_new_impl(PyTypeObject *type, PyObject *data, int digest_size,
93c559
     BLAKE2sObject *self = NULL;
93c559
     Py_buffer buf;
93c559
 
93c559
-    FAIL_RETURN_IN_FIPS_MODE("_blake2");
93c559
+    FAIL_RETURN_IN_FIPS_MODE(PyExc_ValueError, "_blake2");
93c559
 
93c559
     self = new_BLAKE2sObject(type);
93c559
     if (self == NULL) {
93c559
@@ -277,7 +277,7 @@ _blake2_blake2s_update(BLAKE2sObject *self, PyObject *data)
93c559
 {
93c559
     Py_buffer buf;
93c559
 
93c559
-    FAIL_RETURN_IN_FIPS_MODE("_blake2");
93c559
+    FAIL_RETURN_IN_FIPS_MODE(PyExc_ValueError, "_blake2");
93c559
 
93c559
     GET_BUFFER_VIEW_OR_ERROUT(data, &buf;;
93c559
 
93c559
diff --git a/Modules/_hashopenssl.c b/Modules/_hashopenssl.c
93c559
index deecc077ef8..a805183721b 100644
93c559
--- a/Modules/_hashopenssl.c
93c559
+++ b/Modules/_hashopenssl.c
93c559
@@ -253,6 +253,12 @@ py_digest_by_name(const char *name)
93c559
         else if (!strcmp(name, "blake2b512")) {
93c559
             digest = EVP_blake2b512();
93c559
         }
93c559
+        else if (!strcmp(name, "blake2s")) {
93c559
+            digest = EVP_blake2s256();
93c559
+        }
93c559
+        else if (!strcmp(name, "blake2b")) {
93c559
+            digest = EVP_blake2b512();
93c559
+        }
93c559
 #endif
93c559
     }
93c559
 
93c559
@@ -946,6 +952,41 @@ _hashlib_openssl_sha512_impl(PyObject *module, PyObject *data_obj,
93c559
 }
93c559
 
93c559
 
93c559
+/*[clinic input]
93c559
+_hashlib.openssl_blake2b
93c559
+    string as data_obj: object(py_default="b''") = NULL
93c559
+    *
93c559
+    usedforsecurity: bool = True
93c559
+Returns a blake2b hash object; optionally initialized with a string
93c559
+[clinic start generated code]*/
93c559
+
93c559
+static PyObject *
93c559
+_hashlib_openssl_blake2b_impl(PyObject *module, PyObject *data_obj,
93c559
+                              int usedforsecurity)
93c559
+/*[clinic end generated code: output=7a838b1643cde13e input=4ad7fd54268f3689]*/
93c559
+
93c559
+{
93c559
+    return EVP_fast_new(module, data_obj, EVP_blake2b512(), usedforsecurity);
93c559
+}
93c559
+
93c559
+/*[clinic input]
93c559
+_hashlib.openssl_blake2s
93c559
+    string as data_obj: object(py_default="b''") = NULL
93c559
+    *
93c559
+    usedforsecurity: bool = True
93c559
+Returns a blake2s hash object; optionally initialized with a string
93c559
+[clinic start generated code]*/
93c559
+
93c559
+static PyObject *
93c559
+_hashlib_openssl_blake2s_impl(PyObject *module, PyObject *data_obj,
93c559
+                              int usedforsecurity)
93c559
+/*[clinic end generated code: output=4eda6b40757471da input=1ed39481ffa4e26a]*/
93c559
+
93c559
+{
93c559
+    return EVP_fast_new(module, data_obj, EVP_blake2s256(), usedforsecurity);
93c559
+}
93c559
+
93c559
+
93c559
 #ifdef PY_OPENSSL_HAS_SHA3
93c559
 
93c559
 /*[clinic input]
93c559
@@ -1931,6 +1972,8 @@ static struct PyMethodDef EVP_functions[] = {
93c559
     _HASHLIB_OPENSSL_SHA256_METHODDEF
93c559
     _HASHLIB_OPENSSL_SHA384_METHODDEF
93c559
     _HASHLIB_OPENSSL_SHA512_METHODDEF
93c559
+    _HASHLIB_OPENSSL_BLAKE2B_METHODDEF
93c559
+    _HASHLIB_OPENSSL_BLAKE2S_METHODDEF
93c559
     _HASHLIB_OPENSSL_SHA3_224_METHODDEF
93c559
     _HASHLIB_OPENSSL_SHA3_256_METHODDEF
93c559
     _HASHLIB_OPENSSL_SHA3_384_METHODDEF
93c559
diff --git a/Modules/clinic/_hashopenssl.c.h b/Modules/clinic/_hashopenssl.c.h
93c559
index 68aa765e529..2957ae2e135 100644
93c559
--- a/Modules/clinic/_hashopenssl.c.h
93c559
+++ b/Modules/clinic/_hashopenssl.c.h
93c559
@@ -540,6 +540,110 @@ exit:
93c559
     return return_value;
93c559
 }
93c559
 
93c559
+PyDoc_STRVAR(_hashlib_openssl_blake2b__doc__,
93c559
+"openssl_blake2b($module, /, string=b\'\', *, usedforsecurity=True)\n"
93c559
+"--\n"
93c559
+"\n"
93c559
+"Returns a blake2b hash object; optionally initialized with a string");
93c559
+
93c559
+#define _HASHLIB_OPENSSL_BLAKE2B_METHODDEF    \
93c559
+    {"openssl_blake2b", (PyCFunction)(void(*)(void))_hashlib_openssl_blake2b, METH_FASTCALL|METH_KEYWORDS, _hashlib_openssl_blake2b__doc__},
93c559
+
93c559
+static PyObject *
93c559
+_hashlib_openssl_blake2b_impl(PyObject *module, PyObject *data_obj,
93c559
+                              int usedforsecurity);
93c559
+
93c559
+static PyObject *
93c559
+_hashlib_openssl_blake2b(PyObject *module, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
93c559
+{
93c559
+    PyObject *return_value = NULL;
93c559
+    static const char * const _keywords[] = {"string", "usedforsecurity", NULL};
93c559
+    static _PyArg_Parser _parser = {NULL, _keywords, "openssl_blake2b", 0};
93c559
+    PyObject *argsbuf[2];
93c559
+    Py_ssize_t noptargs = nargs + (kwnames ? PyTuple_GET_SIZE(kwnames) : 0) - 0;
93c559
+    PyObject *data_obj = NULL;
93c559
+    int usedforsecurity = 1;
93c559
+
93c559
+    args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser, 0, 1, 0, argsbuf);
93c559
+    if (!args) {
93c559
+        goto exit;
93c559
+    }
93c559
+    if (!noptargs) {
93c559
+        goto skip_optional_pos;
93c559
+    }
93c559
+    if (args[0]) {
93c559
+        data_obj = args[0];
93c559
+        if (!--noptargs) {
93c559
+            goto skip_optional_pos;
93c559
+        }
93c559
+    }
93c559
+skip_optional_pos:
93c559
+    if (!noptargs) {
93c559
+        goto skip_optional_kwonly;
93c559
+    }
93c559
+    usedforsecurity = PyObject_IsTrue(args[1]);
93c559
+    if (usedforsecurity < 0) {
93c559
+        goto exit;
93c559
+    }
93c559
+skip_optional_kwonly:
93c559
+    return_value = _hashlib_openssl_blake2b_impl(module, data_obj, usedforsecurity);
93c559
+
93c559
+exit:
93c559
+    return return_value;
93c559
+}
93c559
+
93c559
+PyDoc_STRVAR(_hashlib_openssl_blake2s__doc__,
93c559
+"openssl_blake2s($module, /, string=b\'\', *, usedforsecurity=True)\n"
93c559
+"--\n"
93c559
+"\n"
93c559
+"Returns a blake2s hash object; optionally initialized with a string");
93c559
+
93c559
+#define _HASHLIB_OPENSSL_BLAKE2S_METHODDEF    \
93c559
+    {"openssl_blake2s", (PyCFunction)(void(*)(void))_hashlib_openssl_blake2s, METH_FASTCALL|METH_KEYWORDS, _hashlib_openssl_blake2s__doc__},
93c559
+
93c559
+static PyObject *
93c559
+_hashlib_openssl_blake2s_impl(PyObject *module, PyObject *data_obj,
93c559
+                              int usedforsecurity);
93c559
+
93c559
+static PyObject *
93c559
+_hashlib_openssl_blake2s(PyObject *module, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
93c559
+{
93c559
+    PyObject *return_value = NULL;
93c559
+    static const char * const _keywords[] = {"string", "usedforsecurity", NULL};
93c559
+    static _PyArg_Parser _parser = {NULL, _keywords, "openssl_blake2s", 0};
93c559
+    PyObject *argsbuf[2];
93c559
+    Py_ssize_t noptargs = nargs + (kwnames ? PyTuple_GET_SIZE(kwnames) : 0) - 0;
93c559
+    PyObject *data_obj = NULL;
93c559
+    int usedforsecurity = 1;
93c559
+
93c559
+    args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser, 0, 1, 0, argsbuf);
93c559
+    if (!args) {
93c559
+        goto exit;
93c559
+    }
93c559
+    if (!noptargs) {
93c559
+        goto skip_optional_pos;
93c559
+    }
93c559
+    if (args[0]) {
93c559
+        data_obj = args[0];
93c559
+        if (!--noptargs) {
93c559
+            goto skip_optional_pos;
93c559
+        }
93c559
+    }
93c559
+skip_optional_pos:
93c559
+    if (!noptargs) {
93c559
+        goto skip_optional_kwonly;
93c559
+    }
93c559
+    usedforsecurity = PyObject_IsTrue(args[1]);
93c559
+    if (usedforsecurity < 0) {
93c559
+        goto exit;
93c559
+    }
93c559
+skip_optional_kwonly:
93c559
+    return_value = _hashlib_openssl_blake2s_impl(module, data_obj, usedforsecurity);
93c559
+
93c559
+exit:
93c559
+    return return_value;
93c559
+}
93c559
+
93c559
 #if defined(PY_OPENSSL_HAS_SHA3)
93c559
 
93c559
 PyDoc_STRVAR(_hashlib_openssl_sha3_224__doc__,
93c559
@@ -1442,4 +1546,4 @@ exit:
93c559
 #ifndef _HASHLIB_GET_FIPS_MODE_METHODDEF
93c559
     #define _HASHLIB_GET_FIPS_MODE_METHODDEF
93c559
 #endif /* !defined(_HASHLIB_GET_FIPS_MODE_METHODDEF) */
93c559
-/*[clinic end generated code: output=b6b280e46bf0b139 input=a9049054013a1b77]*/
93c559
+/*[clinic end generated code: output=4f8cc45bf0337f8e input=a9049054013a1b77]*/
93c559
-- 
93c559
2.26.2
93c559
93c559
93c559
From e024cae691bffa2d093a63f8e2058331fce94d2a Mon Sep 17 00:00:00 2001
93c559
From: Petr Viktorin <pviktori@redhat.com>
93c559
Date: Thu, 25 Jul 2019 18:13:45 +0200
93c559
Subject: [PATCH 04/13] Fix tests
93c559
93c559
---
93c559
 Lib/test/test_hashlib.py | 5 +++++
93c559
 1 file changed, 5 insertions(+)
93c559
93c559
diff --git a/Lib/test/test_hashlib.py b/Lib/test/test_hashlib.py
93c559
index 8235505092b..a838bcee2a8 100644
93c559
--- a/Lib/test/test_hashlib.py
93c559
+++ b/Lib/test/test_hashlib.py
93c559
@@ -354,6 +354,11 @@ class HashLibTestCase(unittest.TestCase):
93c559
         # 2 is for hashlib.name(...) and hashlib.new(name, ...)
93c559
         self.assertGreaterEqual(len(constructors), 2)
93c559
         for hash_object_constructor in constructors:
93c559
+            if (
93c559
+                kwargs
93c559
+                and hash_object_constructor.__name__.startswith('openssl_')
93c559
+            ):
93c559
+                return
93c559
             m = hash_object_constructor(data, **kwargs)
93c559
             computed = m.hexdigest() if not shake else m.hexdigest(length)
93c559
             self.assertEqual(
93c559
-- 
93c559
2.26.2
93c559
93c559
93c559
From 3e87bf1c3d32c09a50385d8576b1164cafce4158 Mon Sep 17 00:00:00 2001
93c559
From: Petr Viktorin <pviktori@redhat.com>
93c559
Date: Fri, 26 Jul 2019 15:41:10 +0200
93c559
Subject: [PATCH 05/13] Implement hmac.new using new built-in module,
93c559
 _hmacopenssl
93c559
93c559
Make _hmacopenssl.HMAC subclassable; subclass it as hmac.HMAC under FIPS
93c559
93c559
This removes the _hmacopenssl.new function.
93c559
---
93c559
 Lib/hmac.py                     |  37 +++
93c559
 Lib/test/test_hmac.py           |  28 ++
93c559
 Modules/_hmacopenssl.c          | 459 ++++++++++++++++++++++++++++++++
93c559
 Modules/clinic/_hmacopenssl.c.h | 104 ++++++++
93c559
 setup.py                        |   4 +
93c559
 5 files changed, 632 insertions(+)
93c559
 create mode 100644 Modules/_hmacopenssl.c
93c559
 create mode 100644 Modules/clinic/_hmacopenssl.c.h
93c559
93c559
diff --git a/Lib/hmac.py b/Lib/hmac.py
93c559
index 180bc378b52..482e443bfe4 100644
93c559
--- a/Lib/hmac.py
93c559
+++ b/Lib/hmac.py
93c559
@@ -14,6 +14,8 @@ else:
93c559
     _openssl_md_meths = frozenset(_hashopenssl.openssl_md_meth_names)
93c559
     compare_digest = _hashopenssl.compare_digest
93c559
 import hashlib as _hashlib
93c559
+import _hashlib as _hashlibopenssl
93c559
+import _hmacopenssl
93c559
 
93c559
 trans_5C = bytes((x ^ 0x5C) for x in range(256))
93c559
 trans_36 = bytes((x ^ 0x36) for x in range(256))
93c559
@@ -48,6 +50,11 @@ class HMAC:
93c559
                    msg argument.  Passing it as a keyword argument is
93c559
                    recommended, though not required for legacy API reasons.
93c559
         """
93c559
+        if _hashlib.get_fips_mode():
93c559
+            raise ValueError(
93c559
+                'This class is not available in FIPS mode. '
93c559
+                + 'Use hmac.new().'
93c559
+            )
93c559
 
93c559
         if not isinstance(key, (bytes, bytearray)):
93c559
             raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__)
93c559
@@ -110,6 +117,8 @@ class HMAC:
93c559
 
93c559
     def update(self, msg):
93c559
         """Feed data from msg into this hashing object."""
93c559
+        if _hashlib.get_fips_mode():
93c559
+            raise ValueError('hmac.HMAC is not available in FIPS mode')
93c559
         self._inner.update(msg)
93c559
 
93c559
     def copy(self):
93c559
@@ -150,6 +159,34 @@ class HMAC:
93c559
         h = self._current()
93c559
         return h.hexdigest()
93c559
 
93c559
+def _get_openssl_name(digestmod):
93c559
+    if isinstance(digestmod, str):
93c559
+        return digestmod.lower()
93c559
+    elif callable(digestmod):
93c559
+        digestmod = digestmod(b'')
93c559
+
93c559
+    if not isinstance(digestmod, _hashlibopenssl.HASH):
93c559
+        raise TypeError(
93c559
+            'Only OpenSSL hashlib hashes are accepted in FIPS mode.')
93c559
+
93c559
+    return digestmod.name.lower().replace('_', '-')
93c559
+
93c559
+class HMAC_openssl(_hmacopenssl.HMAC):
93c559
+    def __new__(cls, key, msg = None, digestmod = None):
93c559
+        if not isinstance(key, (bytes, bytearray)):
93c559
+            raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__)
93c559
+
93c559
+        name = _get_openssl_name(digestmod)
93c559
+        result = _hmacopenssl.HMAC.__new__(cls, key, digestmod=name)
93c559
+        if msg:
93c559
+            result.update(msg)
93c559
+        return result
93c559
+
93c559
+
93c559
+if _hashlib.get_fips_mode():
93c559
+    HMAC = HMAC_openssl
93c559
+
93c559
+
93c559
 def new(key, msg=None, digestmod=''):
93c559
     """Create a new hashing object and return it.
93c559
 
93c559
diff --git a/Lib/test/test_hmac.py b/Lib/test/test_hmac.py
93c559
index 6daf22ca06f..544ec7cb411 100644
93c559
--- a/Lib/test/test_hmac.py
93c559
+++ b/Lib/test/test_hmac.py
93c559
@@ -322,6 +322,7 @@ class TestVectorsTestCase(unittest.TestCase):
93c559
     def test_sha512_rfc4231(self):
93c559
         self._rfc4231_test_cases(hashlib.sha512, 'sha512', 64, 128)
93c559
 
93c559
+    @unittest.skipIf(hashlib.get_fips_mode(), 'MockCrazyHash unacceptable in FIPS mode.')
93c559
     @hashlib_helper.requires_hashdigest('sha256')
93c559
     def test_legacy_block_size_warnings(self):
93c559
         class MockCrazyHash(object):
93c559
@@ -371,6 +372,14 @@ class ConstructorTestCase(unittest.TestCase):
93c559
         except Exception:
93c559
             self.fail("Standard constructor call raised exception.")
93c559
 
93c559
+    def test_normal_digestmod(self):
93c559
+        # Standard constructor call.
93c559
+        failed = 0
93c559
+        try:
93c559
+            h = hmac.HMAC(b"key", digestmod='sha1')
93c559
+        except Exception:
93c559
+            self.fail("Standard constructor call raised exception.")
93c559
+
93c559
     @hashlib_helper.requires_hashdigest('sha256')
93c559
     def test_with_str_key(self):
93c559
         # Pass a key of type str, which is an error, because it expects a key
93c559
@@ -446,6 +455,7 @@ class SanityTestCase(unittest.TestCase):
93c559
 
93c559
 class CopyTestCase(unittest.TestCase):
93c559
 
93c559
+    @unittest.skipIf(hashlib.get_fips_mode(), "Internal attributes unavailable in FIPS mode")
93c559
     @hashlib_helper.requires_hashdigest('sha256')
93c559
     def test_attributes(self):
93c559
         # Testing if attributes are of same type.
93c559
@@ -458,6 +468,8 @@ class CopyTestCase(unittest.TestCase):
93c559
         self.assertEqual(type(h1._outer), type(h2._outer),
93c559
             "Types of outer don't match.")
93c559
 
93c559
+
93c559
+    @unittest.skipIf(hashlib.get_fips_mode(), "Internal attributes unavailable in FIPS mode")
93c559
     @hashlib_helper.requires_hashdigest('sha256')
93c559
     def test_realcopy(self):
93c559
         # Testing if the copy method created a real copy.
93c559
@@ -473,6 +485,7 @@ class CopyTestCase(unittest.TestCase):
93c559
         self.assertEqual(h1._outer, h1.outer)
93c559
         self.assertEqual(h1._digest_cons, h1.digest_cons)
93c559
 
93c559
+    @unittest.skipIf(hashlib.get_fips_mode(), "Internal attributes unavailable in FIPS mode")
93c559
     @hashlib_helper.requires_hashdigest('sha256')
93c559
     def test_properties(self):
93c559
         # deprecated properties
93c559
@@ -481,6 +494,21 @@ class CopyTestCase(unittest.TestCase):
93c559
         self.assertEqual(h1._outer, h1.outer)
93c559
         self.assertEqual(h1._digest_cons, h1.digest_cons)
93c559
 
93c559
+    def test_realcopy_by_digest(self):
93c559
+        # Testing if the copy method created a real copy.
93c559
+        h1 = hmac.HMAC(b"key", digestmod="sha1")
93c559
+        h2 = h1.copy()
93c559
+        # Using id() in case somebody has overridden __eq__/__ne__.
93c559
+        self.assertTrue(id(h1) != id(h2), "No real copy of the HMAC instance.")
93c559
+        old_digest = h1.digest()
93c559
+        assert h1.digest() == h2.digest()
93c559
+        h1.update(b'hi')
93c559
+        assert h1.digest() != h2.digest()
93c559
+        assert h2.digest() == old_digest
93c559
+        new_digest = h1.digest()
93c559
+        h2.update(b'hi')
93c559
+        assert h1.digest() == h2.digest() == new_digest
93c559
+
93c559
     @hashlib_helper.requires_hashdigest('sha256')
93c559
     def test_equality(self):
93c559
         # Testing if the copy has the same digests.
93c559
diff --git a/Modules/_hmacopenssl.c b/Modules/_hmacopenssl.c
93c559
new file mode 100644
93c559
index 00000000000..c31d233fbe4
93c559
--- /dev/null
93c559
+++ b/Modules/_hmacopenssl.c
93c559
@@ -0,0 +1,459 @@
93c559
+/* Module that wraps all OpenSSL MHAC algorithm */
93c559
+
93c559
+/* Copyright (C) 2019 Red Hat, Inc. Red Hat, Inc. and/or its affiliates
93c559
+ *
93c559
+ * Based on _hashopenssl.c, which is:
93c559
+ * Copyright (C) 2005-2010   Gregory P. Smith (greg@krypto.org)
93c559
+ * Licensed to PSF under a Contributor Agreement.
93c559
+ *
93c559
+ * Derived from a skeleton of shamodule.c containing work performed by:
93c559
+ *
93c559
+ * Andrew Kuchling (amk@amk.ca)
93c559
+ * Greg Stein (gstein@lyra.org)
93c559
+ *
93c559
+ */
93c559
+
93c559
+#define PY_SSIZE_T_CLEAN
93c559
+
93c559
+#include "Python.h"
93c559
+#include "structmember.h"
93c559
+#include "hashlib.h"
93c559
+#include "pystrhex.h"
93c559
+#include "_hashopenssl.h"
93c559
+
93c559
+
93c559
+
93c559
+typedef struct hmacopenssl_state {
93c559
+    PyTypeObject *HmacType;
93c559
+} hmacopenssl_state;
93c559
+
93c559
+#include <openssl/hmac.h>
93c559
+
93c559
+typedef struct {
93c559
+    PyObject_HEAD
93c559
+    PyObject *name;  /* name of the hash algorithm */
93c559
+    HMAC_CTX *ctx;   /* OpenSSL hmac context */
93c559
+    PyThread_type_lock lock;  /* HMAC context lock */
93c559
+} HmacObject;
93c559
+
93c559
+#include "clinic/_hmacopenssl.c.h"
93c559
+/*[clinic input]
93c559
+module _hmacopenssl
93c559
+class _hmacopenssl.HMAC "HmacObject *" "((hmacopenssl_state *)PyModule_GetState(module))->HmacType"
93c559
+[clinic start generated code]*/
93c559
+/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9fe07a087adc2cf9]*/
93c559
+
93c559
+
93c559
+static PyObject *
93c559
+Hmac_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds)
93c559
+{
93c559
+    static char *kwarg_names[] = {"key", "digestmod", NULL};
93c559
+    Py_buffer key = {NULL, NULL};
93c559
+    char *digestmod = NULL;
93c559
+
93c559
+    int ret = PyArg_ParseTupleAndKeywords(
93c559
+        args, kwds, "y*|$s:_hmacopenssl.HMAC", kwarg_names,
93c559
+        &key, &digestmod);
93c559
+    if (ret == 0) {
93c559
+        return NULL;
93c559
+    }
93c559
+
93c559
+    if (digestmod == NULL) {
93c559
+        PyErr_SetString(PyExc_ValueError, "digestmod must be specified");
93c559
+        return NULL;
93c559
+    }
93c559
+
93c559
+    /* name must be lowercase */
93c559
+    for (int i=0; digestmod[i]; i++) {
93c559
+        if (
93c559
+            ((digestmod[i] < 'a') || (digestmod[i] > 'z'))
93c559
+            && ((digestmod[i] < '0') || (digestmod[i] > '9'))
93c559
+            && digestmod[i] != '-'
93c559
+        ) {
93c559
+            PyErr_SetString(PyExc_ValueError, "digestmod must be lowercase");
93c559
+            return NULL;
93c559
+        }
93c559
+    }
93c559
+
93c559
+    const EVP_MD *digest = EVP_get_digestbyname(digestmod);
93c559
+    if (!digest) {
93c559
+        PyErr_SetString(PyExc_ValueError, "unknown hash function");
93c559
+        return NULL;
93c559
+    }
93c559
+
93c559
+    PyObject *name = NULL;
93c559
+    HMAC_CTX *ctx = NULL;
93c559
+    HmacObject *retval = NULL;
93c559
+
93c559
+    name = PyUnicode_FromFormat("hmac-%s", digestmod);
93c559
+    if (name == NULL) {
93c559
+        goto error;
93c559
+    }
93c559
+
93c559
+    ctx = HMAC_CTX_new();
93c559
+    if (ctx == NULL) {
93c559
+        _setException(PyExc_ValueError);
93c559
+        goto error;
93c559
+    }
93c559
+
93c559
+    int r = HMAC_Init_ex(
93c559
+        ctx,
93c559
+        (const char*)key.buf,
93c559
+        key.len,
93c559
+        digest,
93c559
+        NULL /*impl*/);
93c559
+    if (r == 0) {
93c559
+        _setException(PyExc_ValueError);
93c559
+        goto error;
93c559
+    }
93c559
+
93c559
+    PyBuffer_Release(&key);
93c559
+    key.buf = NULL;
93c559
+
93c559
+    retval = (HmacObject *)subtype->tp_alloc(subtype, 0);
93c559
+    if (retval == NULL) {
93c559
+        goto error;
93c559
+    }
93c559
+
93c559
+    retval->name = name;
93c559
+    retval->ctx = ctx;
93c559
+    retval->lock = NULL;
93c559
+
93c559
+    return (PyObject*)retval;
93c559
+
93c559
+error:
93c559
+    if (ctx) HMAC_CTX_free(ctx);
93c559
+    if (name) Py_DECREF(name);
93c559
+    if (retval) PyObject_Del(name);
93c559
+    if (key.buf) PyBuffer_Release(&key);
93c559
+    return NULL;
93c559
+}
93c559
+
93c559
+/*[clinic input]
93c559
+_hmacopenssl.HMAC.copy
93c559
+
93c559
+Return a copy (“clone”) of the HMAC object.
93c559
+[clinic start generated code]*/
93c559
+
93c559
+static PyObject *
93c559
+_hmacopenssl_HMAC_copy_impl(HmacObject *self)
93c559
+/*[clinic end generated code: output=fe5ee41faf30dcf0 input=f5ed20feec42d8d0]*/
93c559
+{
93c559
+    HmacObject *retval;
93c559
+
93c559
+    HMAC_CTX *ctx = HMAC_CTX_new();
93c559
+    if (ctx == NULL) {
93c559
+        return _setException(PyExc_ValueError);
93c559
+    }
93c559
+
93c559
+    int r = HMAC_CTX_copy(ctx, self->ctx);
93c559
+    if (r == 0) {
93c559
+        HMAC_CTX_free(ctx);
93c559
+        return _setException(PyExc_ValueError);
93c559
+    }
93c559
+
93c559
+    retval = (HmacObject *)Py_TYPE(self)->tp_alloc(Py_TYPE(self), 0);
93c559
+    if (retval == NULL) {
93c559
+        HMAC_CTX_free(ctx);
93c559
+        return NULL;
93c559
+    }
93c559
+    retval->ctx = ctx;
93c559
+    Py_INCREF(self->name);
93c559
+    retval->name = self->name;
93c559
+
93c559
+    retval->lock = NULL;
93c559
+
93c559
+    return (PyObject *)retval;
93c559
+}
93c559
+
93c559
+static void
93c559
+_hmac_dealloc(HmacObject *self)
93c559
+{
93c559
+    if (self->lock != NULL) {
93c559
+        PyThread_free_lock(self->lock);
93c559
+    }
93c559
+    HMAC_CTX_free(self->ctx);
93c559
+    Py_CLEAR(self->name);
93c559
+    Py_TYPE(self)->tp_free(self);
93c559
+}
93c559
+
93c559
+static PyObject *
93c559
+_hmac_repr(HmacObject *self)
93c559
+{
93c559
+    return PyUnicode_FromFormat("<%U HMAC object @ %p>", self->name, self);
93c559
+}
93c559
+
93c559
+/*[clinic input]
93c559
+_hmacopenssl.HMAC.update
93c559
+
93c559
+    msg: Py_buffer
93c559
+
93c559
+Update the HMAC object with msg.
93c559
+[clinic start generated code]*/
93c559
+
93c559
+static PyObject *
93c559
+_hmacopenssl_HMAC_update_impl(HmacObject *self, Py_buffer *msg)
93c559
+/*[clinic end generated code: output=0efeee663a98cee5 input=0683d64f35808cb9]*/
93c559
+{
93c559
+    if (self->lock == NULL && msg->len >= HASHLIB_GIL_MINSIZE) {
93c559
+        self->lock = PyThread_allocate_lock();
93c559
+        /* fail? lock = NULL and we fail over to non-threaded code. */
93c559
+    }
93c559
+
93c559
+    int r;
93c559
+
93c559
+    if (self->lock != NULL) {
93c559
+        Py_BEGIN_ALLOW_THREADS
93c559
+        PyThread_acquire_lock(self->lock, 1);
93c559
+        r = HMAC_Update(self->ctx, (const unsigned char*)msg->buf, msg->len);
93c559
+        PyThread_release_lock(self->lock);
93c559
+        Py_END_ALLOW_THREADS
93c559
+    } else {
93c559
+        r = HMAC_Update(self->ctx, (const unsigned char*)msg->buf, msg->len);
93c559
+    }
93c559
+
93c559
+    if (r == 0) {
93c559
+        _setException(PyExc_ValueError);
93c559
+        return NULL;
93c559
+    }
93c559
+    Py_RETURN_NONE;
93c559
+}
93c559
+
93c559
+static unsigned int
93c559
+_digest_size(HmacObject *self)
93c559
+{
93c559
+    const EVP_MD *md = HMAC_CTX_get_md(self->ctx);
93c559
+    if (md == NULL) {
93c559
+        _setException(PyExc_ValueError);
93c559
+        return 0;
93c559
+    }
93c559
+    return EVP_MD_size(md);
93c559
+}
93c559
+
93c559
+static int
93c559
+_digest(HmacObject *self, unsigned char *buf, unsigned int len)
93c559
+{
93c559
+    HMAC_CTX *temp_ctx = HMAC_CTX_new();
93c559
+    if (temp_ctx == NULL) {
93c559
+        PyErr_NoMemory();
93c559
+        return 0;
93c559
+    }
93c559
+    int r = HMAC_CTX_copy(temp_ctx, self->ctx);
93c559
+    if (r == 0) {
93c559
+        _setException(PyExc_ValueError);
93c559
+        return 0;
93c559
+    }
93c559
+    r = HMAC_Final(temp_ctx, buf, &len;;
93c559
+    HMAC_CTX_free(temp_ctx);
93c559
+    if (r == 0) {
93c559
+        _setException(PyExc_ValueError);
93c559
+        return 0;
93c559
+    }
93c559
+    return 1;
93c559
+}
93c559
+
93c559
+/*[clinic input]
93c559
+_hmacopenssl.HMAC.digest
93c559
+
93c559
+Return the digest of the bytes passed to the update() method so far.
93c559
+[clinic start generated code]*/
93c559
+
93c559
+static PyObject *
93c559
+_hmacopenssl_HMAC_digest_impl(HmacObject *self)
93c559
+/*[clinic end generated code: output=3aa6dbfc46ec4957 input=bf769a10b1d9edd9]*/
93c559
+{
93c559
+    unsigned int digest_size = _digest_size(self);
93c559
+    if (digest_size == 0) {
93c559
+        return _setException(PyExc_ValueError);
93c559
+    }
93c559
+    unsigned char buf[digest_size]; /* FIXME: C99 feature */
93c559
+    int r = _digest(self, buf, digest_size);
93c559
+    if (r == 0) {
93c559
+        return NULL;
93c559
+    }
93c559
+    return PyBytes_FromStringAndSize((const char *)buf, digest_size);
93c559
+}
93c559
+
93c559
+/*[clinic input]
93c559
+_hmacopenssl.HMAC.hexdigest
93c559
+
93c559
+Return hexadecimal digest of the bytes passed to the update() method so far.
93c559
+
93c559
+This may be used to exchange the value safely in email or other non-binary
93c559
+environments.
93c559
+[clinic start generated code]*/
93c559
+
93c559
+static PyObject *
93c559
+_hmacopenssl_HMAC_hexdigest_impl(HmacObject *self)
93c559
+/*[clinic end generated code: output=630f6fa89f9f1e48 input=b8e60ec8b811c4cd]*/
93c559
+{
93c559
+    unsigned int digest_size = _digest_size(self);
93c559
+    if (digest_size == 0) {
93c559
+        return _setException(PyExc_ValueError);
93c559
+    }
93c559
+    unsigned char buf[digest_size]; /* FIXME: C99 feature */
93c559
+    int r = _digest(self, buf, digest_size);
93c559
+    if (r == 0) {
93c559
+        return NULL;
93c559
+    }
93c559
+    return _Py_strhex((const char *)buf, digest_size);
93c559
+}
93c559
+
93c559
+
93c559
+
93c559
+static PyObject *
93c559
+_hmacopenssl_get_digest_size(HmacObject *self, void *closure)
93c559
+{
93c559
+    unsigned int digest_size = _digest_size(self);
93c559
+    if (digest_size == 0) {
93c559
+        return _setException(PyExc_ValueError);
93c559
+    }
93c559
+    return PyLong_FromLong(digest_size);
93c559
+}
93c559
+
93c559
+static PyObject *
93c559
+_hmacopenssl_get_block_size(HmacObject *self, void *closure)
93c559
+{
93c559
+    const EVP_MD *md = HMAC_CTX_get_md(self->ctx);
93c559
+    if (md == NULL) {
93c559
+        return _setException(PyExc_ValueError);
93c559
+    }
93c559
+    return PyLong_FromLong(EVP_MD_block_size(md));
93c559
+}
93c559
+
93c559
+static PyMethodDef Hmac_methods[] = {
93c559
+    _HMACOPENSSL_HMAC_UPDATE_METHODDEF
93c559
+    _HMACOPENSSL_HMAC_DIGEST_METHODDEF
93c559
+    _HMACOPENSSL_HMAC_HEXDIGEST_METHODDEF
93c559
+    _HMACOPENSSL_HMAC_COPY_METHODDEF
93c559
+    {NULL, NULL}  /* sentinel */
93c559
+};
93c559
+
93c559
+static PyGetSetDef Hmac_getset[] = {
93c559
+    {"digest_size", (getter)_hmacopenssl_get_digest_size, NULL, NULL, NULL},
93c559
+    {"block_size", (getter)_hmacopenssl_get_block_size, NULL, NULL, NULL},
93c559
+    {NULL}  /* Sentinel */
93c559
+};
93c559
+
93c559
+static PyMemberDef Hmac_members[] = {
93c559
+    {"name", T_OBJECT, offsetof(HmacObject, name), READONLY, PyDoc_STR("HMAC name")},
93c559
+    {NULL} /* Sentinel */
93c559
+};
93c559
+
93c559
+PyDoc_STRVAR(hmactype_doc,
93c559
+"The object used to calculate HMAC of a message.\n\
93c559
+\n\
93c559
+Methods:\n\
93c559
+\n\
93c559
+update() -- updates the current digest with an additional string\n\
93c559
+digest() -- return the current digest value\n\
93c559
+hexdigest() -- return the current digest as a string of hexadecimal digits\n\
93c559
+copy() -- return a copy of the current hash object\n\
93c559
+\n\
93c559
+Attributes:\n\
93c559
+\n\
93c559
+name -- the name, including the hash algorithm used by this object\n\
93c559
+digest_size -- number of bytes in digest() output\n");
93c559
+
93c559
+static PyType_Slot HmacType_slots[] = {
93c559
+    {Py_tp_doc, (char*)hmactype_doc},
93c559
+    {Py_tp_repr, (reprfunc)_hmac_repr},
93c559
+    {Py_tp_dealloc,(destructor)_hmac_dealloc},
93c559
+    {Py_tp_methods, Hmac_methods},
93c559
+    {Py_tp_getset, Hmac_getset},
93c559
+    {Py_tp_members, Hmac_members},
93c559
+    {Py_tp_new, Hmac_new},
93c559
+    {0, NULL}
93c559
+};
93c559
+
93c559
+PyType_Spec HmacType_spec = {
93c559
+    "_hmacopenssl.HMAC",    /* name */
93c559
+    sizeof(HmacObject),     /* basicsize */
93c559
+    .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
93c559
+    .slots = HmacType_slots,
93c559
+};
93c559
+
93c559
+
93c559
+static int
93c559
+hmacopenssl_traverse(PyObject *self, visitproc visit, void *arg)
93c559
+{
93c559
+    hmacopenssl_state *state;
93c559
+
93c559
+    state = PyModule_GetState(self);
93c559
+
93c559
+    if (state) {
93c559
+        Py_VISIT(state->HmacType);
93c559
+    }
93c559
+
93c559
+    return 0;
93c559
+}
93c559
+
93c559
+static int
93c559
+hmacopenssl_clear(PyObject *self)
93c559
+{
93c559
+    hmacopenssl_state *state;
93c559
+
93c559
+    state = PyModule_GetState(self);
93c559
+
93c559
+    if (state) {
93c559
+        Py_CLEAR(state->HmacType);
93c559
+    }
93c559
+
93c559
+    return 0;
93c559
+}
93c559
+
93c559
+
93c559
+
93c559
+/* Initialize this module. */
93c559
+
93c559
+static int
93c559
+hmacopenssl_exec(PyObject *m) {
93c559
+    /* TODO build EVP_functions openssl_* entries dynamically based
93c559
+     * on what hashes are supported rather than listing many
93c559
+     * and having some unsupported.  Only init appropriate
93c559
+     * constants. */
93c559
+    PyObject *temp = NULL;
93c559
+    hmacopenssl_state *state;
93c559
+
93c559
+    temp = PyType_FromSpec(&HmacType_spec);
93c559
+    if (temp == NULL) {
93c559
+        goto fail;
93c559
+    }
93c559
+
93c559
+    if (PyModule_AddObject(m, "HMAC", temp) == -1) {
93c559
+        goto fail;
93c559
+    }
93c559
+
93c559
+    state = PyModule_GetState(m);
93c559
+
93c559
+    state->HmacType = (PyTypeObject *)temp;
93c559
+    Py_INCREF(temp);
93c559
+
93c559
+
93c559
+    return 0;
93c559
+
93c559
+fail:
93c559
+    Py_XDECREF(temp);
93c559
+    return -1;
93c559
+}
93c559
+
93c559
+static PyModuleDef_Slot hmacopenssl_slots[] = {
93c559
+    {Py_mod_exec, hmacopenssl_exec},
93c559
+    {0, NULL},
93c559
+};
93c559
+
93c559
+static struct PyModuleDef _hmacopenssl_def = {
93c559
+    PyModuleDef_HEAD_INIT,  /* m_base */
93c559
+    .m_name = "_hmacopenssl",
93c559
+    .m_slots = hmacopenssl_slots,
93c559
+    .m_size = sizeof(hmacopenssl_state),
93c559
+    .m_traverse = hmacopenssl_traverse,
93c559
+    .m_clear = hmacopenssl_clear
93c559
+};
93c559
+
93c559
+
93c559
+PyMODINIT_FUNC
93c559
+PyInit__hmacopenssl(void)
93c559
+{
93c559
+    return PyModuleDef_Init(&_hmacopenssl_def);
93c559
+}
93c559
diff --git a/Modules/clinic/_hmacopenssl.c.h b/Modules/clinic/_hmacopenssl.c.h
93c559
new file mode 100644
93c559
index 00000000000..a2af550838a
93c559
--- /dev/null
93c559
+++ b/Modules/clinic/_hmacopenssl.c.h
93c559
@@ -0,0 +1,104 @@
93c559
+/*[clinic input]
93c559
+preserve
93c559
+[clinic start generated code]*/
93c559
+
93c559
+PyDoc_STRVAR(_hmacopenssl_HMAC_copy__doc__,
93c559
+"copy($self, /)\n"
93c559
+"--\n"
93c559
+"\n"
93c559
+"Return a copy (“clone”) of the HMAC object.");
93c559
+
93c559
+#define _HMACOPENSSL_HMAC_COPY_METHODDEF    \
93c559
+    {"copy", (PyCFunction)_hmacopenssl_HMAC_copy, METH_NOARGS, _hmacopenssl_HMAC_copy__doc__},
93c559
+
93c559
+static PyObject *
93c559
+_hmacopenssl_HMAC_copy_impl(HmacObject *self);
93c559
+
93c559
+static PyObject *
93c559
+_hmacopenssl_HMAC_copy(HmacObject *self, PyObject *Py_UNUSED(ignored))
93c559
+{
93c559
+    return _hmacopenssl_HMAC_copy_impl(self);
93c559
+}
93c559
+
93c559
+PyDoc_STRVAR(_hmacopenssl_HMAC_update__doc__,
93c559
+"update($self, /, msg)\n"
93c559
+"--\n"
93c559
+"\n"
93c559
+"Update the HMAC object with msg.");
93c559
+
93c559
+#define _HMACOPENSSL_HMAC_UPDATE_METHODDEF    \
93c559
+    {"update", (PyCFunction)(void(*)(void))_hmacopenssl_HMAC_update, METH_FASTCALL|METH_KEYWORDS, _hmacopenssl_HMAC_update__doc__},
93c559
+
93c559
+static PyObject *
93c559
+_hmacopenssl_HMAC_update_impl(HmacObject *self, Py_buffer *msg);
93c559
+
93c559
+static PyObject *
93c559
+_hmacopenssl_HMAC_update(HmacObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
93c559
+{
93c559
+    PyObject *return_value = NULL;
93c559
+    static const char * const _keywords[] = {"msg", NULL};
93c559
+    static _PyArg_Parser _parser = {NULL, _keywords, "update", 0};
93c559
+    PyObject *argsbuf[1];
93c559
+    Py_buffer msg = {NULL, NULL};
93c559
+
93c559
+    args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser, 1, 1, 0, argsbuf);
93c559
+    if (!args) {
93c559
+        goto exit;
93c559
+    }
93c559
+    if (PyObject_GetBuffer(args[0], &msg, PyBUF_SIMPLE) != 0) {
93c559
+        goto exit;
93c559
+    }
93c559
+    if (!PyBuffer_IsContiguous(&msg, 'C')) {
93c559
+        _PyArg_BadArgument("update", "argument 'msg'", "contiguous buffer", args[0]);
93c559
+        goto exit;
93c559
+    }
93c559
+    return_value = _hmacopenssl_HMAC_update_impl(self, &msg;;
93c559
+
93c559
+exit:
93c559
+    /* Cleanup for msg */
93c559
+    if (msg.obj) {
93c559
+       PyBuffer_Release(&msg;;
93c559
+    }
93c559
+
93c559
+    return return_value;
93c559
+}
93c559
+
93c559
+PyDoc_STRVAR(_hmacopenssl_HMAC_digest__doc__,
93c559
+"digest($self, /)\n"
93c559
+"--\n"
93c559
+"\n"
93c559
+"Return the digest of the bytes passed to the update() method so far.");
93c559
+
93c559
+#define _HMACOPENSSL_HMAC_DIGEST_METHODDEF    \
93c559
+    {"digest", (PyCFunction)_hmacopenssl_HMAC_digest, METH_NOARGS, _hmacopenssl_HMAC_digest__doc__},
93c559
+
93c559
+static PyObject *
93c559
+_hmacopenssl_HMAC_digest_impl(HmacObject *self);
93c559
+
93c559
+static PyObject *
93c559
+_hmacopenssl_HMAC_digest(HmacObject *self, PyObject *Py_UNUSED(ignored))
93c559
+{
93c559
+    return _hmacopenssl_HMAC_digest_impl(self);
93c559
+}
93c559
+
93c559
+PyDoc_STRVAR(_hmacopenssl_HMAC_hexdigest__doc__,
93c559
+"hexdigest($self, /)\n"
93c559
+"--\n"
93c559
+"\n"
93c559
+"Return hexadecimal digest of the bytes passed to the update() method so far.\n"
93c559
+"\n"
93c559
+"This may be used to exchange the value safely in email or other non-binary\n"
93c559
+"environments.");
93c559
+
93c559
+#define _HMACOPENSSL_HMAC_HEXDIGEST_METHODDEF    \
93c559
+    {"hexdigest", (PyCFunction)_hmacopenssl_HMAC_hexdigest, METH_NOARGS, _hmacopenssl_HMAC_hexdigest__doc__},
93c559
+
93c559
+static PyObject *
93c559
+_hmacopenssl_HMAC_hexdigest_impl(HmacObject *self);
93c559
+
93c559
+static PyObject *
93c559
+_hmacopenssl_HMAC_hexdigest(HmacObject *self, PyObject *Py_UNUSED(ignored))
93c559
+{
93c559
+    return _hmacopenssl_HMAC_hexdigest_impl(self);
93c559
+}
93c559
+/*[clinic end generated code: output=e0c910f3c9ed523e input=a9049054013a1b77]*/
93c559
diff --git a/setup.py b/setup.py
93c559
index 89edbb627fa..5c2cbd665af 100644
93c559
--- a/setup.py
93c559
+++ b/setup.py
93c559
@@ -2371,6 +2371,10 @@ class PyBuildExt(build_ext):
93c559
                            depends=['hashlib.h'],
93c559
                            **self.detect_openssl_args()) )
93c559
 
93c559
+        self.add(Extension('_hmacopenssl', ['_hmacopenssl.c'],
93c559
+                                depends = ['hashlib.h'],
93c559
+                                **self.detect_openssl_args()) )
93c559
+
93c559
     def detect_hash_builtins(self):
93c559
         # By default we always compile these even when OpenSSL is available
93c559
         # (issue #14693). It's harmless and the object code is tiny
93c559
-- 
93c559
2.26.2
93c559
93c559
93c559
From a6d7c4268a6e305b1178b633e59dde7b5c8a1069 Mon Sep 17 00:00:00 2001
93c559
From: Petr Viktorin <pviktori@redhat.com>
93c559
Date: Thu, 1 Aug 2019 17:57:05 +0200
93c559
Subject: [PATCH 06/13] Use a stronger hash in multiprocessing handshake
93c559
93c559
Adapted from patch by David Malcolm,
93c559
https://bugs.python.org/issue17258
93c559
---
93c559
 Lib/multiprocessing/connection.py | 8 ++++++--
93c559
 1 file changed, 6 insertions(+), 2 deletions(-)
93c559
93c559
diff --git a/Lib/multiprocessing/connection.py b/Lib/multiprocessing/connection.py
93c559
index 510e4b5aba4..b68f2fb837a 100644
93c559
--- a/Lib/multiprocessing/connection.py
93c559
+++ b/Lib/multiprocessing/connection.py
93c559
@@ -42,6 +42,10 @@ BUFSIZE = 8192
93c559
 # A very generous timeout when it comes to local connections...
93c559
 CONNECTION_TIMEOUT = 20.
93c559
 
93c559
+# The hmac module implicitly defaults to using MD5.
93c559
+# Support using a stronger algorithm for the challenge/response code:
93c559
+HMAC_DIGEST_NAME='sha256'
93c559
+
93c559
 _mmap_counter = itertools.count()
93c559
 
93c559
 default_family = 'AF_INET'
93c559
@@ -741,7 +745,7 @@ def deliver_challenge(connection, authkey):
93c559
             "Authkey must be bytes, not {0!s}".format(type(authkey)))
93c559
     message = os.urandom(MESSAGE_LENGTH)
93c559
     connection.send_bytes(CHALLENGE + message)
93c559
-    digest = hmac.new(authkey, message, 'md5').digest()
93c559
+    digest = hmac.new(authkey, message, HMAC_DIGEST_NAME).digest()
93c559
     response = connection.recv_bytes(256)        # reject large message
93c559
     if response == digest:
93c559
         connection.send_bytes(WELCOME)
93c559
@@ -757,7 +761,7 @@ def answer_challenge(connection, authkey):
93c559
     message = connection.recv_bytes(256)         # reject large message
93c559
     assert message[:len(CHALLENGE)] == CHALLENGE, 'message = %r' % message
93c559
     message = message[len(CHALLENGE):]
93c559
-    digest = hmac.new(authkey, message, 'md5').digest()
93c559
+    digest = hmac.new(authkey, message, HMAC_DIGEST_NAME).digest()
93c559
     connection.send_bytes(digest)
93c559
     response = connection.recv_bytes(256)        # reject large message
93c559
     if response != WELCOME:
93c559
-- 
93c559
2.26.2
93c559
93c559
93c559
From 86868ca46c47112f771d54a54ee89e2d6c00f56f Mon Sep 17 00:00:00 2001
93c559
From: Charalampos Stratakis <cstratak@redhat.com>
93c559
Date: Wed, 31 Jul 2019 15:43:43 +0200
93c559
Subject: [PATCH 07/13] Add initial tests for various hashes under FIPS mode
93c559
93c559
---
93c559
 Lib/test/test_fips.py | 31 +++++++++++++++++++++++++++++++
93c559
 1 file changed, 31 insertions(+)
93c559
 create mode 100644 Lib/test/test_fips.py
93c559
93c559
diff --git a/Lib/test/test_fips.py b/Lib/test/test_fips.py
93c559
new file mode 100644
93c559
index 00000000000..fe4ea72296e
93c559
--- /dev/null
93c559
+++ b/Lib/test/test_fips.py
93c559
@@ -0,0 +1,31 @@
93c559
+import unittest
93c559
+import hmac, _hmacopenssl
93c559
+import hashlib, _hashlib
93c559
+
93c559
+
93c559
+
93c559
+class HashlibFipsTests(unittest.TestCase):
93c559
+
93c559
+    @unittest.skipUnless(hashlib.get_fips_mode(), "Test only when FIPS is enabled")
93c559
+    def test_fips_imports(self):
93c559
+        """blake2s and blake2b should fail to import in FIPS mode
93c559
+        """
93c559
+        with self.assertRaises(ValueError, msg='blake2s not available in FIPS'):
93c559
+            m = hashlib.blake2s()
93c559
+        with self.assertRaises(ValueError, msg='blake2b not available in FIPS'):
93c559
+            m = hashlib.blake2b()
93c559
+
93c559
+    @unittest.skipIf(hashlib.get_fips_mode(), "blake2 hashes are not available under FIPS")
93c559
+    def test_blake2_hashes(self):
93c559
+        self.assertEqual(hashlib.blake2b(b'abc').hexdigest(), _hashlib.openssl_blake2b(b'abc').hexdigest())
93c559
+        self.assertEqual(hashlib.blake2s(b'abc').hexdigest(), _hashlib.openssl_blake2s(b'abc').hexdigest())
93c559
+
93c559
+    def test_hmac_digests(self):
93c559
+        self.assertEqual(_hmacopenssl.HMAC(b'My hovercraft is full of eels', digestmod='sha384').hexdigest(),
93c559
+                            hmac.new(b'My hovercraft is full of eels', digestmod='sha384').hexdigest())
93c559
+
93c559
+
93c559
+
93c559
+
93c559
+if __name__ == "__main__":
93c559
+    unittest.main()
93c559
-- 
93c559
2.26.2
93c559
93c559
93c559
From 5badab85d3fc725b56a19658f1e9b16aeb0ed663 Mon Sep 17 00:00:00 2001
93c559
From: Petr Viktorin <pviktori@redhat.com>
93c559
Date: Mon, 5 Aug 2019 18:23:57 +0200
93c559
Subject: [PATCH 08/13] Make hashlib tests pass in FIPS mode
93c559
93c559
---
93c559
 Lib/test/test_hashlib.py | 27 ++++++++++++++++++++++++---
93c559
 1 file changed, 24 insertions(+), 3 deletions(-)
93c559
93c559
diff --git a/Lib/test/test_hashlib.py b/Lib/test/test_hashlib.py
93c559
index a838bcee2a8..6f60ad4b8fb 100644
93c559
--- a/Lib/test/test_hashlib.py
93c559
+++ b/Lib/test/test_hashlib.py
93c559
@@ -44,6 +44,12 @@ if builtin_hashes == default_builtin_hashes:
93c559
 else:
93c559
     builtin_hashlib = None
93c559
 
93c559
+
93c559
+if hashlib.get_fips_mode():
93c559
+    FIPS_DISABLED = {'md5', 'MD5', 'blake2b', 'blake2s'}
93c559
+else:
93c559
+    FIPS_DISABLED = set()
93c559
+
93c559
 try:
93c559
     from _hashlib import HASH, HASHXOF, openssl_md_meth_names
93c559
 except ImportError:
93c559
@@ -106,6 +112,7 @@ class HashLibTestCase(unittest.TestCase):
93c559
     # Issue #14693: fallback modules are always compiled under POSIX
93c559
     _warn_on_extension_import = os.name == 'posix' or COMPILED_WITH_PYDEBUG
93c559
 
93c559
+
93c559
     def _conditional_import_module(self, module_name):
93c559
         """Import a module and return a reference to it or None on failure."""
93c559
         try:
93c559
@@ -113,6 +120,9 @@ class HashLibTestCase(unittest.TestCase):
93c559
         except ModuleNotFoundError as error:
93c559
             if self._warn_on_extension_import and module_name in builtin_hashes:
93c559
                 warnings.warn('Did a C extension fail to compile? %s' % error)
93c559
+        except ImportError as error:
93c559
+            if not hashlib.get_fips_mode():
93c559
+                raise
93c559
         return None
93c559
 
93c559
     def __init__(self, *args, **kwargs):
93c559
@@ -211,7 +221,7 @@ class HashLibTestCase(unittest.TestCase):
93c559
                 c.hexdigest()
93c559
 
93c559
     def test_algorithms_guaranteed(self):
93c559
-        self.assertEqual(hashlib.algorithms_guaranteed,
93c559
+        self.assertEqual(hashlib.algorithms_guaranteed - FIPS_DISABLED,
93c559
             set(_algo for _algo in self.supported_hash_names
93c559
                   if _algo.islower()))
93c559
 
93c559
@@ -250,6 +260,12 @@ class HashLibTestCase(unittest.TestCase):
93c559
     def test_new_upper_to_lower(self):
93c559
         self.assertEqual(hashlib.new("SHA256").name, "sha256")
93c559
 
93c559
+    @unittest.skipUnless(hashlib.get_fips_mode(), "Builtin constructor only unavailable in FIPS mode")
93c559
+    def test_get_builtin_constructor_fips(self):
93c559
+        with self.assertRaises(AttributeError):
93c559
+            hashlib.__get_builtin_constructor
93c559
+
93c559
+    @unittest.skipIf(hashlib.get_fips_mode(), "No builtin constructors in FIPS mode")
93c559
     def test_get_builtin_constructor(self):
93c559
         get_builtin_constructor = getattr(hashlib,
93c559
                                           '__get_builtin_constructor')
93c559
@@ -380,7 +396,8 @@ class HashLibTestCase(unittest.TestCase):
93c559
             self.assertRaises(TypeError, hash_object_constructor, 'spam')
93c559
 
93c559
     def test_no_unicode(self):
93c559
-        self.check_no_unicode('md5')
93c559
+        if not hashlib.get_fips_mode():
93c559
+            self.check_no_unicode('md5')
93c559
         self.check_no_unicode('sha1')
93c559
         self.check_no_unicode('sha224')
93c559
         self.check_no_unicode('sha256')
93c559
@@ -421,7 +438,8 @@ class HashLibTestCase(unittest.TestCase):
93c559
             self.assertIn(name.split("_")[0], repr(m))
93c559
 
93c559
     def test_blocksize_name(self):
93c559
-        self.check_blocksize_name('md5', 64, 16)
93c559
+        if not hashlib.get_fips_mode():
93c559
+            self.check_blocksize_name('md5', 64, 16)
93c559
         self.check_blocksize_name('sha1', 64, 20)
93c559
         self.check_blocksize_name('sha224', 64, 28)
93c559
         self.check_blocksize_name('sha256', 64, 32)
93c559
@@ -463,18 +481,21 @@ class HashLibTestCase(unittest.TestCase):
93c559
         self.check_blocksize_name('blake2b', 128, 64)
93c559
         self.check_blocksize_name('blake2s', 64, 32)
93c559
 
93c559
+    @unittest.skipIf(hashlib.get_fips_mode(), "md5 unacceptable in FIPS mode")
93c559
     def test_case_md5_0(self):
93c559
         self.check(
93c559
             'md5', b'', 'd41d8cd98f00b204e9800998ecf8427e',
93c559
             usedforsecurity=False
93c559
         )
93c559
 
93c559
+    @unittest.skipIf(hashlib.get_fips_mode(), "md5 unacceptable in FIPS mode")
93c559
     def test_case_md5_1(self):
93c559
         self.check(
93c559
             'md5', b'abc', '900150983cd24fb0d6963f7d28e17f72',
93c559
             usedforsecurity=False
93c559
         )
93c559
 
93c559
+    @unittest.skipIf(hashlib.get_fips_mode(), "md5 unacceptable in FIPS mode")
93c559
     def test_case_md5_2(self):
93c559
         self.check(
93c559
             'md5',
93c559
-- 
93c559
2.26.2
93c559
93c559
93c559
From 0f7a3094bc4cf691ae0dd093567ceea149e14e8a Mon Sep 17 00:00:00 2001
93c559
From: Petr Viktorin <pviktori@redhat.com>
93c559
Date: Mon, 26 Aug 2019 19:09:39 +0200
93c559
Subject: [PATCH 09/13] Test the usedforsecurity flag
93c559
93c559
---
93c559
 Lib/test/test_hashlib.py | 66 +++++++++++++++++++++++++---------------
93c559
 1 file changed, 42 insertions(+), 24 deletions(-)
93c559
93c559
diff --git a/Lib/test/test_hashlib.py b/Lib/test/test_hashlib.py
93c559
index 6f60ad4b8fb..f306ba33b20 100644
93c559
--- a/Lib/test/test_hashlib.py
93c559
+++ b/Lib/test/test_hashlib.py
93c559
@@ -20,6 +20,7 @@ import warnings
93c559
 from test import support
93c559
 from test.support import _4G, bigmemtest, import_fresh_module
93c559
 from http.client import HTTPException
93c559
+from functools import partial
93c559
 
93c559
 # Were we compiled --with-pydebug or with #define Py_DEBUG?
93c559
 COMPILED_WITH_PYDEBUG = hasattr(sys, 'gettotalrefcount')
93c559
@@ -46,8 +47,10 @@ else:
93c559
 
93c559
 
93c559
 if hashlib.get_fips_mode():
93c559
-    FIPS_DISABLED = {'md5', 'MD5', 'blake2b', 'blake2s'}
93c559
+    FIPS_UNAVAILABLE = {'blake2b', 'blake2s'}
93c559
+    FIPS_DISABLED = {'md5', 'MD5', *FIPS_UNAVAILABLE}
93c559
 else:
93c559
+    FIPS_UNAVAILABLE = set()
93c559
     FIPS_DISABLED = set()
93c559
 
93c559
 try:
93c559
@@ -98,6 +101,14 @@ def read_vectors(hash_name):
93c559
             parts[0] = bytes.fromhex(parts[0])
93c559
             yield parts
93c559
 
93c559
+def _is_openssl_constructor(constructor):
93c559
+    if getattr(constructor, '__name__', '').startswith('openssl_'):
93c559
+        return True
93c559
+    if isinstance(constructor, partial):
93c559
+        if constructor.func.__name__.startswith('openssl_'):
93c559
+            return True
93c559
+    return False
93c559
+
93c559
 
93c559
 class HashLibTestCase(unittest.TestCase):
93c559
     supported_hash_names = ( 'md5', 'MD5', 'sha1', 'SHA1',
93c559
@@ -128,8 +139,8 @@ class HashLibTestCase(unittest.TestCase):
93c559
     def __init__(self, *args, **kwargs):
93c559
         algorithms = set()
93c559
         for algorithm in self.supported_hash_names:
93c559
-            algorithms.add(algorithm.lower())
93c559
-
93c559
+            if algorithm not in FIPS_UNAVAILABLE:
93c559
+                algorithms.add(algorithm.lower())
93c559
         _blake2 = self._conditional_import_module('_blake2')
93c559
         if _blake2:
93c559
             algorithms.update({'blake2b', 'blake2s'})
93c559
@@ -138,15 +149,21 @@ class HashLibTestCase(unittest.TestCase):
93c559
         for algorithm in algorithms:
93c559
             self.constructors_to_test[algorithm] = set()
93c559
 
93c559
+        def _add_constructor(algorithm, constructor):
93c559
+            constructors.add(partial(constructor, usedforsecurity=False))
93c559
+            if algorithm not in FIPS_DISABLED:
93c559
+                constructors.add(constructor)
93c559
+                constructors.add(partial(constructor, usedforsecurity=True))
93c559
+
93c559
         # For each algorithm, test the direct constructor and the use
93c559
         # of hashlib.new given the algorithm name.
93c559
         for algorithm, constructors in self.constructors_to_test.items():
93c559
-            constructors.add(getattr(hashlib, algorithm))
93c559
+            _add_constructor(algorithm, getattr(hashlib, algorithm))
93c559
             def _test_algorithm_via_hashlib_new(data=None, _alg=algorithm, **kwargs):
93c559
                 if data is None:
93c559
                     return hashlib.new(_alg, **kwargs)
93c559
                 return hashlib.new(_alg, data, **kwargs)
93c559
-            constructors.add(_test_algorithm_via_hashlib_new)
93c559
+            _add_constructor(algorithm, _test_algorithm_via_hashlib_new)
93c559
 
93c559
         _hashlib = self._conditional_import_module('_hashlib')
93c559
         self._hashlib = _hashlib
93c559
@@ -158,13 +175,7 @@ class HashLibTestCase(unittest.TestCase):
93c559
             for algorithm, constructors in self.constructors_to_test.items():
93c559
                 constructor = getattr(_hashlib, 'openssl_'+algorithm, None)
93c559
                 if constructor:
93c559
-                    try:
93c559
-                        constructor()
93c559
-                    except ValueError:
93c559
-                        # default constructor blocked by crypto policy
93c559
-                        pass
93c559
-                    else:
93c559
-                        constructors.add(constructor)
93c559
+                    _add_constructor(algorithm, constructor)
93c559
 
93c559
         def add_builtin_constructor(name):
93c559
             constructor = getattr(hashlib, "__get_builtin_constructor")(name)
93c559
@@ -221,7 +232,7 @@ class HashLibTestCase(unittest.TestCase):
93c559
                 c.hexdigest()
93c559
 
93c559
     def test_algorithms_guaranteed(self):
93c559
-        self.assertEqual(hashlib.algorithms_guaranteed - FIPS_DISABLED,
93c559
+        self.assertEqual(hashlib.algorithms_guaranteed,
93c559
             set(_algo for _algo in self.supported_hash_names
93c559
                   if _algo.islower()))
93c559
 
93c559
@@ -326,10 +337,9 @@ class HashLibTestCase(unittest.TestCase):
93c559
                 self.assertIn(h.name, self.supported_hash_names)
93c559
             else:
93c559
                 self.assertNotIn(h.name, self.supported_hash_names)
93c559
-            self.assertEqual(
93c559
-                h.name,
93c559
-                hashlib.new(h.name, usedforsecurity=False).name
93c559
-            )
93c559
+            if h.name not in FIPS_DISABLED:
93c559
+                self.assertEqual(h.name, hashlib.new(h.name).name)
93c559
+            self.assertEqual(h.name, hashlib.new(h.name, usedforsecurity=False).name)
93c559
 
93c559
     def test_large_update(self):
93c559
         aas = b'a' * 128
93c559
@@ -371,9 +381,11 @@ class HashLibTestCase(unittest.TestCase):
93c559
         self.assertGreaterEqual(len(constructors), 2)
93c559
         for hash_object_constructor in constructors:
93c559
             if (
93c559
-                kwargs
93c559
-                and hash_object_constructor.__name__.startswith('openssl_')
93c559
+                (kwargs.keys() - {'usedforsecurity'})
93c559
+                and _is_openssl_constructor(hash_object_constructor)
93c559
             ):
93c559
+                # Don't check openssl constructors with
93c559
+                # any extra keys (except usedforsecurity)
93c559
                 return
93c559
             m = hash_object_constructor(data, **kwargs)
93c559
             computed = m.hexdigest() if not shake else m.hexdigest(length)
93c559
@@ -481,21 +493,18 @@ class HashLibTestCase(unittest.TestCase):
93c559
         self.check_blocksize_name('blake2b', 128, 64)
93c559
         self.check_blocksize_name('blake2s', 64, 32)
93c559
 
93c559
-    @unittest.skipIf(hashlib.get_fips_mode(), "md5 unacceptable in FIPS mode")
93c559
     def test_case_md5_0(self):
93c559
         self.check(
93c559
             'md5', b'', 'd41d8cd98f00b204e9800998ecf8427e',
93c559
             usedforsecurity=False
93c559
         )
93c559
 
93c559
-    @unittest.skipIf(hashlib.get_fips_mode(), "md5 unacceptable in FIPS mode")
93c559
     def test_case_md5_1(self):
93c559
         self.check(
93c559
             'md5', b'abc', '900150983cd24fb0d6963f7d28e17f72',
93c559
             usedforsecurity=False
93c559
         )
93c559
 
93c559
-    @unittest.skipIf(hashlib.get_fips_mode(), "md5 unacceptable in FIPS mode")
93c559
     def test_case_md5_2(self):
93c559
         self.check(
93c559
             'md5',
93c559
@@ -507,12 +516,12 @@ class HashLibTestCase(unittest.TestCase):
93c559
     @unittest.skipIf(sys.maxsize < _4G + 5, 'test cannot run on 32-bit systems')
93c559
     @bigmemtest(size=_4G + 5, memuse=1, dry_run=False)
93c559
     def test_case_md5_huge(self, size):
93c559
-        self.check('md5', b'A'*size, 'c9af2dff37468ce5dfee8f2cfc0a9c6d')
93c559
+        self.check('md5', b'A'*size, 'c9af2dff37468ce5dfee8f2cfc0a9c6d', usedforsecurity=False)
93c559
 
93c559
     @unittest.skipIf(sys.maxsize < _4G - 1, 'test cannot run on 32-bit systems')
93c559
     @bigmemtest(size=_4G - 1, memuse=1, dry_run=False)
93c559
     def test_case_md5_uintmax(self, size):
93c559
-        self.check('md5', b'A'*size, '28138d306ff1b8281f1a9067e1a1a2b3')
93c559
+        self.check('md5', b'A'*size, '28138d306ff1b8281f1a9067e1a1a2b3', usedforsecurity=False)
93c559
 
93c559
     # use the three examples from Federal Information Processing Standards
93c559
     # Publication 180-1, Secure Hash Standard,  1995 April 17
93c559
@@ -958,6 +967,15 @@ class HashLibTestCase(unittest.TestCase):
93c559
         ):
93c559
             HASHXOF()
93c559
 
93c559
+    @unittest.skipUnless(hashlib.get_fips_mode(), 'Needs FIPS mode.')
93c559
+    def test_usedforsecurity_repeat(self):
93c559
+        """Make sure usedforsecurity flag isn't copied to other contexts"""
93c559
+        for i in range(3):
93c559
+            for cons in hashlib.md5, partial(hashlib.new, 'md5'):
93c559
+                self.assertRaises(ValueError, cons)
93c559
+                self.assertRaises(ValueError, partial(cons, usedforsecurity=True))
93c559
+                self.assertEqual(cons(usedforsecurity=False).hexdigest(),
93c559
+                                'd41d8cd98f00b204e9800998ecf8427e')
93c559
 
93c559
 class KDFTests(unittest.TestCase):
93c559
 
93c559
-- 
93c559
2.26.2
93c559
93c559
93c559
From 5feafbf68d297e3f4fcafe4cbeff97817c592c53 Mon Sep 17 00:00:00 2001
93c559
From: Petr Viktorin <pviktori@redhat.com>
93c559
Date: Mon, 26 Aug 2019 19:39:48 +0200
93c559
Subject: [PATCH 10/13] Don't re-export get_fips_mode from hashlib
93c559
93c559
Fixes: https://bugzilla.redhat.com/show_bug.cgi?id=1745685
93c559
---
93c559
 Lib/hashlib.py                    | 22 +++++++++-------------
93c559
 Lib/hmac.py                       |  6 +++---
93c559
 Lib/test/test_fips.py             |  4 ++--
93c559
 Lib/test/test_hashlib.py          | 16 +++++++++-------
93c559
 Lib/test/test_hmac.py             |  9 +++++----
93c559
 Lib/test/test_urllib2_localnet.py |  1 +
93c559
 6 files changed, 29 insertions(+), 29 deletions(-)
93c559
93c559
diff --git a/Lib/hashlib.py b/Lib/hashlib.py
93c559
index 1fd80c7d4fd..6121d251267 100644
93c559
--- a/Lib/hashlib.py
93c559
+++ b/Lib/hashlib.py
93c559
@@ -53,6 +53,8 @@ More condensed:
93c559
 
93c559
 """
93c559
 
93c559
+import _hashlib
93c559
+
93c559
 # This tuple and __get_builtin_constructor() must be modified if a new
93c559
 # always available algorithm is added.
93c559
 __always_supported = ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512',
93c559
@@ -77,13 +79,7 @@ __block_openssl_constructor = {
93c559
     'blake2b', 'blake2s',
93c559
 }
93c559
 
93c559
-try:
93c559
-    from _hashlib import get_fips_mode
93c559
-except ImportError:
93c559
-    def get_fips_mode():
93c559
-        return 0
93c559
-
93c559
-if not get_fips_mode():
93c559
+if not _hashlib.get_fips_mode():
93c559
     __builtin_constructor_cache = {}
93c559
 
93c559
     def __get_builtin_constructor(name):
93c559
@@ -131,7 +127,7 @@ if not get_fips_mode():
93c559
 
93c559
 
93c559
 def __get_openssl_constructor(name):
93c559
-    if not get_fips_mode():
93c559
+    if not _hashlib.get_fips_mode():
93c559
         if name in __block_openssl_constructor:
93c559
             # Prefer our builtin blake2 implementation.
93c559
             return __get_builtin_constructor(name)
93c559
@@ -149,7 +145,7 @@ def __get_openssl_constructor(name):
93c559
         return __get_builtin_constructor(name)
93c559
 
93c559
 
93c559
-if not get_fips_mode():
93c559
+if not _hashlib.get_fips_mode():
93c559
     def __py_new(name, data=b'', **kwargs):
93c559
         """new(name, data=b'', **kwargs) - Return a new hashing object using the
93c559
         named algorithm; optionally initialized with data (which must be
93c559
@@ -162,7 +158,7 @@ def __hash_new(name, data=b'', **kwargs):
93c559
     """new(name, data=b'') - Return a new hashing object using the named algorithm;
93c559
     optionally initialized with data (which must be a bytes-like object).
93c559
     """
93c559
-    if not get_fips_mode():
93c559
+    if not _hashlib.get_fips_mode():
93c559
         if name in __block_openssl_constructor:
93c559
             # Prefer our builtin blake2 implementation.
93c559
             return __get_builtin_constructor(name)(data, **kwargs)
93c559
@@ -173,7 +169,7 @@ def __hash_new(name, data=b'', **kwargs):
93c559
         # hash, try using our builtin implementations.
93c559
         # This allows for SHA224/256 and SHA384/512 support even though
93c559
         # the OpenSSL library prior to 0.9.8 doesn't provide them.
93c559
-        if get_fips_mode():
93c559
+        if _hashlib.get_fips_mode():
93c559
             raise
93c559
         return __get_builtin_constructor(name)(data)
93c559
 
93c559
@@ -185,7 +181,7 @@ try:
93c559
     algorithms_available = algorithms_available.union(
93c559
             _hashlib.openssl_md_meth_names)
93c559
 except ImportError:
93c559
-    if get_fips_mode:
93c559
+    if _hashlib.get_fips_mode:
93c559
         raise
93c559
     new = __py_new
93c559
     __get_hash = __get_builtin_constructor
93c559
@@ -214,5 +210,5 @@ for __func_name in __always_supported:
93c559
 # Cleanup locals()
93c559
 del __always_supported, __func_name, __get_hash
93c559
 del __hash_new, __get_openssl_constructor
93c559
-if not get_fips_mode():
93c559
+if not _hashlib.get_fips_mode():
93c559
     del __py_new
93c559
diff --git a/Lib/hmac.py b/Lib/hmac.py
93c559
index 482e443bfe4..ff466322d7b 100644
93c559
--- a/Lib/hmac.py
93c559
+++ b/Lib/hmac.py
93c559
@@ -50,7 +50,7 @@ class HMAC:
93c559
                    msg argument.  Passing it as a keyword argument is
93c559
                    recommended, though not required for legacy API reasons.
93c559
         """
93c559
-        if _hashlib.get_fips_mode():
93c559
+        if _hashlibopenssl.get_fips_mode():
93c559
             raise ValueError(
93c559
                 'This class is not available in FIPS mode. '
93c559
                 + 'Use hmac.new().'
93c559
@@ -117,7 +117,7 @@ class HMAC:
93c559
 
93c559
     def update(self, msg):
93c559
         """Feed data from msg into this hashing object."""
93c559
-        if _hashlib.get_fips_mode():
93c559
+        if _hashlibopenssl.get_fips_mode():
93c559
             raise ValueError('hmac.HMAC is not available in FIPS mode')
93c559
         self._inner.update(msg)
93c559
 
93c559
@@ -183,7 +183,7 @@ class HMAC_openssl(_hmacopenssl.HMAC):
93c559
         return result
93c559
 
93c559
 
93c559
-if _hashlib.get_fips_mode():
93c559
+if _hashlibopenssl.get_fips_mode():
93c559
     HMAC = HMAC_openssl
93c559
 
93c559
 
93c559
diff --git a/Lib/test/test_fips.py b/Lib/test/test_fips.py
93c559
index fe4ea72296e..6b50f8b45d4 100644
93c559
--- a/Lib/test/test_fips.py
93c559
+++ b/Lib/test/test_fips.py
93c559
@@ -6,7 +6,7 @@ import hashlib, _hashlib
93c559
 
93c559
 class HashlibFipsTests(unittest.TestCase):
93c559
 
93c559
-    @unittest.skipUnless(hashlib.get_fips_mode(), "Test only when FIPS is enabled")
93c559
+    @unittest.skipUnless(_hashlib.get_fips_mode(), "Test only when FIPS is enabled")
93c559
     def test_fips_imports(self):
93c559
         """blake2s and blake2b should fail to import in FIPS mode
93c559
         """
93c559
@@ -15,7 +15,7 @@ class HashlibFipsTests(unittest.TestCase):
93c559
         with self.assertRaises(ValueError, msg='blake2b not available in FIPS'):
93c559
             m = hashlib.blake2b()
93c559
 
93c559
-    @unittest.skipIf(hashlib.get_fips_mode(), "blake2 hashes are not available under FIPS")
93c559
+    @unittest.skipIf(_hashlib.get_fips_mode(), "blake2 hashes are not available under FIPS")
93c559
     def test_blake2_hashes(self):
93c559
         self.assertEqual(hashlib.blake2b(b'abc').hexdigest(), _hashlib.openssl_blake2b(b'abc').hexdigest())
93c559
         self.assertEqual(hashlib.blake2s(b'abc').hexdigest(), _hashlib.openssl_blake2s(b'abc').hexdigest())
93c559
diff --git a/Lib/test/test_hashlib.py b/Lib/test/test_hashlib.py
93c559
index f306ba33b20..03cfb6b2fb4 100644
93c559
--- a/Lib/test/test_hashlib.py
93c559
+++ b/Lib/test/test_hashlib.py
93c559
@@ -46,7 +46,9 @@ else:
93c559
     builtin_hashlib = None
93c559
 
93c559
 
93c559
-if hashlib.get_fips_mode():
93c559
+from _hashlib import get_fips_mode as _get_fips_mode
93c559
+
93c559
+if _get_fips_mode():
93c559
     FIPS_UNAVAILABLE = {'blake2b', 'blake2s'}
93c559
     FIPS_DISABLED = {'md5', 'MD5', *FIPS_UNAVAILABLE}
93c559
 else:
93c559
@@ -132,7 +134,7 @@ class HashLibTestCase(unittest.TestCase):
93c559
             if self._warn_on_extension_import and module_name in builtin_hashes:
93c559
                 warnings.warn('Did a C extension fail to compile? %s' % error)
93c559
         except ImportError as error:
93c559
-            if not hashlib.get_fips_mode():
93c559
+            if not _get_fips_mode():
93c559
                 raise
93c559
         return None
93c559
 
93c559
@@ -271,12 +273,12 @@ class HashLibTestCase(unittest.TestCase):
93c559
     def test_new_upper_to_lower(self):
93c559
         self.assertEqual(hashlib.new("SHA256").name, "sha256")
93c559
 
93c559
-    @unittest.skipUnless(hashlib.get_fips_mode(), "Builtin constructor only unavailable in FIPS mode")
93c559
+    @unittest.skipUnless(_get_fips_mode(), "Builtin constructor only unavailable in FIPS mode")
93c559
     def test_get_builtin_constructor_fips(self):
93c559
         with self.assertRaises(AttributeError):
93c559
             hashlib.__get_builtin_constructor
93c559
 
93c559
-    @unittest.skipIf(hashlib.get_fips_mode(), "No builtin constructors in FIPS mode")
93c559
+    @unittest.skipIf(_get_fips_mode(), "No builtin constructors in FIPS mode")
93c559
     def test_get_builtin_constructor(self):
93c559
         get_builtin_constructor = getattr(hashlib,
93c559
                                           '__get_builtin_constructor')
93c559
@@ -408,7 +410,7 @@ class HashLibTestCase(unittest.TestCase):
93c559
             self.assertRaises(TypeError, hash_object_constructor, 'spam')
93c559
 
93c559
     def test_no_unicode(self):
93c559
-        if not hashlib.get_fips_mode():
93c559
+        if not _get_fips_mode():
93c559
             self.check_no_unicode('md5')
93c559
         self.check_no_unicode('sha1')
93c559
         self.check_no_unicode('sha224')
93c559
@@ -450,7 +452,7 @@ class HashLibTestCase(unittest.TestCase):
93c559
             self.assertIn(name.split("_")[0], repr(m))
93c559
 
93c559
     def test_blocksize_name(self):
93c559
-        if not hashlib.get_fips_mode():
93c559
+        if not _get_fips_mode():
93c559
             self.check_blocksize_name('md5', 64, 16)
93c559
         self.check_blocksize_name('sha1', 64, 20)
93c559
         self.check_blocksize_name('sha224', 64, 28)
93c559
@@ -967,7 +969,7 @@ class HashLibTestCase(unittest.TestCase):
93c559
         ):
93c559
             HASHXOF()
93c559
 
93c559
-    @unittest.skipUnless(hashlib.get_fips_mode(), 'Needs FIPS mode.')
93c559
+    @unittest.skipUnless(_get_fips_mode(), 'Needs FIPS mode.')
93c559
     def test_usedforsecurity_repeat(self):
93c559
         """Make sure usedforsecurity flag isn't copied to other contexts"""
93c559
         for i in range(3):
93c559
diff --git a/Lib/test/test_hmac.py b/Lib/test/test_hmac.py
93c559
index 544ec7cb411..2d4484911c2 100644
93c559
--- a/Lib/test/test_hmac.py
93c559
+++ b/Lib/test/test_hmac.py
93c559
@@ -5,6 +5,7 @@ import hashlib
93c559
 import unittest
93c559
 import unittest.mock
93c559
 import warnings
93c559
+from _hashlib import get_fips_mode
93c559
 
93c559
 from test.support import hashlib_helper
93c559
 
93c559
@@ -322,7 +323,7 @@ class TestVectorsTestCase(unittest.TestCase):
93c559
     def test_sha512_rfc4231(self):
93c559
         self._rfc4231_test_cases(hashlib.sha512, 'sha512', 64, 128)
93c559
 
93c559
-    @unittest.skipIf(hashlib.get_fips_mode(), 'MockCrazyHash unacceptable in FIPS mode.')
93c559
+    @unittest.skipIf(get_fips_mode(), 'MockCrazyHash unacceptable in FIPS mode.')
93c559
     @hashlib_helper.requires_hashdigest('sha256')
93c559
     def test_legacy_block_size_warnings(self):
93c559
         class MockCrazyHash(object):
93c559
@@ -455,7 +456,7 @@ class SanityTestCase(unittest.TestCase):
93c559
 
93c559
 class CopyTestCase(unittest.TestCase):
93c559
 
93c559
-    @unittest.skipIf(hashlib.get_fips_mode(), "Internal attributes unavailable in FIPS mode")
93c559
+    @unittest.skipIf(get_fips_mode(), "Internal attributes unavailable in FIPS mode")
93c559
     @hashlib_helper.requires_hashdigest('sha256')
93c559
     def test_attributes(self):
93c559
         # Testing if attributes are of same type.
93c559
@@ -469,7 +470,7 @@ class CopyTestCase(unittest.TestCase):
93c559
             "Types of outer don't match.")
93c559
 
93c559
 
93c559
-    @unittest.skipIf(hashlib.get_fips_mode(), "Internal attributes unavailable in FIPS mode")
93c559
+    @unittest.skipIf(get_fips_mode(), "Internal attributes unavailable in FIPS mode")
93c559
     @hashlib_helper.requires_hashdigest('sha256')
93c559
     def test_realcopy(self):
93c559
         # Testing if the copy method created a real copy.
93c559
@@ -485,7 +486,7 @@ class CopyTestCase(unittest.TestCase):
93c559
         self.assertEqual(h1._outer, h1.outer)
93c559
         self.assertEqual(h1._digest_cons, h1.digest_cons)
93c559
 
93c559
-    @unittest.skipIf(hashlib.get_fips_mode(), "Internal attributes unavailable in FIPS mode")
93c559
+    @unittest.skipIf(get_fips_mode(), "Internal attributes unavailable in FIPS mode")
93c559
     @hashlib_helper.requires_hashdigest('sha256')
93c559
     def test_properties(self):
93c559
         # deprecated properties
93c559
diff --git a/Lib/test/test_urllib2_localnet.py b/Lib/test/test_urllib2_localnet.py
93c559
index ed426b05a71..faec6844f9a 100644
93c559
--- a/Lib/test/test_urllib2_localnet.py
93c559
+++ b/Lib/test/test_urllib2_localnet.py
93c559
@@ -7,6 +7,7 @@ import http.server
93c559
 import threading
93c559
 import unittest
93c559
 import hashlib
93c559
+from _hashlib import get_fips_mode
93c559
 
93c559
 from test import support
93c559
 from test.support import hashlib_helper
93c559
-- 
93c559
2.26.2
93c559
93c559
93c559
From 3e314b647bc316dda3cef1f611fbac9170ed1030 Mon Sep 17 00:00:00 2001
93c559
From: Christian Heimes <christian@python.org>
93c559
Date: Wed, 20 Nov 2019 10:59:25 +0100
93c559
Subject: [PATCH 11/13] Use FIPS compliant CSPRNG
93c559
93c559
Kernel's getrandom() source is not yet FIPS compliant. Use OpenSSL's
93c559
DRBG in FIPS mode and disable os.getrandom() function.
93c559
93c559
Signed-off-by: Christian Heimes <christian@python.org>
93c559
---
93c559
 Lib/test/test_os.py     |  6 ++++++
93c559
 Makefile.pre.in         |  2 +-
93c559
 Modules/posixmodule.c   |  8 +++++++
93c559
 Python/bootstrap_hash.c | 48 +++++++++++++++++++++++++++++++++++++++++
93c559
 4 files changed, 63 insertions(+), 1 deletion(-)
93c559
93c559
diff --git a/Lib/test/test_os.py b/Lib/test/test_os.py
93c559
index bf1cb5f5112..d3b1d9c8969 100644
93c559
--- a/Lib/test/test_os.py
93c559
+++ b/Lib/test/test_os.py
93c559
@@ -29,6 +29,7 @@ import types
93c559
 import unittest
93c559
 import uuid
93c559
 import warnings
93c559
+from _hashlib import get_fips_mode
93c559
 from test import support
93c559
 from test.support import socket_helper
93c559
 from platform import win32_is_iot
93c559
@@ -1661,6 +1662,11 @@ class GetRandomTests(unittest.TestCase):
93c559
                 raise unittest.SkipTest("getrandom() syscall fails with ENOSYS")
93c559
             else:
93c559
                 raise
93c559
+        except ValueError as exc:
93c559
+            if get_fips_mode() and exc.args[0] == "getrandom is not FIPS compliant":
93c559
+                raise unittest.SkipTest("Skip in FIPS mode")
93c559
+            else:
93c559
+                raise
93c559
 
93c559
     def test_getrandom_type(self):
93c559
         data = os.getrandom(16)
93c559
diff --git a/Makefile.pre.in b/Makefile.pre.in
93c559
index f128444b985..3ea348a5461 100644
93c559
--- a/Makefile.pre.in
93c559
+++ b/Makefile.pre.in
93c559
@@ -116,7 +116,7 @@ PY_STDMODULE_CFLAGS= $(PY_CFLAGS) $(PY_CFLAGS_NODIST) $(PY_CPPFLAGS) $(CFLAGSFOR
93c559
 PY_BUILTIN_MODULE_CFLAGS= $(PY_STDMODULE_CFLAGS) -DPy_BUILD_CORE_BUILTIN
93c559
 PY_CORE_CFLAGS=	$(PY_STDMODULE_CFLAGS) -DPy_BUILD_CORE
93c559
 # Linker flags used for building the interpreter object files
93c559
-PY_CORE_LDFLAGS=$(PY_LDFLAGS) $(PY_LDFLAGS_NODIST)
93c559
+PY_CORE_LDFLAGS=$(PY_LDFLAGS) $(PY_LDFLAGS_NODIST) -lcrypto
93c559
 # Strict or non-strict aliasing flags used to compile dtoa.c, see above
93c559
 CFLAGS_ALIASING=@CFLAGS_ALIASING@
93c559
 
93c559
diff --git a/Modules/posixmodule.c b/Modules/posixmodule.c
93c559
index 12f72f525f7..d244d264d8a 100644
93c559
--- a/Modules/posixmodule.c
93c559
+++ b/Modules/posixmodule.c
93c559
@@ -495,6 +495,9 @@ extern char        *ctermid_r(char *);
93c559
 #  define MODNAME "posix"
93c559
 #endif
93c559
 
93c559
+/* for FIPS check in os.getrandom() */
93c559
+#include <openssl/crypto.h>
93c559
+
93c559
 #if defined(__sun)
93c559
 /* Something to implement in autoconf, not present in autoconf 2.69 */
93c559
 #  define HAVE_STRUCT_STAT_ST_FSTYPE 1
93c559
@@ -14171,6 +14174,11 @@ os_getrandom_impl(PyObject *module, Py_ssize_t size, int flags)
93c559
         return posix_error();
93c559
     }
93c559
 
93c559
+    if (FIPS_mode()) {
93c559
+        PyErr_SetString(PyExc_ValueError, "getrandom is not FIPS compliant");
93c559
+        return NULL;
93c559
+    }
93c559
+
93c559
     bytes = PyBytes_FromStringAndSize(NULL, size);
93c559
     if (bytes == NULL) {
93c559
         PyErr_NoMemory();
93c559
diff --git a/Python/bootstrap_hash.c b/Python/bootstrap_hash.c
93c559
index a212f69870e..6333cd446dc 100644
93c559
--- a/Python/bootstrap_hash.c
93c559
+++ b/Python/bootstrap_hash.c
93c559
@@ -429,6 +429,50 @@ dev_urandom_close(void)
93c559
 }
93c559
 #endif /* !MS_WINDOWS */
93c559
 
93c559
+#include <openssl/rand.h>
93c559
+#include <_hashopenssl.h>
93c559
+
93c559
+#if (OPENSSL_VERSION_NUMBER < 0x10101000L) || defined(LIBRESSL_VERSION_NUMBER)
93c559
+#  error "py_openssl_drbg_urandom requires OpenSSL 1.1.1 for fork safety"
93c559
+#endif
93c559
+
93c559
+static int
93c559
+py_openssl_drbg_urandom(char *buffer, Py_ssize_t size, int raise)
93c559
+{
93c559
+    int res;
93c559
+    static int init = 0;
93c559
+
93c559
+    if (!init) {
93c559
+        init = 1;
93c559
+        res = OPENSSL_init_crypto(OPENSSL_INIT_ATFORK, NULL);
93c559
+        if (res == 0) {
93c559
+            if (raise) {
93c559
+                _setException(PyExc_RuntimeError);
93c559
+            }
93c559
+            return 0;
93c559
+        }
93c559
+    }
93c559
+
93c559
+    if (size > INT_MAX) {
93c559
+        if (raise) {
93c559
+            PyErr_Format(PyExc_OverflowError,
93c559
+                         "RAND_bytes() size is limited to 2GB.");
93c559
+        }
93c559
+        return -1;
93c559
+    }
93c559
+
93c559
+    res = RAND_bytes((unsigned char*)buffer, (int)size);
93c559
+
93c559
+    if (res == 1) {
93c559
+        return 1;
93c559
+    } else {
93c559
+        if (raise) {
93c559
+            _setException(PyExc_RuntimeError);
93c559
+        }
93c559
+        return 0;
93c559
+    }
93c559
+}
93c559
+
93c559
 
93c559
 /* Fill buffer with pseudo-random bytes generated by a linear congruent
93c559
    generator (LCG):
93c559
@@ -513,6 +557,10 @@ pyurandom(void *buffer, Py_ssize_t size, int blocking, int raise)
93c559
         return 0;
93c559
     }
93c559
 
93c559
+    if (FIPS_mode()) {
93c559
+        return py_openssl_drbg_urandom(buffer, size, raise);
93c559
+    }
93c559
+
93c559
 #ifdef MS_WINDOWS
93c559
     return win32_urandom((unsigned char *)buffer, size, raise);
93c559
 #else
93c559
-- 
93c559
2.26.2
93c559
93c559
93c559
From 16b9a981697b94c348fdc0d73d2d12e12b1b4227 Mon Sep 17 00:00:00 2001
93c559
From: Petr Viktorin <pviktori@redhat.com>
93c559
Date: Tue, 7 Apr 2020 15:16:45 +0200
93c559
Subject: [PATCH 12/13] Pass kwargs (like usedforsecurity) through __hash_new
93c559
93c559
---
93c559
 Lib/hashlib.py | 2 +-
93c559
 1 file changed, 1 insertion(+), 1 deletion(-)
93c559
93c559
diff --git a/Lib/hashlib.py b/Lib/hashlib.py
93c559
index 6121d251267..00794adffc1 100644
93c559
--- a/Lib/hashlib.py
93c559
+++ b/Lib/hashlib.py
93c559
@@ -171,7 +171,7 @@ def __hash_new(name, data=b'', **kwargs):
93c559
         # the OpenSSL library prior to 0.9.8 doesn't provide them.
93c559
         if _hashlib.get_fips_mode():
93c559
             raise
93c559
-        return __get_builtin_constructor(name)(data)
93c559
+        return __get_builtin_constructor(name)(data, **kwargs)
93c559
 
93c559
 
93c559
 try:
93c559
-- 
93c559
2.26.2
93c559
93c559
93c559
From 48fb6366a0fcb95c8565be35495b25a23dc03896 Mon Sep 17 00:00:00 2001
93c559
From: Charalampos Stratakis <cstratak@redhat.com>
93c559
Date: Fri, 24 Apr 2020 19:57:16 +0200
93c559
Subject: [PATCH 13/13] Skip the test_with_digestmod_no_default under FIPS
93c559
93c559
Also add a new test for testing the error values of
93c559
the digestmod parameter misuse under FIPS mode.
93c559
---
93c559
 Lib/test/test_hmac.py | 13 +++++++++++++
93c559
 1 file changed, 13 insertions(+)
93c559
93c559
diff --git a/Lib/test/test_hmac.py b/Lib/test/test_hmac.py
93c559
index 2d4484911c2..e0a5b6a053b 100644
93c559
--- a/Lib/test/test_hmac.py
93c559
+++ b/Lib/test/test_hmac.py
93c559
@@ -347,6 +347,7 @@ class TestVectorsTestCase(unittest.TestCase):
93c559
                 hmac.HMAC(b'a', b'b', digestmod=MockCrazyHash)
93c559
                 self.fail('Expected warning about small block_size')
93c559
 
93c559
+    @unittest.skipIf(get_fips_mode(), "digestmod misuse raises different errors under FIPS mode")
93c559
     def test_with_digestmod_no_default(self):
93c559
         """The digestmod parameter is required as of Python 3.8."""
93c559
         with self.assertRaisesRegex(TypeError, r'required.*digestmod'):
93c559
@@ -358,6 +359,18 @@ class TestVectorsTestCase(unittest.TestCase):
93c559
         with self.assertRaisesRegex(TypeError, r'required.*digestmod'):
93c559
             hmac.HMAC(key, msg=data, digestmod='')
93c559
 
93c559
+    @unittest.skipIf(not get_fips_mode(), "test is run only under FIPS mode")
93c559
+    def test_with_digestmod_no_default_under_fips(self):
93c559
+        """Test the error values of digestmod misuse under FIPS mode."""
93c559
+        with self.assertRaises(TypeError):
93c559
+            key = b"\x0b" * 16
93c559
+            data = b"Hi There"
93c559
+            hmac.HMAC(key, data, digestmod=None)
93c559
+        with self.assertRaises(ValueError):
93c559
+            hmac.new(key, data)
93c559
+        with self.assertRaises(ValueError):
93c559
+            hmac.HMAC(key, msg=data, digestmod='')
93c559
+
93c559
 
93c559
 class ConstructorTestCase(unittest.TestCase):
93c559
 
93c559
-- 
93c559
2.26.2
93c559