Blame SOURCES/00146-hashlib-fips.patch

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