Blame SOURCES/00146-hashlib-fips.patch

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