Blame SOURCES/00329-fips.patch

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