Blame 00146-hashlib-fips.patch

90c54fb
diff --git a/Lib/hashlib.py b/Lib/hashlib.py
90c54fb
index 316cece..b7ad879 100644
90c54fb
--- a/Lib/hashlib.py
90c54fb
+++ b/Lib/hashlib.py
90c54fb
@@ -23,6 +23,16 @@ the zlib module.
a8ffdf3
 Choose your hash function wisely.  Some have known collision weaknesses.
a8ffdf3
 sha384 and sha512 will be slow on 32 bit platforms.
a8ffdf3
 
a8ffdf3
+If the underlying implementation supports "FIPS mode", and this is enabled, it
a8ffdf3
+may restrict the available hashes to only those that are compliant with FIPS
a8ffdf3
+regulations.  For example, it may deny the use of MD5, on the grounds that this
a8ffdf3
+is not secure for uses such as authentication, system integrity checking, or
a8ffdf3
+digital signatures.   If you need to use such a hash for non-security purposes
a8ffdf3
+(such as indexing into a data structure for speed), you can override the keyword
a8ffdf3
+argument "usedforsecurity" from True to False to signify that your code is not
a8ffdf3
+relying on the hash for security purposes, and this will allow the hash to be
a8ffdf3
+usable even in FIPS mode.
a8ffdf3
+
a8ffdf3
 Hash objects have these methods:
a8ffdf3
  - update(arg): Update the hash object with the bytes in arg. Repeated calls
a8ffdf3
                 are equivalent to a single call with the concatenation of all
90c54fb
@@ -62,6 +72,18 @@ algorithms_available = set(__always_supported)
a8ffdf3
 __all__ = __always_supported + ('new', 'algorithms_guaranteed',
a8ffdf3
                                 'algorithms_available', 'pbkdf2_hmac')
a8ffdf3
 
a8ffdf3
+import functools
a8ffdf3
+def __ignore_usedforsecurity(func):
a8ffdf3
+    """Used for sha3_* functions. Until OpenSSL implements them, we want
a8ffdf3
+    to use them from Python _sha3 module, but we want them to accept
a8ffdf3
+    usedforsecurity argument too."""
a8ffdf3
+    # TODO: remove this function when OpenSSL implements sha3
a8ffdf3
+    @functools.wraps(func)
a8ffdf3
+    def inner(*args, **kwargs):
a8ffdf3
+        if 'usedforsecurity' in kwargs:
a8ffdf3
+            kwargs.pop('usedforsecurity')
a8ffdf3
+        return func(*args, **kwargs)
a8ffdf3
+    return inner
a8ffdf3
 
a8ffdf3
 __builtin_constructor_cache = {}
a8ffdf3
 
90c54fb
@@ -100,31 +122,39 @@ def __get_openssl_constructor(name):
a8ffdf3
         f = getattr(_hashlib, 'openssl_' + name)
a8ffdf3
         # Allow the C module to raise ValueError.  The function will be
a8ffdf3
         # defined but the hash not actually available thanks to OpenSSL.
a8ffdf3
-        f()
a8ffdf3
+        # We pass "usedforsecurity=False" to disable FIPS-based restrictions:
a8ffdf3
+        # at this stage we're merely seeing if the function is callable,
a8ffdf3
+        # rather than using it for actual work.
a8ffdf3
+        f(usedforsecurity=False)
a8ffdf3
         # Use the C function directly (very fast)
a8ffdf3
         return f
a8ffdf3
     except (AttributeError, ValueError):
a8ffdf3
+        # TODO: We want to just raise here when OpenSSL implements sha3
a8ffdf3
+        # because we want to make sure that Fedora uses everything from OpenSSL
a8ffdf3
         return __get_builtin_constructor(name)
a8ffdf3
 
a8ffdf3
 
a8ffdf3
-def __py_new(name, data=b''):
a8ffdf3
-    """new(name, data=b'') - Return a new hashing object using the named algorithm;
a8ffdf3
-    optionally initialized with data (which must be bytes).
a8ffdf3
+def __py_new(name, data=b'', usedforsecurity=True):
a8ffdf3
+    """new(name, data=b'', usedforsecurity=True) - Return a new hashing object using
a8ffdf3
+    the named algorithm; optionally initialized with data (which must be bytes).
a8ffdf3
+    The 'usedforsecurity' keyword argument does nothing, and is for compatibilty
a8ffdf3
+    with the OpenSSL implementation
a8ffdf3
     """
a8ffdf3
     return __get_builtin_constructor(name)(data)
a8ffdf3
 
a8ffdf3
 
a8ffdf3
-def __hash_new(name, data=b''):
a8ffdf3
-    """new(name, data=b'') - Return a new hashing object using the named algorithm;
a8ffdf3
-    optionally initialized with data (which must be bytes).
a8ffdf3
+def __hash_new(name, data=b'', usedforsecurity=True):
a8ffdf3
+    """new(name, data=b'', usedforsecurity=True) - Return a new hashing object using
a8ffdf3
+    the named algorithm; optionally initialized with data (which must be bytes).
a8ffdf3
+    
a8ffdf3
+    Override 'usedforsecurity' to False when using for non-security purposes in
a8ffdf3
+    a FIPS environment
a8ffdf3
     """
a8ffdf3
     try:
a8ffdf3
-        return _hashlib.new(name, data)
a8ffdf3
+        return _hashlib.new(name, data, usedforsecurity)
a8ffdf3
     except ValueError:
a8ffdf3
-        # If the _hashlib module (OpenSSL) doesn't support the named
a8ffdf3
-        # hash, try using our builtin implementations.
a8ffdf3
-        # This allows for SHA224/256 and SHA384/512 support even though
a8ffdf3
-        # the OpenSSL library prior to 0.9.8 doesn't provide them.
a8ffdf3
+        # TODO: We want to just raise here when OpenSSL implements sha3
a8ffdf3
+        # because we want to make sure that Fedora uses everything from OpenSSL
a8ffdf3
         return __get_builtin_constructor(name)(data)
a8ffdf3
 
90c54fb
 
90c54fb
@@ -207,7 +237,10 @@ for __func_name in __always_supported:
a8ffdf3
     # try them all, some may not work due to the OpenSSL
a8ffdf3
     # version not supporting that algorithm.
a8ffdf3
     try:
a8ffdf3
-        globals()[__func_name] = __get_hash(__func_name)
a8ffdf3
+        func = __get_hash(__func_name)
a8ffdf3
+        if 'sha3_' in __func_name:
a8ffdf3
+            func = __ignore_usedforsecurity(func)
a8ffdf3
+        globals()[__func_name] = func
a8ffdf3
     except ValueError:
a8ffdf3
         import logging
a8ffdf3
         logging.exception('code for hash %s was not found.', __func_name)
90c54fb
@@ -215,3 +248,4 @@ for __func_name in __always_supported:
a8ffdf3
 # Cleanup locals()
a8ffdf3
 del __always_supported, __func_name, __get_hash
a8ffdf3
 del __py_new, __hash_new, __get_openssl_constructor
a8ffdf3
+del __ignore_usedforsecurity
90c54fb
\ No newline at end of file
90c54fb
diff --git a/Lib/test/test_hashlib.py b/Lib/test/test_hashlib.py
90c54fb
index c9b113e..60e2392 100644
90c54fb
--- a/Lib/test/test_hashlib.py
90c54fb
+++ b/Lib/test/test_hashlib.py
90c54fb
@@ -24,7 +24,22 @@ from test.support import _4G, bigmemtest, import_fresh_module
a8ffdf3
 COMPILED_WITH_PYDEBUG = hasattr(sys, 'gettotalrefcount')
a8ffdf3
 
a8ffdf3
 c_hashlib = import_fresh_module('hashlib', fresh=['_hashlib'])
a8ffdf3
-py_hashlib = import_fresh_module('hashlib', blocked=['_hashlib'])
a8ffdf3
+# skipped on Fedora, since we always use OpenSSL implementation
a8ffdf3
+# py_hashlib = import_fresh_module('hashlib', blocked=['_hashlib'])
a8ffdf3
+
a8ffdf3
+def openssl_enforces_fips():
a8ffdf3
+    # Use the "openssl" command (if present) to try to determine if the local
a8ffdf3
+    # OpenSSL is configured to enforce FIPS
a8ffdf3
+    from subprocess import Popen, PIPE
a8ffdf3
+    try:
a8ffdf3
+        p = Popen(['openssl', 'md5'],
a8ffdf3
+                  stdin=PIPE, stdout=PIPE, stderr=PIPE)
a8ffdf3
+    except OSError:
a8ffdf3
+        # "openssl" command not found
a8ffdf3
+        return False
a8ffdf3
+    stdout, stderr = p.communicate(input=b'abc')
a8ffdf3
+    return b'unknown cipher' in stderr
a8ffdf3
+OPENSSL_ENFORCES_FIPS = openssl_enforces_fips()
a8ffdf3
 
a8ffdf3
 def hexstr(s):
a8ffdf3
     assert isinstance(s, bytes), repr(s)
90c54fb
@@ -34,6 +49,16 @@ def hexstr(s):
a8ffdf3
         r += h[(i >> 4) & 0xF] + h[i & 0xF]
a8ffdf3
     return r
a8ffdf3
 
a8ffdf3
+# hashlib and _hashlib-based functions support a "usedforsecurity" keyword
a8ffdf3
+# argument, and FIPS mode requires that it be used overridden with a False
a8ffdf3
+# value for these selftests to work.  Other cryptographic code within Python
a8ffdf3
+# doesn't support this keyword.
a8ffdf3
+# Modify a function to one in which "usedforsecurity=False" is added to the
a8ffdf3
+# keyword arguments:
a8ffdf3
+def suppress_fips(f):
a8ffdf3
+    def g(*args, **kwargs):
a8ffdf3
+        return f(*args, usedforsecurity=False, **kwargs)
a8ffdf3
+    return g
a8ffdf3
 
a8ffdf3
 class HashLibTestCase(unittest.TestCase):
a8ffdf3
     supported_hash_names = ( 'md5', 'MD5', 'sha1', 'SHA1',
90c54fb
@@ -63,11 +88,11 @@ class HashLibTestCase(unittest.TestCase):
a8ffdf3
         # For each algorithm, test the direct constructor and the use
a8ffdf3
         # of hashlib.new given the algorithm name.
a8ffdf3
         for algorithm, constructors in self.constructors_to_test.items():
a8ffdf3
-            constructors.add(getattr(hashlib, algorithm))
a8ffdf3
+            constructors.add(suppress_fips(getattr(hashlib, algorithm)))
a8ffdf3
             def _test_algorithm_via_hashlib_new(data=None, _alg=algorithm):
a8ffdf3
                 if data is None:
a8ffdf3
-                    return hashlib.new(_alg)
a8ffdf3
-                return hashlib.new(_alg, data)
a8ffdf3
+                    return suppress_fips(hashlib.new)(_alg)
a8ffdf3
+                return suppress_fips(hashlib.new)(_alg, data)
a8ffdf3
             constructors.add(_test_algorithm_via_hashlib_new)
a8ffdf3
 
a8ffdf3
         _hashlib = self._conditional_import_module('_hashlib')
90c54fb
@@ -79,27 +104,12 @@ class HashLibTestCase(unittest.TestCase):
a8ffdf3
             for algorithm, constructors in self.constructors_to_test.items():
a8ffdf3
                 constructor = getattr(_hashlib, 'openssl_'+algorithm, None)
a8ffdf3
                 if constructor:
a8ffdf3
-                    constructors.add(constructor)
a8ffdf3
+                    constructors.add(suppress_fips(constructor))
a8ffdf3
 
a8ffdf3
         def add_builtin_constructor(name):
a8ffdf3
             constructor = getattr(hashlib, "__get_builtin_constructor")(name)
a8ffdf3
             self.constructors_to_test[name].add(constructor)
a8ffdf3
 
a8ffdf3
-        _md5 = self._conditional_import_module('_md5')
a8ffdf3
-        if _md5:
a8ffdf3
-            add_builtin_constructor('md5')
a8ffdf3
-        _sha1 = self._conditional_import_module('_sha1')
a8ffdf3
-        if _sha1:
a8ffdf3
-            add_builtin_constructor('sha1')
a8ffdf3
-        _sha256 = self._conditional_import_module('_sha256')
a8ffdf3
-        if _sha256:
a8ffdf3
-            add_builtin_constructor('sha224')
a8ffdf3
-            add_builtin_constructor('sha256')
a8ffdf3
-        _sha512 = self._conditional_import_module('_sha512')
a8ffdf3
-        if _sha512:
a8ffdf3
-            add_builtin_constructor('sha384')
a8ffdf3
-            add_builtin_constructor('sha512')
90c54fb
-
a8ffdf3
         super(HashLibTestCase, self).__init__(*args, **kwargs)
a8ffdf3
 
90c54fb
     @property
90c54fb
@@ -148,9 +158,6 @@ class HashLibTestCase(unittest.TestCase):
a8ffdf3
             else:
a8ffdf3
                 del sys.modules['_md5']
a8ffdf3
         self.assertRaises(TypeError, get_builtin_constructor, 3)
a8ffdf3
-        constructor = get_builtin_constructor('md5')
a8ffdf3
-        self.assertIs(constructor, _md5.md5)
a8ffdf3
-        self.assertEqual(sorted(builtin_constructor_cache), ['MD5', 'md5'])
a8ffdf3
 
a8ffdf3
     def test_hexdigest(self):
a8ffdf3
         for cons in self.hash_constructors:
90c54fb
@@ -433,6 +440,64 @@ class HashLibTestCase(unittest.TestCase):
a8ffdf3
 
a8ffdf3
         self.assertEqual(expected_hash, hasher.hexdigest())
a8ffdf3
 
a8ffdf3
+    def test_issue9146(self):
a8ffdf3
+        # Ensure that various ways to use "MD5" from "hashlib" don't segfault:
a8ffdf3
+        m = hashlib.md5(usedforsecurity=False)
a8ffdf3
+        m.update(b'abc\n')
a8ffdf3
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
a8ffdf3
+        
a8ffdf3
+        m = hashlib.new('md5', usedforsecurity=False)
a8ffdf3
+        m.update(b'abc\n')
a8ffdf3
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
a8ffdf3
+        
a8ffdf3
+        m = hashlib.md5(b'abc\n', usedforsecurity=False)
a8ffdf3
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
a8ffdf3
+        
a8ffdf3
+        m = hashlib.new('md5', b'abc\n', usedforsecurity=False)
a8ffdf3
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
a8ffdf3
+
a8ffdf3
+    @unittest.skipUnless(OPENSSL_ENFORCES_FIPS,
a8ffdf3
+                         'FIPS enforcement required for this test.')
a8ffdf3
+    def test_hashlib_fips_mode(self):        
a8ffdf3
+        # Ensure that we raise a ValueError on vanilla attempts to use MD5
a8ffdf3
+        # in hashlib in a FIPS-enforced setting:
a8ffdf3
+        with self.assertRaisesRegexp(ValueError, '.*unknown cipher'):
a8ffdf3
+            m = hashlib.md5()
a8ffdf3
+            
a8ffdf3
+        if not self._conditional_import_module('_md5'):
a8ffdf3
+            with self.assertRaisesRegexp(ValueError, '.*unknown cipher'):
a8ffdf3
+                m = hashlib.new('md5')
a8ffdf3
+
a8ffdf3
+    @unittest.skipUnless(OPENSSL_ENFORCES_FIPS,
a8ffdf3
+                         'FIPS enforcement required for this test.')
a8ffdf3
+    def test_hashopenssl_fips_mode(self):
a8ffdf3
+        # Verify the _hashlib module's handling of md5:
a8ffdf3
+        _hashlib = self._conditional_import_module('_hashlib')
a8ffdf3
+        if _hashlib:
a8ffdf3
+            assert hasattr(_hashlib, 'openssl_md5')
a8ffdf3
+
a8ffdf3
+            # Ensure that _hashlib raises a ValueError on vanilla attempts to
a8ffdf3
+            # use MD5 in a FIPS-enforced setting:
a8ffdf3
+            with self.assertRaisesRegexp(ValueError, '.*unknown cipher'):
a8ffdf3
+                m = _hashlib.openssl_md5()
a8ffdf3
+            with self.assertRaisesRegexp(ValueError, '.*unknown cipher'):
a8ffdf3
+                m = _hashlib.new('md5')
a8ffdf3
+
a8ffdf3
+            # Ensure that in such a setting we can whitelist a callsite with
a8ffdf3
+            # usedforsecurity=False and have it succeed:
a8ffdf3
+            m = _hashlib.openssl_md5(usedforsecurity=False)
a8ffdf3
+            m.update(b'abc\n')
a8ffdf3
+            self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
a8ffdf3
+        
a8ffdf3
+            m = _hashlib.new('md5', usedforsecurity=False)
a8ffdf3
+            m.update(b'abc\n')
a8ffdf3
+            self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
a8ffdf3
+       
a8ffdf3
+            m = _hashlib.openssl_md5(b'abc\n', usedforsecurity=False)
a8ffdf3
+            self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
a8ffdf3
+        
a8ffdf3
+            m = _hashlib.new('md5', b'abc\n', usedforsecurity=False)
a8ffdf3
+            self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
a8ffdf3
 
a8ffdf3
 class KDFTests(unittest.TestCase):
a8ffdf3
 
90c54fb
@@ -516,7 +581,7 @@ class KDFTests(unittest.TestCase):
90c54fb
         out = pbkdf2(hash_name='sha1', password=b'password', salt=b'salt',
90c54fb
             iterations=1, dklen=None)
90c54fb
         self.assertEqual(out, self.pbkdf2_results['sha1'][0][0])
90c54fb
-
a8ffdf3
+    @unittest.skip('skipped on Fedora, as we always use OpenSSL pbkdf2_hmac')
a8ffdf3
     def test_pbkdf2_hmac_py(self):
a8ffdf3
         self._test_pbkdf2_hmac(py_hashlib.pbkdf2_hmac)
a8ffdf3
 
90c54fb
diff --git a/Modules/_hashopenssl.c b/Modules/_hashopenssl.c
9dab8a4
index ff57614..8cd1b77 100644
90c54fb
--- a/Modules/_hashopenssl.c
90c54fb
+++ b/Modules/_hashopenssl.c
90c54fb
@@ -20,6 +20,8 @@
a8ffdf3
 
a8ffdf3
 
a8ffdf3
 /* EVP is the preferred interface to hashing in OpenSSL */
a8ffdf3
+#include <openssl/ssl.h>
a8ffdf3
+#include <openssl/err.h>
a8ffdf3
 #include <openssl/evp.h>
a8ffdf3
 /* We use the object interface to discover what hashes OpenSSL supports. */
9dab8a4
 #include <openssl/objects.h>
9dab8a4
@@ -55,10 +57,19 @@ typedef struct {
a8ffdf3
 
a8ffdf3
 static PyTypeObject EVPtype;
a8ffdf3
 
a8ffdf3
+/* Struct to hold all the cached information we need on a specific algorithm.
a8ffdf3
+   We have one of these per algorithm */
a8ffdf3
+typedef struct {
a8ffdf3
+    PyObject *name_obj;
a8ffdf3
+    EVP_MD_CTX ctxs[2];
a8ffdf3
+    /* ctx_ptrs will point to ctxs unless an error occurred, when it will
a8ffdf3
+       be NULL: */
a8ffdf3
+    EVP_MD_CTX *ctx_ptrs[2];
a8ffdf3
+    PyObject *error_msgs[2];
a8ffdf3
+} EVPCachedInfo;
a8ffdf3
 
a8ffdf3
-#define DEFINE_CONSTS_FOR_NEW(Name)  \
a8ffdf3
-    static PyObject *CONST_ ## Name ## _name_obj = NULL; \
a8ffdf3
-    static EVP_MD_CTX *CONST_new_ ## Name ## _ctx_p = NULL;
a8ffdf3
+#define DEFINE_CONSTS_FOR_NEW(Name) \
a8ffdf3
+    static EVPCachedInfo cached_info_ ##Name;
a8ffdf3
 
a8ffdf3
 DEFINE_CONSTS_FOR_NEW(md5)
a8ffdf3
 DEFINE_CONSTS_FOR_NEW(sha1)
9dab8a4
@@ -139,6 +150,48 @@ EVP_hash(EVPobject *self, const void *vp, Py_ssize_t len)
a8ffdf3
     }
a8ffdf3
 }
a8ffdf3
 
a8ffdf3
+static void
a8ffdf3
+mc_ctx_init(EVP_MD_CTX *ctx, int usedforsecurity)
a8ffdf3
+{
a8ffdf3
+    EVP_MD_CTX_init(ctx);
a8ffdf3
+
a8ffdf3
+    /*
a8ffdf3
+      If the user has declared that this digest is being used in a
a8ffdf3
+      non-security role (e.g. indexing into a data structure), set
a8ffdf3
+      the exception flag for openssl to allow it
a8ffdf3
+    */
a8ffdf3
+    if (!usedforsecurity) {
a8ffdf3
+#ifdef EVP_MD_CTX_FLAG_NON_FIPS_ALLOW
a8ffdf3
+        EVP_MD_CTX_set_flags(ctx,
a8ffdf3
+                             EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
a8ffdf3
+#endif
a8ffdf3
+    }
a8ffdf3
+}
a8ffdf3
+
a8ffdf3
+/* Get an error msg for the last error as a PyObject */
a8ffdf3
+static PyObject *
a8ffdf3
+error_msg_for_last_error(void)
a8ffdf3
+{
a8ffdf3
+    char *errstr;
a8ffdf3
+
a8ffdf3
+    errstr = ERR_error_string(ERR_peek_last_error(), NULL);
a8ffdf3
+    ERR_clear_error();
a8ffdf3
+
a8ffdf3
+    return PyUnicode_FromString(errstr); /* Can be NULL */
a8ffdf3
+}
a8ffdf3
+
a8ffdf3
+static void
a8ffdf3
+set_evp_exception(void)
a8ffdf3
+{
a8ffdf3
+    char *errstr;
a8ffdf3
+
a8ffdf3
+    errstr = ERR_error_string(ERR_peek_last_error(), NULL);
a8ffdf3
+    ERR_clear_error();
a8ffdf3
+
a8ffdf3
+    PyErr_SetString(PyExc_ValueError, errstr);
a8ffdf3
+}
a8ffdf3
+
a8ffdf3
+
a8ffdf3
 /* Internal methods for a hash object */
a8ffdf3
 
a8ffdf3
 static void
9dab8a4
@@ -327,15 +380,16 @@ EVP_repr(EVPobject *self)
a8ffdf3
 static int
a8ffdf3
 EVP_tp_init(EVPobject *self, PyObject *args, PyObject *kwds)
a8ffdf3
 {
a8ffdf3
-    static char *kwlist[] = {"name", "string", NULL};
a8ffdf3
+    static char *kwlist[] = {"name", "string", "usedforsecurity", NULL};
a8ffdf3
     PyObject *name_obj = NULL;
a8ffdf3
     PyObject *data_obj = NULL;
a8ffdf3
+    int usedforsecurity = 1;
a8ffdf3
     Py_buffer view;
a8ffdf3
     char *nameStr;
a8ffdf3
     const EVP_MD *digest;
a8ffdf3
 
a8ffdf3
-    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:HASH", kwlist,
a8ffdf3
-                                     &name_obj, &data_obj)) {
a8ffdf3
+    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:HASH", kwlist,
a8ffdf3
+                                     &name_obj, &data_obj, &usedforsecurity)) {
a8ffdf3
         return -1;
a8ffdf3
     }
a8ffdf3
 
9dab8a4
@@ -356,7 +410,12 @@ EVP_tp_init(EVPobject *self, PyObject *args, PyObject *kwds)
a8ffdf3
             PyBuffer_Release(&view);
a8ffdf3
         return -1;
a8ffdf3
     }
9dab8a4
-    EVP_DigestInit(self->ctx, digest);
9dab8a4
+    mc_ctx_init(self->ctx, usedforsecurity);
9dab8a4
+    if (!EVP_DigestInit_ex(self->ctx, digest, NULL)) {
a8ffdf3
+        set_evp_exception();
a8ffdf3
+        PyBuffer_Release(&view);
9dab8a4
+        Py_RETURN_NONE;
a8ffdf3
+    }
a8ffdf3
 
a8ffdf3
     self->name = name_obj;
a8ffdf3
     Py_INCREF(self->name);
9dab8a4
@@ -440,7 +499,8 @@ static PyTypeObject EVPtype = {
a8ffdf3
 static PyObject *
a8ffdf3
 EVPnew(PyObject *name_obj,
a8ffdf3
        const EVP_MD *digest, const EVP_MD_CTX *initial_ctx,
a8ffdf3
-       const unsigned char *cp, Py_ssize_t len)
a8ffdf3
+       const unsigned char *cp, Py_ssize_t len,
a8ffdf3
+       int usedforsecurity)
a8ffdf3
 {
a8ffdf3
     EVPobject *self;
a8ffdf3
 
9dab8a4
@@ -455,7 +515,12 @@ EVPnew(PyObject *name_obj,
a8ffdf3
     if (initial_ctx) {
9dab8a4
         EVP_MD_CTX_copy(self->ctx, initial_ctx);
a8ffdf3
     } else {
9dab8a4
-        EVP_DigestInit(self->ctx, digest);
9dab8a4
+        mc_ctx_init(self->ctx, usedforsecurity);
9dab8a4
+        if (!EVP_DigestInit_ex(self->ctx, digest, NULL)) {
a8ffdf3
+            set_evp_exception();
a8ffdf3
+            Py_DECREF(self);
a8ffdf3
+            return NULL;
a8ffdf3
+        }
a8ffdf3
     }
a8ffdf3
 
a8ffdf3
     if (cp && len) {
9dab8a4
@@ -479,21 +544,29 @@ PyDoc_STRVAR(EVP_new__doc__,
a8ffdf3
 An optional string argument may be provided and will be\n\
a8ffdf3
 automatically hashed.\n\
a8ffdf3
 \n\
a8ffdf3
-The MD5 and SHA1 algorithms are always supported.\n");
a8ffdf3
+The MD5 and SHA1 algorithms are always supported.\n\
a8ffdf3
+\n\
a8ffdf3
+An optional \"usedforsecurity=True\" keyword argument is provided for use in\n\
a8ffdf3
+environments that enforce FIPS-based restrictions.  Some implementations of\n\
a8ffdf3
+OpenSSL can be configured to prevent the usage of non-secure algorithms (such\n\
a8ffdf3
+as MD5).  If you have a non-security use for these algorithms (e.g. a hash\n\
a8ffdf3
+table), you can override this argument by marking the callsite as\n\
a8ffdf3
+\"usedforsecurity=False\".");
a8ffdf3
 
a8ffdf3
 static PyObject *
a8ffdf3
 EVP_new(PyObject *self, PyObject *args, PyObject *kwdict)
a8ffdf3
 {
a8ffdf3
-    static char *kwlist[] = {"name", "string", NULL};
a8ffdf3
+    static char *kwlist[] = {"name", "string", "usedforsecurity", NULL};
a8ffdf3
     PyObject *name_obj = NULL;
a8ffdf3
     PyObject *data_obj = NULL;
a8ffdf3
+    int usedforsecurity = 1;
a8ffdf3
     Py_buffer view = { 0 };
a8ffdf3
     PyObject *ret_obj;
a8ffdf3
     char *name;
a8ffdf3
     const EVP_MD *digest;
a8ffdf3
 
a8ffdf3
-    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "O|O:new", kwlist,
a8ffdf3
-                                     &name_obj, &data_obj)) {
a8ffdf3
+    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "O|Oi:new", kwlist,
a8ffdf3
+                                     &name_obj, &data_obj, &usedforsecurity)) {
a8ffdf3
         return NULL;
a8ffdf3
     }
a8ffdf3
 
9dab8a4
@@ -507,7 +580,8 @@ EVP_new(PyObject *self, PyObject *args, PyObject *kwdict)
a8ffdf3
 
a8ffdf3
     digest = EVP_get_digestbyname(name);
a8ffdf3
 
a8ffdf3
-    ret_obj = EVPnew(name_obj, digest, NULL, (unsigned char*)view.buf, view.len);
a8ffdf3
+    ret_obj = EVPnew(name_obj, digest, NULL, (unsigned char*)view.buf, view.len,
90c54fb
+                    usedforsecurity);
a8ffdf3
 
a8ffdf3
     if (data_obj)
a8ffdf3
         PyBuffer_Release(&view);
9dab8a4
@@ -769,57 +843,114 @@ generate_hash_name_list(void)
a8ffdf3
 
a8ffdf3
 
a8ffdf3
 /*
a8ffdf3
- *  This macro generates constructor function definitions for specific
a8ffdf3
- *  hash algorithms.  These constructors are much faster than calling
9dab8a4
- *  the generic one passing it a python string and are noticeably
a8ffdf3
- *  faster than calling a python new() wrapper.  Thats important for
a8ffdf3
+ *  This macro and function generates a family of constructor function
a8ffdf3
+ *  definitions for specific hash algorithms.  These constructors are much
a8ffdf3
+ *  faster than calling the generic one passing it a python string and are
a8ffdf3
+ *  noticably faster than calling a python new() wrapper.  That's important for
a8ffdf3
  *  code that wants to make hashes of a bunch of small strings.
a8ffdf3
  */
a8ffdf3
 #define GEN_CONSTRUCTOR(NAME)  \
a8ffdf3
     static PyObject * \
a8ffdf3
-    EVP_new_ ## NAME (PyObject *self, PyObject *args) \
a8ffdf3
+    EVP_new_ ## NAME (PyObject *self, PyObject *args, PyObject *kwdict)        \
a8ffdf3
     { \
a8ffdf3
-        PyObject *data_obj = NULL; \
a8ffdf3
-        Py_buffer view = { 0 }; \
a8ffdf3
-        PyObject *ret_obj; \
a8ffdf3
-     \
a8ffdf3
-        if (!PyArg_ParseTuple(args, "|O:" #NAME , &data_obj)) { \
a8ffdf3
-            return NULL; \
a8ffdf3
-        } \
a8ffdf3
-     \
a8ffdf3
-        if (data_obj) \
a8ffdf3
-            GET_BUFFER_VIEW_OR_ERROUT(data_obj, &view); \
a8ffdf3
-     \
a8ffdf3
-        ret_obj = EVPnew( \
a8ffdf3
-                    CONST_ ## NAME ## _name_obj, \
a8ffdf3
-                    NULL, \
a8ffdf3
-                    CONST_new_ ## NAME ## _ctx_p, \
a8ffdf3
-                    (unsigned char*)view.buf, \
a8ffdf3
-                    view.len); \
a8ffdf3
-     \
a8ffdf3
-        if (data_obj) \
a8ffdf3
-            PyBuffer_Release(&view); \
a8ffdf3
-        return ret_obj; \
a8ffdf3
+       return implement_specific_EVP_new(self, args, kwdict,      \
a8ffdf3
+                                         "|Oi:" #NAME,            \
a8ffdf3
+                                         &cached_info_ ## NAME ); \
9dab8a4
+    }
9dab8a4
+
a8ffdf3
+static PyObject *
a8ffdf3
+implement_specific_EVP_new(PyObject *self, PyObject *args, PyObject *kwdict,
a8ffdf3
+                           const char *format,
a8ffdf3
+                           EVPCachedInfo *cached_info)
a8ffdf3
+{
a8ffdf3
+    static char *kwlist[] = {"string", "usedforsecurity", NULL}; 
a8ffdf3
+    PyObject *data_obj = NULL;
a8ffdf3
+    Py_buffer view = { 0 };
a8ffdf3
+    int usedforsecurity = 1;
a8ffdf3
+    int idx;
a8ffdf3
+    PyObject *ret_obj = NULL;
a8ffdf3
+
a8ffdf3
+    assert(cached_info);
a8ffdf3
+
a8ffdf3
+    if (!PyArg_ParseTupleAndKeywords(args, kwdict, format, kwlist,
a8ffdf3
+                                     &data_obj, &usedforsecurity)) {
a8ffdf3
+        return NULL;
9dab8a4
     }
9dab8a4
 
a8ffdf3
+    if (data_obj)
a8ffdf3
+       GET_BUFFER_VIEW_OR_ERROUT(data_obj, &view);
a8ffdf3
+
a8ffdf3
+    idx = usedforsecurity ? 1 : 0;
a8ffdf3
+
a8ffdf3
+    /*
a8ffdf3
+     * If an error occurred during creation of the global content, the ctx_ptr
a8ffdf3
+     * will be NULL, and the error_msg will hopefully be non-NULL:
a8ffdf3
+     */
a8ffdf3
+    if (cached_info->ctx_ptrs[idx]) {
a8ffdf3
+        /* We successfully initialized this context; copy it: */
a8ffdf3
+        ret_obj = EVPnew(cached_info->name_obj,
a8ffdf3
+                         NULL,
a8ffdf3
+                         cached_info->ctx_ptrs[idx],
a8ffdf3
+                         (unsigned char*)view.buf, view.len,
a8ffdf3
+                         usedforsecurity);
a8ffdf3
+    } else {
a8ffdf3
+        /* Some kind of error happened initializing the global context for
a8ffdf3
+           this (digest, usedforsecurity) pair.
a8ffdf3
+           Raise an exception with the saved error message: */
a8ffdf3
+        if (cached_info->error_msgs[idx]) {
a8ffdf3
+            PyErr_SetObject(PyExc_ValueError, cached_info->error_msgs[idx]);
a8ffdf3
+        } else {
a8ffdf3
+            PyErr_SetString(PyExc_ValueError, "Error initializing hash");
a8ffdf3
+        }
90c54fb
+     }
90c54fb
+ 
a8ffdf3
+    if (data_obj)
a8ffdf3
+        PyBuffer_Release(&view);
a8ffdf3
+
a8ffdf3
+    return ret_obj;
a8ffdf3
+}
a8ffdf3
+
a8ffdf3
 /* a PyMethodDef structure for the constructor */
a8ffdf3
 #define CONSTRUCTOR_METH_DEF(NAME)  \
a8ffdf3
-    {"openssl_" #NAME, (PyCFunction)EVP_new_ ## NAME, METH_VARARGS, \
a8ffdf3
+    {"openssl_" #NAME, (PyCFunction)EVP_new_ ## NAME, \
a8ffdf3
+        METH_VARARGS|METH_KEYWORDS, \
a8ffdf3
         PyDoc_STR("Returns a " #NAME \
a8ffdf3
                   " hash object; optionally initialized with a string") \
a8ffdf3
     }
a8ffdf3
 
a8ffdf3
-/* used in the init function to setup a constructor: initialize OpenSSL
a8ffdf3
-   constructor constants if they haven't been initialized already.  */
a8ffdf3
-#define INIT_CONSTRUCTOR_CONSTANTS(NAME)  do { \
a8ffdf3
-    if (CONST_ ## NAME ## _name_obj == NULL) { \
a8ffdf3
-        CONST_ ## NAME ## _name_obj = PyUnicode_FromString(#NAME); \
a8ffdf3
-        if (EVP_get_digestbyname(#NAME)) { \
9dab8a4
-            CONST_new_ ## NAME ## _ctx_p = EVP_MD_CTX_new(); \
a8ffdf3
-            EVP_DigestInit(CONST_new_ ## NAME ## _ctx_p, EVP_get_digestbyname(#NAME)); \
a8ffdf3
-        } \
a8ffdf3
-    } \
a8ffdf3
+/*
a8ffdf3
+  Macro/function pair to set up the constructors.
a8ffdf3
+
a8ffdf3
+  Try to initialize a context for each hash twice, once with
a8ffdf3
+  EVP_MD_CTX_FLAG_NON_FIPS_ALLOW and once without.
a8ffdf3
+  
a8ffdf3
+  Any that have errors during initialization will end up with a NULL ctx_ptrs
a8ffdf3
+  entry, and err_msgs will be set (unless we're very low on memory)
a8ffdf3
+*/
a8ffdf3
+#define INIT_CONSTRUCTOR_CONSTANTS(NAME)  do {    \
a8ffdf3
+    init_constructor_constant(&cached_info_ ## NAME, #NAME); \
a8ffdf3
 } while (0);
a8ffdf3
+static void
a8ffdf3
+init_constructor_constant(EVPCachedInfo *cached_info, const char *name)
a8ffdf3
+{
a8ffdf3
+    assert(cached_info);
a8ffdf3
+    cached_info->name_obj = PyUnicode_FromString(name);
a8ffdf3
+    if (EVP_get_digestbyname(name)) {
a8ffdf3
+        int i;
a8ffdf3
+        for (i=0; i<2; i++) {
a8ffdf3
+            mc_ctx_init(&cached_info->ctxs[i], i);
a8ffdf3
+            if (EVP_DigestInit_ex(&cached_info->ctxs[i],
a8ffdf3
+                                  EVP_get_digestbyname(name), NULL)) {
a8ffdf3
+                /* Success: */
a8ffdf3
+                cached_info->ctx_ptrs[i] = &cached_info->ctxs[i];
a8ffdf3
+            } else {
a8ffdf3
+                /* Failure: */
a8ffdf3
+              cached_info->ctx_ptrs[i] = NULL;
a8ffdf3
+              cached_info->error_msgs[i] = error_msg_for_last_error();
a8ffdf3
+            }
a8ffdf3
+        }
a8ffdf3
+    }
a8ffdf3
+}
a8ffdf3
 
a8ffdf3
 GEN_CONSTRUCTOR(md5)
a8ffdf3
 GEN_CONSTRUCTOR(sha1)
9dab8a4
@@ -866,13 +997,10 @@ PyInit__hashlib(void)
a8ffdf3
 {
a8ffdf3
     PyObject *m, *openssl_md_meth_names;
a8ffdf3
 
a8ffdf3
-    OpenSSL_add_all_digests();
a8ffdf3
-    ERR_load_crypto_strings();
a8ffdf3
+    SSL_load_error_strings();
a8ffdf3
+    SSL_library_init();
a8ffdf3
 
a8ffdf3
-    /* TODO build EVP_functions openssl_* entries dynamically based
a8ffdf3
-     * on what hashes are supported rather than listing many
a8ffdf3
-     * but having some be unsupported.  Only init appropriate
a8ffdf3
-     * constants. */
a8ffdf3
+    OpenSSL_add_all_digests();
a8ffdf3
 
a8ffdf3
     Py_TYPE(&EVPtype) = &PyType_Type;
a8ffdf3
     if (PyType_Ready(&EVPtype) < 0)