b8f92b4
diff -up Python-3.2.2/Lib/hashlib.py.hashlib-fips Python-3.2.2/Lib/hashlib.py
b8f92b4
--- Python-3.2.2/Lib/hashlib.py.hashlib-fips	2011-09-03 12:16:41.000000000 -0400
b8f92b4
+++ Python-3.2.2/Lib/hashlib.py	2011-09-14 01:55:48.090252006 -0400
b8f92b4
@@ -23,6 +23,16 @@ the zlib module.
b8f92b4
 Choose your hash function wisely.  Some have known collision weaknesses.
b8f92b4
 sha384 and sha512 will be slow on 32 bit platforms.
b8f92b4
 
b8f92b4
+If the underlying implementation supports "FIPS mode", and this is enabled, it
b8f92b4
+may restrict the available hashes to only those that are compliant with FIPS
b8f92b4
+regulations.  For example, it may deny the use of MD5, on the grounds that this
b8f92b4
+is not secure for uses such as authentication, system integrity checking, or
b8f92b4
+digital signatures.   If you need to use such a hash for non-security purposes
b8f92b4
+(such as indexing into a data structure for speed), you can override the keyword
b8f92b4
+argument "usedforsecurity" from True to False to signify that your code is not
b8f92b4
+relying on the hash for security purposes, and this will allow the hash to be
b8f92b4
+usable even in FIPS mode.
b8f92b4
+
b8f92b4
 Hash objects have these methods:
b8f92b4
  - update(arg): Update the hash object with the bytes in arg. Repeated calls
b8f92b4
                 are equivalent to a single call with the concatenation of all
b8f92b4
@@ -96,33 +106,36 @@ def __get_openssl_constructor(name):
b8f92b4
         f = getattr(_hashlib, 'openssl_' + name)
b8f92b4
         # Allow the C module to raise ValueError.  The function will be
b8f92b4
         # defined but the hash not actually available thanks to OpenSSL.
b8f92b4
-        f()
b8f92b4
+        # We pass "usedforsecurity=False" to disable FIPS-based restrictions:
b8f92b4
+        # at this stage we're merely seeing if the function is callable,
b8f92b4
+        # rather than using it for actual work.
b8f92b4
+        f(usedforsecurity=False)
b8f92b4
         # Use the C function directly (very fast)
b8f92b4
         return f
b8f92b4
     except (AttributeError, ValueError):
b8f92b4
-        return __get_builtin_constructor(name)
b8f92b4
+        raise
b8f92b4
 
b8f92b4
+def __py_new(name, data=b'', usedforsecurity=True):
b8f92b4
+    """new(name, data=b'', usedforsecurity=True) - Return a new hashing object using
b8f92b4
+    the named algorithm; optionally initialized with data (which must be bytes).
b8f92b4
 
b8f92b4
-def __py_new(name, data=b''):
b8f92b4
-    """new(name, data=b'') - Return a new hashing object using the named algorithm;
b8f92b4
-    optionally initialized with data (which must be bytes).
b8f92b4
+    The 'usedforsecurity' keyword argument does nothing, and is for compatibilty
b8f92b4
+    with the OpenSSL implementation
b8f92b4
     """
b8f92b4
     return __get_builtin_constructor(name)(data)
b8f92b4
 
b8f92b4
 
b8f92b4
-def __hash_new(name, data=b''):
b8f92b4
-    """new(name, data=b'') - Return a new hashing object using the named algorithm;
b8f92b4
-    optionally initialized with data (which must be bytes).
b8f92b4
+def __hash_new(name, data=b'', usedforsecurity=True):
b8f92b4
+    """new(name, data=b'', usedforsecurity=True) - Return a new hashing object using
b8f92b4
+    the named algorithm; optionally initialized with data (which must be bytes).
b8f92b4
+    
b8f92b4
+    Override 'usedforsecurity' to False when using for non-security purposes in
b8f92b4
+    a FIPS environment
b8f92b4
     """
b8f92b4
     try:
b8f92b4
-        return _hashlib.new(name, data)
b8f92b4
+        return _hashlib.new(name, data, usedforsecurity)
b8f92b4
     except ValueError:
b8f92b4
-        # If the _hashlib module (OpenSSL) doesn't support the named
b8f92b4
-        # hash, try using our builtin implementations.
b8f92b4
-        # This allows for SHA224/256 and SHA384/512 support even though
b8f92b4
-        # the OpenSSL library prior to 0.9.8 doesn't provide them.
b8f92b4
-        return __get_builtin_constructor(name)(data)
b8f92b4
-
b8f92b4
+        raise 
b8f92b4
 
b8f92b4
 try:
b8f92b4
     import _hashlib
b8f92b4
diff -up Python-3.2.2/Lib/test/test_hashlib.py.hashlib-fips Python-3.2.2/Lib/test/test_hashlib.py
b8f92b4
--- Python-3.2.2/Lib/test/test_hashlib.py.hashlib-fips	2011-09-03 12:16:43.000000000 -0400
b8f92b4
+++ Python-3.2.2/Lib/test/test_hashlib.py	2011-09-14 01:45:48.462251974 -0400
b8f92b4
@@ -22,6 +22,19 @@ from test.support import _4G, precisionb
b8f92b4
 # Were we compiled --with-pydebug or with #define Py_DEBUG?
b8f92b4
 COMPILED_WITH_PYDEBUG = hasattr(sys, 'gettotalrefcount')
b8f92b4
 
b8f92b4
+def openssl_enforces_fips():
b8f92b4
+    # Use the "openssl" command (if present) to try to determine if the local
b8f92b4
+    # OpenSSL is configured to enforce FIPS
b8f92b4
+    from subprocess import Popen, PIPE
b8f92b4
+    try:
b8f92b4
+        p = Popen(['openssl', 'md5'],
b8f92b4
+                  stdin=PIPE, stdout=PIPE, stderr=PIPE)
b8f92b4
+    except OSError:
b8f92b4
+        # "openssl" command not found
b8f92b4
+        return False
b8f92b4
+    stdout, stderr = p.communicate(input=b'abc')
b8f92b4
+    return b'unknown cipher' in stderr
b8f92b4
+OPENSSL_ENFORCES_FIPS = openssl_enforces_fips()
b8f92b4
 
b8f92b4
 def hexstr(s):
b8f92b4
     assert isinstance(s, bytes), repr(s)
b8f92b4
@@ -31,6 +44,16 @@ def hexstr(s):
b8f92b4
         r += h[(i >> 4) & 0xF] + h[i & 0xF]
b8f92b4
     return r
b8f92b4
 
b8f92b4
+# hashlib and _hashlib-based functions support a "usedforsecurity" keyword
b8f92b4
+# argument, and FIPS mode requires that it be used overridden with a False
b8f92b4
+# value for these selftests to work.  Other cryptographic code within Python
b8f92b4
+# doesn't support this keyword.
b8f92b4
+# Modify a function to one in which "usedforsecurity=False" is added to the
b8f92b4
+# keyword arguments:
b8f92b4
+def suppress_fips(f):
b8f92b4
+    def g(*args, **kwargs):
b8f92b4
+        return f(*args, usedforsecurity=False, **kwargs)
b8f92b4
+    return g
b8f92b4
 
b8f92b4
 class HashLibTestCase(unittest.TestCase):
b8f92b4
     supported_hash_names = ( 'md5', 'MD5', 'sha1', 'SHA1',
b8f92b4
@@ -59,11 +82,11 @@ class HashLibTestCase(unittest.TestCase)
b8f92b4
         # For each algorithm, test the direct constructor and the use
b8f92b4
         # of hashlib.new given the algorithm name.
b8f92b4
         for algorithm, constructors in self.constructors_to_test.items():
b8f92b4
-            constructors.add(getattr(hashlib, algorithm))
b8f92b4
+            constructors.add(suppress_fips(getattr(hashlib, algorithm)))
b8f92b4
             def _test_algorithm_via_hashlib_new(data=None, _alg=algorithm):
b8f92b4
                 if data is None:
b8f92b4
-                    return hashlib.new(_alg)
b8f92b4
-                return hashlib.new(_alg, data)
b8f92b4
+                    return suppress_fips(hashlib.new)(_alg)
b8f92b4
+                return suppress_fips(hashlib.new)(_alg, data)
b8f92b4
             constructors.add(_test_algorithm_via_hashlib_new)
b8f92b4
 
b8f92b4
         _hashlib = self._conditional_import_module('_hashlib')
b8f92b4
@@ -75,22 +98,7 @@ class HashLibTestCase(unittest.TestCase)
b8f92b4
             for algorithm, constructors in self.constructors_to_test.items():
b8f92b4
                 constructor = getattr(_hashlib, 'openssl_'+algorithm, None)
b8f92b4
                 if constructor:
b8f92b4
-                    constructors.add(constructor)
b8f92b4
-
b8f92b4
-        _md5 = self._conditional_import_module('_md5')
b8f92b4
-        if _md5:
b8f92b4
-            self.constructors_to_test['md5'].add(_md5.md5)
b8f92b4
-        _sha1 = self._conditional_import_module('_sha1')
b8f92b4
-        if _sha1:
b8f92b4
-            self.constructors_to_test['sha1'].add(_sha1.sha1)
b8f92b4
-        _sha256 = self._conditional_import_module('_sha256')
b8f92b4
-        if _sha256:
b8f92b4
-            self.constructors_to_test['sha224'].add(_sha256.sha224)
b8f92b4
-            self.constructors_to_test['sha256'].add(_sha256.sha256)
b8f92b4
-        _sha512 = self._conditional_import_module('_sha512')
b8f92b4
-        if _sha512:
b8f92b4
-            self.constructors_to_test['sha384'].add(_sha512.sha384)
b8f92b4
-            self.constructors_to_test['sha512'].add(_sha512.sha512)
b8f92b4
+                    constructors.add(suppress_fips(constructor))
b8f92b4
 
b8f92b4
         super(HashLibTestCase, self).__init__(*args, **kwargs)
b8f92b4
 
b8f92b4
@@ -138,7 +146,7 @@ class HashLibTestCase(unittest.TestCase)
b8f92b4
 
b8f92b4
     def test_hexdigest(self):
b8f92b4
         for name in self.supported_hash_names:
b8f92b4
-            h = hashlib.new(name)
b8f92b4
+            h = hashlib.new(name, usedforsecurity=False)
b8f92b4
             assert isinstance(h.digest(), bytes), name
b8f92b4
             self.assertEqual(hexstr(h.digest()), h.hexdigest())
b8f92b4
 
b8f92b4
@@ -149,12 +157,12 @@ class HashLibTestCase(unittest.TestCase)
b8f92b4
         cees = b'c' * 126
b8f92b4
 
b8f92b4
         for name in self.supported_hash_names:
b8f92b4
-            m1 = hashlib.new(name)
b8f92b4
+            m1 = hashlib.new(name, usedforsecurity=False)
b8f92b4
             m1.update(aas)
b8f92b4
             m1.update(bees)
b8f92b4
             m1.update(cees)
b8f92b4
 
b8f92b4
-            m2 = hashlib.new(name)
b8f92b4
+            m2 = hashlib.new(name, usedforsecurity=False)
b8f92b4
             m2.update(aas + bees + cees)
b8f92b4
             self.assertEqual(m1.digest(), m2.digest())
b8f92b4
 
b8f92b4
@@ -324,13 +332,13 @@ class HashLibTestCase(unittest.TestCase)
b8f92b4
         # for multithreaded operation (which is hardwired to 2048).
b8f92b4
         gil_minsize = 2048
b8f92b4
 
b8f92b4
-        m = hashlib.md5()
b8f92b4
+        m = hashlib.md5(usedforsecurity=False)
b8f92b4
         m.update(b'1')
b8f92b4
         m.update(b'#' * gil_minsize)
b8f92b4
         m.update(b'1')
b8f92b4
         self.assertEqual(m.hexdigest(), 'cb1e1a2cbc80be75e19935d621fb9b21')
b8f92b4
 
b8f92b4
-        m = hashlib.md5(b'x' * gil_minsize)
b8f92b4
+        m = hashlib.md5(b'x' * gil_minsize, usedforsecurity=False)
b8f92b4
         self.assertEqual(m.hexdigest(), 'cfb767f225d58469c5de3632a8803958')
b8f92b4
 
b8f92b4
     @unittest.skipUnless(threading, 'Threading required for this test.')
b8f92b4
@@ -370,6 +378,67 @@ class HashLibTestCase(unittest.TestCase)
b8f92b4
 
b8f92b4
         self.assertEqual(expected_hash, hasher.hexdigest())
b8f92b4
 
b8f92b4
+    def test_issue9146(self):
b8f92b4
+        # Ensure that various ways to use "MD5" from "hashlib" don't segfault:
b8f92b4
+        m = hashlib.md5(usedforsecurity=False)
b8f92b4
+        m.update(b'abc\n')
b8f92b4
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
b8f92b4
+        
b8f92b4
+        m = hashlib.new('md5', usedforsecurity=False)
b8f92b4
+        m.update(b'abc\n')
b8f92b4
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
b8f92b4
+        
b8f92b4
+        m = hashlib.md5(b'abc\n', usedforsecurity=False)
b8f92b4
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
b8f92b4
+        
b8f92b4
+        m = hashlib.new('md5', b'abc\n', usedforsecurity=False)
b8f92b4
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
b8f92b4
+
b8f92b4
+    @unittest.skipUnless(OPENSSL_ENFORCES_FIPS,
b8f92b4
+                         'FIPS enforcement required for this test.')
b8f92b4
+    def test_hashlib_fips_mode(self):        
b8f92b4
+        # Ensure that we raise a ValueError on vanilla attempts to use MD5
b8f92b4
+        # in hashlib in a FIPS-enforced setting:
b8f92b4
+        with self.assertRaisesRegexp(ValueError, '.*unknown cipher'):
b8f92b4
+            m = hashlib.md5()
b8f92b4
+            
b8f92b4
+        if not self._conditional_import_module('_md5'):
b8f92b4
+            with self.assertRaisesRegexp(ValueError, '.*unknown cipher'):
b8f92b4
+                m = hashlib.new('md5')
b8f92b4
+
b8f92b4
+    @unittest.skipUnless(OPENSSL_ENFORCES_FIPS,
b8f92b4
+                         'FIPS enforcement required for this test.')
b8f92b4
+    def test_hashopenssl_fips_mode(self):
b8f92b4
+        # Verify the _hashlib module's handling of md5:
b8f92b4
+        _hashlib = self._conditional_import_module('_hashlib')
b8f92b4
+        if _hashlib:
b8f92b4
+            assert hasattr(_hashlib, 'openssl_md5')
b8f92b4
+
b8f92b4
+            # Ensure that _hashlib raises a ValueError on vanilla attempts to
b8f92b4
+            # use MD5 in a FIPS-enforced setting:
b8f92b4
+            with self.assertRaisesRegexp(ValueError, '.*unknown cipher'):
b8f92b4
+                m = _hashlib.openssl_md5()
b8f92b4
+            with self.assertRaisesRegexp(ValueError, '.*unknown cipher'):
b8f92b4
+                m = _hashlib.new('md5')
b8f92b4
+
b8f92b4
+            # Ensure that in such a setting we can whitelist a callsite with
b8f92b4
+            # usedforsecurity=False and have it succeed:
b8f92b4
+            m = _hashlib.openssl_md5(usedforsecurity=False)
b8f92b4
+            m.update(b'abc\n')
b8f92b4
+            self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
b8f92b4
+        
b8f92b4
+            m = _hashlib.new('md5', usedforsecurity=False)
b8f92b4
+            m.update(b'abc\n')
b8f92b4
+            self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
b8f92b4
+        
b8f92b4
+            m = _hashlib.openssl_md5(b'abc\n', usedforsecurity=False)
b8f92b4
+            self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
b8f92b4
+        
b8f92b4
+            m = _hashlib.new('md5', b'abc\n', usedforsecurity=False)
b8f92b4
+            self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
b8f92b4
+        
b8f92b4
+
b8f92b4
+
b8f92b4
 def test_main():
b8f92b4
     support.run_unittest(HashLibTestCase)
b8f92b4
 
b8f92b4
diff -up Python-3.2.2/Modules/_hashopenssl.c.hashlib-fips Python-3.2.2/Modules/_hashopenssl.c
b8f92b4
--- Python-3.2.2/Modules/_hashopenssl.c.hashlib-fips	2011-09-03 12:16:46.000000000 -0400
b8f92b4
+++ Python-3.2.2/Modules/_hashopenssl.c	2011-09-14 00:52:41.225252001 -0400
b8f92b4
@@ -37,6 +37,8 @@
b8f92b4
 #endif
b8f92b4
 
b8f92b4
 /* EVP is the preferred interface to hashing in OpenSSL */
b8f92b4
+#include <openssl/ssl.h>
b8f92b4
+#include <openssl/err.h>
b8f92b4
 #include <openssl/evp.h>
b8f92b4
 /* We use the object interface to discover what hashes OpenSSL supports. */
b8f92b4
 #include <openssl/objects.h>
b8f92b4
@@ -68,11 +70,19 @@ typedef struct {
b8f92b4
 
b8f92b4
 static PyTypeObject EVPtype;
b8f92b4
 
b8f92b4
+/* Struct to hold all the cached information we need on a specific algorithm.
b8f92b4
+   We have one of these per algorithm */
b8f92b4
+typedef struct {
b8f92b4
+    PyObject *name_obj;
b8f92b4
+    EVP_MD_CTX ctxs[2];
b8f92b4
+    /* ctx_ptrs will point to ctxs unless an error occurred, when it will
b8f92b4
+       be NULL: */
b8f92b4
+    EVP_MD_CTX *ctx_ptrs[2];
b8f92b4
+    PyObject *error_msgs[2];
b8f92b4
+} EVPCachedInfo;
b8f92b4
 
b8f92b4
-#define DEFINE_CONSTS_FOR_NEW(Name)  \
b8f92b4
-    static PyObject *CONST_ ## Name ## _name_obj; \
b8f92b4
-    static EVP_MD_CTX CONST_new_ ## Name ## _ctx; \
b8f92b4
-    static EVP_MD_CTX *CONST_new_ ## Name ## _ctx_p = NULL;
b8f92b4
+#define DEFINE_CONSTS_FOR_NEW(Name) \
b8f92b4
+    static EVPCachedInfo cached_info_ ##Name;
b8f92b4
 
b8f92b4
 DEFINE_CONSTS_FOR_NEW(md5)
b8f92b4
 DEFINE_CONSTS_FOR_NEW(sha1)
b8f92b4
@@ -117,6 +127,48 @@ EVP_hash(EVPobject *self, const void *vp
b8f92b4
     }
b8f92b4
 }
b8f92b4
 
b8f92b4
+static void
b8f92b4
+mc_ctx_init(EVP_MD_CTX *ctx, int usedforsecurity)
b8f92b4
+{
b8f92b4
+    EVP_MD_CTX_init(ctx);
b8f92b4
+
b8f92b4
+    /*
b8f92b4
+      If the user has declared that this digest is being used in a
b8f92b4
+      non-security role (e.g. indexing into a data structure), set
b8f92b4
+      the exception flag for openssl to allow it
b8f92b4
+    */
b8f92b4
+    if (!usedforsecurity) {
b8f92b4
+#ifdef EVP_MD_CTX_FLAG_NON_FIPS_ALLOW
b8f92b4
+        EVP_MD_CTX_set_flags(ctx,
b8f92b4
+                             EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
b8f92b4
+#endif
b8f92b4
+    }
b8f92b4
+}
b8f92b4
+
b8f92b4
+/* Get an error msg for the last error as a PyObject */
b8f92b4
+static PyObject *
b8f92b4
+error_msg_for_last_error(void)
b8f92b4
+{
b8f92b4
+    char *errstr;
b8f92b4
+
b8f92b4
+    errstr = ERR_error_string(ERR_peek_last_error(), NULL);
b8f92b4
+    ERR_clear_error();
b8f92b4
+
b8f92b4
+    return PyUnicode_FromString(errstr); /* Can be NULL */
b8f92b4
+}
b8f92b4
+
b8f92b4
+static void
b8f92b4
+set_evp_exception(void)
b8f92b4
+{
b8f92b4
+    char *errstr;
b8f92b4
+
b8f92b4
+    errstr = ERR_error_string(ERR_peek_last_error(), NULL);
b8f92b4
+    ERR_clear_error();
b8f92b4
+
b8f92b4
+    PyErr_SetString(PyExc_ValueError, errstr);
b8f92b4
+}
b8f92b4
+
b8f92b4
+
b8f92b4
 /* Internal methods for a hash object */
b8f92b4
 
b8f92b4
 static void
b8f92b4
@@ -303,15 +355,16 @@ EVP_repr(EVPobject *self)
b8f92b4
 static int
b8f92b4
 EVP_tp_init(EVPobject *self, PyObject *args, PyObject *kwds)
b8f92b4
 {
b8f92b4
-    static char *kwlist[] = {"name", "string", NULL};
b8f92b4
+    static char *kwlist[] = {"name", "string", "usedforsecurity", NULL};
b8f92b4
     PyObject *name_obj = NULL;
b8f92b4
     PyObject *data_obj = NULL;
b8f92b4
+    int usedforsecurity = 1;
b8f92b4
     Py_buffer view;
b8f92b4
     char *nameStr;
b8f92b4
     const EVP_MD *digest;
b8f92b4
 
b8f92b4
-    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:HASH", kwlist,
b8f92b4
-                                     &name_obj, &data_obj)) {
b8f92b4
+    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:HASH", kwlist,
b8f92b4
+                                     &name_obj, &data_obj, &usedforsecurity)) {
b8f92b4
         return -1;
b8f92b4
     }
b8f92b4
 
b8f92b4
@@ -332,7 +385,12 @@ EVP_tp_init(EVPobject *self, PyObject *a
b8f92b4
             PyBuffer_Release(&view);
b8f92b4
         return -1;
b8f92b4
     }
b8f92b4
-    EVP_DigestInit(&self->ctx, digest);
b8f92b4
+    mc_ctx_init(&self->ctx, usedforsecurity);
b8f92b4
+    if (!EVP_DigestInit_ex(&self->ctx, digest, NULL)) {
b8f92b4
+        set_evp_exception();
b8f92b4
+        PyBuffer_Release(&view);
b8f92b4
+        return -1;
b8f92b4
+    }
b8f92b4
 
b8f92b4
     self->name = name_obj;
b8f92b4
     Py_INCREF(self->name);
b8f92b4
@@ -416,7 +474,8 @@ static PyTypeObject EVPtype = {
b8f92b4
 static PyObject *
b8f92b4
 EVPnew(PyObject *name_obj,
b8f92b4
        const EVP_MD *digest, const EVP_MD_CTX *initial_ctx,
b8f92b4
-       const unsigned char *cp, Py_ssize_t len)
b8f92b4
+       const unsigned char *cp, Py_ssize_t len,
b8f92b4
+       int usedforsecurity)
b8f92b4
 {
b8f92b4
     EVPobject *self;
b8f92b4
 
b8f92b4
@@ -431,7 +490,12 @@ EVPnew(PyObject *name_obj,
b8f92b4
     if (initial_ctx) {
b8f92b4
         EVP_MD_CTX_copy(&self->ctx, initial_ctx);
b8f92b4
     } else {
b8f92b4
-        EVP_DigestInit(&self->ctx, digest);
b8f92b4
+        mc_ctx_init(&self->ctx, usedforsecurity);
b8f92b4
+        if (!EVP_DigestInit_ex(&self->ctx, digest, NULL)) {
b8f92b4
+            set_evp_exception();
b8f92b4
+            Py_DECREF(self);
b8f92b4
+            return NULL;
b8f92b4
+        }
b8f92b4
     }
b8f92b4
 
b8f92b4
     if (cp && len) {
b8f92b4
@@ -455,21 +519,29 @@ PyDoc_STRVAR(EVP_new__doc__,
b8f92b4
 An optional string argument may be provided and will be\n\
b8f92b4
 automatically hashed.\n\
b8f92b4
 \n\
b8f92b4
-The MD5 and SHA1 algorithms are always supported.\n");
b8f92b4
+The MD5 and SHA1 algorithms are always supported.\n\
b8f92b4
+\n\
b8f92b4
+An optional \"usedforsecurity=True\" keyword argument is provided for use in\n\
b8f92b4
+environments that enforce FIPS-based restrictions.  Some implementations of\n\
b8f92b4
+OpenSSL can be configured to prevent the usage of non-secure algorithms (such\n\
b8f92b4
+as MD5).  If you have a non-security use for these algorithms (e.g. a hash\n\
b8f92b4
+table), you can override this argument by marking the callsite as\n\
b8f92b4
+\"usedforsecurity=False\".");
b8f92b4
 
b8f92b4
 static PyObject *
b8f92b4
 EVP_new(PyObject *self, PyObject *args, PyObject *kwdict)
b8f92b4
 {
b8f92b4
-    static char *kwlist[] = {"name", "string", NULL};
b8f92b4
+    static char *kwlist[] = {"name", "string", "usedforsecurity", NULL};
b8f92b4
     PyObject *name_obj = NULL;
b8f92b4
     PyObject *data_obj = NULL;
b8f92b4
+    int usedforsecurity = 1;
b8f92b4
     Py_buffer view = { 0 };
b8f92b4
     PyObject *ret_obj;
b8f92b4
     char *name;
b8f92b4
     const EVP_MD *digest;
b8f92b4
 
b8f92b4
-    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "O|O:new", kwlist,
b8f92b4
-                                     &name_obj, &data_obj)) {
b8f92b4
+    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "O|Oi:new", kwlist,
b8f92b4
+                                     &name_obj, &data_obj, &usedforsecurity)) {
b8f92b4
         return NULL;
b8f92b4
     }
b8f92b4
 
b8f92b4
@@ -483,7 +555,8 @@ EVP_new(PyObject *self, PyObject *args,
b8f92b4
 
b8f92b4
     digest = EVP_get_digestbyname(name);
b8f92b4
 
b8f92b4
-    ret_obj = EVPnew(name_obj, digest, NULL, (unsigned char*)view.buf, view.len);
b8f92b4
+    ret_obj = EVPnew(name_obj, digest, NULL, (unsigned char*)view.buf, view.len,
b8f92b4
+                     usedforsecurity);
b8f92b4
 
b8f92b4
     if (data_obj)
b8f92b4
         PyBuffer_Release(&view);
b8f92b4
@@ -547,55 +620,115 @@ generate_hash_name_list(void)
b8f92b4
 
b8f92b4
 
b8f92b4
 /*
b8f92b4
- *  This macro generates constructor function definitions for specific
b8f92b4
- *  hash algorithms.  These constructors are much faster than calling
b8f92b4
- *  the generic one passing it a python string and are noticably
b8f92b4
- *  faster than calling a python new() wrapper.  Thats important for
b8f92b4
+ *  This macro and function generates a family of constructor function
b8f92b4
+ *  definitions for specific hash algorithms.  These constructors are much
b8f92b4
+ *  faster than calling the generic one passing it a python string and are
b8f92b4
+ *  noticably faster than calling a python new() wrapper.  That's important for
b8f92b4
  *  code that wants to make hashes of a bunch of small strings.
b8f92b4
  */
b8f92b4
 #define GEN_CONSTRUCTOR(NAME)  \
b8f92b4
     static PyObject * \
b8f92b4
-    EVP_new_ ## NAME (PyObject *self, PyObject *args) \
b8f92b4
+    EVP_new_ ## NAME (PyObject *self, PyObject *args, PyObject *kwdict)	\
b8f92b4
     { \
b8f92b4
-        PyObject *data_obj = NULL; \
b8f92b4
-        Py_buffer view = { 0 }; \
b8f92b4
-        PyObject *ret_obj; \
b8f92b4
-     \
b8f92b4
-        if (!PyArg_ParseTuple(args, "|O:" #NAME , &data_obj)) { \
b8f92b4
-            return NULL; \
b8f92b4
-        } \
b8f92b4
-     \
b8f92b4
-        if (data_obj) \
b8f92b4
-            GET_BUFFER_VIEW_OR_ERROUT(data_obj, &view); \
b8f92b4
-     \
b8f92b4
-        ret_obj = EVPnew( \
b8f92b4
-                    CONST_ ## NAME ## _name_obj, \
b8f92b4
-                    NULL, \
b8f92b4
-                    CONST_new_ ## NAME ## _ctx_p, \
b8f92b4
-                    (unsigned char*)view.buf, \
b8f92b4
-                    view.len); \
b8f92b4
-     \
b8f92b4
-        if (data_obj) \
b8f92b4
-            PyBuffer_Release(&view); \
b8f92b4
-        return ret_obj; \
b8f92b4
+       return implement_specific_EVP_new(self, args, kwdict,      \
b8f92b4
+                                         "|Oi:" #NAME,            \
b8f92b4
+                                         &cached_info_ ## NAME ); \
b8f92b4
     }
b8f92b4
 
b8f92b4
+static PyObject *
b8f92b4
+implement_specific_EVP_new(PyObject *self, PyObject *args, PyObject *kwdict,
b8f92b4
+                           const char *format,
b8f92b4
+                           EVPCachedInfo *cached_info)
b8f92b4
+{
b8f92b4
+    static char *kwlist[] = {"string", "usedforsecurity", NULL}; 
b8f92b4
+    PyObject *data_obj = NULL;
b8f92b4
+    Py_buffer view = { 0 };
b8f92b4
+    int usedforsecurity = 1;
b8f92b4
+    int idx;
b8f92b4
+    PyObject *ret_obj = NULL;
b8f92b4
+
b8f92b4
+    assert(cached_info);
b8f92b4
+
b8f92b4
+    if (!PyArg_ParseTupleAndKeywords(args, kwdict, format, kwlist,
b8f92b4
+                                     &data_obj, &usedforsecurity)) {
b8f92b4
+        return NULL;
b8f92b4
+    }
b8f92b4
+
b8f92b4
+    if (data_obj)
b8f92b4
+       GET_BUFFER_VIEW_OR_ERROUT(data_obj, &view);
b8f92b4
+
b8f92b4
+    idx = usedforsecurity ? 1 : 0;
b8f92b4
+
b8f92b4
+    /*
b8f92b4
+     * If an error occurred during creation of the global content, the ctx_ptr
b8f92b4
+     * will be NULL, and the error_msg will hopefully be non-NULL:
b8f92b4
+     */
b8f92b4
+    if (cached_info->ctx_ptrs[idx]) {
b8f92b4
+        /* We successfully initialized this context; copy it: */
b8f92b4
+        ret_obj = EVPnew(cached_info->name_obj,
b8f92b4
+                         NULL,
b8f92b4
+                         cached_info->ctx_ptrs[idx],
b8f92b4
+                         (unsigned char*)view.buf, view.len,
b8f92b4
+                         usedforsecurity);
b8f92b4
+    } else {
b8f92b4
+        /* Some kind of error happened initializing the global context for
b8f92b4
+           this (digest, usedforsecurity) pair.
b8f92b4
+           Raise an exception with the saved error message: */
b8f92b4
+        if (cached_info->error_msgs[idx]) {
b8f92b4
+            PyErr_SetObject(PyExc_ValueError, cached_info->error_msgs[idx]);
b8f92b4
+        } else {
b8f92b4
+            PyErr_SetString(PyExc_ValueError, "Error initializing hash");
b8f92b4
+        }
b8f92b4
+    }
b8f92b4
+
b8f92b4
+    if (data_obj)
b8f92b4
+        PyBuffer_Release(&view);
b8f92b4
+
b8f92b4
+    return ret_obj;
b8f92b4
+}
b8f92b4
+
b8f92b4
 /* a PyMethodDef structure for the constructor */
b8f92b4
 #define CONSTRUCTOR_METH_DEF(NAME)  \
b8f92b4
-    {"openssl_" #NAME, (PyCFunction)EVP_new_ ## NAME, METH_VARARGS, \
b8f92b4
+    {"openssl_" #NAME, (PyCFunction)EVP_new_ ## NAME, \
b8f92b4
+        METH_VARARGS|METH_KEYWORDS, \
b8f92b4
         PyDoc_STR("Returns a " #NAME \
b8f92b4
                   " hash object; optionally initialized with a string") \
b8f92b4
     }
b8f92b4
 
b8f92b4
-/* used in the init function to setup a constructor */
b8f92b4
-#define INIT_CONSTRUCTOR_CONSTANTS(NAME)  do { \
b8f92b4
-    CONST_ ## NAME ## _name_obj = PyUnicode_FromString(#NAME); \
b8f92b4
-    if (EVP_get_digestbyname(#NAME)) { \
b8f92b4
-        CONST_new_ ## NAME ## _ctx_p = &CONST_new_ ## NAME ## _ctx; \
b8f92b4
-        EVP_DigestInit(CONST_new_ ## NAME ## _ctx_p, EVP_get_digestbyname(#NAME)); \
b8f92b4
-    } \
b8f92b4
-} while (0);
b8f92b4
+/*
b8f92b4
+  Macro/function pair to set up the constructors.
b8f92b4
 
b8f92b4
+  Try to initialize a context for each hash twice, once with
b8f92b4
+  EVP_MD_CTX_FLAG_NON_FIPS_ALLOW and once without.
b8f92b4
+  
b8f92b4
+  Any that have errors during initialization will end up with a NULL ctx_ptrs
b8f92b4
+  entry, and err_msgs will be set (unless we're very low on memory)
b8f92b4
+*/
b8f92b4
+#define INIT_CONSTRUCTOR_CONSTANTS(NAME)  do {    \
b8f92b4
+    init_constructor_constant(&cached_info_ ## NAME, #NAME); \
b8f92b4
+} while (0);
b8f92b4
+static void
b8f92b4
+init_constructor_constant(EVPCachedInfo *cached_info, const char *name)
b8f92b4
+{
b8f92b4
+    assert(cached_info);
b8f92b4
+    cached_info->name_obj = PyUnicode_FromString(name);
b8f92b4
+    if (EVP_get_digestbyname(name)) {
b8f92b4
+        int i;
b8f92b4
+        for (i=0; i<2; i++) {
b8f92b4
+            mc_ctx_init(&cached_info->ctxs[i], i);
b8f92b4
+            if (EVP_DigestInit_ex(&cached_info->ctxs[i],
b8f92b4
+                                  EVP_get_digestbyname(name), NULL)) {
b8f92b4
+                /* Success: */
b8f92b4
+                cached_info->ctx_ptrs[i] = &cached_info->ctxs[i];
b8f92b4
+            } else {
b8f92b4
+                /* Failure: */
b8f92b4
+              cached_info->ctx_ptrs[i] = NULL;
b8f92b4
+              cached_info->error_msgs[i] = error_msg_for_last_error();
b8f92b4
+            }
b8f92b4
+        }
b8f92b4
+    }
b8f92b4
+}
b8f92b4
+ 
b8f92b4
 GEN_CONSTRUCTOR(md5)
b8f92b4
 GEN_CONSTRUCTOR(sha1)
b8f92b4
 #ifdef _OPENSSL_SUPPORTS_SHA2
b8f92b4
@@ -641,12 +774,10 @@ PyInit__hashlib(void)
b8f92b4
 {
b8f92b4
     PyObject *m, *openssl_md_meth_names;
b8f92b4
 
b8f92b4
-    OpenSSL_add_all_digests();
b8f92b4
+    SSL_load_error_strings();
b8f92b4
+    SSL_library_init();
b8f92b4
 
b8f92b4
-    /* TODO build EVP_functions openssl_* entries dynamically based
b8f92b4
-     * on what hashes are supported rather than listing many
b8f92b4
-     * but having some be unsupported.  Only init appropriate
b8f92b4
-     * constants. */
b8f92b4
+    OpenSSL_add_all_digests();
b8f92b4
 
b8f92b4
     Py_TYPE(&EVPtype) = &PyType_Type;
b8f92b4
     if (PyType_Ready(&EVPtype) < 0)