| 1 |
# (c) 2012-2014, Michael DeHaan <[email protected]> |
| 2 |
# (c) 2017 Ansible Project |
| 3 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
import random |
| 7 |
import secrets |
| 8 |
import string |
| 9 |
|
| 10 |
from dataclasses import dataclass |
| 11 |
|
| 12 |
from ansible import constants as C |
| 13 |
from ansible.errors import AnsibleError, AnsibleAssertionError |
| 14 |
from ansible.module_utils.common.text.converters import to_text, to_bytes |
| 15 |
from ansible.utils.display import Display |
| 16 |
|
| 17 |
PASSLIB_E = None |
| 18 |
PASSLIB_AVAILABLE = False |
| 19 |
|
| 20 |
try: |
| 21 |
import passlib |
| 22 |
import passlib.hash |
| 23 |
from passlib.utils.handlers import HasRawSalt, PrefixWrapper |
| 24 |
try: |
| 25 |
from passlib.utils.binary import bcrypt64 |
| 26 |
except ImportError: |
| 27 |
from passlib.utils import bcrypt64 |
| 28 |
|
| 29 |
PASSLIB_AVAILABLE = True |
| 30 |
except Exception as e: |
| 31 |
PASSLIB_E = e |
| 32 |
|
| 33 |
CRYPT_E = None |
| 34 |
HAS_CRYPT = False |
| 35 |
try: |
| 36 |
from ansible._internal._encryption._crypt import CryptFacade |
| 37 |
_crypt_facade = CryptFacade() |
| 38 |
HAS_CRYPT = True |
| 39 |
except Exception as e: |
| 40 |
CRYPT_E = e |
| 41 |
|
| 42 |
|
| 43 |
display = Display() |
| 44 |
|
| 45 |
__all__ = ['do_encrypt'] |
| 46 |
|
| 47 |
DEFAULT_PASSWORD_LENGTH = 20 |
| 48 |
|
| 49 |
|
| 50 |
def random_password(length=DEFAULT_PASSWORD_LENGTH, chars=C.DEFAULT_PASSWORD_CHARS, seed=None): |
| 51 |
"""Return a random password string of length containing only chars |
| 52 |
|
| 53 |
:kwarg length: The number of characters in the new password. Defaults to 20. |
| 54 |
:kwarg chars: The characters to choose from. The default is all ascii |
| 55 |
letters, ascii digits, and these symbols ``.,:-_`` |
| 56 |
""" |
| 57 |
if not isinstance(chars, str): |
| 58 |
raise AnsibleAssertionError(f'{chars=!r} ({type(chars)}) is not a {type(str)}.') |
| 59 |
|
| 60 |
if seed is None: |
| 61 |
random_generator = secrets.SystemRandom() |
| 62 |
else: |
| 63 |
random_generator = random.Random(seed) |
| 64 |
|
| 65 |
return u''.join(random_generator.choice(chars) for dummy in range(length)) |
| 66 |
|
| 67 |
|
| 68 |
_SALT_CHARS = string.ascii_letters + string.digits + './' |
| 69 |
_VALID_SALT_CHARS = frozenset(_SALT_CHARS) |
| 70 |
|
| 71 |
|
| 72 |
def random_salt(length=8): |
| 73 |
"""Return a text string suitable for use as a salt for the hash functions we use to encrypt passwords. |
| 74 |
""" |
| 75 |
# Note passlib salt values must be pure ascii so we can't let the user |
| 76 |
# configure this |
| 77 |
return random_password(length=length, chars=_SALT_CHARS) |
| 78 |
|
| 79 |
|
| 80 |
@dataclass(frozen=True) |
| 81 |
class _Algo: |
| 82 |
crypt_id: str |
| 83 |
salt_size: int |
| 84 |
implicit_rounds: int | None = None |
| 85 |
salt_exact: bool = False |
| 86 |
implicit_ident: str | None = None |
| 87 |
rounds_format: str | None = None |
| 88 |
requires_gensalt: bool = False |
| 89 |
|
| 90 |
|
| 91 |
class BaseHash(object): |
| 92 |
algorithms = { |
| 93 |
'md5_crypt': _Algo(crypt_id='1', salt_size=8), |
| 94 |
'bcrypt': _Algo(crypt_id='2b', salt_size=22, implicit_rounds=12, salt_exact=True, implicit_ident='2b', rounds_format='cost'), |
| 95 |
'sha256_crypt': _Algo(crypt_id='5', salt_size=16, implicit_rounds=535000, rounds_format='rounds'), |
| 96 |
'sha512_crypt': _Algo(crypt_id='6', salt_size=16, implicit_rounds=656000, rounds_format='rounds'), |
| 97 |
} |
| 98 |
|
| 99 |
def __init__(self, algorithm): |
| 100 |
self.algorithm = algorithm |
| 101 |
display.vv(f"Using {self.__class__.__name__} to hash input with {algorithm!r}") |
| 102 |
|
| 103 |
|
| 104 |
class CryptHash(BaseHash): |
| 105 |
algorithms = { |
| 106 |
**BaseHash.algorithms, |
| 107 |
'yescrypt': _Algo(crypt_id='y', salt_size=16, implicit_rounds=5, rounds_format='cost', requires_gensalt=True, salt_exact=True), |
| 108 |
} |
| 109 |
|
| 110 |
def __init__(self, algorithm: str) -> None: |
| 111 |
super(CryptHash, self).__init__(algorithm) |
| 112 |
|
| 113 |
if not HAS_CRYPT: |
| 114 |
raise AnsibleError("crypt cannot be used as the 'libxcrypt' library is not installed or is unusable.") from CRYPT_E |
| 115 |
|
| 116 |
if algorithm not in self.algorithms: |
| 117 |
raise AnsibleError(f"crypt does not support {self.algorithm!r} algorithm") |
| 118 |
|
| 119 |
self.algo_data = self.algorithms[algorithm] |
| 120 |
|
| 121 |
if self.algo_data.requires_gensalt and not _crypt_facade.has_crypt_gensalt: |
| 122 |
raise AnsibleError(f"{self.algorithm!r} algorithm requires libxcrypt") |
| 123 |
|
| 124 |
def hash(self, secret: str, salt: str | None = None, salt_size: int | None = None, rounds: int | None = None, ident: str | None = None) -> str: |
| 125 |
rounds = self._rounds(rounds) |
| 126 |
ident = self._ident(ident) |
| 127 |
|
| 128 |
if _crypt_facade.has_crypt_gensalt: |
| 129 |
saltstring = self._gensalt(ident, rounds, salt, salt_size) |
| 130 |
else: |
| 131 |
saltstring = self._build_saltstring(ident, rounds, salt, salt_size) |
| 132 |
|
| 133 |
return self._hash(secret, saltstring) |
| 134 |
|
| 135 |
def _validate_salt_size(self, salt_size: int | None) -> int: |
| 136 |
if salt_size is not None and not isinstance(salt_size, int): |
| 137 |
raise TypeError('salt_size must be an integer') |
| 138 |
salt_size = salt_size or self.algo_data.salt_size |
| 139 |
if self.algo_data.salt_exact and salt_size != self.algo_data.salt_size: |
| 140 |
raise AnsibleError(f"invalid salt size supplied ({salt_size}), expected {self.algo_data.salt_size}") |
| 141 |
elif not self.algo_data.salt_exact and salt_size > self.algo_data.salt_size: |
| 142 |
raise AnsibleError(f"invalid salt size supplied ({salt_size}), expected at most {self.algo_data.salt_size}") |
| 143 |
return salt_size |
| 144 |
|
| 145 |
def _salt(self, salt: str | None, salt_size: int | None) -> str: |
| 146 |
salt_size = self._validate_salt_size(salt_size) |
| 147 |
ret = salt or random_salt(salt_size) |
| 148 |
if not set(ret).issubset(_VALID_SALT_CHARS): |
| 149 |
raise AnsibleError("invalid characters in salt") |
| 150 |
if self.algo_data.salt_exact and len(ret) != self.algo_data.salt_size: |
| 151 |
raise AnsibleError(f"invalid salt size supplied ({len(ret)}), expected {self.algo_data.salt_size}") |
| 152 |
elif not self.algo_data.salt_exact and len(ret) > self.algo_data.salt_size: |
| 153 |
raise AnsibleError(f"invalid salt size supplied ({len(ret)}), expected at most {self.algo_data.salt_size}") |
| 154 |
return ret |
| 155 |
|
| 156 |
def _rounds(self, rounds: int | None) -> int | None: |
| 157 |
return rounds or self.algo_data.implicit_rounds |
| 158 |
|
| 159 |
def _ident(self, ident: str | None) -> str | None: |
| 160 |
return ident or self.algo_data.crypt_id |
| 161 |
|
| 162 |
def _gensalt(self, ident: str, rounds: int | None, salt: str | None, salt_size: int | None) -> str: |
| 163 |
if salt is None: |
| 164 |
salt_size = self._validate_salt_size(salt_size) |
| 165 |
rbytes = secrets.token_bytes(salt_size) |
| 166 |
else: |
| 167 |
salt = self._salt(salt, salt_size) |
| 168 |
rbytes = to_bytes(salt) |
| 169 |
|
| 170 |
prefix = f'${ident}$' |
| 171 |
count = rounds or 0 |
| 172 |
|
| 173 |
try: |
| 174 |
salt_bytes = _crypt_facade.crypt_gensalt(to_bytes(prefix), count, rbytes) |
| 175 |
return to_text(salt_bytes, errors='strict') |
| 176 |
except (NotImplementedError, ValueError) as e: |
| 177 |
raise AnsibleError(f"Failed to generate salt for {self.algorithm!r} algorithm") from e |
| 178 |
|
| 179 |
def _build_saltstring(self, ident: str, rounds: int | None, salt: str | None, salt_size: int | None) -> str: |
| 180 |
salt = self._salt(salt, salt_size) |
| 181 |
saltstring = f'${ident}' if ident else '' |
| 182 |
if rounds: |
| 183 |
if self.algo_data.rounds_format == 'cost': |
| 184 |
# musl libc requires a 2-digit bcrypt cost ($2b$05$, not $2b$5$). |
| 185 |
saltstring += f'${rounds:02d}' |
| 186 |
else: |
| 187 |
saltstring += f'$rounds={rounds}' |
| 188 |
saltstring += f'${salt}' |
| 189 |
return saltstring |
| 190 |
|
| 191 |
def _hash(self, secret: str, saltstring: str) -> str: |
| 192 |
try: |
| 193 |
result = _crypt_facade.crypt(to_bytes(secret), to_bytes(saltstring)) |
| 194 |
except (OSError, ValueError) as e: |
| 195 |
raise AnsibleError(f"crypt does not support {self.algorithm!r} algorithm") from e |
| 196 |
|
| 197 |
return to_text(result, errors='strict') |
| 198 |
|
| 199 |
|
| 200 |
class PasslibHash(BaseHash): |
| 201 |
def __init__(self, algorithm): |
| 202 |
super(PasslibHash, self).__init__(algorithm) |
| 203 |
|
| 204 |
if not PASSLIB_AVAILABLE: |
| 205 |
raise AnsibleError(f"The passlib Python package must be installed to hash with the {algorithm!r} algorithm.") from PASSLIB_E |
| 206 |
|
| 207 |
try: |
| 208 |
self.crypt_algo = getattr(passlib.hash, algorithm) |
| 209 |
except Exception: |
| 210 |
raise AnsibleError(f"Installed passlib version {passlib.__version__} does not support the {algorithm!r} algorithm.") from None |
| 211 |
|
| 212 |
def hash(self, secret, salt=None, salt_size=None, rounds=None, ident=None): |
| 213 |
salt = self._clean_salt(salt) |
| 214 |
rounds = self._clean_rounds(rounds) |
| 215 |
ident = self._clean_ident(ident) |
| 216 |
if salt_size is not None and not isinstance(salt_size, int): |
| 217 |
raise TypeError("salt_size must be an integer") |
| 218 |
return self._hash(secret, salt=salt, salt_size=salt_size, rounds=rounds, ident=ident) |
| 219 |
|
| 220 |
def _clean_ident(self, ident): |
| 221 |
ret = None |
| 222 |
if not ident: |
| 223 |
if self.algorithm in self.algorithms: |
| 224 |
return self.algorithms.get(self.algorithm).implicit_ident |
| 225 |
return ret |
| 226 |
if self.algorithm == 'bcrypt': |
| 227 |
return ident |
| 228 |
return ret |
| 229 |
|
| 230 |
def _clean_salt(self, salt): |
| 231 |
if not salt: |
| 232 |
return None |
| 233 |
elif issubclass(self.crypt_algo.wrapped if isinstance(self.crypt_algo, PrefixWrapper) else self.crypt_algo, HasRawSalt): |
| 234 |
ret = to_bytes(salt, encoding='ascii', errors='strict') |
| 235 |
else: |
| 236 |
ret = to_text(salt, encoding='ascii', errors='strict') |
| 237 |
|
| 238 |
# Ensure the salt has the correct padding |
| 239 |
if self.algorithm == 'bcrypt': |
| 240 |
ret = bcrypt64.repair_unused(ret) |
| 241 |
|
| 242 |
return ret |
| 243 |
|
| 244 |
def _clean_rounds(self, rounds): |
| 245 |
algo_data = self.algorithms.get(self.algorithm) |
| 246 |
if rounds: |
| 247 |
return rounds |
| 248 |
elif algo_data and algo_data.implicit_rounds: |
| 249 |
# The default rounds used by passlib depend on the passlib version. |
| 250 |
# For consistency ensure that passlib behaves the same as crypt in case no rounds were specified. |
| 251 |
# Thus use the crypt defaults. |
| 252 |
return algo_data.implicit_rounds |
| 253 |
else: |
| 254 |
return None |
| 255 |
|
| 256 |
def _hash(self, secret, salt, salt_size, rounds, ident): |
| 257 |
# Not every hash algorithm supports every parameter. |
| 258 |
# Thus create the settings dict only with set parameters. |
| 259 |
settings = {} |
| 260 |
if salt: |
| 261 |
settings['salt'] = salt |
| 262 |
if salt_size: |
| 263 |
settings['salt_size'] = salt_size |
| 264 |
if rounds: |
| 265 |
settings['rounds'] = rounds |
| 266 |
if ident: |
| 267 |
settings['ident'] = ident |
| 268 |
|
| 269 |
# starting with passlib 1.7 'using' and 'hash' should be used instead of 'encrypt' |
| 270 |
try: |
| 271 |
if hasattr(self.crypt_algo, 'hash'): |
| 272 |
result = self.crypt_algo.using(**settings).hash(secret) |
| 273 |
elif hasattr(self.crypt_algo, 'encrypt'): |
| 274 |
result = self.crypt_algo.encrypt(secret, **settings) |
| 275 |
else: |
| 276 |
raise ValueError(f"Installed passlib version {passlib.__version__} is not supported.") |
| 277 |
except ValueError as ex: |
| 278 |
raise AnsibleError("Could not hash the secret.") from ex |
| 279 |
|
| 280 |
# passlib.hash should always return something or raise an exception. |
| 281 |
# Still ensure that there is always a result. |
| 282 |
# Otherwise an empty password might be assumed by some modules, like the user module. |
| 283 |
if not result: |
| 284 |
raise AnsibleError(f"Failed to hash with passlib using the {self.algorithm!r} algorithm.") |
| 285 |
|
| 286 |
# Hashes from passlib.hash should be represented as ascii strings of hex |
| 287 |
# digits so this should not traceback. If it's not representable as such |
| 288 |
# we need to traceback and then block such algorithms because it may |
| 289 |
# impact calling code. |
| 290 |
return to_text(result, errors='strict') |
| 291 |
|
| 292 |
|
| 293 |
def do_encrypt(result, algorithm, salt_size=None, salt=None, ident=None, rounds=None): |
| 294 |
if HAS_CRYPT and algorithm in CryptHash.algorithms: |
| 295 |
return CryptHash(algorithm).hash(result, salt=salt, salt_size=salt_size, rounds=rounds, ident=ident) |
| 296 |
elif PASSLIB_AVAILABLE: |
| 297 |
# TODO: deprecate passlib |
| 298 |
return PasslibHash(algorithm).hash(result, salt=salt, salt_size=salt_size, rounds=rounds, ident=ident) |
| 299 |
elif not PASSLIB_AVAILABLE and algorithm not in CryptHash.algorithms: |
| 300 |
# When passlib support is removed, this branch can be removed too |
| 301 |
raise AnsibleError(f"crypt does not support {algorithm!r} algorithm") |
| 302 |
raise AnsibleError("Unable to encrypt nor hash, either libxcrypt (recommended), crypt, or passlib must be installed.") from CRYPT_E |