Blame SOURCES/00165-crypt-module-salt-backport.patch

556498
diff --git a/Doc/library/crypt.rst b/Doc/library/crypt.rst
556498
index 91464ef..6ee64d6 100644
556498
--- a/Doc/library/crypt.rst
556498
+++ b/Doc/library/crypt.rst
556498
@@ -16,9 +16,9 @@
556498
 
556498
 This module implements an interface to the :manpage:`crypt(3)` routine, which is
556498
 a one-way hash function based upon a modified DES algorithm; see the Unix man
556498
-page for further details.  Possible uses include allowing Python scripts to
556498
-accept typed passwords from the user, or attempting to crack Unix passwords with
556498
-a dictionary.
556498
+page for further details.  Possible uses include storing hashed passwords
556498
+so you can check passwords without storing the actual password, or attempting
556498
+to crack Unix passwords with a dictionary.
556498
 
556498
 .. index:: single: crypt(3)
556498
 
556498
@@ -27,15 +27,81 @@ the :manpage:`crypt(3)` routine in the running system.  Therefore, any
556498
 extensions available on the current implementation will also  be available on
556498
 this module.
556498
 
556498
+Hashing Methods
556498
+---------------
556498
 
556498
-.. function:: crypt(word, salt)
556498
+The :mod:`crypt` module defines the list of hashing methods (not all methods
556498
+are available on all platforms):
556498
+
556498
+.. data:: METHOD_SHA512
556498
+
556498
+   A Modular Crypt Format method with 16 character salt and 86 character
556498
+   hash.  This is the strongest method.
556498
+
556498
+.. versionadded:: 3.3
556498
+
556498
+.. data:: METHOD_SHA256
556498
+
556498
+   Another Modular Crypt Format method with 16 character salt and 43
556498
+   character hash.
556498
+
556498
+.. versionadded:: 3.3
556498
+
556498
+.. data:: METHOD_MD5
556498
+
556498
+   Another Modular Crypt Format method with 8 character salt and 22
556498
+   character hash.
556498
+
556498
+.. versionadded:: 3.3
556498
+
556498
+.. data:: METHOD_CRYPT
556498
+
556498
+   The traditional method with a 2 character salt and 13 characters of
556498
+   hash.  This is the weakest method.
556498
+
556498
+.. versionadded:: 3.3
556498
+
556498
+
556498
+Module Attributes
556498
+-----------------
556498
+
556498
+
556498
+.. attribute:: methods
556498
+
556498
+   A list of available password hashing algorithms, as
556498
+   ``crypt.METHOD_*`` objects.  This list is sorted from strongest to
556498
+   weakest, and is guaranteed to have at least ``crypt.METHOD_CRYPT``.
556498
+
556498
+.. versionadded:: 3.3
556498
+
556498
+
556498
+Module Functions
556498
+----------------
556498
+
556498
+The :mod:`crypt` module defines the following functions:
556498
+
556498
+.. function:: crypt(word, salt=None)
556498
 
556498
    *word* will usually be a user's password as typed at a prompt or  in a graphical
556498
-   interface.  *salt* is usually a random two-character string which will be used
556498
-   to perturb the DES algorithm in one of 4096 ways.  The characters in *salt* must
556498
-   be in the set ``[./a-zA-Z0-9]``.  Returns the hashed password as a string, which
556498
-   will be composed of characters from the same alphabet as the salt (the first two
556498
-   characters represent the salt itself).
556498
+   interface.  The optional *salt* is either a string as returned from
556498
+   :func:`mksalt`, one of the ``crypt.METHOD_*`` values (though not all
556498
+   may be available on all platforms), or a full encrypted password
556498
+   including salt, as returned by this function.  If *salt* is not
556498
+   provided, the strongest method will be used (as returned by
556498
+   :func:`methods`.
556498
+
556498
+   Checking a password is usually done by passing the plain-text password
556498
+   as *word* and the full results of a previous :func:`crypt` call,
556498
+   which should be the same as the results of this call.
556498
+
556498
+   *salt* (either a random 2 or 16 character string, possibly prefixed with
556498
+   ``$digit$`` to indicate the method) which will be used to perturb the
556498
+   encryption algorithm.  The characters in *salt* must be in the set
556498
+   ``[./a-zA-Z0-9]``, with the exception of Modular Crypt Format which
556498
+   prefixes a ``$digit$``.
556498
+
556498
+   Returns the hashed password as a string, which will be composed of
556498
+   characters from the same alphabet as the salt.
556498
 
556498
    .. index:: single: crypt(3)
556498
 
556498
@@ -43,6 +109,27 @@ this module.
556498
    different sizes in the *salt*, it is recommended to use  the full crypted
556498
    password as salt when checking for a password.
556498
 
556498
+.. versionchanged:: 3.3
556498
+   Before version 3.3, *salt*  must be specified as a string and cannot
556498
+   accept ``crypt.METHOD_*`` values (which don't exist anyway).
556498
+
556498
+
556498
+.. function:: mksalt(method=None)
556498
+
556498
+   Return a randomly generated salt of the specified method.  If no
556498
+   *method* is given, the strongest method available as returned by
556498
+   :func:`methods` is used.
556498
+
556498
+   The return value is a string either of 2 characters in length for
556498
+   ``crypt.METHOD_CRYPT``, or 19 characters starting with ``$digit$`` and
556498
+   16 random characters from the set ``[./a-zA-Z0-9]``, suitable for
556498
+   passing as the *salt* argument to :func:`crypt`.
556498
+
556498
+.. versionadded:: 3.3
556498
+
556498
+Examples
556498
+--------
556498
+
556498
 A simple example illustrating typical use::
556498
 
556498
    import crypt, getpass, pwd
556498
@@ -59,3 +146,11 @@ A simple example illustrating typical use::
556498
        else:
556498
            return 1
556498
 
556498
+To generate a hash of a password using the strongest available method and
556498
+check it against the original::
556498
+
556498
+   import crypt
556498
+
556498
+   hashed = crypt.crypt(plaintext)
556498
+   if hashed != crypt.crypt(plaintext, hashed):
556498
+      raise "Hashed version doesn't validate against original"
556498
diff --git a/Lib/crypt.py b/Lib/crypt.py
556498
new file mode 100644
556498
index 0000000..bf0a416
556498
--- /dev/null
556498
+++ b/Lib/crypt.py
556498
@@ -0,0 +1,71 @@
556498
+"""Wrapper to the POSIX crypt library call and associated functionality.
556498
+
556498
+Note that the ``methods`` and ``METHOD_*`` attributes are non-standard
556498
+extensions to Python 2.7, backported from 3.3"""
556498
+
556498
+import _crypt
556498
+import string as _string
556498
+from random import SystemRandom as _SystemRandom
556498
+from collections import namedtuple as _namedtuple
556498
+
556498
+
556498
+_saltchars = _string.ascii_letters + _string.digits + './'
556498
+_sr = _SystemRandom()
556498
+
556498
+
556498
+class _Method(_namedtuple('_Method', 'name ident salt_chars total_size')):
556498
+
556498
+    """Class representing a salt method per the Modular Crypt Format or the
556498
+    legacy 2-character crypt method."""
556498
+
556498
+    def __repr__(self):
556498
+        return '<crypt.METHOD_%s>' % self.name
556498
+
556498
+
556498
+def mksalt(method=None):
556498
+    """Generate a salt for the specified method.
556498
+
556498
+    If not specified, the strongest available method will be used.
556498
+
556498
+    This is a non-standard extension to Python 2.7, backported from 3.3
556498
+    """
556498
+    if method is None:
556498
+        method = methods[0]
556498
+    s = '$%s$' % method.ident if method.ident else ''
556498
+    s += ''.join(_sr.sample(_saltchars, method.salt_chars))
556498
+    return s
556498
+
556498
+
556498
+def crypt(word, salt=None):
556498
+    """Return a string representing the one-way hash of a password, with a salt
556498
+    prepended.
556498
+
556498
+    If ``salt`` is not specified or is ``None``, the strongest
556498
+    available method will be selected and a salt generated.  Otherwise,
556498
+    ``salt`` may be one of the ``crypt.METHOD_*`` values, or a string as
556498
+    returned by ``crypt.mksalt()``.
556498
+
556498
+    Note that these are non-standard extensions to Python 2.7's crypt.crypt()
556498
+    entrypoint, backported from 3.3: the standard Python 2.7 crypt.crypt()
556498
+    entrypoint requires two strings as the parameters, and does not support
556498
+    keyword arguments.
556498
+    """
556498
+    if salt is None or isinstance(salt, _Method):
556498
+        salt = mksalt(salt)
556498
+    return _crypt.crypt(word, salt)
556498
+
556498
+
556498
+#  available salting/crypto methods
556498
+METHOD_CRYPT = _Method('CRYPT', None, 2, 13)
556498
+METHOD_MD5 = _Method('MD5', '1', 8, 34)
556498
+METHOD_SHA256 = _Method('SHA256', '5', 16, 63)
556498
+METHOD_SHA512 = _Method('SHA512', '6', 16, 106)
556498
+
556498
+methods = []
556498
+for _method in (METHOD_SHA512, METHOD_SHA256, METHOD_MD5):
556498
+    _result = crypt('', _method)
556498
+    if _result and len(_result) == _method.total_size:
556498
+        methods.append(_method)
556498
+methods.append(METHOD_CRYPT)
556498
+del _result, _method
556498
+
556498
diff --git a/Lib/test/test_crypt.py b/Lib/test/test_crypt.py
556498
index 7cd9c71..b061a55 100644
556498
--- a/Lib/test/test_crypt.py
556498
+++ b/Lib/test/test_crypt.py
556498
@@ -16,6 +16,25 @@ class CryptTestCase(unittest.TestCase):
556498
             self.assertEqual(cr2, cr)
556498
 
556498
 
556498
+    def test_salt(self):
556498
+        self.assertEqual(len(crypt._saltchars), 64)
556498
+        for method in crypt.methods:
556498
+            salt = crypt.mksalt(method)
556498
+            self.assertEqual(len(salt),
556498
+                    method.salt_chars + (3 if method.ident else 0))
556498
+
556498
+    def test_saltedcrypt(self):
556498
+        for method in crypt.methods:
556498
+            pw = crypt.crypt('assword', method)
556498
+            self.assertEqual(len(pw), method.total_size)
556498
+            pw = crypt.crypt('assword', crypt.mksalt(method))
556498
+            self.assertEqual(len(pw), method.total_size)
556498
+
556498
+    def test_methods(self):
556498
+        # Gurantee that METHOD_CRYPT is the last method in crypt.methods.
556498
+        self.assertTrue(len(crypt.methods) >= 1)
556498
+        self.assertEqual(crypt.METHOD_CRYPT, crypt.methods[-1])
556498
+
556498
 def test_main():
556498
     test_support.run_unittest(CryptTestCase)
556498
 
556498
diff --git a/Modules/Setup.dist b/Modules/Setup.dist
556498
index 2712f06..3ea4f0c 100644
556498
--- a/Modules/Setup.dist
556498
+++ b/Modules/Setup.dist
556498
@@ -225,7 +225,7 @@ _ssl _ssl.c \
556498
 #
556498
 # First, look at Setup.config; configure may have set this for you.
556498
 
556498
-crypt cryptmodule.c # -lcrypt	# crypt(3); needs -lcrypt on some systems
556498
+_crypt _cryptmodule.c -lcrypt	# crypt(3); needs -lcrypt on some systems
556498
 
556498
 
556498
 # Some more UNIX dependent modules -- off by default, since these
556498
diff --git a/Modules/cryptmodule.c b/Modules/cryptmodule.c
556498
index 76de54f..7c69ca6 100644
556498
--- a/Modules/cryptmodule.c
556498
+++ b/Modules/cryptmodule.c
556498
@@ -43,7 +43,7 @@ static PyMethodDef crypt_methods[] = {
556498
 };
556498
 
556498
 PyMODINIT_FUNC
556498
-initcrypt(void)
556498
+init_crypt(void)
556498
 {
556498
-    Py_InitModule("crypt", crypt_methods);
556498
+    Py_InitModule("_crypt", crypt_methods);
556498
 }
556498
diff --git a/setup.py b/setup.py
556498
index b787487..c60ac35 100644
556498
--- a/setup.py
556498
+++ b/setup.py
556498
@@ -798,7 +798,7 @@ class PyBuildExt(build_ext):
556498
             libs = ['crypt']
556498
         else:
556498
             libs = []
556498
-        exts.append( Extension('crypt', ['cryptmodule.c'], libraries=libs) )
556498
+        exts.append( Extension('_crypt', ['_cryptmodule.c'], libraries=libs) )
556498
 
556498
         # CSV files
556498
         exts.append( Extension('_csv', ['_csv.c']) )