v0.163.0
  1from __future__ import annotations
  2
  3import base64
  4import functools
  5import hashlib
  6import hmac
  7import math
  8import warnings
  9from abc import ABC, abstractmethod
 10from collections.abc import Callable
 11from typing import Any
 12
 13from plain.exceptions import ImproperlyConfigured
 14from plain.runtime import settings
 15from plain.utils.crypto import (
 16    RANDOM_STRING_CHARS,
 17    get_random_string,
 18    pbkdf2,
 19)
 20from plain.utils.encoding import force_bytes
 21from plain.utils.module_loading import import_string
 22
 23
 24def check_password(
 25    password: str,
 26    encoded: str,
 27    setter: Callable[[str], None] | None = None,
 28    preferred: str | BasePasswordHasher = "default",
 29) -> bool:
 30    """
 31    Return a boolean of whether the raw password matches the three
 32    part encoded digest.
 33
 34    If setter is specified, it'll be called when you need to
 35    regenerate the password.
 36    """
 37    if not password:
 38        return False
 39
 40    preferred = get_hasher(preferred)
 41    try:
 42        hasher = identify_hasher(encoded)
 43    except ValueError:
 44        # encoded is gibberish or uses a hasher that's no longer installed.
 45        return False
 46
 47    hasher_changed = hasher.algorithm != preferred.algorithm
 48    must_update = hasher_changed or preferred.must_update(encoded)
 49    is_correct = hasher.verify(password, encoded)
 50
 51    # If the hasher didn't change (we don't protect against enumeration if it
 52    # does) and the password should get updated, try to close the timing gap
 53    # between the work factor of the current encoded password and the default
 54    # work factor.
 55    if not is_correct and not hasher_changed and must_update:
 56        hasher.harden_runtime(password, encoded)
 57
 58    if setter and is_correct and must_update:
 59        setter(password)
 60    return is_correct
 61
 62
 63def hash_password(
 64    password: str,
 65    salt: str | None = None,
 66    hasher: str | BasePasswordHasher = "default",
 67) -> str:
 68    """
 69    Turn a plain-text password into a hash for database storage
 70
 71    Same as encode() but generate a new random salt. If password is None then
 72    return a concatenation of UNUSABLE_PASSWORD_PREFIX and a random string,
 73    which disallows logins. Additional random string reduces chances of gaining
 74    access to admin or superuser accounts. See ticket #20079 for more info.
 75    """
 76    hasher = get_hasher(hasher)
 77    salt = salt or hasher.salt()
 78    return hasher.encode(password, salt)
 79
 80
 81@functools.lru_cache
 82def get_hashers() -> list[BasePasswordHasher]:
 83    hashers = []
 84    for hasher_path in settings.PASSWORD_HASHERS:
 85        hasher_cls = import_string(hasher_path)
 86        hasher = hasher_cls()
 87        if not hasher.algorithm:
 88            raise ImproperlyConfigured(
 89                f"hasher doesn't specify an algorithm name: {hasher_path}"
 90            )
 91        hashers.append(hasher)
 92    return hashers
 93
 94
 95@functools.lru_cache
 96def get_hashers_by_algorithm() -> dict[str, BasePasswordHasher]:
 97    return {
 98        hasher.algorithm: hasher
 99        for hasher in get_hashers()
100        if hasher.algorithm is not None
101    }
102
103
104def get_hasher(algorithm: str | BasePasswordHasher = "default") -> BasePasswordHasher:
105    """
106    Return an instance of a loaded password hasher.
107
108    If algorithm is 'default', return the default hasher. Lazily import hashers
109    specified in the project's settings file if needed.
110    """
111    if isinstance(algorithm, BasePasswordHasher):
112        return algorithm
113
114    elif algorithm == "default":
115        return get_hashers()[0]
116
117    else:
118        hashers = get_hashers_by_algorithm()
119        try:
120            return hashers[algorithm]
121        except KeyError:
122            raise ValueError(
123                f"Unknown password hashing algorithm '{algorithm}'. "
124                "Did you specify it in the PASSWORD_HASHERS "
125                "setting?"
126            )
127
128
129def identify_hasher(encoded: str) -> BasePasswordHasher:
130    """
131    Return an instance of a loaded password hasher.
132
133    Identify hasher algorithm by examining encoded hash, and call
134    get_hasher() to return hasher. Raise ValueError if
135    algorithm cannot be identified, or if hasher is not loaded.
136    """
137    algorithm = encoded.split("$", 1)[0]
138    return get_hasher(algorithm)
139
140
141def mask_hash(hash: str, show: int = 6, char: str = "*") -> str:
142    """
143    Return the given hash, with only the first ``show`` number shown. The
144    rest are masked with ``char`` for security reasons.
145    """
146    masked = hash[:show]
147    masked += char * len(hash[show:])
148    return masked
149
150
151def must_update_salt(salt: str, expected_entropy: int) -> bool:
152    # Each character in the salt provides log_2(len(alphabet)) bits of entropy.
153    return len(salt) * math.log2(len(RANDOM_STRING_CHARS)) < expected_entropy
154
155
156class BasePasswordHasher(ABC):
157    """
158    Abstract base class for password hashers
159
160    When creating your own hasher, you need to override algorithm,
161    verify(), encode() and safe_summary().
162
163    PasswordHasher objects are immutable.
164    """
165
166    algorithm: str | None = None
167    salt_entropy: int = 128
168
169    def salt(self) -> str:
170        """
171        Generate a cryptographically secure nonce salt in ASCII with an entropy
172        of at least `salt_entropy` bits.
173        """
174        # Each character in the salt provides
175        # log_2(len(alphabet)) bits of entropy.
176        char_count = math.ceil(self.salt_entropy / math.log2(len(RANDOM_STRING_CHARS)))
177        return get_random_string(char_count, allowed_chars=RANDOM_STRING_CHARS)
178
179    @abstractmethod
180    def verify(self, password: str, encoded: str) -> bool:
181        """Check if the given password is correct."""
182        ...
183
184    def _check_encode_args(self, password: str, salt: str) -> None:
185        if password is None:
186            raise TypeError("password must be provided.")
187        if not salt or "$" in salt:
188            raise ValueError("salt must be provided and cannot contain $.")
189
190    @abstractmethod
191    def encode(self, password: str, salt: str) -> str:
192        """
193        Create an encoded database value.
194
195        The result is normally formatted as "algorithm$salt$hash" and
196        must be fewer than 128 characters.
197        """
198        ...
199
200    @abstractmethod
201    def decode(self, encoded: str) -> dict[str, Any]:
202        """
203        Return a decoded database value.
204
205        The result is a dictionary and should contain `algorithm`, `hash`, and
206        `salt`. Extra keys can be algorithm specific like `iterations` or
207        `work_factor`.
208        """
209        ...
210
211    @abstractmethod
212    def safe_summary(self, encoded: str) -> dict[str, Any]:
213        """
214        Return a summary of safe values.
215
216        The result is a dictionary and will be used where the password field
217        must be displayed to construct a safe representation of the password.
218        """
219        ...
220
221    def must_update(self, encoded: str) -> bool:
222        return False
223
224    def harden_runtime(self, password: str, encoded: str) -> None:
225        """
226        Bridge the runtime gap between the work factor supplied in `encoded`
227        and the work factor suggested by this hasher.
228
229        Taking PBKDF2 as an example, if `encoded` contains 20000 iterations and
230        `self.iterations` is 30000, this method should run password through
231        another 10000 iterations of PBKDF2. Similar approaches should exist
232        for any hasher that has a work factor. If not, this method should be
233        defined as a no-op to silence the warning.
234        """
235        warnings.warn(
236            "subclasses of BasePasswordHasher should provide a harden_runtime() method"
237        )
238
239
240class PBKDF2PasswordHasher(BasePasswordHasher):
241    """
242    Secure password hashing using the PBKDF2 algorithm (recommended)
243
244    Configured to use PBKDF2 + HMAC + SHA256.
245    The result is a 64 byte binary string.  Iterations may be changed
246    safely but you must rename the algorithm if you change SHA256.
247    """
248
249    algorithm = "pbkdf2_sha256"
250    iterations = 720000
251    digest = hashlib.sha256
252
253    def encode(self, password: str, salt: str, iterations: int | None = None) -> str:
254        self._check_encode_args(password, salt)
255        iterations = iterations or self.iterations
256        hash = pbkdf2(password, salt, iterations, digest=self.digest)
257        hash = base64.b64encode(hash).decode("ascii").strip()
258        return "%s$%d$%s$%s" % (self.algorithm, iterations, salt, hash)  # noqa: UP031
259
260    def decode(self, encoded: str) -> dict[str, Any]:
261        algorithm, iterations, salt, hash = encoded.split("$", 3)
262        assert algorithm == self.algorithm
263        return {
264            "algorithm": algorithm,
265            "hash": hash,
266            "iterations": int(iterations),
267            "salt": salt,
268        }
269
270    def verify(self, password: str, encoded: str) -> bool:
271        decoded = self.decode(encoded)
272        encoded_2 = self.encode(password, decoded["salt"], decoded["iterations"])
273        return hmac.compare_digest(force_bytes(encoded), force_bytes(encoded_2))
274
275    def safe_summary(self, encoded: str) -> dict[str, Any]:
276        decoded = self.decode(encoded)
277        return {
278            "algorithm": decoded["algorithm"],
279            "iterations": decoded["iterations"],
280            "salt": mask_hash(decoded["salt"]),
281            "hash": mask_hash(decoded["hash"]),
282        }
283
284    def must_update(self, encoded: str) -> bool:
285        decoded = self.decode(encoded)
286        update_salt = must_update_salt(decoded["salt"], self.salt_entropy)
287        return (decoded["iterations"] != self.iterations) or update_salt
288
289    def harden_runtime(self, password: str, encoded: str) -> None:
290        decoded = self.decode(encoded)
291        extra_iterations = self.iterations - decoded["iterations"]
292        if extra_iterations > 0:
293            self.encode(password, decoded["salt"], extra_iterations)