| 1 |
# Copyright: Contributors to the Ansible project |
| 2 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
import ctypes |
| 7 |
import ctypes.util |
| 8 |
import os |
| 9 |
import sys |
| 10 |
import typing as t |
| 11 |
from dataclasses import dataclass |
| 12 |
|
| 13 |
__all__ = ['CryptFacade'] |
| 14 |
|
| 15 |
_FAILURE_TOKENS = frozenset({b'*', b'*0', b'*1'}) |
| 16 |
|
| 17 |
|
| 18 |
@dataclass(frozen=True) |
| 19 |
class _CryptLib: |
| 20 |
name: str | None |
| 21 |
exclude_platforms: frozenset[str] = frozenset() |
| 22 |
include_platforms: frozenset[str] = frozenset() |
| 23 |
is_path: bool = False |
| 24 |
|
| 25 |
|
| 26 |
_CRYPT_LIBS = ( |
| 27 |
_CryptLib('crypt'), # libxcrypt |
| 28 |
_CryptLib(None, exclude_platforms=frozenset({'darwin'})), # fallback to default libc |
| 29 |
_CryptLib( # macOS Homebrew (Apple Silicon) |
| 30 |
'/opt/homebrew/opt/libxcrypt/lib/libcrypt.dylib', |
| 31 |
include_platforms=frozenset({'darwin'}), |
| 32 |
is_path=True, |
| 33 |
), |
| 34 |
_CryptLib( # macOS Homebrew (Intel) |
| 35 |
'/usr/local/opt/libxcrypt/lib/libcrypt.dylib', |
| 36 |
include_platforms=frozenset({'darwin'}), |
| 37 |
is_path=True, |
| 38 |
), |
| 39 |
) |
| 40 |
|
| 41 |
|
| 42 |
class CryptFacade: |
| 43 |
""" |
| 44 |
Provide an interface for various crypt libraries that might be available. |
| 45 |
""" |
| 46 |
|
| 47 |
def __init__(self) -> None: |
| 48 |
self._crypt_impl: t.Callable | None = None |
| 49 |
self._crypt_gensalt_impl: t.Callable | None = None |
| 50 |
self._use_crypt_r = False |
| 51 |
self._use_crypt_gensalt_rn = False |
| 52 |
self._crypt_name = "" |
| 53 |
|
| 54 |
self._setup() |
| 55 |
|
| 56 |
class _CryptData(ctypes.Structure): |
| 57 |
_fields_ = [('_opaque', ctypes.c_char * 131072)] |
| 58 |
|
| 59 |
@property |
| 60 |
def has_crypt_gensalt(self) -> bool: |
| 61 |
return self._crypt_gensalt_impl is not None |
| 62 |
|
| 63 |
def _setup(self) -> None: |
| 64 |
"""Setup crypt implementation""" |
| 65 |
for lib_config in _CRYPT_LIBS: |
| 66 |
if sys.platform in lib_config.exclude_platforms: |
| 67 |
continue |
| 68 |
if lib_config.include_platforms and sys.platform not in lib_config.include_platforms: |
| 69 |
continue |
| 70 |
|
| 71 |
if lib_config.name is None: |
| 72 |
lib_so = None |
| 73 |
elif lib_config.is_path: |
| 74 |
if os.path.exists(lib_config.name): |
| 75 |
lib_so = lib_config.name |
| 76 |
else: |
| 77 |
continue |
| 78 |
else: |
| 79 |
lib_so = ctypes.util.find_library(lib_config.name) |
| 80 |
if not lib_so: |
| 81 |
continue |
| 82 |
|
| 83 |
loaded_lib = ctypes.cdll.LoadLibrary(lib_so) |
| 84 |
|
| 85 |
try: |
| 86 |
self._crypt_impl = loaded_lib.crypt_r |
| 87 |
self._use_crypt_r = True |
| 88 |
except AttributeError: |
| 89 |
try: |
| 90 |
self._crypt_impl = loaded_lib.crypt |
| 91 |
except AttributeError: |
| 92 |
continue |
| 93 |
|
| 94 |
if self._use_crypt_r: |
| 95 |
self._crypt_impl.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.POINTER(self._CryptData)] |
| 96 |
else: |
| 97 |
self._crypt_impl.argtypes = [ctypes.c_char_p, ctypes.c_char_p] |
| 98 |
self._crypt_impl.restype = ctypes.c_char_p |
| 99 |
|
| 100 |
# Try to load crypt_gensalt (available in libxcrypt) |
| 101 |
try: |
| 102 |
self._crypt_gensalt_impl = loaded_lib.crypt_gensalt_rn |
| 103 |
self._crypt_gensalt_impl.argtypes = [ctypes.c_char_p, ctypes.c_ulong, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_int] |
| 104 |
self._crypt_gensalt_impl.restype = ctypes.c_char_p |
| 105 |
self._use_crypt_gensalt_rn = True |
| 106 |
except AttributeError: |
| 107 |
try: |
| 108 |
self._crypt_gensalt_impl = loaded_lib.crypt_gensalt |
| 109 |
self._crypt_gensalt_impl.argtypes = [ctypes.c_char_p, ctypes.c_ulong, ctypes.c_char_p, ctypes.c_int] |
| 110 |
self._crypt_gensalt_impl.restype = ctypes.c_char_p |
| 111 |
except AttributeError: |
| 112 |
self._crypt_gensalt_impl = None |
| 113 |
|
| 114 |
self._crypt_name = lib_config.name |
| 115 |
break |
| 116 |
else: |
| 117 |
raise ImportError('Cannot find crypt implementation') |
| 118 |
|
| 119 |
def crypt(self, word: bytes, salt: bytes) -> bytes: |
| 120 |
"""Hash a password using the system's crypt function.""" |
| 121 |
ctypes.set_errno(0) |
| 122 |
|
| 123 |
if self._use_crypt_r: |
| 124 |
data = self._CryptData() |
| 125 |
ctypes.memset(ctypes.byref(data), 0, ctypes.sizeof(data)) |
| 126 |
result = self._crypt_impl(word, salt, ctypes.byref(data)) |
| 127 |
else: |
| 128 |
result = self._crypt_impl(word, salt) |
| 129 |
|
| 130 |
errno = ctypes.get_errno() |
| 131 |
if errno: |
| 132 |
error_msg = os.strerror(errno) |
| 133 |
raise OSError(errno, f'crypt failed: {error_msg}') |
| 134 |
|
| 135 |
if result is None or result in _FAILURE_TOKENS: |
| 136 |
raise ValueError('crypt failed: invalid salt or unsupported algorithm') |
| 137 |
|
| 138 |
return result |
| 139 |
|
| 140 |
def crypt_gensalt(self, prefix: bytes, count: int, rbytes: bytes) -> bytes: |
| 141 |
"""Generate a salt string for use with crypt.""" |
| 142 |
if not self.has_crypt_gensalt: |
| 143 |
raise NotImplementedError('crypt_gensalt not available (requires libxcrypt)') |
| 144 |
|
| 145 |
ctypes.set_errno(0) |
| 146 |
|
| 147 |
if self._use_crypt_gensalt_rn: |
| 148 |
output = ctypes.create_string_buffer(256) |
| 149 |
result = self._crypt_gensalt_impl(prefix, count, rbytes, len(rbytes), output, len(output)) |
| 150 |
if result is not None: |
| 151 |
result = output.value |
| 152 |
else: |
| 153 |
result = self._crypt_gensalt_impl(prefix, count, rbytes, len(rbytes)) |
| 154 |
|
| 155 |
errno = ctypes.get_errno() |
| 156 |
if errno: |
| 157 |
error_msg = os.strerror(errno) |
| 158 |
raise OSError(errno, f'crypt_gensalt failed: {error_msg}') |
| 159 |
|
| 160 |
if result is None: |
| 161 |
raise ValueError('crypt_gensalt failed: unable to generate salt') |
| 162 |
|
| 163 |
if result in _FAILURE_TOKENS: |
| 164 |
raise ValueError('crypt_gensalt failed: invalid prefix or unsupported algorithm') |
| 165 |
|
| 166 |
return result |