churchyard / rpms / python2

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