| 1 |
|
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import os |
| 6 |
|
| 7 |
from typing import ClassVar, Literal |
| 8 |
|
| 9 |
from ._utils import ( |
| 10 |
Parameters, |
| 11 |
_check_types, |
| 12 |
extract_parameters, |
| 13 |
validate_params_for_platform, |
| 14 |
) |
| 15 |
from .exceptions import InvalidHashError |
| 16 |
from .low_level import Type, hash_secret, verify_secret |
| 17 |
from .profiles import get_default_parameters |
| 18 |
|
| 19 |
|
| 20 |
default_params = get_default_parameters() |
| 21 |
|
| 22 |
DEFAULT_RANDOM_SALT_LENGTH = default_params.salt_len |
| 23 |
DEFAULT_HASH_LENGTH = default_params.hash_len |
| 24 |
DEFAULT_TIME_COST = default_params.time_cost |
| 25 |
DEFAULT_MEMORY_COST = default_params.memory_cost |
| 26 |
DEFAULT_PARALLELISM = default_params.parallelism |
| 27 |
|
| 28 |
|
| 29 |
def _ensure_bytes(s: bytes | str, encoding: str) -> bytes: |
| 30 |
""" |
| 31 |
Ensure *s* is a bytes string. Encode using *encoding* if it isn't. |
| 32 |
""" |
| 33 |
if isinstance(s, bytes): |
| 34 |
return s |
| 35 |
return s.encode(encoding) |
| 36 |
|
| 37 |
|
| 38 |
class PasswordHasher: |
| 39 |
r""" |
| 40 |
High level class to hash passwords with sensible defaults. |
| 41 |
|
| 42 |
Uses Argon2\ **id** by default and uses a random salt_ for hashing. But it |
| 43 |
can verify any type of Argon2 as long as the hash is correctly encoded. |
| 44 |
|
| 45 |
The reason for this being a class is both for convenience to carry |
| 46 |
parameters and to verify the parameters only *once*. Any unnecessary |
| 47 |
slowdown when hashing is a tangible advantage for a brute-force attacker. |
| 48 |
|
| 49 |
Args: |
| 50 |
time_cost: |
| 51 |
Defines the amount of computation realized and therefore the |
| 52 |
execution time, given in number of iterations. |
| 53 |
|
| 54 |
memory_cost: Defines the memory usage, given in kibibytes_. |
| 55 |
|
| 56 |
parallelism: |
| 57 |
Defines the number of parallel threads (*changes* the resulting |
| 58 |
hash value). |
| 59 |
|
| 60 |
hash_len: Length of the hash in bytes. |
| 61 |
|
| 62 |
salt_len: Length of random salt to be generated for each password. |
| 63 |
|
| 64 |
encoding: |
| 65 |
The Argon2 C library expects bytes. So if :meth:`hash` or |
| 66 |
:meth:`verify` are passed a ``str``, it will be encoded using this |
| 67 |
encoding. |
| 68 |
|
| 69 |
type: |
| 70 |
Argon2 type to use. Only change for interoperability with legacy |
| 71 |
systems. |
| 72 |
|
| 73 |
.. versionadded:: 16.0.0 |
| 74 |
.. versionchanged:: 18.2.0 |
| 75 |
Switch from Argon2i to Argon2id based on the recommendation by the |
| 76 |
current RFC draft. See also :doc:`parameters`. |
| 77 |
.. versionchanged:: 18.2.0 |
| 78 |
Changed default *memory_cost* to 100 MiB and default *parallelism* to 8. |
| 79 |
.. versionchanged:: 18.2.0 ``verify`` now will determine the type of hash. |
| 80 |
.. versionchanged:: 18.3.0 The Argon2 type is configurable now. |
| 81 |
.. versionadded:: 21.2.0 :meth:`from_parameters` |
| 82 |
.. versionchanged:: 21.2.0 |
| 83 |
Changed defaults to :data:`argon2.profiles.RFC_9106_LOW_MEMORY`. |
| 84 |
|
| 85 |
.. _salt: https://en.wikipedia.org/wiki/Salt_(cryptography) |
| 86 |
.. _kibibytes: https://en.wikipedia.org/wiki/Binary_prefix#kibi |
| 87 |
""" |
| 88 |
|
| 89 |
__slots__ = ["_parameters", "encoding"] |
| 90 |
|
| 91 |
_parameters: Parameters |
| 92 |
encoding: str |
| 93 |
|
| 94 |
def __init__( |
| 95 |
self, |
| 96 |
time_cost: int = DEFAULT_TIME_COST, |
| 97 |
memory_cost: int = DEFAULT_MEMORY_COST, |
| 98 |
parallelism: int = DEFAULT_PARALLELISM, |
| 99 |
hash_len: int = DEFAULT_HASH_LENGTH, |
| 100 |
salt_len: int = DEFAULT_RANDOM_SALT_LENGTH, |
| 101 |
encoding: str = "utf-8", |
| 102 |
type: Type = Type.ID, |
| 103 |
): |
| 104 |
e = _check_types( |
| 105 |
time_cost=(time_cost, int), |
| 106 |
memory_cost=(memory_cost, int), |
| 107 |
parallelism=(parallelism, int), |
| 108 |
hash_len=(hash_len, int), |
| 109 |
salt_len=(salt_len, int), |
| 110 |
encoding=(encoding, str), |
| 111 |
type=(type, Type), |
| 112 |
) |
| 113 |
if e: |
| 114 |
raise TypeError(e) |
| 115 |
|
| 116 |
params = Parameters( |
| 117 |
type=type, |
| 118 |
version=19, |
| 119 |
salt_len=salt_len, |
| 120 |
hash_len=hash_len, |
| 121 |
time_cost=time_cost, |
| 122 |
memory_cost=memory_cost, |
| 123 |
parallelism=parallelism, |
| 124 |
) |
| 125 |
|
| 126 |
validate_params_for_platform(params) |
| 127 |
|
| 128 |
|
| 129 |
self._parameters = params |
| 130 |
self.encoding = encoding |
| 131 |
|
| 132 |
@classmethod |
| 133 |
def from_parameters(cls, params: Parameters) -> PasswordHasher: |
| 134 |
""" |
| 135 |
Construct a `PasswordHasher` from *params*. |
| 136 |
|
| 137 |
Returns: |
| 138 |
A `PasswordHasher` instance with the parameters from *params*. |
| 139 |
|
| 140 |
.. versionadded:: 21.2.0 |
| 141 |
""" |
| 142 |
|
| 143 |
return cls( |
| 144 |
time_cost=params.time_cost, |
| 145 |
memory_cost=params.memory_cost, |
| 146 |
parallelism=params.parallelism, |
| 147 |
hash_len=params.hash_len, |
| 148 |
salt_len=params.salt_len, |
| 149 |
type=params.type, |
| 150 |
) |
| 151 |
|
| 152 |
@property |
| 153 |
def time_cost(self) -> int: |
| 154 |
return self._parameters.time_cost |
| 155 |
|
| 156 |
@property |
| 157 |
def memory_cost(self) -> int: |
| 158 |
return self._parameters.memory_cost |
| 159 |
|
| 160 |
@property |
| 161 |
def parallelism(self) -> int: |
| 162 |
return self._parameters.parallelism |
| 163 |
|
| 164 |
@property |
| 165 |
def hash_len(self) -> int: |
| 166 |
return self._parameters.hash_len |
| 167 |
|
| 168 |
@property |
| 169 |
def salt_len(self) -> int: |
| 170 |
return self._parameters.salt_len |
| 171 |
|
| 172 |
@property |
| 173 |
def type(self) -> Type: |
| 174 |
return self._parameters.type |
| 175 |
|
| 176 |
def hash(self, password: str | bytes, *, salt: bytes | None = None) -> str: |
| 177 |
""" |
| 178 |
Hash *password* and return an encoded hash. |
| 179 |
|
| 180 |
Args: |
| 181 |
password: Password to hash. |
| 182 |
|
| 183 |
salt: |
| 184 |
If None, a random salt is securely created. |
| 185 |
|
| 186 |
.. danger:: |
| 187 |
|
| 188 |
You should **not** pass a salt unless you really know what |
| 189 |
you are doing. |
| 190 |
|
| 191 |
Raises: |
| 192 |
argon2.exceptions.HashingError: If hashing fails. |
| 193 |
|
| 194 |
Returns: |
| 195 |
Hashed *password*. |
| 196 |
|
| 197 |
.. versionadded:: 23.1.0 *salt* parameter |
| 198 |
""" |
| 199 |
return hash_secret( |
| 200 |
secret=_ensure_bytes(password, self.encoding), |
| 201 |
salt=salt or os.urandom(self.salt_len), |
| 202 |
time_cost=self.time_cost, |
| 203 |
memory_cost=self.memory_cost, |
| 204 |
parallelism=self.parallelism, |
| 205 |
hash_len=self.hash_len, |
| 206 |
type=self.type, |
| 207 |
).decode("ascii") |
| 208 |
|
| 209 |
_header_to_type: ClassVar[dict[bytes, Type]] = { |
| 210 |
b"$argon2i$": Type.I, |
| 211 |
b"$argon2d$": Type.D, |
| 212 |
b"$argon2id": Type.ID, |
| 213 |
} |
| 214 |
|
| 215 |
def verify( |
| 216 |
self, hash: str | bytes, password: str | bytes |
| 217 |
) -> Literal[True]: |
| 218 |
""" |
| 219 |
Verify that *password* matches *hash*. |
| 220 |
|
| 221 |
.. warning:: |
| 222 |
|
| 223 |
It is assumed that the caller is in full control of the hash. No |
| 224 |
other parsing than the determination of the hash type is done by |
| 225 |
*argon2-cffi*. |
| 226 |
|
| 227 |
Args: |
| 228 |
hash: An encoded hash as returned from :meth:`PasswordHasher.hash`. |
| 229 |
|
| 230 |
password: The password to verify. |
| 231 |
|
| 232 |
Raises: |
| 233 |
argon2.exceptions.VerifyMismatchError: |
| 234 |
If verification fails because *hash* is not valid for |
| 235 |
*password*. |
| 236 |
|
| 237 |
argon2.exceptions.VerificationError: |
| 238 |
If verification fails for other reasons. |
| 239 |
|
| 240 |
argon2.exceptions.InvalidHashError: |
| 241 |
If *hash* is so clearly invalid, that it couldn't be passed to |
| 242 |
Argon2. |
| 243 |
|
| 244 |
Returns: |
| 245 |
``True`` on success, otherwise an exception is raised. |
| 246 |
|
| 247 |
.. versionchanged:: 16.1.0 |
| 248 |
Raise :exc:`~argon2.exceptions.VerifyMismatchError` on mismatches |
| 249 |
instead of its more generic superclass. |
| 250 |
.. versionadded:: 18.2.0 Hash type agility. |
| 251 |
""" |
| 252 |
hash = _ensure_bytes(hash, "ascii") |
| 253 |
try: |
| 254 |
hash_type = self._header_to_type[hash[:9]] |
| 255 |
except LookupError: |
| 256 |
raise InvalidHashError from None |
| 257 |
|
| 258 |
return verify_secret( |
| 259 |
hash, _ensure_bytes(password, self.encoding), hash_type |
| 260 |
) |
| 261 |
|
| 262 |
def check_needs_rehash(self, hash: str | bytes) -> bool: |
| 263 |
""" |
| 264 |
Check whether *hash* was created using the instance's parameters. |
| 265 |
|
| 266 |
Whenever your Argon2 parameters -- or *argon2-cffi*'s defaults! -- |
| 267 |
change, you should rehash your passwords at the next opportunity. The |
| 268 |
common approach is to do that whenever a user logs in, since that |
| 269 |
should be the only time when you have access to the cleartext |
| 270 |
password. |
| 271 |
|
| 272 |
Therefore it's best practice to check -- and if necessary rehash -- |
| 273 |
passwords after each successful authentication. |
| 274 |
|
| 275 |
Args: |
| 276 |
hash: An encoded Argon2 password hash. |
| 277 |
|
| 278 |
Returns: |
| 279 |
Whether *hash* was created using the instance's parameters. |
| 280 |
|
| 281 |
.. versionadded:: 18.2.0 |
| 282 |
.. versionchanged:: 24.1.0 Accepts bytes for *hash*. |
| 283 |
""" |
| 284 |
if isinstance(hash, bytes): |
| 285 |
hash = hash.decode("ascii") |
| 286 |
|
| 287 |
return self._parameters != extract_parameters(hash) |