Blame SOURCES/00146-hashlib-fips.patch

ae2451
diff -up Python-2.7.2/Lib/hashlib.py.hashlib-fips Python-2.7.2/Lib/hashlib.py
ae2451
--- Python-2.7.2/Lib/hashlib.py.hashlib-fips	2011-06-11 11:46:24.000000000 -0400
ae2451
+++ Python-2.7.2/Lib/hashlib.py	2011-09-14 00:21:26.194252001 -0400
ae2451
@@ -6,9 +6,12 @@
ae2451
 
ae2451
 __doc__ = """hashlib module - A common interface to many hash functions.
ae2451
 
ae2451
-new(name, string='') - returns a new hash object implementing the
ae2451
-                       given hash function; initializing the hash
ae2451
-                       using the given string data.
ae2451
+new(name, string='', usedforsecurity=True)
ae2451
+     - returns a new hash object implementing the given hash function;
ae2451
+       initializing the hash using the given string data.
ae2451
+
ae2451
+       "usedforsecurity" is a non-standard extension for better supporting
ae2451
+       FIPS-compliant environments (see below)
ae2451
 
ae2451
 Named constructor functions are also available, these are much faster
ae2451
 than using new():
ae2451
@@ -24,6 +27,20 @@ the zlib module.
ae2451
 Choose your hash function wisely.  Some have known collision weaknesses.
ae2451
 sha384 and sha512 will be slow on 32 bit platforms.
ae2451
 
ae2451
+Our implementation of hashlib uses OpenSSL.
ae2451
+
ae2451
+OpenSSL has a "FIPS mode", which, if enabled, may restrict the available hashes
ae2451
+to only those that are compliant with FIPS regulations.  For example, it may
ae2451
+deny the use of MD5, on the grounds that this is not secure for uses such as
ae2451
+authentication, system integrity checking, or digital signatures.   
ae2451
+
ae2451
+If you need to use such a hash for non-security purposes (such as indexing into
ae2451
+a data structure for speed), you can override the keyword argument
ae2451
+"usedforsecurity" from True to False to signify that your code is not relying
ae2451
+on the hash for security purposes, and this will allow the hash to be usable
ae2451
+even in FIPS mode.  This is not a standard feature of Python 2.7's hashlib, and
ae2451
+is included here to better support FIPS mode.
ae2451
+
ae2451
 Hash objects have these methods:
ae2451
  - update(arg): Update the hash object with the string arg. Repeated calls
ae2451
                 are equivalent to a single call with the concatenation of all
ae2451
@@ -63,74 +80,39 @@ algorithms = __always_supported
ae2451
 __all__ = __always_supported + ('new', 'algorithms')
ae2451
 
ae2451
 
ae2451
-def __get_builtin_constructor(name):
ae2451
-    try:
ae2451
-        if name in ('SHA1', 'sha1'):
ae2451
-            import _sha
ae2451
-            return _sha.new
ae2451
-        elif name in ('MD5', 'md5'):
ae2451
-            import _md5
ae2451
-            return _md5.new
ae2451
-        elif name in ('SHA256', 'sha256', 'SHA224', 'sha224'):
ae2451
-            import _sha256
ae2451
-            bs = name[3:]
ae2451
-            if bs == '256':
ae2451
-                return _sha256.sha256
ae2451
-            elif bs == '224':
ae2451
-                return _sha256.sha224
ae2451
-        elif name in ('SHA512', 'sha512', 'SHA384', 'sha384'):
ae2451
-            import _sha512
ae2451
-            bs = name[3:]
ae2451
-            if bs == '512':
ae2451
-                return _sha512.sha512
ae2451
-            elif bs == '384':
ae2451
-                return _sha512.sha384
ae2451
-    except ImportError:
ae2451
-        pass  # no extension module, this hash is unsupported.
ae2451
-
ae2451
-    raise ValueError('unsupported hash type ' + name)
ae2451
-
ae2451
-
ae2451
 def __get_openssl_constructor(name):
ae2451
     try:
ae2451
         f = getattr(_hashlib, 'openssl_' + name)
ae2451
         # Allow the C module to raise ValueError.  The function will be
ae2451
         # defined but the hash not actually available thanks to OpenSSL.
ae2451
-        f()
ae2451
+        #
ae2451
+        # We pass "usedforsecurity=False" to disable FIPS-based restrictions:
ae2451
+        # at this stage we're merely seeing if the function is callable,
ae2451
+        # rather than using it for actual work.
ae2451
+        f(usedforsecurity=False)
ae2451
         # Use the C function directly (very fast)
ae2451
         return f
ae2451
     except (AttributeError, ValueError):
ae2451
-        return __get_builtin_constructor(name)
ae2451
+        raise
ae2451
 
ae2451
-
ae2451
-def __py_new(name, string=''):
ae2451
-    """new(name, string='') - Return a new hashing object using the named algorithm;
ae2451
-    optionally initialized with a string.
ae2451
-    """
ae2451
-    return __get_builtin_constructor(name)(string)
ae2451
-
ae2451
-
ae2451
-def __hash_new(name, string=''):
ae2451
+def __hash_new(name, string='', usedforsecurity=True):
ae2451
     """new(name, string='') - Return a new hashing object using the named algorithm;
ae2451
     optionally initialized with a string.
ae2451
+    Override 'usedforsecurity' to False when using for non-security purposes in
ae2451
+    a FIPS environment
ae2451
     """
ae2451
     try:
ae2451
-        return _hashlib.new(name, string)
ae2451
+        return _hashlib.new(name, string, usedforsecurity)
ae2451
     except ValueError:
ae2451
-        # If the _hashlib module (OpenSSL) doesn't support the named
ae2451
-        # hash, try using our builtin implementations.
ae2451
-        # This allows for SHA224/256 and SHA384/512 support even though
ae2451
-        # the OpenSSL library prior to 0.9.8 doesn't provide them.
ae2451
-        return __get_builtin_constructor(name)(string)
ae2451
-
ae2451
+        raise
ae2451
 
ae2451
 try:
ae2451
     import _hashlib
ae2451
     new = __hash_new
ae2451
     __get_hash = __get_openssl_constructor
ae2451
 except ImportError:
ae2451
-    new = __py_new
ae2451
-    __get_hash = __get_builtin_constructor
ae2451
+    # We don't build the legacy modules
ae2451
+    raise
ae2451
 
ae2451
 for __func_name in __always_supported:
ae2451
     # try them all, some may not work due to the OpenSSL
ae2451
@@ -143,4 +125,4 @@ for __func_name in __always_supported:
ae2451
 
ae2451
 # Cleanup locals()
ae2451
 del __always_supported, __func_name, __get_hash
ae2451
-del __py_new, __hash_new, __get_openssl_constructor
ae2451
+del __hash_new, __get_openssl_constructor
ae2451
diff -up Python-2.7.2/Lib/test/test_hashlib.py.hashlib-fips Python-2.7.2/Lib/test/test_hashlib.py
ae2451
--- Python-2.7.2/Lib/test/test_hashlib.py.hashlib-fips	2011-06-11 11:46:25.000000000 -0400
ae2451
+++ Python-2.7.2/Lib/test/test_hashlib.py	2011-09-14 01:08:55.525254195 -0400
ae2451
@@ -32,6 +32,19 @@ def hexstr(s):
ae2451
         r = r + h[(i >> 4) & 0xF] + h[i & 0xF]
ae2451
     return r
ae2451
 
ae2451
+def openssl_enforces_fips():
ae2451
+    # Use the "openssl" command (if present) to try to determine if the local
ae2451
+    # OpenSSL is configured to enforce FIPS
ae2451
+    from subprocess import Popen, PIPE
ae2451
+    try:
ae2451
+        p = Popen(['openssl', 'md5'],
ae2451
+                  stdin=PIPE, stdout=PIPE, stderr=PIPE)
ae2451
+    except OSError:
ae2451
+        # "openssl" command not found
ae2451
+        return False
ae2451
+    stdout, stderr = p.communicate(input=b'abc')
ae2451
+    return b'unknown cipher' in stderr
ae2451
+OPENSSL_ENFORCES_FIPS = openssl_enforces_fips()
ae2451
 
ae2451
 class HashLibTestCase(unittest.TestCase):
ae2451
     supported_hash_names = ( 'md5', 'MD5', 'sha1', 'SHA1',
ae2451
@@ -61,10 +74,10 @@ class HashLibTestCase(unittest.TestCase)
ae2451
         # of hashlib.new given the algorithm name.
ae2451
         for algorithm, constructors in self.constructors_to_test.items():
ae2451
             constructors.add(getattr(hashlib, algorithm))
ae2451
-            def _test_algorithm_via_hashlib_new(data=None, _alg=algorithm):
ae2451
+            def _test_algorithm_via_hashlib_new(data=None, _alg=algorithm, usedforsecurity=True):
ae2451
                 if data is None:
ae2451
-                    return hashlib.new(_alg)
ae2451
-                return hashlib.new(_alg, data)
ae2451
+                    return hashlib.new(_alg, usedforsecurity=usedforsecurity)
ae2451
+                return hashlib.new(_alg, data, usedforsecurity=usedforsecurity)
ae2451
             constructors.add(_test_algorithm_via_hashlib_new)
ae2451
 
ae2451
         _hashlib = self._conditional_import_module('_hashlib')
ae2451
@@ -78,28 +91,13 @@ class HashLibTestCase(unittest.TestCase)
ae2451
                 if constructor:
ae2451
                     constructors.add(constructor)
ae2451
 
ae2451
-        _md5 = self._conditional_import_module('_md5')
ae2451
-        if _md5:
ae2451
-            self.constructors_to_test['md5'].add(_md5.new)
ae2451
-        _sha = self._conditional_import_module('_sha')
ae2451
-        if _sha:
ae2451
-            self.constructors_to_test['sha1'].add(_sha.new)
ae2451
-        _sha256 = self._conditional_import_module('_sha256')
ae2451
-        if _sha256:
ae2451
-            self.constructors_to_test['sha224'].add(_sha256.sha224)
ae2451
-            self.constructors_to_test['sha256'].add(_sha256.sha256)
ae2451
-        _sha512 = self._conditional_import_module('_sha512')
ae2451
-        if _sha512:
ae2451
-            self.constructors_to_test['sha384'].add(_sha512.sha384)
ae2451
-            self.constructors_to_test['sha512'].add(_sha512.sha512)
ae2451
-
ae2451
         super(HashLibTestCase, self).__init__(*args, **kwargs)
ae2451
 
ae2451
     def test_hash_array(self):
ae2451
         a = array.array("b", range(10))
ae2451
         constructors = self.constructors_to_test.itervalues()
ae2451
         for cons in itertools.chain.from_iterable(constructors):
ae2451
-            c = cons(a)
ae2451
+            c = cons(a, usedforsecurity=False)
ae2451
             c.hexdigest()
ae2451
 
ae2451
     def test_algorithms_attribute(self):
ae2451
@@ -115,28 +113,9 @@ class HashLibTestCase(unittest.TestCase)
ae2451
         self.assertRaises(ValueError, hashlib.new, 'spam spam spam spam spam')
ae2451
         self.assertRaises(TypeError, hashlib.new, 1)
ae2451
 
ae2451
-    def test_get_builtin_constructor(self):
ae2451
-        get_builtin_constructor = hashlib.__dict__[
ae2451
-                '__get_builtin_constructor']
ae2451
-        self.assertRaises(ValueError, get_builtin_constructor, 'test')
ae2451
-        try:
ae2451
-            import _md5
ae2451
-        except ImportError:
ae2451
-            pass
ae2451
-        # This forces an ImportError for "import _md5" statements
ae2451
-        sys.modules['_md5'] = None
ae2451
-        try:
ae2451
-            self.assertRaises(ValueError, get_builtin_constructor, 'md5')
ae2451
-        finally:
ae2451
-            if '_md5' in locals():
ae2451
-                sys.modules['_md5'] = _md5
ae2451
-            else:
ae2451
-                del sys.modules['_md5']
ae2451
-        self.assertRaises(TypeError, get_builtin_constructor, 3)
ae2451
-
ae2451
     def test_hexdigest(self):
ae2451
         for name in self.supported_hash_names:
ae2451
-            h = hashlib.new(name)
ae2451
+            h = hashlib.new(name, usedforsecurity=False)
ae2451
             self.assertTrue(hexstr(h.digest()) == h.hexdigest())
ae2451
 
ae2451
     def test_large_update(self):
ae2451
@@ -145,16 +125,16 @@ class HashLibTestCase(unittest.TestCase)
ae2451
         abcs = aas + bees + cees
ae2451
 
ae2451
         for name in self.supported_hash_names:
ae2451
-            m1 = hashlib.new(name)
ae2451
+            m1 = hashlib.new(name, usedforsecurity=False)
ae2451
             m1.update(aas)
ae2451
             m1.update(bees)
ae2451
             m1.update(cees)
ae2451
 
ae2451
-            m2 = hashlib.new(name)
ae2451
+            m2 = hashlib.new(name, usedforsecurity=False)
ae2451
             m2.update(abcs)
ae2451
             self.assertEqual(m1.digest(), m2.digest(), name+' update problem.')
ae2451
 
ae2451
-            m3 = hashlib.new(name, abcs)
ae2451
+            m3 = hashlib.new(name, abcs, usedforsecurity=False)
ae2451
             self.assertEqual(m1.digest(), m3.digest(), name+' new problem.')
ae2451
 
ae2451
     def check(self, name, data, digest):
ae2451
@@ -162,7 +142,7 @@ class HashLibTestCase(unittest.TestCase)
ae2451
         # 2 is for hashlib.name(...) and hashlib.new(name, ...)
ae2451
         self.assertGreaterEqual(len(constructors), 2)
ae2451
         for hash_object_constructor in constructors:
ae2451
-            computed = hash_object_constructor(data).hexdigest()
ae2451
+            computed = hash_object_constructor(data, usedforsecurity=False).hexdigest()
ae2451
             self.assertEqual(
ae2451
                     computed, digest,
ae2451
                     "Hash algorithm %s constructed using %s returned hexdigest"
ae2451
@@ -172,7 +152,8 @@ class HashLibTestCase(unittest.TestCase)
ae2451
 
ae2451
     def check_unicode(self, algorithm_name):
ae2451
         # Unicode objects are not allowed as input.
ae2451
-        expected = hashlib.new(algorithm_name, str(u'spam')).hexdigest()
ae2451
+        expected = hashlib.new(algorithm_name, str(u'spam'),
ae2451
+                               usedforsecurity=False).hexdigest()
ae2451
         self.check(algorithm_name, u'spam', expected)
ae2451
 
ae2451
     def test_unicode(self):
ae2451
@@ -354,6 +335,70 @@ class HashLibTestCase(unittest.TestCase)
ae2451
 
ae2451
         self.assertEqual(expected_hash, hasher.hexdigest())
ae2451
 
ae2451
+    def test_issue9146(self):
ae2451
+        # Ensure that various ways to use "MD5" from "hashlib" don't segfault:
ae2451
+        m = hashlib.md5(usedforsecurity=False)
ae2451
+        m.update(b'abc\n')
ae2451
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
ae2451
+        
ae2451
+        m = hashlib.new('md5', usedforsecurity=False)
ae2451
+        m.update(b'abc\n')
ae2451
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
ae2451
+        
ae2451
+        m = hashlib.md5(b'abc\n', usedforsecurity=False)
ae2451
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
ae2451
+        
ae2451
+        m = hashlib.new('md5', b'abc\n', usedforsecurity=False)
ae2451
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
ae2451
+
ae2451
+    def assertRaisesUnknownCipher(self, callable_obj=None, *args, **kwargs):
ae2451
+        try:
ae2451
+            callable_obj(*args, **kwargs)
ae2451
+        except ValueError, e:
ae2451
+            if not e.args[0].endswith('unknown cipher'):
ae2451
+                self.fail('Incorrect exception raised')
ae2451
+        else:
ae2451
+            self.fail('Exception was not raised')
ae2451
+
ae2451
+    @unittest.skipUnless(OPENSSL_ENFORCES_FIPS,
ae2451
+                         'FIPS enforcement required for this test.')
ae2451
+    def test_hashlib_fips_mode(self):        
ae2451
+        # Ensure that we raise a ValueError on vanilla attempts to use MD5
ae2451
+        # in hashlib in a FIPS-enforced setting:
ae2451
+        self.assertRaisesUnknownCipher(hashlib.md5)
ae2451
+        self.assertRaisesUnknownCipher(hashlib.new, 'md5')
ae2451
+
ae2451
+    @unittest.skipUnless(OPENSSL_ENFORCES_FIPS,
ae2451
+                         'FIPS enforcement required for this test.')
ae2451
+    def test_hashopenssl_fips_mode(self):
ae2451
+        # Verify the _hashlib module's handling of md5:
ae2451
+        import _hashlib
ae2451
+
ae2451
+        assert hasattr(_hashlib, 'openssl_md5')
ae2451
+
ae2451
+        # Ensure that _hashlib raises a ValueError on vanilla attempts to
ae2451
+        # use MD5 in a FIPS-enforced setting:
ae2451
+        self.assertRaisesUnknownCipher(_hashlib.openssl_md5)
ae2451
+        self.assertRaisesUnknownCipher(_hashlib.new, 'md5')
ae2451
+
ae2451
+        # Ensure that in such a setting we can whitelist a callsite with
ae2451
+        # usedforsecurity=False and have it succeed:
ae2451
+        m = _hashlib.openssl_md5(usedforsecurity=False)
ae2451
+        m.update('abc\n')
ae2451
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
ae2451
+        
ae2451
+        m = _hashlib.new('md5', usedforsecurity=False)
ae2451
+        m.update('abc\n')
ae2451
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
ae2451
+        
ae2451
+        m = _hashlib.openssl_md5('abc\n', usedforsecurity=False)
ae2451
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
ae2451
+        
ae2451
+        m = _hashlib.new('md5', 'abc\n', usedforsecurity=False)
ae2451
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
ae2451
+        
ae2451
+
ae2451
+
ae2451
 def test_main():
ae2451
     test_support.run_unittest(HashLibTestCase)
ae2451
 
ae2451
diff -up Python-2.7.2/Modules/_hashopenssl.c.hashlib-fips Python-2.7.2/Modules/_hashopenssl.c
ae2451
--- Python-2.7.2/Modules/_hashopenssl.c.hashlib-fips	2011-06-11 11:46:26.000000000 -0400
ae2451
+++ Python-2.7.2/Modules/_hashopenssl.c	2011-09-14 00:21:26.199252001 -0400
ae2451
@@ -36,6 +36,8 @@
ae2451
 #endif
ae2451
 
ae2451
 /* EVP is the preferred interface to hashing in OpenSSL */
ae2451
+#include <openssl/ssl.h>
ae2451
+#include <openssl/err.h>
ae2451
 #include <openssl/evp.h>
ae2451
 
ae2451
 #define MUNCH_SIZE INT_MAX
ae2451
@@ -65,11 +67,19 @@ typedef struct {
ae2451
 
ae2451
 static PyTypeObject EVPtype;
ae2451
 
ae2451
+/* Struct to hold all the cached information we need on a specific algorithm.
ae2451
+   We have one of these per algorithm */
ae2451
+typedef struct {
ae2451
+    PyObject *name_obj;
ae2451
+    EVP_MD_CTX ctxs[2];
ae2451
+    /* ctx_ptrs will point to ctxs unless an error occurred, when it will
ae2451
+       be NULL: */
ae2451
+    EVP_MD_CTX *ctx_ptrs[2];
ae2451
+    PyObject *error_msgs[2];
ae2451
+} EVPCachedInfo;
ae2451
 
ae2451
-#define DEFINE_CONSTS_FOR_NEW(Name)  \
ae2451
-    static PyObject *CONST_ ## Name ## _name_obj = NULL; \
ae2451
-    static EVP_MD_CTX CONST_new_ ## Name ## _ctx; \
ae2451
-    static EVP_MD_CTX *CONST_new_ ## Name ## _ctx_p = NULL;
ae2451
+#define DEFINE_CONSTS_FOR_NEW(Name) \
ae2451
+    static EVPCachedInfo cached_info_ ##Name;
ae2451
 
ae2451
 DEFINE_CONSTS_FOR_NEW(md5)
ae2451
 DEFINE_CONSTS_FOR_NEW(sha1)
ae2451
@@ -115,6 +125,48 @@ EVP_hash(EVPobject *self, const void *vp
ae2451
     }
ae2451
 }
ae2451
 
ae2451
+static void
ae2451
+mc_ctx_init(EVP_MD_CTX *ctx, int usedforsecurity)
ae2451
+{
ae2451
+    EVP_MD_CTX_init(ctx);
ae2451
+
ae2451
+    /*
ae2451
+      If the user has declared that this digest is being used in a
ae2451
+      non-security role (e.g. indexing into a data structure), set
ae2451
+      the exception flag for openssl to allow it
ae2451
+    */
ae2451
+    if (!usedforsecurity) {
ae2451
+#ifdef EVP_MD_CTX_FLAG_NON_FIPS_ALLOW
ae2451
+        EVP_MD_CTX_set_flags(ctx,
ae2451
+                             EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
ae2451
+#endif
ae2451
+    }
ae2451
+}
ae2451
+
ae2451
+/* Get an error msg for the last error as a PyObject */
ae2451
+static PyObject *
ae2451
+error_msg_for_last_error(void)
ae2451
+{
ae2451
+    char *errstr;
ae2451
+
ae2451
+    errstr = ERR_error_string(ERR_peek_last_error(), NULL);
ae2451
+    ERR_clear_error();
ae2451
+
ae2451
+    return PyString_FromString(errstr); /* Can be NULL */
ae2451
+}
ae2451
+
ae2451
+static void
ae2451
+set_evp_exception(void)
ae2451
+{
ae2451
+    char *errstr;
ae2451
+
ae2451
+    errstr = ERR_error_string(ERR_peek_last_error(), NULL);
ae2451
+    ERR_clear_error();
ae2451
+
ae2451
+    PyErr_SetString(PyExc_ValueError, errstr);
ae2451
+}
ae2451
+
ae2451
+
ae2451
 /* Internal methods for a hash object */
ae2451
 
ae2451
 static void
ae2451
@@ -313,14 +365,15 @@ EVP_repr(PyObject *self)
ae2451
 static int
ae2451
 EVP_tp_init(EVPobject *self, PyObject *args, PyObject *kwds)
ae2451
 {
ae2451
-    static char *kwlist[] = {"name", "string", NULL};
ae2451
+    static char *kwlist[] = {"name", "string", "usedforsecurity", NULL};
ae2451
     PyObject *name_obj = NULL;
ae2451
+    int usedforsecurity = 1;
ae2451
     Py_buffer view = { 0 };
ae2451
     char *nameStr;
ae2451
     const EVP_MD *digest;
ae2451
 
ae2451
-    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|s*:HASH", kwlist,
ae2451
-                                     &name_obj, &view)) {
ae2451
+    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|s*i:HASH", kwlist,
ae2451
+                                     &name_obj, &view, &usedforsecurity)) {
ae2451
         return -1;
ae2451
     }
ae2451
 
ae2451
@@ -336,7 +389,12 @@ EVP_tp_init(EVPobject *self, PyObject *a
ae2451
         PyBuffer_Release(&view);
ae2451
         return -1;
ae2451
     }
ae2451
-    EVP_DigestInit(&self->ctx, digest);
ae2451
+    mc_ctx_init(&self->ctx, usedforsecurity);
ae2451
+    if (!EVP_DigestInit_ex(&self->ctx, digest, NULL)) {
ae2451
+        set_evp_exception();
ae2451
+        PyBuffer_Release(&view);
ae2451
+        return -1;
ae2451
+    }
ae2451
 
ae2451
     self->name = name_obj;
ae2451
     Py_INCREF(self->name);
ae2451
@@ -420,7 +478,8 @@ static PyTypeObject EVPtype = {
ae2451
 static PyObject *
ae2451
 EVPnew(PyObject *name_obj,
ae2451
        const EVP_MD *digest, const EVP_MD_CTX *initial_ctx,
ae2451
-       const unsigned char *cp, Py_ssize_t len)
ae2451
+       const unsigned char *cp, Py_ssize_t len,
ae2451
+       int usedforsecurity)
ae2451
 {
ae2451
     EVPobject *self;
ae2451
 
ae2451
@@ -435,7 +494,12 @@ EVPnew(PyObject *name_obj,
ae2451
     if (initial_ctx) {
ae2451
         EVP_MD_CTX_copy(&self->ctx, initial_ctx);
ae2451
     } else {
ae2451
-        EVP_DigestInit(&self->ctx, digest);
ae2451
+        mc_ctx_init(&self->ctx, usedforsecurity);
ae2451
+        if (!EVP_DigestInit_ex(&self->ctx, digest, NULL)) {
ae2451
+            set_evp_exception();
ae2451
+            Py_DECREF(self);
ae2451
+            return NULL;
ae2451
+        }
ae2451
     }
ae2451
 
ae2451
     if (cp && len) {
ae2451
@@ -459,20 +523,28 @@ PyDoc_STRVAR(EVP_new__doc__,
ae2451
 An optional string argument may be provided and will be\n\
ae2451
 automatically hashed.\n\
ae2451
 \n\
ae2451
-The MD5 and SHA1 algorithms are always supported.\n");
ae2451
+The MD5 and SHA1 algorithms are always supported.\n\
ae2451
+\n\
ae2451
+An optional \"usedforsecurity=True\" keyword argument is provided for use in\n\
ae2451
+environments that enforce FIPS-based restrictions.  Some implementations of\n\
ae2451
+OpenSSL can be configured to prevent the usage of non-secure algorithms (such\n\
ae2451
+as MD5).  If you have a non-security use for these algorithms (e.g. a hash\n\
ae2451
+table), you can override this argument by marking the callsite as\n\
ae2451
+\"usedforsecurity=False\".");
ae2451
 
ae2451
 static PyObject *
ae2451
 EVP_new(PyObject *self, PyObject *args, PyObject *kwdict)
ae2451
 {
ae2451
-    static char *kwlist[] = {"name", "string", NULL};
ae2451
+    static char *kwlist[] = {"name", "string", "usedforsecurity", NULL};
ae2451
     PyObject *name_obj = NULL;
ae2451
     Py_buffer view = { 0 };
ae2451
     PyObject *ret_obj;
ae2451
     char *name;
ae2451
     const EVP_MD *digest;
ae2451
+    int usedforsecurity = 1;
ae2451
 
ae2451
-    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "O|s*:new", kwlist,
ae2451
-                                     &name_obj, &view)) {
ae2451
+    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "O|s*i:new", kwlist,
ae2451
+                                     &name_obj, &view, &usedforsecurity)) {
ae2451
         return NULL;
ae2451
     }
ae2451
 
ae2451
@@ -484,58 +556,118 @@ EVP_new(PyObject *self, PyObject *args,
ae2451
     digest = EVP_get_digestbyname(name);
ae2451
 
ae2451
     ret_obj = EVPnew(name_obj, digest, NULL, (unsigned char*)view.buf,
ae2451
-                     view.len);
ae2451
+                     view.len, usedforsecurity);
ae2451
     PyBuffer_Release(&view);
ae2451
 
ae2451
     return ret_obj;
ae2451
 }
ae2451
 
ae2451
 /*
ae2451
- *  This macro generates constructor function definitions for specific
ae2451
- *  hash algorithms.  These constructors are much faster than calling
ae2451
- *  the generic one passing it a python string and are noticably
ae2451
- *  faster than calling a python new() wrapper.  Thats important for
ae2451
+ *  This macro and function generates a family of constructor function
ae2451
+ *  definitions for specific hash algorithms.  These constructors are much
ae2451
+ *  faster than calling the generic one passing it a python string and are
ae2451
+ *  noticably faster than calling a python new() wrapper.  That's important for
ae2451
  *  code that wants to make hashes of a bunch of small strings.
ae2451
  */
ae2451
 #define GEN_CONSTRUCTOR(NAME)  \
ae2451
     static PyObject * \
ae2451
-    EVP_new_ ## NAME (PyObject *self, PyObject *args) \
ae2451
+    EVP_new_ ## NAME (PyObject *self, PyObject *args, PyObject *kwdict)  \
ae2451
     { \
ae2451
-        Py_buffer view = { 0 }; \
ae2451
-        PyObject *ret_obj; \
ae2451
-     \
ae2451
-        if (!PyArg_ParseTuple(args, "|s*:" #NAME , &view)) { \
ae2451
-            return NULL; \
ae2451
-        } \
ae2451
-     \
ae2451
-        ret_obj = EVPnew( \
ae2451
-                    CONST_ ## NAME ## _name_obj, \
ae2451
-                    NULL, \
ae2451
-                    CONST_new_ ## NAME ## _ctx_p, \
ae2451
-                    (unsigned char*)view.buf, view.len); \
ae2451
-        PyBuffer_Release(&view); \
ae2451
-        return ret_obj; \
ae2451
+        return implement_specific_EVP_new(self, args, kwdict,      \
ae2451
+                                          "|s*i:" #NAME,           \
ae2451
+                                          &cached_info_ ## NAME ); \
ae2451
     }
ae2451
 
ae2451
+static PyObject *
ae2451
+implement_specific_EVP_new(PyObject *self, PyObject *args, PyObject *kwdict,
ae2451
+                           const char *format,
ae2451
+                           EVPCachedInfo *cached_info)
ae2451
+{
ae2451
+    static char *kwlist[] = {"string", "usedforsecurity", NULL}; 
ae2451
+    Py_buffer view = { 0 };
ae2451
+    int usedforsecurity = 1;
ae2451
+    int idx;
ae2451
+    PyObject *ret_obj = NULL;
ae2451
+
ae2451
+    assert(cached_info);
ae2451
+
ae2451
+    if (!PyArg_ParseTupleAndKeywords(args, kwdict, format, kwlist,
ae2451
+                                     &view, &usedforsecurity)) {
ae2451
+        return NULL;
ae2451
+    }
ae2451
+
ae2451
+    idx = usedforsecurity ? 1 : 0;
ae2451
+
ae2451
+    /*
ae2451
+     * If an error occurred during creation of the global content, the ctx_ptr
ae2451
+     * will be NULL, and the error_msg will hopefully be non-NULL:
ae2451
+     */
ae2451
+    if (cached_info->ctx_ptrs[idx]) {
ae2451
+        /* We successfully initialized this context; copy it: */
ae2451
+        ret_obj = EVPnew(cached_info->name_obj,
ae2451
+                         NULL,
ae2451
+                         cached_info->ctx_ptrs[idx],
ae2451
+                         (unsigned char*)view.buf, view.len,
ae2451
+                         usedforsecurity);
ae2451
+    } else {
ae2451
+        /* Some kind of error happened initializing the global context for
ae2451
+           this (digest, usedforsecurity) pair.
ae2451
+           Raise an exception with the saved error message: */
ae2451
+        if (cached_info->error_msgs[idx]) {
ae2451
+            PyErr_SetObject(PyExc_ValueError, cached_info->error_msgs[idx]);
ae2451
+        } else {
ae2451
+            PyErr_SetString(PyExc_ValueError, "Error initializing hash");
ae2451
+        }
ae2451
+    }
ae2451
+
ae2451
+    PyBuffer_Release(&view);
ae2451
+
ae2451
+    return ret_obj;
ae2451
+}
ae2451
+
ae2451
 /* a PyMethodDef structure for the constructor */
ae2451
 #define CONSTRUCTOR_METH_DEF(NAME)  \
ae2451
-    {"openssl_" #NAME, (PyCFunction)EVP_new_ ## NAME, METH_VARARGS, \
ae2451
+    {"openssl_" #NAME, (PyCFunction)EVP_new_ ## NAME, \
ae2451
+        METH_VARARGS |METH_KEYWORDS, \
ae2451
         PyDoc_STR("Returns a " #NAME \
ae2451
                   " hash object; optionally initialized with a string") \
ae2451
     }
ae2451
 
ae2451
-/* used in the init function to setup a constructor: initialize OpenSSL
ae2451
-   constructor constants if they haven't been initialized already.  */
ae2451
-#define INIT_CONSTRUCTOR_CONSTANTS(NAME)  do { \
ae2451
-    if (CONST_ ## NAME ## _name_obj == NULL) { \
ae2451
-    CONST_ ## NAME ## _name_obj = PyString_FromString(#NAME); \
ae2451
-        if (EVP_get_digestbyname(#NAME)) { \
ae2451
-            CONST_new_ ## NAME ## _ctx_p = &CONST_new_ ## NAME ## _ctx; \
ae2451
-            EVP_DigestInit(CONST_new_ ## NAME ## _ctx_p, EVP_get_digestbyname(#NAME)); \
ae2451
-        } \
ae2451
-    } \
ae2451
+/*
ae2451
+  Macro/function pair to set up the constructors.
ae2451
+
ae2451
+  Try to initialize a context for each hash twice, once with
ae2451
+  EVP_MD_CTX_FLAG_NON_FIPS_ALLOW and once without.
ae2451
+  
ae2451
+  Any that have errors during initialization will end up wit a NULL ctx_ptrs
ae2451
+  entry, and err_msgs will be set (unless we're very low on memory)
ae2451
+*/
ae2451
+#define INIT_CONSTRUCTOR_CONSTANTS(NAME)  do {    \
ae2451
+    init_constructor_constant(&cached_info_ ## NAME, #NAME); \
ae2451
 } while (0);
ae2451
 
ae2451
+static void
ae2451
+init_constructor_constant(EVPCachedInfo *cached_info, const char *name)
ae2451
+{
ae2451
+    assert(cached_info);
ae2451
+    cached_info->name_obj = PyString_FromString(name);
ae2451
+    if (EVP_get_digestbyname(name)) {
ae2451
+        int i;
ae2451
+        for (i=0; i<2; i++) {
ae2451
+            mc_ctx_init(&cached_info->ctxs[i], i);
ae2451
+            if (EVP_DigestInit_ex(&cached_info->ctxs[i],
ae2451
+                                  EVP_get_digestbyname(name), NULL)) {
ae2451
+                /* Success: */
ae2451
+                cached_info->ctx_ptrs[i] = &cached_info->ctxs[i];
ae2451
+            } else {
ae2451
+                /* Failure: */
ae2451
+                cached_info->ctx_ptrs[i] = NULL;
ae2451
+                cached_info->error_msgs[i] = error_msg_for_last_error();
ae2451
+            }
ae2451
+        }
ae2451
+    }
ae2451
+}
ae2451
+
ae2451
 GEN_CONSTRUCTOR(md5)
ae2451
 GEN_CONSTRUCTOR(sha1)
ae2451
 #ifdef _OPENSSL_SUPPORTS_SHA2
ae2451
@@ -565,13 +700,10 @@ init_hashlib(void)
ae2451
 {
ae2451
     PyObject *m;
ae2451
 
ae2451
+    SSL_load_error_strings();
ae2451
+    SSL_library_init();
ae2451
     OpenSSL_add_all_digests();
ae2451
 
ae2451
-    /* TODO build EVP_functions openssl_* entries dynamically based
ae2451
-     * on what hashes are supported rather than listing many
ae2451
-     * but having some be unsupported.  Only init appropriate
ae2451
-     * constants. */
ae2451
-
ae2451
     Py_TYPE(&EVPtype) = &PyType_Type;
ae2451
     if (PyType_Ready(&EVPtype) < 0)
ae2451
         return;
ae2451
diff -up Python-2.7.2/Modules/Setup.dist.hashlib-fips Python-2.7.2/Modules/Setup.dist
ae2451
--- Python-2.7.2/Modules/Setup.dist.hashlib-fips	2011-09-14 00:21:26.163252001 -0400
ae2451
+++ Python-2.7.2/Modules/Setup.dist	2011-09-14 00:21:26.201252001 -0400
ae2451
@@ -248,14 +248,14 @@ imageop imageop.c	# Operations on images
ae2451
 # Message-Digest Algorithm, described in RFC 1321.  The necessary files
ae2451
 # md5.c and md5.h are included here.
ae2451
 
ae2451
-_md5 md5module.c md5.c
ae2451
+#_md5 md5module.c md5.c
ae2451
 
ae2451
 
ae2451
 # The _sha module implements the SHA checksum algorithms.
ae2451
 # (NIST's Secure Hash Algorithms.)
ae2451
-_sha shamodule.c
ae2451
-_sha256 sha256module.c
ae2451
-_sha512 sha512module.c
ae2451
+#_sha shamodule.c
ae2451
+#_sha256 sha256module.c
ae2451
+#_sha512 sha512module.c
ae2451
 
ae2451
 
ae2451
 # SGI IRIX specific modules -- off by default.
ae2451
diff -up Python-2.7.2/setup.py.hashlib-fips Python-2.7.2/setup.py
ae2451
--- Python-2.7.2/setup.py.hashlib-fips	2011-09-14 00:21:25.722252001 -0400
ae2451
+++ Python-2.7.2/setup.py	2011-09-14 00:21:26.203252001 -0400
ae2451
@@ -768,21 +768,6 @@ class PyBuildExt(build_ext):
ae2451
                 print ("warning: openssl 0x%08x is too old for _hashlib" %
ae2451
                        openssl_ver)
ae2451
                 missing.append('_hashlib')
ae2451
-        if COMPILED_WITH_PYDEBUG or not have_usable_openssl:
ae2451
-            # The _sha module implements the SHA1 hash algorithm.
ae2451
-            exts.append( Extension('_sha', ['shamodule.c']) )
ae2451
-            # The _md5 module implements the RSA Data Security, Inc. MD5
ae2451
-            # Message-Digest Algorithm, described in RFC 1321.  The
ae2451
-            # necessary files md5.c and md5.h are included here.
ae2451
-            exts.append( Extension('_md5',
ae2451
-                            sources = ['md5module.c', 'md5.c'],
ae2451
-                            depends = ['md5.h']) )
ae2451
-
ae2451
-        min_sha2_openssl_ver = 0x00908000
ae2451
-        if COMPILED_WITH_PYDEBUG or openssl_ver < min_sha2_openssl_ver:
ae2451
-            # OpenSSL doesn't do these until 0.9.8 so we'll bring our own hash
ae2451
-            exts.append( Extension('_sha256', ['sha256module.c']) )
ae2451
-            exts.append( Extension('_sha512', ['sha512module.c']) )
ae2451
 
ae2451
         # Modules that provide persistent dictionary-like semantics.  You will
ae2451
         # probably want to arrange for at least one of them to be available on