churchyard / rpms / python2

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