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

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