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

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