| 1 |
"""Wrapper to the POSIX crypt library call and associated functionality.""" |
| 2 |
|
| 3 |
import ctypes as _ctypes |
| 4 |
from ctypes.util import find_library as _find_library |
| 5 |
import string as _string |
| 6 |
from random import SystemRandom as _SystemRandom |
| 7 |
from collections import namedtuple as _namedtuple |
| 8 |
|
| 9 |
__version__ = "0.3" |
| 10 |
__py_version__ = "3.7.3" |
| 11 |
|
| 12 |
|
| 13 |
# |
| 14 |
# ctypes replacement for _crypt |
| 15 |
# |
| 16 |
|
| 17 |
class _crypt_data_libcrypt(_ctypes.Structure): |
| 18 |
"""struct crypt_data from glibc's crypt.h |
| 19 |
|
| 20 |
struct crypt_data |
| 21 |
{ |
| 22 |
char keysched[16 * 8]; |
| 23 |
char sb0[32768]; |
| 24 |
char sb1[32768]; |
| 25 |
char sb2[32768]; |
| 26 |
char sb3[32768]; |
| 27 |
/* end-of-aligment-critical-data */ |
| 28 |
char crypt_3_buf[14]; |
| 29 |
char current_salt[2]; |
| 30 |
long int current_saltbits; |
| 31 |
int direction, initialized; |
| 32 |
}; |
| 33 |
""" |
| 34 |
__slots__ = () |
| 35 |
_fields_ = [ |
| 36 |
("keysched", _ctypes.c_char * 16 * 8), |
| 37 |
("sb0", _ctypes.c_char * 32768), |
| 38 |
("sb1", _ctypes.c_char * 32768), |
| 39 |
("sb2", _ctypes.c_char * 32768), |
| 40 |
("sb3", _ctypes.c_char * 32768), |
| 41 |
("crypt_3_buf", _ctypes.c_char * 14), |
| 42 |
("current_salt", _ctypes.c_char * 2), |
| 43 |
("current_saltbits", _ctypes.c_int64), |
| 44 |
("direction", _ctypes.c_int32), |
| 45 |
("initialized", _ctypes.c_int32), |
| 46 |
] |
| 47 |
|
| 48 |
|
| 49 |
class _crypt_data_libxcrypt(_ctypes.Structure): |
| 50 |
"""struct crypt_data from libxcrypt's crypt.h |
| 51 |
|
| 52 |
#define CRYPT_OUTPUT_SIZE 384 |
| 53 |
#define CRYPT_MAX_PASSPHRASE_SIZE 512 |
| 54 |
#define CRYPT_DATA_RESERVED_SIZE 767 |
| 55 |
#define CRYPT_DATA_INTERNAL_SIZE 30720 |
| 56 |
|
| 57 |
struct crypt_data |
| 58 |
{ |
| 59 |
char output[CRYPT_OUTPUT_SIZE]; |
| 60 |
char setting[CRYPT_OUTPUT_SIZE]; |
| 61 |
char input[CRYPT_MAX_PASSPHRASE_SIZE]; |
| 62 |
char reserved[CRYPT_DATA_RESERVED_SIZE]; |
| 63 |
char initialized; |
| 64 |
char internal[CRYPT_DATA_INTERNAL_SIZE]; |
| 65 |
}; |
| 66 |
""" |
| 67 |
__slots__ = () |
| 68 |
CRYPT_OUTPUT_SIZE = 384 |
| 69 |
CRYPT_MAX_PASSPHRASE_SIZE = 512 |
| 70 |
CRYPT_DATA_RESERVED_SIZE = 767 |
| 71 |
CRYPT_DATA_INTERNAL_SIZE = 30720 |
| 72 |
_fields_ = [ |
| 73 |
("output", _ctypes.c_char * CRYPT_OUTPUT_SIZE), |
| 74 |
("setting", _ctypes.c_char * CRYPT_OUTPUT_SIZE), |
| 75 |
("input", _ctypes.c_char * CRYPT_MAX_PASSPHRASE_SIZE), |
| 76 |
("reserved", _ctypes.c_char * CRYPT_DATA_RESERVED_SIZE), |
| 77 |
("initialized", _ctypes.c_char), |
| 78 |
("internal", _ctypes.c_char * CRYPT_DATA_INTERNAL_SIZE), |
| 79 |
] |
| 80 |
|
| 81 |
|
| 82 |
try: |
| 83 |
# prefer libxcrypt |
| 84 |
_libname = _find_library('xcrypt') |
| 85 |
if _libname is not None: |
| 86 |
_crypt_data = _crypt_data_libxcrypt |
| 87 |
else: |
| 88 |
# fallback to libcrypt |
| 89 |
_libname = _find_library('crypt') |
| 90 |
if _libname is not None: |
| 91 |
_crypt_data = _crypt_data_libcrypt |
| 92 |
if _libname is not None: |
| 93 |
_libcrypt = _ctypes.CDLL(_libname) |
| 94 |
else: |
| 95 |
raise OSError |
| 96 |
except OSError: |
| 97 |
raise ImportError("libcrypt / libxcrypt missing") from None |
| 98 |
|
| 99 |
|
| 100 |
_crypt_r_func = _crypt_func = None |
| 101 |
|
| 102 |
if hasattr(_libcrypt, "crypt_r"): |
| 103 |
_crypt_r_func = _libcrypt.crypt_r |
| 104 |
_crypt_r_func.argtypes = ( |
| 105 |
_ctypes.c_char_p, |
| 106 |
_ctypes.c_char_p, |
| 107 |
_ctypes.POINTER(_crypt_data) |
| 108 |
) |
| 109 |
_crypt_r_func.restype = _ctypes.c_char_p |
| 110 |
else: |
| 111 |
_crypt_func = _libcrypt.crypt |
| 112 |
_crypt_func.argtypes = ( |
| 113 |
_ctypes.c_char_p, |
| 114 |
_ctypes.c_char_p, |
| 115 |
) |
| 116 |
_crypt_func.restype = _ctypes.c_char_p |
| 117 |
|
| 118 |
|
| 119 |
def _crypt_crypt(word, salt): |
| 120 |
"""Hash a *word* with the given *salt* and return the hashed password. |
| 121 |
|
| 122 |
[clinic input] |
| 123 |
crypt.crypt |
| 124 |
|
| 125 |
word: str |
| 126 |
salt: str |
| 127 |
/ |
| 128 |
|
| 129 |
*word* will usually be a user's password. *salt* (either a random 2 or 16 |
| 130 |
character string, possibly prefixed with $digit$ to indicate the method) |
| 131 |
will be used to perturb the encryption algorithm and produce distinct |
| 132 |
results for a given *word*. |
| 133 |
|
| 134 |
returns Py_BuildValue("s", crypt_result) |
| 135 |
""" |
| 136 |
if isinstance(word, str): |
| 137 |
word = word.encode('utf-8') |
| 138 |
else: |
| 139 |
raise TypeError( |
| 140 |
f"crypt() argument 1 must be str, not {word.__class__.__name__}" |
| 141 |
) |
| 142 |
if isinstance(salt, str): |
| 143 |
salt = salt.encode('utf-8') |
| 144 |
else: |
| 145 |
raise TypeError( |
| 146 |
f"crypt() argument 2 must be str, not {salt.__class__.__name__}" |
| 147 |
) |
| 148 |
|
| 149 |
if _crypt_r_func is not None: |
| 150 |
data = _crypt_data() |
| 151 |
crypt_result = _crypt_r_func(word, salt, data) |
| 152 |
# poor man's memory wiping |
| 153 |
_ctypes.memset(_ctypes.byref(data), 0, _ctypes.sizeof(data)) |
| 154 |
del data |
| 155 |
else: |
| 156 |
crypt_result = _crypt_func(word, salt) |
| 157 |
|
| 158 |
return crypt_result.decode('utf-8') if crypt_result else None |
| 159 |
|
| 160 |
|
| 161 |
# |
| 162 |
# original crypt module |
| 163 |
# |
| 164 |
|
| 165 |
_saltchars = _string.ascii_letters + _string.digits + './' |
| 166 |
_sr = _SystemRandom() |
| 167 |
|
| 168 |
|
| 169 |
class _Method(_namedtuple('_Method', 'name ident salt_chars total_size')): |
| 170 |
|
| 171 |
"""Class representing a salt method per the Modular Crypt Format or the |
| 172 |
legacy 2-character crypt method.""" |
| 173 |
|
| 174 |
def __repr__(self): |
| 175 |
return '<crypt.METHOD_{}>'.format(self.name) |
| 176 |
|
| 177 |
|
| 178 |
def mksalt(method=None, *, rounds=None): |
| 179 |
"""Generate a salt for the specified method. |
| 180 |
|
| 181 |
If not specified, the strongest available method will be used. |
| 182 |
|
| 183 |
""" |
| 184 |
if method is None: |
| 185 |
method = methods[0] |
| 186 |
if rounds is not None and not isinstance(rounds, int): |
| 187 |
raise TypeError(f'{rounds.__class__.__name__} object cannot be ' |
| 188 |
f'interpreted as an integer') |
| 189 |
if not method.ident: # traditional |
| 190 |
s = '' |
| 191 |
else: # modular |
| 192 |
s = f'${method.ident}$' |
| 193 |
|
| 194 |
if method.ident and method.ident[0] == '2': # Blowfish variants |
| 195 |
if rounds is None: |
| 196 |
log_rounds = 12 |
| 197 |
else: |
| 198 |
log_rounds = int.bit_length(rounds-1) |
| 199 |
if rounds != 1 << log_rounds: |
| 200 |
raise ValueError('rounds must be a power of 2') |
| 201 |
if not 4 <= log_rounds <= 31: |
| 202 |
raise ValueError('rounds out of the range 2**4 to 2**31') |
| 203 |
s += f'{log_rounds:02d}$' |
| 204 |
elif method.ident in ('5', '6'): # SHA-2 |
| 205 |
if rounds is not None: |
| 206 |
if not 1000 <= rounds <= 999999999: |
| 207 |
raise ValueError('rounds out of the range 1000 to 999_999_999') |
| 208 |
s += f'rounds={rounds}$' |
| 209 |
elif rounds is not None: |
| 210 |
raise ValueError(f"{method} doesn't support the rounds argument") |
| 211 |
|
| 212 |
s += ''.join(_sr.choice(_saltchars) for char in range(method.salt_chars)) |
| 213 |
return s |
| 214 |
|
| 215 |
|
| 216 |
def crypt(word, salt=None): |
| 217 |
"""Return a string representing the one-way hash of a password, with a salt |
| 218 |
prepended. |
| 219 |
|
| 220 |
If ``salt`` is not specified or is ``None``, the strongest |
| 221 |
available method will be selected and a salt generated. Otherwise, |
| 222 |
``salt`` may be one of the ``crypt.METHOD_*`` values, or a string as |
| 223 |
returned by ``crypt.mksalt()``. |
| 224 |
|
| 225 |
""" |
| 226 |
if salt is None or isinstance(salt, _Method): |
| 227 |
salt = mksalt(salt) |
| 228 |
return _crypt_crypt(word, salt) |
| 229 |
|
| 230 |
|
| 231 |
# available salting/crypto methods |
| 232 |
methods = [] |
| 233 |
|
| 234 |
def _add_method(name, *args, rounds=None): |
| 235 |
method = _Method(name, *args) |
| 236 |
globals()['METHOD_' + name] = method |
| 237 |
salt = mksalt(method, rounds=rounds) |
| 238 |
result = crypt('', salt) |
| 239 |
if result and len(result) == method.total_size: |
| 240 |
methods.append(method) |
| 241 |
return True |
| 242 |
return False |
| 243 |
|
| 244 |
_add_method('SHA512', '6', 16, 106) |
| 245 |
_add_method('SHA256', '5', 16, 63) |
| 246 |
|
| 247 |
# Choose the strongest supported version of Blowfish hashing. |
| 248 |
# Early versions have flaws. Version 'a' fixes flaws of |
| 249 |
# the initial implementation, 'b' fixes flaws of 'a'. |
| 250 |
# 'y' is the same as 'b', for compatibility |
| 251 |
# with openwall crypt_blowfish. |
| 252 |
for _v in 'b', 'y', 'a', '': |
| 253 |
if _add_method('BLOWFISH', '2' + _v, 22, 59 + len(_v), rounds=1<<4): |
| 254 |
break |
| 255 |
|
| 256 |
_add_method('MD5', '1', 8, 34) |
| 257 |
_add_method('CRYPT', None, 2, 13) |
| 258 |
|
| 259 |
del _v, _add_method |