Blame SOURCES/00146-hashlib-fips.patch

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