Blame SOURCES/00210-pep466-backport-hashlib.pbkdf2_hmac.patch

f63228
f63228
# HG changeset patch
f63228
# User Benjamin Peterson <benjamin@python.org>
f63228
# Date 1401567982 25200
f63228
# Node ID e4da3ba9dcac4374ca0ccc46a48c32be6f951038
f63228
# Parent  8fa8c290c165dccd613632b69a816623b51e801e
f63228
backport hashlib.pbkdf2_hmac per PEP 466 (closes #21304)
f63228
f63228
Backport by Alex Gaynor.
f63228
f63228
diff --git a/Doc/library/hashlib.rst b/Doc/library/hashlib.rst
f63228
--- a/Doc/library/hashlib.rst
f63228
+++ b/Doc/library/hashlib.rst
f63228
@@ -135,6 +135,46 @@ A hash object has the following methods:
f63228
    compute the digests of strings that share a common initial substring.
f63228
 
f63228
 
f63228
+Key Derivation Function
f63228
+-----------------------
f63228
+
f63228
+Key derivation and key stretching algorithms are designed for secure password
f63228
+hashing. Naive algorithms such as ``sha1(password)`` are not resistant against
f63228
+brute-force attacks. A good password hashing function must be tunable, slow, and
f63228
+include a `salt <https://en.wikipedia.org/wiki/Salt_%28cryptography%29>`_.
f63228
+
f63228
+
f63228
+.. function:: pbkdf2_hmac(name, password, salt, rounds, dklen=None)
f63228
+
f63228
+   The function provides PKCS#5 password-based key derivation function 2. It
f63228
+   uses HMAC as pseudorandom function.
f63228
+
f63228
+   The string *name* is the desired name of the hash digest algorithm for
f63228
+   HMAC, e.g. 'sha1' or 'sha256'. *password* and *salt* are interpreted as
f63228
+   buffers of bytes. Applications and libraries should limit *password* to
f63228
+   a sensible value (e.g. 1024). *salt* should be about 16 or more bytes from
f63228
+   a proper source, e.g. :func:`os.urandom`.
f63228
+
f63228
+   The number of *rounds* should be chosen based on the hash algorithm and
f63228
+   computing power. As of 2013, at least 100,000 rounds of SHA-256 is suggested.
f63228
+
f63228
+   *dklen* is the length of the derived key. If *dklen* is ``None`` then the
f63228
+   digest size of the hash algorithm *name* is used, e.g. 64 for SHA-512.
f63228
+
f63228
+   >>> import hashlib, binascii
f63228
+   >>> dk = hashlib.pbkdf2_hmac('sha256', b'password', b'salt', 100000)
f63228
+   >>> binascii.hexlify(dk)
f63228
+   b'0394a2ede332c9a13eb82e9b24631604c31df978b4e2f0fbd2c549944f9d79a5'
f63228
+
f63228
+   .. versionadded:: 2.7.8
f63228
+
f63228
+   .. note::
f63228
+
f63228
+      A fast implementation of *pbkdf2_hmac* is available with OpenSSL.  The
f63228
+      Python implementation uses an inline version of :mod:`hmac`. It is about
f63228
+      three times slower and doesn't release the GIL.
f63228
+
f63228
+
f63228
 .. seealso::
f63228
f63228
    Module :mod:`hmac`
f63228
diff --git a/Lib/hashlib.py b/Lib/hashlib.py
f63228
--- a/Lib/hashlib.py
f63228
+++ b/Lib/hashlib.py
f63228
@@ -77,7 +77,7 @@ __always_supported = ('md5', 'sha1', 'sh
f63228
 
f63228
 algorithms = __always_supported
f63228
 
f63228
-__all__ = __always_supported + ('new', 'algorithms')
f63228
+__all__ = __always_supported + ('new', 'algorithms', 'pbkdf2_hmac')
f63228
 
f63228
 
f63228
 def __get_openssl_constructor(name):
f63228
@@ -123,6 +123,72 @@ for __func_name in __always_supported:
f63228
         import logging
f63228
         logging.exception('code for hash %s was not found.', __func_name)
f63228
 
f63228
+try:
f63228
+    # OpenSSL's PKCS5_PBKDF2_HMAC requires OpenSSL 1.0+ with HMAC and SHA
f63228
+    from _hashlib import pbkdf2_hmac
f63228
+except ImportError:
f63228
+    import binascii
f63228
+    import struct
f63228
+
f63228
+    _trans_5C = b"".join(chr(x ^ 0x5C) for x in range(256))
f63228
+    _trans_36 = b"".join(chr(x ^ 0x36) for x in range(256))
f63228
+
f63228
+    def pbkdf2_hmac(hash_name, password, salt, iterations, dklen=None):
f63228
+        """Password based key derivation function 2 (PKCS #5 v2.0)
f63228
+
f63228
+        This Python implementations based on the hmac module about as fast
f63228
+        as OpenSSL's PKCS5_PBKDF2_HMAC for short passwords and much faster
f63228
+        for long passwords.
f63228
+        """
f63228
+        if not isinstance(hash_name, str):
f63228
+            raise TypeError(hash_name)
f63228
+
f63228
+        if not isinstance(password, (bytes, bytearray)):
f63228
+            password = bytes(buffer(password))
f63228
+        if not isinstance(salt, (bytes, bytearray)):
f63228
+            salt = bytes(buffer(salt))
f63228
+
f63228
+        # Fast inline HMAC implementation
f63228
+        inner = new(hash_name)
f63228
+        outer = new(hash_name)
f63228
+        blocksize = getattr(inner, 'block_size', 64)
f63228
+        if len(password) > blocksize:
f63228
+            password = new(hash_name, password).digest()
f63228
+        password = password + b'\x00' * (blocksize - len(password))
f63228
+        inner.update(password.translate(_trans_36))
f63228
+        outer.update(password.translate(_trans_5C))
f63228
+
f63228
+        def prf(msg, inner=inner, outer=outer):
f63228
+            # PBKDF2_HMAC uses the password as key. We can re-use the same
f63228
+            # digest objects and and just update copies to skip initialization.
f63228
+            icpy = inner.copy()
f63228
+            ocpy = outer.copy()
f63228
+            icpy.update(msg)
f63228
+            ocpy.update(icpy.digest())
f63228
+            return ocpy.digest()
f63228
+
f63228
+        if iterations < 1:
f63228
+            raise ValueError(iterations)
f63228
+        if dklen is None:
f63228
+            dklen = outer.digest_size
f63228
+        if dklen < 1:
f63228
+            raise ValueError(dklen)
f63228
+
f63228
+        hex_format_string = "%%0%ix" % (new(hash_name).digest_size * 2)
f63228
+
f63228
+        dkey = b''
f63228
+        loop = 1
f63228
+        while len(dkey) < dklen:
f63228
+            prev = prf(salt + struct.pack(b'>I', loop))
f63228
+            rkey = int(binascii.hexlify(prev), 16)
f63228
+            for i in xrange(iterations - 1):
f63228
+                prev = prf(prev)
f63228
+                rkey ^= int(binascii.hexlify(prev), 16)
f63228
+            loop += 1
f63228
+            dkey += binascii.unhexlify(hex_format_string % rkey)
f63228
+
f63228
+        return dkey[:dklen]
f63228
+
f63228
 # Cleanup locals()
f63228
 del __always_supported, __func_name, __get_hash
f63228
 del __hash_new, __get_openssl_constructor
f63228
diff --git a/Lib/test/test_hashlib.py b/Lib/test/test_hashlib.py
f63228
--- a/Lib/test/test_hashlib.py
f63228
+++ b/Lib/test/test_hashlib.py
f63228
@@ -16,6 +16,8 @@ except ImportError:
f63228
     threading = None
f63228
 import unittest
f63228
 import warnings
f63228
+from binascii import unhexlify
f63228
+
f63228
 from test import test_support
f63228
 from test.test_support import _4G, precisionbigmemtest
f63228
 
f63228
@@ -436,8 +438,72 @@ class HashLibTestCase(unittest.TestCase)
f63228
         
f63228
 
f63228
 
f63228
+class KDFTests(unittest.TestCase):
f63228
+    pbkdf2_test_vectors = [
f63228
+        (b'password', b'salt', 1, None),
f63228
+        (b'password', b'salt', 2, None),
f63228
+        (b'password', b'salt', 4096, None),
f63228
+        # too slow, it takes over a minute on a fast CPU.
f63228
+        #(b'password', b'salt', 16777216, None),
f63228
+        (b'passwordPASSWORDpassword', b'saltSALTsaltSALTsaltSALTsaltSALTsalt',
f63228
+         4096, -1),
f63228
+        (b'pass\0word', b'sa\0lt', 4096, 16),
f63228
+    ]
f63228
+
f63228
+    pbkdf2_results = {
f63228
+        "sha1": [
f63228
+            # offical test vectors from RFC 6070
f63228
+            (unhexlify('0c60c80f961f0e71f3a9b524af6012062fe037a6'), None),
f63228
+            (unhexlify('ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957'), None),
f63228
+            (unhexlify('4b007901b765489abead49d926f721d065a429c1'), None),
f63228
+            #(unhexlify('eefe3d61cd4da4e4e9945b3d6ba2158c2634e984'), None),
f63228
+            (unhexlify('3d2eec4fe41c849b80c8d83662c0e44a8b291a964c'
f63228
+                           'f2f07038'), 25),
f63228
+            (unhexlify('56fa6aa75548099dcc37d7f03425e0c3'), None),],
f63228
+        "sha256": [
f63228
+            (unhexlify('120fb6cffcf8b32c43e7225256c4f837'
f63228
+                           'a86548c92ccc35480805987cb70be17b'), None),
f63228
+            (unhexlify('ae4d0c95af6b46d32d0adff928f06dd0'
f63228
+                           '2a303f8ef3c251dfd6e2d85a95474c43'), None),
f63228
+            (unhexlify('c5e478d59288c841aa530db6845c4c8d'
f63228
+                           '962893a001ce4e11a4963873aa98134a'), None),
f63228
+            #(unhexlify('cf81c66fe8cfc04d1f31ecb65dab4089'
f63228
+            #               'f7f179e89b3b0bcb17ad10e3ac6eba46'), None),
f63228
+            (unhexlify('348c89dbcbd32b2f32d814b8116e84cf2b17'
f63228
+                           '347ebc1800181c4e2a1fb8dd53e1c635518c7dac47e9'), 40),
f63228
+            (unhexlify('89b69d0516f829893c696226650a8687'), None),],
f63228
+        "sha512": [
f63228
+            (unhexlify('867f70cf1ade02cff3752599a3a53dc4af34c7a669815ae5'
f63228
+                           'd513554e1c8cf252c02d470a285a0501bad999bfe943c08f'
f63228
+                           '050235d7d68b1da55e63f73b60a57fce'), None),
f63228
+            (unhexlify('e1d9c16aa681708a45f5c7c4e215ceb66e011a2e9f004071'
f63228
+                           '3f18aefdb866d53cf76cab2868a39b9f7840edce4fef5a82'
f63228
+                           'be67335c77a6068e04112754f27ccf4e'), None),
f63228
+            (unhexlify('d197b1b33db0143e018b12f3d1d1479e6cdebdcc97c5c0f8'
f63228
+                           '7f6902e072f457b5143f30602641b3d55cd335988cb36b84'
f63228
+                           '376060ecd532e039b742a239434af2d5'), None),
f63228
+            (unhexlify('8c0511f4c6e597c6ac6315d8f0362e225f3c501495ba23b8'
f63228
+                           '68c005174dc4ee71115b59f9e60cd9532fa33e0f75aefe30'
f63228
+                           '225c583a186cd82bd4daea9724a3d3b8'), 64),
f63228
+            (unhexlify('9d9e9c4cd21fe4be24d5b8244c759665'), None),],
f63228
+    }
f63228
+
f63228
+    def test_pbkdf2_hmac(self):
f63228
+        for digest_name, results in self.pbkdf2_results.items():
f63228
+            for i, vector in enumerate(self.pbkdf2_test_vectors):
f63228
+                password, salt, rounds, dklen = vector
f63228
+                expected, overwrite_dklen = results[i]
f63228
+                if overwrite_dklen:
f63228
+                    dklen = overwrite_dklen
f63228
+                out = hashlib.pbkdf2_hmac(
f63228
+                    digest_name, password, salt, rounds, dklen)
f63228
+                self.assertEqual(out, expected,
f63228
+                                 (digest_name, password, salt, rounds, dklen))
f63228
+
f63228
+
f63228
+
f63228
 def test_main():
f63228
-    test_support.run_unittest(HashLibTestCase)
f63228
+    test_support.run_unittest(HashLibTestCase, KDFTests)
f63228
 
f63228
 if __name__ == "__main__":
f63228
     test_main()
f63228
diff --git a/Modules/_hashopenssl.c b/Modules/_hashopenssl.c
f63228
--- a/Modules/_hashopenssl.c
f63228
+++ b/Modules/_hashopenssl.c
f63228
@@ -39,6 +39,7 @@
f63228
 #include <openssl/ssl.h>
f63228
 #include <openssl/err.h>
f63228
 #include <openssl/evp.h>
f63228
+#include <openssl/hmac.h>
f63228
 
f63228
 #define MUNCH_SIZE INT_MAX
f63228
 
f63228
@@ -563,6 +564,226 @@ EVP_new(PyObject *self, PyObject *args,
f63228
     return ret_obj;
f63228
 }
f63228
 
f63228
+
f63228
+
f63228
+#if (OPENSSL_VERSION_NUMBER >= 0x10000000 && !defined(OPENSSL_NO_HMAC) \
f63228
+     && !defined(OPENSSL_NO_SHA))
f63228
+
f63228
+#define PY_PBKDF2_HMAC 1
f63228
+
f63228
+/* Improved implementation of PKCS5_PBKDF2_HMAC()
f63228
+ *
f63228
+ * PKCS5_PBKDF2_HMAC_fast() hashes the password exactly one time instead of
f63228
+ * `iter` times. Today (2013) the iteration count is typically 100,000 or
f63228
+ * more. The improved algorithm is not subject to a Denial-of-Service
f63228
+ * vulnerability with overly large passwords.
f63228
+ *
f63228
+ * Also OpenSSL < 1.0 don't provide PKCS5_PBKDF2_HMAC(), only
f63228
+ * PKCS5_PBKDF2_SHA1.
f63228
+ */
f63228
+static int
f63228
+PKCS5_PBKDF2_HMAC_fast(const char *pass, int passlen,
f63228
+                       const unsigned char *salt, int saltlen,
f63228
+                       int iter, const EVP_MD *digest,
f63228
+                       int keylen, unsigned char *out)
f63228
+{
f63228
+    unsigned char digtmp[EVP_MAX_MD_SIZE], *p, itmp[4];
f63228
+    int cplen, j, k, tkeylen, mdlen;
f63228
+    unsigned long i = 1;
f63228
+    HMAC_CTX hctx_tpl, hctx;
f63228
+
f63228
+    mdlen = EVP_MD_size(digest);
f63228
+    if (mdlen < 0)
f63228
+        return 0;
f63228
+
f63228
+    HMAC_CTX_init(&hctx_tpl);
f63228
+    HMAC_CTX_init(&hctx);
f63228
+    p = out;
f63228
+    tkeylen = keylen;
f63228
+    if (!HMAC_Init_ex(&hctx_tpl, pass, passlen, digest, NULL)) {
f63228
+        HMAC_CTX_cleanup(&hctx_tpl);
f63228
+        return 0;
f63228
+    }
f63228
+    while(tkeylen) {
f63228
+        if(tkeylen > mdlen)
f63228
+            cplen = mdlen;
f63228
+        else
f63228
+            cplen = tkeylen;
f63228
+        /* We are unlikely to ever use more than 256 blocks (5120 bits!)
f63228
+         * but just in case...
f63228
+         */
f63228
+        itmp[0] = (unsigned char)((i >> 24) & 0xff);
f63228
+        itmp[1] = (unsigned char)((i >> 16) & 0xff);
f63228
+        itmp[2] = (unsigned char)((i >> 8) & 0xff);
f63228
+        itmp[3] = (unsigned char)(i & 0xff);
f63228
+        if (!HMAC_CTX_copy(&hctx, &hctx_tpl)) {
f63228
+            HMAC_CTX_cleanup(&hctx_tpl);
f63228
+            return 0;
f63228
+        }
f63228
+        if (!HMAC_Update(&hctx, salt, saltlen)
f63228
+                || !HMAC_Update(&hctx, itmp, 4)
f63228
+                || !HMAC_Final(&hctx, digtmp, NULL)) {
f63228
+            HMAC_CTX_cleanup(&hctx_tpl);
f63228
+            HMAC_CTX_cleanup(&hctx);
f63228
+            return 0;
f63228
+        }
f63228
+        HMAC_CTX_cleanup(&hctx);
f63228
+        memcpy(p, digtmp, cplen);
f63228
+        for (j = 1; j < iter; j++) {
f63228
+            if (!HMAC_CTX_copy(&hctx, &hctx_tpl)) {
f63228
+                HMAC_CTX_cleanup(&hctx_tpl);
f63228
+                return 0;
f63228
+            }
f63228
+            if (!HMAC_Update(&hctx, digtmp, mdlen)
f63228
+                    || !HMAC_Final(&hctx, digtmp, NULL)) {
f63228
+                HMAC_CTX_cleanup(&hctx_tpl);
f63228
+                HMAC_CTX_cleanup(&hctx);
f63228
+                return 0;
f63228
+            }
f63228
+            HMAC_CTX_cleanup(&hctx);
f63228
+            for (k = 0; k < cplen; k++) {
f63228
+                p[k] ^= digtmp[k];
f63228
+            }
f63228
+        }
f63228
+        tkeylen-= cplen;
f63228
+        i++;
f63228
+        p+= cplen;
f63228
+    }
f63228
+    HMAC_CTX_cleanup(&hctx_tpl);
f63228
+    return 1;
f63228
+}
f63228
+
f63228
+/* LCOV_EXCL_START */
f63228
+static PyObject *
f63228
+_setException(PyObject *exc)
f63228
+{
f63228
+    unsigned long errcode;
f63228
+    const char *lib, *func, *reason;
f63228
+
f63228
+    errcode = ERR_peek_last_error();
f63228
+    if (!errcode) {
f63228
+        PyErr_SetString(exc, "unknown reasons");
f63228
+        return NULL;
f63228
+    }
f63228
+    ERR_clear_error();
f63228
+
f63228
+    lib = ERR_lib_error_string(errcode);
f63228
+    func = ERR_func_error_string(errcode);
f63228
+    reason = ERR_reason_error_string(errcode);
f63228
+
f63228
+    if (lib && func) {
f63228
+        PyErr_Format(exc, "[%s: %s] %s", lib, func, reason);
f63228
+    }
f63228
+    else if (lib) {
f63228
+        PyErr_Format(exc, "[%s] %s", lib, reason);
f63228
+    }
f63228
+    else {
f63228
+        PyErr_SetString(exc, reason);
f63228
+    }
f63228
+    return NULL;
f63228
+}
f63228
+/* LCOV_EXCL_STOP */
f63228
+
f63228
+PyDoc_STRVAR(pbkdf2_hmac__doc__,
f63228
+"pbkdf2_hmac(hash_name, password, salt, iterations, dklen=None) -> key\n\
f63228
+\n\
f63228
+Password based key derivation function 2 (PKCS #5 v2.0) with HMAC as\n\
f63228
+pseudorandom function.");
f63228
+
f63228
+static PyObject *
f63228
+pbkdf2_hmac(PyObject *self, PyObject *args, PyObject *kwdict)
f63228
+{
f63228
+    static char *kwlist[] = {"hash_name", "password", "salt", "iterations",
f63228
+                             "dklen", NULL};
f63228
+    PyObject *key_obj = NULL, *dklen_obj = Py_None;
f63228
+    char *name, *key;
f63228
+    Py_buffer password, salt;
f63228
+    long iterations, dklen;
f63228
+    int retval;
f63228
+    const EVP_MD *digest;
f63228
+
f63228
+    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "ss*s*l|O:pbkdf2_hmac",
f63228
+                                     kwlist, &name, &password, &salt,
f63228
+                                     &iterations, &dklen_obj)) {
f63228
+        return NULL;
f63228
+    }
f63228
+
f63228
+    digest = EVP_get_digestbyname(name);
f63228
+    if (digest == NULL) {
f63228
+        PyErr_SetString(PyExc_ValueError, "unsupported hash type");
f63228
+        goto end;
f63228
+    }
f63228
+
f63228
+    if (password.len > INT_MAX) {
f63228
+        PyErr_SetString(PyExc_OverflowError,
f63228
+                        "password is too long.");
f63228
+        goto end;
f63228
+    }
f63228
+
f63228
+    if (salt.len > INT_MAX) {
f63228
+        PyErr_SetString(PyExc_OverflowError,
f63228
+                        "salt is too long.");
f63228
+        goto end;
f63228
+    }
f63228
+
f63228
+    if (iterations < 1) {
f63228
+        PyErr_SetString(PyExc_ValueError,
f63228
+                        "iteration value must be greater than 0.");
f63228
+        goto end;
f63228
+    }
f63228
+    if (iterations > INT_MAX) {
f63228
+        PyErr_SetString(PyExc_OverflowError,
f63228
+                        "iteration value is too great.");
f63228
+        goto end;
f63228
+    }
f63228
+
f63228
+    if (dklen_obj == Py_None) {
f63228
+        dklen = EVP_MD_size(digest);
f63228
+    } else {
f63228
+        dklen = PyLong_AsLong(dklen_obj);
f63228
+        if ((dklen == -1) && PyErr_Occurred()) {
f63228
+            goto end;
f63228
+        }
f63228
+    }
f63228
+    if (dklen < 1) {
f63228
+        PyErr_SetString(PyExc_ValueError,
f63228
+                        "key length must be greater than 0.");
f63228
+        goto end;
f63228
+    }
f63228
+    if (dklen > INT_MAX) {
f63228
+        /* INT_MAX is always smaller than dkLen max (2^32 - 1) * hLen */
f63228
+        PyErr_SetString(PyExc_OverflowError,
f63228
+                        "key length is too great.");
f63228
+        goto end;
f63228
+    }
f63228
+
f63228
+    key_obj = PyBytes_FromStringAndSize(NULL, dklen);
f63228
+    if (key_obj == NULL) {
f63228
+        goto end;
f63228
+    }
f63228
+    key = PyBytes_AS_STRING(key_obj);
f63228
+
f63228
+    Py_BEGIN_ALLOW_THREADS
f63228
+    retval = PKCS5_PBKDF2_HMAC_fast((char*)password.buf, (int)password.len,
f63228
+                                    (unsigned char *)salt.buf, (int)salt.len,
f63228
+                                    iterations, digest, dklen,
f63228
+                                    (unsigned char *)key);
f63228
+    Py_END_ALLOW_THREADS
f63228
+
f63228
+    if (!retval) {
f63228
+        Py_CLEAR(key_obj);
f63228
+        _setException(PyExc_ValueError);
f63228
+        goto end;
f63228
+    }
f63228
+
f63228
+  end:
f63228
+    PyBuffer_Release(&password);
f63228
+    PyBuffer_Release(&salt);
f63228
+    return key_obj;
f63228
+}
f63228
+
f63228
+#endif
f63228
+
f63228
 /*
f63228
  *  This macro and function generates a family of constructor function
f63228
  *  definitions for specific hash algorithms.  These constructors are much
f63228
@@ -690,6 +911,10 @@ static struct PyMethodDef EVP_functions[
f63228
     CONSTRUCTOR_METH_DEF(sha384),
f63228
     CONSTRUCTOR_METH_DEF(sha512),
f63228
 #endif
f63228
+#ifdef PY_PBKDF2_HMAC
f63228
+    {"pbkdf2_hmac", (PyCFunction)pbkdf2_hmac, METH_VARARGS|METH_KEYWORDS,
f63228
+     pbkdf2_hmac__doc__},
f63228
+#endif
f63228
     {NULL,      NULL}            /* Sentinel */
f63228
 };
f63228
 
f63228
diff -up Python-2.7.5/Lib/test/test_hmac.py.cod Python-2.7.5/Lib/test/test_hmac.py
f63228
--- Python-2.7.5/Lib/test/test_hmac.py.cod	2015-02-23 10:37:13.448594606 +0100
f63228
+++ Python-2.7.5/Lib/test/test_hmac.py	2015-02-23 10:37:27.581717509 +0100
f63228
@@ -1,3 +1,5 @@
f63228
+# coding: utf-8
f63228
+
f63228
 import hmac
f63228
 import hashlib
f63228
 import unittest