blob: 8846602d7613ec76c365021ab500252a3f0546e9 [file] [log] [blame]
Brett Cannondaa57992011-02-22 21:48:06 +00001"""Wrapper to the POSIX crypt library call and associated functionality."""
Sean Reifscheidere2dfefb2011-02-22 10:55:44 +00002
Miss Islington (bot)7f7f7472019-08-13 14:27:14 -07003import sys as _sys
4
5try:
6 import _crypt
7except ModuleNotFoundError:
8 if _sys.platform == 'win32':
9 raise ImportError("The crypt module is not supported on Windows")
10 else:
11 raise ImportError("The required _crypt module was not built as part of CPython")
12
Christian Heimesafa29732012-06-27 15:36:46 +020013import string as _string
14from random import SystemRandom as _SystemRandom
15from collections import namedtuple as _namedtuple
Sean Reifscheidere2dfefb2011-02-22 10:55:44 +000016
17
Christian Heimesafa29732012-06-27 15:36:46 +020018_saltchars = _string.ascii_letters + _string.digits + './'
19_sr = _SystemRandom()
Brett Cannondaa57992011-02-22 21:48:06 +000020
21
Christian Heimesafa29732012-06-27 15:36:46 +020022class _Method(_namedtuple('_Method', 'name ident salt_chars total_size')):
Brett Cannondaa57992011-02-22 21:48:06 +000023
24 """Class representing a salt method per the Modular Crypt Format or the
25 legacy 2-character crypt method."""
Sean Reifscheidere2dfefb2011-02-22 10:55:44 +000026
27 def __repr__(self):
Brett Cannondaa57992011-02-22 21:48:06 +000028 return '<crypt.METHOD_{}>'.format(self.name)
29
30
Serhiy Storchakacede8c92017-11-16 13:22:51 +020031def mksalt(method=None, *, rounds=None):
Brett Cannondaa57992011-02-22 21:48:06 +000032 """Generate a salt for the specified method.
33
34 If not specified, the strongest available method will be used.
35
36 """
37 if method is None:
38 method = methods[0]
Serhiy Storchakacede8c92017-11-16 13:22:51 +020039 if rounds is not None and not isinstance(rounds, int):
40 raise TypeError(f'{rounds.__class__.__name__} object cannot be '
41 f'interpreted as an integer')
42 if not method.ident: # traditional
Serhiy Storchakaeab3ff72017-10-24 19:36:17 +030043 s = ''
Serhiy Storchakacede8c92017-11-16 13:22:51 +020044 else: # modular
Serhiy Storchakaeab3ff72017-10-24 19:36:17 +030045 s = f'${method.ident}$'
Serhiy Storchakacede8c92017-11-16 13:22:51 +020046
47 if method.ident and method.ident[0] == '2': # Blowfish variants
48 if rounds is None:
49 log_rounds = 12
50 else:
51 log_rounds = int.bit_length(rounds-1)
52 if rounds != 1 << log_rounds:
53 raise ValueError('rounds must be a power of 2')
54 if not 4 <= log_rounds <= 31:
55 raise ValueError('rounds out of the range 2**4 to 2**31')
56 s += f'{log_rounds:02d}$'
57 elif method.ident in ('5', '6'): # SHA-2
58 if rounds is not None:
59 if not 1000 <= rounds <= 999_999_999:
60 raise ValueError('rounds out of the range 1000 to 999_999_999')
61 s += f'rounds={rounds}$'
62 elif rounds is not None:
63 raise ValueError(f"{method} doesn't support the rounds argument")
64
Victor Stinner7f7b9412013-08-14 01:39:14 +020065 s += ''.join(_sr.choice(_saltchars) for char in range(method.salt_chars))
Brett Cannondaa57992011-02-22 21:48:06 +000066 return s
67
68
69def crypt(word, salt=None):
70 """Return a string representing the one-way hash of a password, with a salt
71 prepended.
72
73 If ``salt`` is not specified or is ``None``, the strongest
74 available method will be selected and a salt generated. Otherwise,
75 ``salt`` may be one of the ``crypt.METHOD_*`` values, or a string as
76 returned by ``crypt.mksalt()``.
77
78 """
79 if salt is None or isinstance(salt, _Method):
80 salt = mksalt(salt)
81 return _crypt.crypt(word, salt)
Sean Reifscheidere2dfefb2011-02-22 10:55:44 +000082
83
84# available salting/crypto methods
Brett Cannoncfbcdbb2011-02-22 21:55:51 +000085methods = []
Serhiy Storchakaeab3ff72017-10-24 19:36:17 +030086
Serhiy Storchakacede8c92017-11-16 13:22:51 +020087def _add_method(name, *args, rounds=None):
Serhiy Storchakaeab3ff72017-10-24 19:36:17 +030088 method = _Method(name, *args)
89 globals()['METHOD_' + name] = method
Serhiy Storchakacede8c92017-11-16 13:22:51 +020090 salt = mksalt(method, rounds=rounds)
Serhiy Storchakaeab3ff72017-10-24 19:36:17 +030091 result = crypt('', salt)
92 if result and len(result) == method.total_size:
93 methods.append(method)
94 return True
95 return False
96
97_add_method('SHA512', '6', 16, 106)
98_add_method('SHA256', '5', 16, 63)
99
100# Choose the strongest supported version of Blowfish hashing.
101# Early versions have flaws. Version 'a' fixes flaws of
102# the initial implementation, 'b' fixes flaws of 'a'.
103# 'y' is the same as 'b', for compatibility
104# with openwall crypt_blowfish.
105for _v in 'b', 'y', 'a', '':
Serhiy Storchakacede8c92017-11-16 13:22:51 +0200106 if _add_method('BLOWFISH', '2' + _v, 22, 59 + len(_v), rounds=1<<4):
Serhiy Storchakaeab3ff72017-10-24 19:36:17 +0300107 break
108
109_add_method('MD5', '1', 8, 34)
110_add_method('CRYPT', None, 2, 13)
111
112del _v, _add_method