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