Blame 00146-hashlib-fips.patch

e32ce18
--- Python-3.4.0b1/Lib/hashlib.py.hashlib-fips	2013-11-24 21:36:54.000000000 +0100
e32ce18
+++ Python-3.4.0b1/Lib/hashlib.py	2013-11-27 11:45:17.073617547 +0100
e32ce18
@@ -23,6 +23,16 @@
e32ce18
 Choose your hash function wisely.  Some have known collision weaknesses.
e32ce18
 sha384 and sha512 will be slow on 32 bit platforms.
e32ce18
 
e32ce18
+If the underlying implementation supports "FIPS mode", and this is enabled, it
e32ce18
+may restrict the available hashes to only those that are compliant with FIPS
e32ce18
+regulations.  For example, it may deny the use of MD5, on the grounds that this
e32ce18
+is not secure for uses such as authentication, system integrity checking, or
e32ce18
+digital signatures.   If you need to use such a hash for non-security purposes
e32ce18
+(such as indexing into a data structure for speed), you can override the keyword
e32ce18
+argument "usedforsecurity" from True to False to signify that your code is not
e32ce18
+relying on the hash for security purposes, and this will allow the hash to be
e32ce18
+usable even in FIPS mode.
e32ce18
+
e32ce18
 Hash objects have these methods:
e32ce18
  - update(arg): Update the hash object with the bytes in arg. Repeated calls
e32ce18
                 are equivalent to a single call with the concatenation of all
e32ce18
@@ -63,6 +73,19 @@
e32ce18
 __all__ = __always_supported + ('new', 'algorithms_guaranteed',
e32ce18
                                 'algorithms_available', 'pbkdf2_hmac')
e32ce18
 
e32ce18
+import functools
e32ce18
+def __ignore_usedforsecurity(func):
e32ce18
+    """Used for sha3_* functions. Until OpenSSL implements them, we want
e32ce18
+    to use them from Python _sha3 module, but we want them to accept
e32ce18
+    usedforsecurity argument too."""
e32ce18
+    # TODO: remove this function when OpenSSL implements sha3
e32ce18
+    @functools.wraps(func)
e32ce18
+    def inner(*args, **kwargs):
e32ce18
+        if 'usedforsecurity' in kwargs:
e32ce18
+            kwargs.pop('usedforsecurity')
e32ce18
+        return func(*args, **kwargs)
e32ce18
+    return inner
e32ce18
+
e32ce18
 
e32ce18
 __builtin_constructor_cache = {}
e32ce18
 
e32ce18
@@ -108,34 +131,41 @@
e32ce18
         f = getattr(_hashlib, 'openssl_' + name)
e32ce18
         # Allow the C module to raise ValueError.  The function will be
e32ce18
         # defined but the hash not actually available thanks to OpenSSL.
e32ce18
-        f()
e32ce18
+        # We pass "usedforsecurity=False" to disable FIPS-based restrictions:
e32ce18
+        # at this stage we're merely seeing if the function is callable,
e32ce18
+        # rather than using it for actual work.
e32ce18
+        f(usedforsecurity=False)
e32ce18
         # Use the C function directly (very fast)
e32ce18
         return f
e32ce18
     except (AttributeError, ValueError):
e32ce18
+        # TODO: We want to just raise here when OpenSSL implements sha3
e32ce18
+        # because we want to make sure that Fedora uses everything from OpenSSL
e32ce18
         return __get_builtin_constructor(name)
e32ce18
 
e32ce18
 
e32ce18
-def __py_new(name, data=b''):
e32ce18
-    """new(name, data=b'') - Return a new hashing object using the named algorithm;
e32ce18
-    optionally initialized with data (which must be bytes).
e32ce18
+def __py_new(name, data=b'', usedforsecurity=True):
e32ce18
+    """new(name, data=b'', usedforsecurity=True) - Return a new hashing object using
e32ce18
+    the named algorithm; optionally initialized with data (which must be bytes).
e32ce18
+    The 'usedforsecurity' keyword argument does nothing, and is for compatibilty
e32ce18
+    with the OpenSSL implementation
e32ce18
     """
e32ce18
     return __get_builtin_constructor(name)(data)
e32ce18
 
e32ce18
 
e32ce18
-def __hash_new(name, data=b''):
e32ce18
-    """new(name, data=b'') - Return a new hashing object using the named algorithm;
e32ce18
-    optionally initialized with data (which must be bytes).
e32ce18
+def __hash_new(name, data=b'', usedforsecurity=True):
e32ce18
+    """new(name, data=b'', usedforsecurity=True) - Return a new hashing object using
e32ce18
+    the named algorithm; optionally initialized with data (which must be bytes).
e32ce18
+    
e32ce18
+    Override 'usedforsecurity' to False when using for non-security purposes in
e32ce18
+    a FIPS environment
e32ce18
     """
e32ce18
     try:
e32ce18
-        return _hashlib.new(name, data)
e32ce18
+        return _hashlib.new(name, data, usedforsecurity)
e32ce18
     except ValueError:
e32ce18
-        # If the _hashlib module (OpenSSL) doesn't support the named
e32ce18
-        # hash, try using our builtin implementations.
e32ce18
-        # This allows for SHA224/256 and SHA384/512 support even though
e32ce18
-        # the OpenSSL library prior to 0.9.8 doesn't provide them.
e32ce18
+        # TODO: We want to just raise here when OpenSSL implements sha3
e32ce18
+        # because we want to make sure that Fedora uses everything from OpenSSL
e32ce18
         return __get_builtin_constructor(name)(data)
e32ce18
 
e32ce18
-
e32ce18
 try:
e32ce18
     import _hashlib
e32ce18
     new = __hash_new
e32ce18
@@ -215,7 +245,10 @@
e32ce18
     # try them all, some may not work due to the OpenSSL
e32ce18
     # version not supporting that algorithm.
e32ce18
     try:
e32ce18
-        globals()[__func_name] = __get_hash(__func_name)
e32ce18
+        func = __get_hash(__func_name)
e32ce18
+        if 'sha3_' in __func_name:
e32ce18
+            func = __ignore_usedforsecurity(func)
e32ce18
+        globals()[__func_name] = func
e32ce18
     except ValueError:
e32ce18
         import logging
e32ce18
         logging.exception('code for hash %s was not found.', __func_name)
e32ce18
@@ -223,3 +256,4 @@
e32ce18
 # Cleanup locals()
e32ce18
 del __always_supported, __func_name, __get_hash
e32ce18
 del __py_new, __hash_new, __get_openssl_constructor
e32ce18
+del __ignore_usedforsecurity
e32ce18
--- Python-3.4.0b1/Lib/test/test_hashlib.py	2013-11-27 11:55:42.769601363 +0100
e32ce18
+++ Python-3.4.0b1/Lib/test/test_hashlib.py	2013-11-28 09:33:03.929008508 +0100
e32ce18
@@ -24,7 +24,22 @@
e32ce18
 COMPILED_WITH_PYDEBUG = hasattr(sys, 'gettotalrefcount')
e32ce18
 
e32ce18
 c_hashlib = import_fresh_module('hashlib', fresh=['_hashlib'])
e32ce18
-py_hashlib = import_fresh_module('hashlib', blocked=['_hashlib'])
e32ce18
+# skipped on Fedora, since we always use OpenSSL implementation
e32ce18
+# py_hashlib = import_fresh_module('hashlib', blocked=['_hashlib'])
e32ce18
+
e32ce18
+def openssl_enforces_fips():
e32ce18
+    # Use the "openssl" command (if present) to try to determine if the local
e32ce18
+    # OpenSSL is configured to enforce FIPS
e32ce18
+    from subprocess import Popen, PIPE
e32ce18
+    try:
e32ce18
+        p = Popen(['openssl', 'md5'],
e32ce18
+                  stdin=PIPE, stdout=PIPE, stderr=PIPE)
e32ce18
+    except OSError:
e32ce18
+        # "openssl" command not found
e32ce18
+        return False
e32ce18
+    stdout, stderr = p.communicate(input=b'abc')
e32ce18
+    return b'unknown cipher' in stderr
e32ce18
+OPENSSL_ENFORCES_FIPS = openssl_enforces_fips()
e32ce18
 
e32ce18
 def hexstr(s):
e32ce18
     assert isinstance(s, bytes), repr(s)
e32ce18
@@ -34,6 +49,16 @@
e32ce18
         r += h[(i >> 4) & 0xF] + h[i & 0xF]
e32ce18
     return r
e32ce18
 
e32ce18
+# hashlib and _hashlib-based functions support a "usedforsecurity" keyword
e32ce18
+# argument, and FIPS mode requires that it be used overridden with a False
e32ce18
+# value for these selftests to work.  Other cryptographic code within Python
e32ce18
+# doesn't support this keyword.
e32ce18
+# Modify a function to one in which "usedforsecurity=False" is added to the
e32ce18
+# keyword arguments:
e32ce18
+def suppress_fips(f):
e32ce18
+    def g(*args, **kwargs):
e32ce18
+        return f(*args, usedforsecurity=False, **kwargs)
e32ce18
+    return g
e32ce18
 
e32ce18
 class HashLibTestCase(unittest.TestCase):
e32ce18
     supported_hash_names = ( 'md5', 'MD5', 'sha1', 'SHA1',
e32ce18
@@ -66,11 +91,11 @@
e32ce18
         # For each algorithm, test the direct constructor and the use
e32ce18
         # of hashlib.new given the algorithm name.
e32ce18
         for algorithm, constructors in self.constructors_to_test.items():
e32ce18
-            constructors.add(getattr(hashlib, algorithm))
e32ce18
+            constructors.add(suppress_fips(getattr(hashlib, algorithm)))
e32ce18
             def _test_algorithm_via_hashlib_new(data=None, _alg=algorithm):
e32ce18
                 if data is None:
e32ce18
-                    return hashlib.new(_alg)
e32ce18
-                return hashlib.new(_alg, data)
e32ce18
+                    return suppress_fips(hashlib.new)(_alg)
e32ce18
+                return suppress_fips(hashlib.new)(_alg, data)
e32ce18
             constructors.add(_test_algorithm_via_hashlib_new)
e32ce18
 
e32ce18
         _hashlib = self._conditional_import_module('_hashlib')
e32ce18
@@ -82,26 +107,12 @@
e32ce18
             for algorithm, constructors in self.constructors_to_test.items():
e32ce18
                 constructor = getattr(_hashlib, 'openssl_'+algorithm, None)
e32ce18
                 if constructor:
e32ce18
-                    constructors.add(constructor)
e32ce18
+                    constructors.add(suppress_fips(constructor))
e32ce18
 
e32ce18
         def add_builtin_constructor(name):
e32ce18
             constructor = getattr(hashlib, "__get_builtin_constructor")(name)
e32ce18
             self.constructors_to_test[name].add(constructor)
e32ce18
 
e32ce18
-        _md5 = self._conditional_import_module('_md5')
e32ce18
-        if _md5:
e32ce18
-            add_builtin_constructor('md5')
e32ce18
-        _sha1 = self._conditional_import_module('_sha1')
e32ce18
-        if _sha1:
e32ce18
-            add_builtin_constructor('sha1')
e32ce18
-        _sha256 = self._conditional_import_module('_sha256')
e32ce18
-        if _sha256:
e32ce18
-            add_builtin_constructor('sha224')
e32ce18
-            add_builtin_constructor('sha256')
e32ce18
-        _sha512 = self._conditional_import_module('_sha512')
e32ce18
-        if _sha512:
e32ce18
-            add_builtin_constructor('sha384')
e32ce18
-            add_builtin_constructor('sha512')
e32ce18
 
e32ce18
         super(HashLibTestCase, self).__init__(*args, **kwargs)
e32ce18
 
e32ce18
@@ -157,9 +169,6 @@
e32ce18
             else:
e32ce18
                 del sys.modules['_md5']
e32ce18
         self.assertRaises(TypeError, get_builtin_constructor, 3)
e32ce18
-        constructor = get_builtin_constructor('md5')
e32ce18
-        self.assertIs(constructor, _md5.md5)
e32ce18
-        self.assertEqual(sorted(builtin_constructor_cache), ['MD5', 'md5'])
e32ce18
 
e32ce18
     def test_hexdigest(self):
e32ce18
         for cons in self.hash_constructors:
e32ce18
@@ -558,6 +567,65 @@
e32ce18
 
e32ce18
         self.assertEqual(expected_hash, hasher.hexdigest())
e32ce18
 
e32ce18
+    def test_issue9146(self):
e32ce18
+        # Ensure that various ways to use "MD5" from "hashlib" don't segfault:
e32ce18
+        m = hashlib.md5(usedforsecurity=False)
e32ce18
+        m.update(b'abc\n')
e32ce18
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
e32ce18
+        
e32ce18
+        m = hashlib.new('md5', usedforsecurity=False)
e32ce18
+        m.update(b'abc\n')
e32ce18
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
e32ce18
+        
e32ce18
+        m = hashlib.md5(b'abc\n', usedforsecurity=False)
e32ce18
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
e32ce18
+        
e32ce18
+        m = hashlib.new('md5', b'abc\n', usedforsecurity=False)
e32ce18
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
e32ce18
+
e32ce18
+    @unittest.skipUnless(OPENSSL_ENFORCES_FIPS,
e32ce18
+                         'FIPS enforcement required for this test.')
e32ce18
+    def test_hashlib_fips_mode(self):        
e32ce18
+        # Ensure that we raise a ValueError on vanilla attempts to use MD5
e32ce18
+        # in hashlib in a FIPS-enforced setting:
e32ce18
+        with self.assertRaisesRegexp(ValueError, '.*unknown cipher'):
e32ce18
+            m = hashlib.md5()
e32ce18
+            
e32ce18
+        if not self._conditional_import_module('_md5'):
e32ce18
+            with self.assertRaisesRegexp(ValueError, '.*unknown cipher'):
e32ce18
+                m = hashlib.new('md5')
e32ce18
+
e32ce18
+    @unittest.skipUnless(OPENSSL_ENFORCES_FIPS,
e32ce18
+                         'FIPS enforcement required for this test.')
e32ce18
+    def test_hashopenssl_fips_mode(self):
e32ce18
+        # Verify the _hashlib module's handling of md5:
e32ce18
+        _hashlib = self._conditional_import_module('_hashlib')
e32ce18
+        if _hashlib:
e32ce18
+            assert hasattr(_hashlib, 'openssl_md5')
e32ce18
+
e32ce18
+            # Ensure that _hashlib raises a ValueError on vanilla attempts to
e32ce18
+            # use MD5 in a FIPS-enforced setting:
e32ce18
+            with self.assertRaisesRegexp(ValueError, '.*unknown cipher'):
e32ce18
+                m = _hashlib.openssl_md5()
e32ce18
+            with self.assertRaisesRegexp(ValueError, '.*unknown cipher'):
e32ce18
+                m = _hashlib.new('md5')
e32ce18
+
e32ce18
+            # Ensure that in such a setting we can whitelist a callsite with
e32ce18
+            # usedforsecurity=False and have it succeed:
e32ce18
+            m = _hashlib.openssl_md5(usedforsecurity=False)
e32ce18
+            m.update(b'abc\n')
e32ce18
+            self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
e32ce18
+        
e32ce18
+            m = _hashlib.new('md5', usedforsecurity=False)
e32ce18
+            m.update(b'abc\n')
e32ce18
+            self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
e32ce18
+       
e32ce18
+            m = _hashlib.openssl_md5(b'abc\n', usedforsecurity=False)
e32ce18
+            self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
e32ce18
+        
e32ce18
+            m = _hashlib.new('md5', b'abc\n', usedforsecurity=False)
e32ce18
+            self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
e32ce18
+
e32ce18
 
e32ce18
 class KDFTests(unittest.TestCase):
e32ce18
 
e32ce18
@@ -639,6 +707,7 @@
e32ce18
         with self.assertRaisesRegex(ValueError, 'unsupported hash type'):
e32ce18
             pbkdf2('unknown', b'pass', b'salt', 1)
e32ce18
 
e32ce18
+    @unittest.skip('skipped on Fedora, as we always use OpenSSL pbkdf2_hmac')
e32ce18
     def test_pbkdf2_hmac_py(self):
e32ce18
         self._test_pbkdf2_hmac(py_hashlib.pbkdf2_hmac)
e32ce18
 
e32ce18
--- Python-3.4.0b1/Modules/_hashopenssl.c.hashlib-fips	2013-11-24 21:36:56.000000000 +0100
e32ce18
+++ Python-3.4.0b1/Modules/_hashopenssl.c	2013-11-27 12:01:57.443537463 +0100
e32ce18
@@ -19,6 +19,8 @@
e32ce18
 
e32ce18
 
e32ce18
 /* EVP is the preferred interface to hashing in OpenSSL */
e32ce18
+#include <openssl/ssl.h>
e32ce18
+#include <openssl/err.h>
e32ce18
 #include <openssl/evp.h>
e32ce18
 #include <openssl/hmac.h>
e32ce18
 /* We use the object interface to discover what hashes OpenSSL supports. */
e32ce18
@@ -48,11 +50,19 @@
e32ce18
 
e32ce18
 static PyTypeObject EVPtype;
e32ce18
 
e32ce18
+/* Struct to hold all the cached information we need on a specific algorithm.
e32ce18
+   We have one of these per algorithm */
e32ce18
+typedef struct {
e32ce18
+    PyObject *name_obj;
e32ce18
+    EVP_MD_CTX ctxs[2];
e32ce18
+    /* ctx_ptrs will point to ctxs unless an error occurred, when it will
e32ce18
+       be NULL: */
e32ce18
+    EVP_MD_CTX *ctx_ptrs[2];
e32ce18
+    PyObject *error_msgs[2];
e32ce18
+} EVPCachedInfo;
e32ce18
 
e32ce18
-#define DEFINE_CONSTS_FOR_NEW(Name)  \
e32ce18
-    static PyObject *CONST_ ## Name ## _name_obj = NULL; \
e32ce18
-    static EVP_MD_CTX CONST_new_ ## Name ## _ctx; \
e32ce18
-    static EVP_MD_CTX *CONST_new_ ## Name ## _ctx_p = NULL;
e32ce18
+#define DEFINE_CONSTS_FOR_NEW(Name) \
e32ce18
+    static EVPCachedInfo cached_info_ ##Name;
e32ce18
 
e32ce18
 DEFINE_CONSTS_FOR_NEW(md5)
e32ce18
 DEFINE_CONSTS_FOR_NEW(sha1)
e32ce18
@@ -97,6 +107,48 @@
e32ce18
     }
e32ce18
 }
e32ce18
 
e32ce18
+static void
e32ce18
+mc_ctx_init(EVP_MD_CTX *ctx, int usedforsecurity)
e32ce18
+{
e32ce18
+    EVP_MD_CTX_init(ctx);
e32ce18
+
e32ce18
+    /*
e32ce18
+      If the user has declared that this digest is being used in a
e32ce18
+      non-security role (e.g. indexing into a data structure), set
e32ce18
+      the exception flag for openssl to allow it
e32ce18
+    */
e32ce18
+    if (!usedforsecurity) {
e32ce18
+#ifdef EVP_MD_CTX_FLAG_NON_FIPS_ALLOW
e32ce18
+        EVP_MD_CTX_set_flags(ctx,
e32ce18
+                             EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
e32ce18
+#endif
e32ce18
+    }
e32ce18
+}
e32ce18
+
e32ce18
+/* Get an error msg for the last error as a PyObject */
e32ce18
+static PyObject *
e32ce18
+error_msg_for_last_error(void)
e32ce18
+{
e32ce18
+    char *errstr;
e32ce18
+
e32ce18
+    errstr = ERR_error_string(ERR_peek_last_error(), NULL);
e32ce18
+    ERR_clear_error();
e32ce18
+
e32ce18
+    return PyUnicode_FromString(errstr); /* Can be NULL */
e32ce18
+}
e32ce18
+
e32ce18
+static void
e32ce18
+set_evp_exception(void)
e32ce18
+{
e32ce18
+    char *errstr;
e32ce18
+
e32ce18
+    errstr = ERR_error_string(ERR_peek_last_error(), NULL);
e32ce18
+    ERR_clear_error();
e32ce18
+
e32ce18
+    PyErr_SetString(PyExc_ValueError, errstr);
e32ce18
+}
e32ce18
+
e32ce18
+
e32ce18
 /* Internal methods for a hash object */
e32ce18
 
e32ce18
 static void
e32ce18
@@ -281,15 +333,16 @@
e32ce18
 static int
e32ce18
 EVP_tp_init(EVPobject *self, PyObject *args, PyObject *kwds)
e32ce18
 {
e32ce18
-    static char *kwlist[] = {"name", "string", NULL};
e32ce18
+    static char *kwlist[] = {"name", "string", "usedforsecurity", NULL};
e32ce18
     PyObject *name_obj = NULL;
e32ce18
     PyObject *data_obj = NULL;
e32ce18
+    int usedforsecurity = 1;
e32ce18
     Py_buffer view;
e32ce18
     char *nameStr;
e32ce18
     const EVP_MD *digest;
e32ce18
 
e32ce18
-    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:HASH", kwlist,
e32ce18
-                                     &name_obj, &data_obj)) {
e32ce18
+    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:HASH", kwlist,
e32ce18
+                                     &name_obj, &data_obj, &usedforsecurity)) {
e32ce18
         return -1;
e32ce18
     }
e32ce18
 
e32ce18
@@ -310,7 +363,12 @@
e32ce18
             PyBuffer_Release(&view);
e32ce18
         return -1;
e32ce18
     }
e32ce18
-    EVP_DigestInit(&self->ctx, digest);
e32ce18
+    mc_ctx_init(&self->ctx, usedforsecurity);
e32ce18
+    if (!EVP_DigestInit_ex(&self->ctx, digest, NULL)) {
e32ce18
+        set_evp_exception();
e32ce18
+        PyBuffer_Release(&view);
e32ce18
+        return -1;
e32ce18
+    }
e32ce18
 
e32ce18
     self->name = name_obj;
e32ce18
     Py_INCREF(self->name);
e32ce18
@@ -394,7 +452,8 @@
e32ce18
 static PyObject *
e32ce18
 EVPnew(PyObject *name_obj,
e32ce18
        const EVP_MD *digest, const EVP_MD_CTX *initial_ctx,
e32ce18
-       const unsigned char *cp, Py_ssize_t len)
e32ce18
+       const unsigned char *cp, Py_ssize_t len,
e32ce18
+       int usedforsecurity)
e32ce18
 {
e32ce18
     EVPobject *self;
e32ce18
 
e32ce18
@@ -409,7 +468,12 @@
e32ce18
     if (initial_ctx) {
e32ce18
         EVP_MD_CTX_copy(&self->ctx, initial_ctx);
e32ce18
     } else {
e32ce18
-        EVP_DigestInit(&self->ctx, digest);
e32ce18
+        mc_ctx_init(&self->ctx, usedforsecurity);
e32ce18
+        if (!EVP_DigestInit_ex(&self->ctx, digest, NULL)) {
e32ce18
+            set_evp_exception();
e32ce18
+            Py_DECREF(self);
e32ce18
+            return NULL;
e32ce18
+        }
e32ce18
     }
e32ce18
 
e32ce18
     if (cp && len) {
e32ce18
@@ -433,21 +497,29 @@
e32ce18
 An optional string argument may be provided and will be\n\
e32ce18
 automatically hashed.\n\
e32ce18
 \n\
e32ce18
-The MD5 and SHA1 algorithms are always supported.\n");
e32ce18
+The MD5 and SHA1 algorithms are always supported.\n\
e32ce18
+\n\
e32ce18
+An optional \"usedforsecurity=True\" keyword argument is provided for use in\n\
e32ce18
+environments that enforce FIPS-based restrictions.  Some implementations of\n\
e32ce18
+OpenSSL can be configured to prevent the usage of non-secure algorithms (such\n\
e32ce18
+as MD5).  If you have a non-security use for these algorithms (e.g. a hash\n\
e32ce18
+table), you can override this argument by marking the callsite as\n\
e32ce18
+\"usedforsecurity=False\".");
e32ce18
 
e32ce18
 static PyObject *
e32ce18
 EVP_new(PyObject *self, PyObject *args, PyObject *kwdict)
e32ce18
 {
e32ce18
-    static char *kwlist[] = {"name", "string", NULL};
e32ce18
+    static char *kwlist[] = {"name", "string", "usedforsecurity", NULL};
e32ce18
     PyObject *name_obj = NULL;
e32ce18
     PyObject *data_obj = NULL;
e32ce18
+    int usedforsecurity = 1;
e32ce18
     Py_buffer view = { 0 };
e32ce18
     PyObject *ret_obj;
e32ce18
     char *name;
e32ce18
     const EVP_MD *digest;
e32ce18
 
e32ce18
-    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "O|O:new", kwlist,
e32ce18
-                                     &name_obj, &data_obj)) {
e32ce18
+    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "O|Oi:new", kwlist,
e32ce18
+                                     &name_obj, &data_obj, &usedforsecurity)) {
e32ce18
         return NULL;
e32ce18
     }
e32ce18
 
e32ce18
@@ -461,7 +533,8 @@
e32ce18
 
e32ce18
     digest = EVP_get_digestbyname(name);
e32ce18
 
e32ce18
-    ret_obj = EVPnew(name_obj, digest, NULL, (unsigned char*)view.buf, view.len);
e32ce18
+    ret_obj = EVPnew(name_obj, digest, NULL, (unsigned char*)view.buf, view.len,
e32ce18
+                     usedforsecurity);
e32ce18
 
e32ce18
     if (data_obj)
e32ce18
         PyBuffer_Release(&view);
e32ce18
@@ -742,57 +815,115 @@
e32ce18
 
e32ce18
 
e32ce18
 /*
e32ce18
- *  This macro generates constructor function definitions for specific
e32ce18
- *  hash algorithms.  These constructors are much faster than calling
e32ce18
- *  the generic one passing it a python string and are noticably
e32ce18
- *  faster than calling a python new() wrapper.  Thats important for
e32ce18
+ *  This macro and function generates a family of constructor function
e32ce18
+ *  definitions for specific hash algorithms.  These constructors are much
e32ce18
+ *  faster than calling the generic one passing it a python string and are
e32ce18
+ *  noticably faster than calling a python new() wrapper.  That's important for
e32ce18
  *  code that wants to make hashes of a bunch of small strings.
e32ce18
  */
e32ce18
 #define GEN_CONSTRUCTOR(NAME)  \
e32ce18
     static PyObject * \
e32ce18
-    EVP_new_ ## NAME (PyObject *self, PyObject *args) \
e32ce18
+    EVP_new_ ## NAME (PyObject *self, PyObject *args, PyObject *kwdict)        \
e32ce18
     { \
e32ce18
-        PyObject *data_obj = NULL; \
e32ce18
-        Py_buffer view = { 0 }; \
e32ce18
-        PyObject *ret_obj; \
e32ce18
-     \
e32ce18
-        if (!PyArg_ParseTuple(args, "|O:" #NAME , &data_obj)) { \
e32ce18
-            return NULL; \
e32ce18
-        } \
e32ce18
-     \
e32ce18
-        if (data_obj) \
e32ce18
-            GET_BUFFER_VIEW_OR_ERROUT(data_obj, &view); \
e32ce18
-     \
e32ce18
-        ret_obj = EVPnew( \
e32ce18
-                    CONST_ ## NAME ## _name_obj, \
e32ce18
-                    NULL, \
e32ce18
-                    CONST_new_ ## NAME ## _ctx_p, \
e32ce18
-                    (unsigned char*)view.buf, \
e32ce18
-                    view.len); \
e32ce18
-     \
e32ce18
-        if (data_obj) \
e32ce18
-            PyBuffer_Release(&view); \
e32ce18
-        return ret_obj; \
e32ce18
+       return implement_specific_EVP_new(self, args, kwdict,      \
e32ce18
+                                         "|Oi:" #NAME,            \
e32ce18
+                                         &cached_info_ ## NAME ); \
e32ce18
+    }
e32ce18
+
e32ce18
+static PyObject *
e32ce18
+implement_specific_EVP_new(PyObject *self, PyObject *args, PyObject *kwdict,
e32ce18
+                           const char *format,
e32ce18
+                           EVPCachedInfo *cached_info)
e32ce18
+{
e32ce18
+    static char *kwlist[] = {"string", "usedforsecurity", NULL}; 
e32ce18
+    PyObject *data_obj = NULL;
e32ce18
+    Py_buffer view = { 0 };
e32ce18
+    int usedforsecurity = 1;
e32ce18
+    int idx;
e32ce18
+    PyObject *ret_obj = NULL;
e32ce18
+
e32ce18
+    assert(cached_info);
e32ce18
+
e32ce18
+    if (!PyArg_ParseTupleAndKeywords(args, kwdict, format, kwlist,
e32ce18
+                                     &data_obj, &usedforsecurity)) {
e32ce18
+        return NULL;
e32ce18
+    }
e32ce18
+
e32ce18
+    if (data_obj)
e32ce18
+       GET_BUFFER_VIEW_OR_ERROUT(data_obj, &view);
e32ce18
+
e32ce18
+    idx = usedforsecurity ? 1 : 0;
e32ce18
+
e32ce18
+    /*
e32ce18
+     * If an error occurred during creation of the global content, the ctx_ptr
e32ce18
+     * will be NULL, and the error_msg will hopefully be non-NULL:
e32ce18
+     */
e32ce18
+    if (cached_info->ctx_ptrs[idx]) {
e32ce18
+        /* We successfully initialized this context; copy it: */
e32ce18
+        ret_obj = EVPnew(cached_info->name_obj,
e32ce18
+                         NULL,
e32ce18
+                         cached_info->ctx_ptrs[idx],
e32ce18
+                         (unsigned char*)view.buf, view.len,
e32ce18
+                         usedforsecurity);
e32ce18
+    } else {
e32ce18
+        /* Some kind of error happened initializing the global context for
e32ce18
+           this (digest, usedforsecurity) pair.
e32ce18
+           Raise an exception with the saved error message: */
e32ce18
+        if (cached_info->error_msgs[idx]) {
e32ce18
+            PyErr_SetObject(PyExc_ValueError, cached_info->error_msgs[idx]);
e32ce18
+        } else {
e32ce18
+            PyErr_SetString(PyExc_ValueError, "Error initializing hash");
e32ce18
+        }
e32ce18
     }
e32ce18
 
e32ce18
+    if (data_obj)
e32ce18
+        PyBuffer_Release(&view);
e32ce18
+
e32ce18
+    return ret_obj;
e32ce18
+}
e32ce18
+
e32ce18
 /* a PyMethodDef structure for the constructor */
e32ce18
 #define CONSTRUCTOR_METH_DEF(NAME)  \
e32ce18
-    {"openssl_" #NAME, (PyCFunction)EVP_new_ ## NAME, METH_VARARGS, \
e32ce18
+    {"openssl_" #NAME, (PyCFunction)EVP_new_ ## NAME, \
e32ce18
+        METH_VARARGS|METH_KEYWORDS, \
e32ce18
         PyDoc_STR("Returns a " #NAME \
e32ce18
                   " hash object; optionally initialized with a string") \
e32ce18
     }
e32ce18
 
e32ce18
-/* used in the init function to setup a constructor: initialize OpenSSL
e32ce18
-   constructor constants if they haven't been initialized already.  */
e32ce18
-#define INIT_CONSTRUCTOR_CONSTANTS(NAME)  do { \
e32ce18
-    if (CONST_ ## NAME ## _name_obj == NULL) { \
e32ce18
-        CONST_ ## NAME ## _name_obj = PyUnicode_FromString(#NAME); \
e32ce18
-        if (EVP_get_digestbyname(#NAME)) { \
e32ce18
-            CONST_new_ ## NAME ## _ctx_p = &CONST_new_ ## NAME ## _ctx; \
e32ce18
-            EVP_DigestInit(CONST_new_ ## NAME ## _ctx_p, EVP_get_digestbyname(#NAME)); \
e32ce18
-        } \
e32ce18
-    } \
e32ce18
+/*
e32ce18
+  Macro/function pair to set up the constructors.
e32ce18
+
e32ce18
+  Try to initialize a context for each hash twice, once with
e32ce18
+  EVP_MD_CTX_FLAG_NON_FIPS_ALLOW and once without.
e32ce18
+  
e32ce18
+  Any that have errors during initialization will end up with a NULL ctx_ptrs
e32ce18
+  entry, and err_msgs will be set (unless we're very low on memory)
e32ce18
+*/
e32ce18
+#define INIT_CONSTRUCTOR_CONSTANTS(NAME)  do {    \
e32ce18
+    init_constructor_constant(&cached_info_ ## NAME, #NAME); \
e32ce18
 } while (0);
e32ce18
+static void
e32ce18
+init_constructor_constant(EVPCachedInfo *cached_info, const char *name)
e32ce18
+{
e32ce18
+    assert(cached_info);
e32ce18
+    cached_info->name_obj = PyUnicode_FromString(name);
e32ce18
+    if (EVP_get_digestbyname(name)) {
e32ce18
+        int i;
e32ce18
+        for (i=0; i<2; i++) {
e32ce18
+            mc_ctx_init(&cached_info->ctxs[i], i);
e32ce18
+            if (EVP_DigestInit_ex(&cached_info->ctxs[i],
e32ce18
+                                  EVP_get_digestbyname(name), NULL)) {
e32ce18
+                /* Success: */
e32ce18
+                cached_info->ctx_ptrs[i] = &cached_info->ctxs[i];
e32ce18
+            } else {
e32ce18
+                /* Failure: */
e32ce18
+              cached_info->ctx_ptrs[i] = NULL;
e32ce18
+              cached_info->error_msgs[i] = error_msg_for_last_error();
e32ce18
+            }
e32ce18
+        }
e32ce18
+    }
e32ce18
+}
e32ce18
+
e32ce18
 
e32ce18
 GEN_CONSTRUCTOR(md5)
e32ce18
 GEN_CONSTRUCTOR(sha1)
e32ce18
@@ -843,13 +974,10 @@
e32ce18
 {
e32ce18
     PyObject *m, *openssl_md_meth_names;
e32ce18
 
e32ce18
-    OpenSSL_add_all_digests();
e32ce18
-    ERR_load_crypto_strings();
e32ce18
+    SSL_load_error_strings();
e32ce18
+    SSL_library_init();
e32ce18
 
e32ce18
-    /* TODO build EVP_functions openssl_* entries dynamically based
e32ce18
-     * on what hashes are supported rather than listing many
e32ce18
-     * but having some be unsupported.  Only init appropriate
e32ce18
-     * constants. */
e32ce18
+    OpenSSL_add_all_digests();
e32ce18
 
e32ce18
     Py_TYPE(&EVPtype) = &PyType_Type;
e32ce18
     if (PyType_Ready(&EVPtype) < 0)