churchyard / rpms / python2

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