Brett Cannon | daa5799 | 2011-02-22 21:48:06 +0000 | [diff] [blame] | 1 | """Wrapper to the POSIX crypt library call and associated functionality.""" |
Sean Reifscheider | e2dfefb | 2011-02-22 10:55:44 +0000 | [diff] [blame] | 2 | |
| 3 | import _crypt |
Christian Heimes | afa2973 | 2012-06-27 15:36:46 +0200 | [diff] [blame] | 4 | import string as _string |
| 5 | from random import SystemRandom as _SystemRandom |
| 6 | from collections import namedtuple as _namedtuple |
Sean Reifscheider | e2dfefb | 2011-02-22 10:55:44 +0000 | [diff] [blame] | 7 | |
| 8 | |
Christian Heimes | afa2973 | 2012-06-27 15:36:46 +0200 | [diff] [blame] | 9 | _saltchars = _string.ascii_letters + _string.digits + './' |
| 10 | _sr = _SystemRandom() |
Brett Cannon | daa5799 | 2011-02-22 21:48:06 +0000 | [diff] [blame] | 11 | |
| 12 | |
Christian Heimes | afa2973 | 2012-06-27 15:36:46 +0200 | [diff] [blame] | 13 | class _Method(_namedtuple('_Method', 'name ident salt_chars total_size')): |
Brett Cannon | daa5799 | 2011-02-22 21:48:06 +0000 | [diff] [blame] | 14 | |
| 15 | """Class representing a salt method per the Modular Crypt Format or the |
| 16 | legacy 2-character crypt method.""" |
Sean Reifscheider | e2dfefb | 2011-02-22 10:55:44 +0000 | [diff] [blame] | 17 | |
| 18 | def __repr__(self): |
Brett Cannon | daa5799 | 2011-02-22 21:48:06 +0000 | [diff] [blame] | 19 | return '<crypt.METHOD_{}>'.format(self.name) |
| 20 | |
| 21 | |
Serhiy Storchaka | cede8c9 | 2017-11-16 13:22:51 +0200 | [diff] [blame] | 22 | def mksalt(method=None, *, rounds=None): |
Brett Cannon | daa5799 | 2011-02-22 21:48:06 +0000 | [diff] [blame] | 23 | """Generate a salt for the specified method. |
| 24 | |
| 25 | If not specified, the strongest available method will be used. |
| 26 | |
| 27 | """ |
| 28 | if method is None: |
| 29 | method = methods[0] |
Serhiy Storchaka | cede8c9 | 2017-11-16 13:22:51 +0200 | [diff] [blame] | 30 | if rounds is not None and not isinstance(rounds, int): |
| 31 | raise TypeError(f'{rounds.__class__.__name__} object cannot be ' |
| 32 | f'interpreted as an integer') |
| 33 | if not method.ident: # traditional |
Serhiy Storchaka | eab3ff7 | 2017-10-24 19:36:17 +0300 | [diff] [blame] | 34 | s = '' |
Serhiy Storchaka | cede8c9 | 2017-11-16 13:22:51 +0200 | [diff] [blame] | 35 | else: # modular |
Serhiy Storchaka | eab3ff7 | 2017-10-24 19:36:17 +0300 | [diff] [blame] | 36 | s = f'${method.ident}$' |
Serhiy Storchaka | cede8c9 | 2017-11-16 13:22:51 +0200 | [diff] [blame] | 37 | |
| 38 | if method.ident and method.ident[0] == '2': # Blowfish variants |
| 39 | if rounds is None: |
| 40 | log_rounds = 12 |
| 41 | else: |
| 42 | log_rounds = int.bit_length(rounds-1) |
| 43 | if rounds != 1 << log_rounds: |
| 44 | raise ValueError('rounds must be a power of 2') |
| 45 | if not 4 <= log_rounds <= 31: |
| 46 | raise ValueError('rounds out of the range 2**4 to 2**31') |
| 47 | s += f'{log_rounds:02d}$' |
| 48 | elif method.ident in ('5', '6'): # SHA-2 |
| 49 | if rounds is not None: |
| 50 | if not 1000 <= rounds <= 999_999_999: |
| 51 | raise ValueError('rounds out of the range 1000 to 999_999_999') |
| 52 | s += f'rounds={rounds}$' |
| 53 | elif rounds is not None: |
| 54 | raise ValueError(f"{method} doesn't support the rounds argument") |
| 55 | |
Victor Stinner | 7f7b941 | 2013-08-14 01:39:14 +0200 | [diff] [blame] | 56 | s += ''.join(_sr.choice(_saltchars) for char in range(method.salt_chars)) |
Brett Cannon | daa5799 | 2011-02-22 21:48:06 +0000 | [diff] [blame] | 57 | return s |
| 58 | |
| 59 | |
| 60 | def crypt(word, salt=None): |
| 61 | """Return a string representing the one-way hash of a password, with a salt |
| 62 | prepended. |
| 63 | |
| 64 | If ``salt`` is not specified or is ``None``, the strongest |
| 65 | available method will be selected and a salt generated. Otherwise, |
| 66 | ``salt`` may be one of the ``crypt.METHOD_*`` values, or a string as |
| 67 | returned by ``crypt.mksalt()``. |
| 68 | |
| 69 | """ |
| 70 | if salt is None or isinstance(salt, _Method): |
| 71 | salt = mksalt(salt) |
| 72 | return _crypt.crypt(word, salt) |
Sean Reifscheider | e2dfefb | 2011-02-22 10:55:44 +0000 | [diff] [blame] | 73 | |
| 74 | |
| 75 | # available salting/crypto methods |
Brett Cannon | cfbcdbb | 2011-02-22 21:55:51 +0000 | [diff] [blame] | 76 | methods = [] |
Serhiy Storchaka | eab3ff7 | 2017-10-24 19:36:17 +0300 | [diff] [blame] | 77 | |
Serhiy Storchaka | cede8c9 | 2017-11-16 13:22:51 +0200 | [diff] [blame] | 78 | def _add_method(name, *args, rounds=None): |
Serhiy Storchaka | eab3ff7 | 2017-10-24 19:36:17 +0300 | [diff] [blame] | 79 | method = _Method(name, *args) |
| 80 | globals()['METHOD_' + name] = method |
Serhiy Storchaka | cede8c9 | 2017-11-16 13:22:51 +0200 | [diff] [blame] | 81 | salt = mksalt(method, rounds=rounds) |
Serhiy Storchaka | eab3ff7 | 2017-10-24 19:36:17 +0300 | [diff] [blame] | 82 | result = crypt('', salt) |
| 83 | if result and len(result) == method.total_size: |
| 84 | methods.append(method) |
| 85 | return True |
| 86 | return False |
| 87 | |
| 88 | _add_method('SHA512', '6', 16, 106) |
| 89 | _add_method('SHA256', '5', 16, 63) |
| 90 | |
| 91 | # Choose the strongest supported version of Blowfish hashing. |
| 92 | # Early versions have flaws. Version 'a' fixes flaws of |
| 93 | # the initial implementation, 'b' fixes flaws of 'a'. |
| 94 | # 'y' is the same as 'b', for compatibility |
| 95 | # with openwall crypt_blowfish. |
| 96 | for _v in 'b', 'y', 'a', '': |
Serhiy Storchaka | cede8c9 | 2017-11-16 13:22:51 +0200 | [diff] [blame] | 97 | if _add_method('BLOWFISH', '2' + _v, 22, 59 + len(_v), rounds=1<<4): |
Serhiy Storchaka | eab3ff7 | 2017-10-24 19:36:17 +0300 | [diff] [blame] | 98 | break |
| 99 | |
| 100 | _add_method('MD5', '1', 8, 34) |
| 101 | _add_method('CRYPT', None, 2, 13) |
| 102 | |
| 103 | del _v, _add_method |