Debian Codegraph @

django/contrib/auth/hashers.py

raw
1 import base64
2 import binascii
3 import functools
4 import hashlib
5 import importlib
6 import math
7 import warnings
8
9 from django.conf import settings
10 from django.core.exceptions import ImproperlyConfigured
11 from django.core.signals import setting_changed
12 from django.dispatch import receiver
13 from django.utils.crypto import (
14 RANDOM_STRING_CHARS,
15 constant_time_compare,
16 get_random_string,
17 pbkdf2,
18 )
19 from django.utils.module_loading import import_string
20 from django.utils.translation import gettext_noop as _
21
22 UNUSABLE_PASSWORD_PREFIX = "!" # This will never be a valid encoded hash
23 UNUSABLE_PASSWORD_SUFFIX_LENGTH = (
24 40 # number of random chars to add after UNUSABLE_PASSWORD_PREFIX
25 )
26
27
28 def is_password_usable(encoded):
29 """
30 Return True if this password wasn't generated by
31 User.set_unusable_password(), i.e. make_password(None).
32 """
33 return encoded is None or not encoded.startswith(UNUSABLE_PASSWORD_PREFIX)
34
35
36 def verify_password(password, encoded, preferred="default"):
37 """
38 Return two booleans. The first is whether the raw password matches the
39 three part encoded digest, and the second whether to regenerate the
40 password.
41 """
42 fake_runtime = password is None or not is_password_usable(encoded)
43
44 preferred = get_hasher(preferred)
45 try:
46 hasher = identify_hasher(encoded)
47 except ValueError:
48 # encoded is gibberish or uses a hasher that's no longer installed.
49 fake_runtime = True
50
51 if fake_runtime:
52 # Run the default password hasher once to reduce the timing difference
53 # between an existing user with an unusable password and a nonexistent
54 # user or missing hasher (similar to #20760).
55 make_password(get_random_string(UNUSABLE_PASSWORD_SUFFIX_LENGTH))
56 return False, False
57
58 hasher_changed = hasher.algorithm != preferred.algorithm
59 must_update = hasher_changed or preferred.must_update(encoded)
60 is_correct = hasher.verify(password, encoded)
61
62 # If the hasher didn't change (we don't protect against enumeration if it
63 # does) and the password should get updated, try to close the timing gap
64 # between the work factor of the current encoded password and the default
65 # work factor.
66 if not is_correct and not hasher_changed and must_update:
67 hasher.harden_runtime(password, encoded)
68
69 return is_correct, must_update
70
71
72 def check_password(password, encoded, setter=None, preferred="default"):
73 """
74 Return a boolean of whether the raw password matches the three part encoded
75 digest.
76
77 If setter is specified, it'll be called when you need to regenerate the
78 password.
79 """
80 is_correct, must_update = verify_password(password, encoded, preferred=preferred)
81 if setter and is_correct and must_update:
82 setter(password)
83 return is_correct
84
85
86 async def acheck_password(password, encoded, setter=None, preferred="default"):
87 """See check_password()."""
88 is_correct, must_update = verify_password(password, encoded, preferred=preferred)
89 if setter and is_correct and must_update:
90 await setter(password)
91 return is_correct
92
93
94 def make_password(password, salt=None, hasher="default"):
95 """
96 Turn a plain-text password into a hash for database storage
97
98 Same as encode() but generate a new random salt. If password is None then
99 return a concatenation of UNUSABLE_PASSWORD_PREFIX and a random string,
100 which disallows logins. Additional random string reduces chances of gaining
101 access to staff or superuser accounts. See ticket #20079 for more info.
102 """
103 if password is None:
104 return UNUSABLE_PASSWORD_PREFIX + get_random_string(
105 UNUSABLE_PASSWORD_SUFFIX_LENGTH
106 )
107 if not isinstance(password, (bytes, str)):
108 raise TypeError(
109 "Password must be a string or bytes, got %s." % type(password).__qualname__
110 )
111 hasher = get_hasher(hasher)
112 salt = salt or hasher.salt()
113 return hasher.encode(password, salt)
114
115
116 @functools.lru_cache
117 def get_hashers():
118 hashers = []
119 for hasher_path in settings.PASSWORD_HASHERS:
120 hasher_cls = import_string(hasher_path)
121 hasher = hasher_cls()
122 if not getattr(hasher, "algorithm"):
123 raise ImproperlyConfigured(
124 "hasher doesn't specify an algorithm name: %s" % hasher_path
125 )
126 hashers.append(hasher)
127 return hashers
128
129
130 @functools.lru_cache
131 def get_hashers_by_algorithm():
132 return {hasher.algorithm: hasher for hasher in get_hashers()}
133
134
135 @receiver(setting_changed)
136 def reset_hashers(*, setting, **kwargs):
137 if setting == "PASSWORD_HASHERS":
138 get_hashers.cache_clear()
139 get_hashers_by_algorithm.cache_clear()
140
141
142 def get_hasher(algorithm="default"):
143 """
144 Return an instance of a loaded password hasher.
145
146 If algorithm is 'default', return the default hasher. Lazily import hashers
147 specified in the project's settings file if needed.
148 """
149 if hasattr(algorithm, "algorithm"):
150 return algorithm
151
152 elif algorithm == "default":
153 return get_hashers()[0]
154
155 else:
156 hashers = get_hashers_by_algorithm()
157 try:
158 return hashers[algorithm]
159 except KeyError:
160 raise ValueError(
161 "Unknown password hashing algorithm '%s'. "
162 "Did you specify it in the PASSWORD_HASHERS "
163 "setting?" % algorithm
164 )
165
166
167 def identify_hasher(encoded):
168 """
169 Return an instance of a loaded password hasher.
170
171 Identify hasher algorithm by examining encoded hash, and call
172 get_hasher() to return hasher. Raise ValueError if
173 algorithm cannot be identified, or if hasher is not loaded.
174 """
175 # Ancient versions of Django created plain MD5 passwords and accepted
176 # MD5 passwords with an empty salt.
177 if (len(encoded) == 32 and "$" not in encoded) or (
178 len(encoded) == 37 and encoded.startswith("md5$$")
179 ):
180 algorithm = "unsalted_md5"
181 # Ancient versions of Django accepted SHA1 passwords with an empty salt.
182 elif len(encoded) == 46 and encoded.startswith("sha1$$"):
183 algorithm = "unsalted_sha1"
184 else:
185 algorithm = encoded.split("$", 1)[0]
186 return get_hasher(algorithm)
187
188
189 def mask_hash(hash, show=6, char="*"):
190 """
191 Return the given hash, with only the first ``show`` number shown. The
192 rest are masked with ``char`` for security reasons.
193 """
194 masked = hash[:show]
195 masked += char * len(hash[show:])
196 return masked
197
198
199 def must_update_salt(salt, expected_entropy):
200 # Each character in the salt provides log_2(len(alphabet)) bits of entropy.
201 return len(salt) * math.log2(len(RANDOM_STRING_CHARS)) < expected_entropy
202
203
204 class BasePasswordHasher:
205 """
206 Abstract base class for password hashers
207
208 When creating your own hasher, you need to override algorithm,
209 verify(), encode() and safe_summary().
210
211 PasswordHasher objects are immutable.
212 """
213
214 algorithm = None
215 library = None
216 salt_entropy = 128
217
218 def _load_library(self):
219 if self.library is not None:
220 if isinstance(self.library, (tuple, list)):
221 name, mod_path = self.library
222 else:
223 mod_path = self.library
224 try:
225 module = importlib.import_module(mod_path)
226 except ImportError as e:
227 raise ValueError(
228 "Couldn't load %r algorithm library: %s"
229 % (self.__class__.__name__, e)
230 )
231 return module
232 raise ValueError(
233 "Hasher %r doesn't specify a library attribute" % self.__class__.__name__
234 )
235
236 def salt(self):
237 """
238 Generate a cryptographically secure nonce salt in ASCII with an entropy
239 of at least `salt_entropy` bits.
240 """
241 # Each character in the salt provides
242 # log_2(len(alphabet)) bits of entropy.
243 char_count = math.ceil(self.salt_entropy / math.log2(len(RANDOM_STRING_CHARS)))
244 return get_random_string(char_count, allowed_chars=RANDOM_STRING_CHARS)
245
246 def verify(self, password, encoded):
247 """Check if the given password is correct."""
248 raise NotImplementedError(
249 "subclasses of BasePasswordHasher must provide a verify() method"
250 )
251
252 def _check_encode_args(self, password, salt):
253 if password is None:
254 raise TypeError("password must be provided.")
255 if not salt or "$" in salt:
256 raise ValueError("salt must be provided and cannot contain $.")
257
258 def encode(self, password, salt):
259 """
260 Create an encoded database value.
261
262 The result is normally formatted as "algorithm$salt$hash" and
263 must be fewer than 128 characters.
264 """
265 raise NotImplementedError(
266 "subclasses of BasePasswordHasher must provide an encode() method"
267 )
268
269 def decode(self, encoded):
270 """
271 Return a decoded database value.
272
273 The result is a dictionary and should contain `algorithm`, `hash`, and
274 `salt`. Extra keys can be algorithm specific like `iterations` or
275 `work_factor`.
276 """
277 raise NotImplementedError(
278 "subclasses of BasePasswordHasher must provide a decode() method."
279 )
280
281 def safe_summary(self, encoded):
282 """
283 Return a summary of safe values.
284
285 The result is a dictionary and will be used where the password field
286 must be displayed to construct a safe representation of the password.
287 """
288 raise NotImplementedError(
289 "subclasses of BasePasswordHasher must provide a safe_summary() method"
290 )
291
292 def must_update(self, encoded):
293 return False
294
295 def harden_runtime(self, password, encoded):
296 """
297 Bridge the runtime gap between the work factor supplied in `encoded`
298 and the work factor suggested by this hasher.
299
300 Taking PBKDF2 as an example, if `encoded` contains 20000 iterations and
301 `self.iterations` is 30000, this method should run password through
302 another 10000 iterations of PBKDF2. Similar approaches should exist
303 for any hasher that has a work factor. If not, this method should be
304 defined as a no-op to silence the warning.
305 """
306 warnings.warn(
307 "subclasses of BasePasswordHasher should provide a harden_runtime() method"
308 )
309
310
311 class PBKDF2PasswordHasher(BasePasswordHasher):
312 """
313 Secure password hashing using the PBKDF2 algorithm (recommended)
314
315 Configured to use PBKDF2 + HMAC + SHA256.
316 The result is a 64 byte binary string. Iterations may be changed
317 safely but you must rename the algorithm if you change SHA256.
318 """
319
320 algorithm = "pbkdf2_sha256"
321 iterations = 1_000_000
322 digest = hashlib.sha256
323
324 def encode(self, password, salt, iterations=None):
325 self._check_encode_args(password, salt)
326 iterations = iterations or self.iterations
327 hash = pbkdf2(password, salt, iterations, digest=self.digest)
328 hash = base64.b64encode(hash).decode("ascii").strip()
329 return "%s$%d$%s$%s" % (self.algorithm, iterations, salt, hash)
330
331 def decode(self, encoded):
332 algorithm, iterations, salt, hash = encoded.split("$", 3)
333 assert algorithm == self.algorithm
334 return {
335 "algorithm": algorithm,
336 "hash": hash,
337 "iterations": int(iterations),
338 "salt": salt,
339 }
340
341 def verify(self, password, encoded):
342 decoded = self.decode(encoded)
343 encoded_2 = self.encode(password, decoded["salt"], decoded["iterations"])
344 return constant_time_compare(encoded, encoded_2)
345
346 def safe_summary(self, encoded):
347 decoded = self.decode(encoded)
348 return {
349 _("algorithm"): decoded["algorithm"],
350 _("iterations"): decoded["iterations"],
351 _("salt"): mask_hash(decoded["salt"]),
352 _("hash"): mask_hash(decoded["hash"]),
353 }
354
355 def must_update(self, encoded):
356 decoded = self.decode(encoded)
357 update_salt = must_update_salt(decoded["salt"], self.salt_entropy)
358 return (decoded["iterations"] != self.iterations) or update_salt
359
360 def harden_runtime(self, password, encoded):
361 decoded = self.decode(encoded)
362 extra_iterations = self.iterations - decoded["iterations"]
363 if extra_iterations > 0:
364 self.encode(password, decoded["salt"], extra_iterations)
365
366
367 class PBKDF2SHA1PasswordHasher(PBKDF2PasswordHasher):
368 """
369 Alternate PBKDF2 hasher which uses SHA1, the default PRF
370 recommended by PKCS #5. This is compatible with other
371 implementations of PBKDF2, such as openssl's
372 PKCS5_PBKDF2_HMAC_SHA1().
373 """
374
375 algorithm = "pbkdf2_sha1"
376 digest = hashlib.sha1
377
378
379 class Argon2PasswordHasher(BasePasswordHasher):
380 """
381 Secure password hashing using the argon2 algorithm.
382
383 This is the winner of the Password Hashing Competition 2013-2015
384 (https://password-hashing.net). It requires the argon2-cffi library which
385 depends on native C code and might cause portability issues.
386 """
387
388 algorithm = "argon2"
389 library = "argon2"
390
391 time_cost = 2
392 memory_cost = 102400
393 parallelism = 8
394
395 def encode(self, password, salt):
396 argon2 = self._load_library()
397 params = self.params()
398 data = argon2.low_level.hash_secret(
399 password.encode(),
400 salt.encode(),
401 time_cost=params.time_cost,
402 memory_cost=params.memory_cost,
403 parallelism=params.parallelism,
404 hash_len=params.hash_len,
405 type=params.type,
406 )
407 return self.algorithm + data.decode("ascii")
408
409 def decode(self, encoded):
410 argon2 = self._load_library()
411 algorithm, rest = encoded.split("$", 1)
412 assert algorithm == self.algorithm
413 params = argon2.extract_parameters("$" + rest)
414 variety, *_, b64salt, hash = rest.split("$")
415 # Add padding.
416 b64salt += "=" * (-len(b64salt) % 4)
417 salt = base64.b64decode(b64salt).decode("latin1")
418 return {
419 "algorithm": algorithm,
420 "hash": hash,
421 "memory_cost": params.memory_cost,
422 "parallelism": params.parallelism,
423 "salt": salt,
424 "time_cost": params.time_cost,
425 "variety": variety,
426 "version": params.version,
427 "params": params,
428 }
429
430 def verify(self, password, encoded):
431 argon2 = self._load_library()
432 algorithm, rest = encoded.split("$", 1)
433 assert algorithm == self.algorithm
434 try:
435 return argon2.PasswordHasher().verify("$" + rest, password)
436 except argon2.exceptions.VerificationError:
437 return False
438
439 def safe_summary(self, encoded):
440 decoded = self.decode(encoded)
441 return {
442 _("algorithm"): decoded["algorithm"],
443 _("variety"): decoded["variety"],
444 _("version"): decoded["version"],
445 _("memory cost"): decoded["memory_cost"],
446 _("time cost"): decoded["time_cost"],
447 _("parallelism"): decoded["parallelism"],
448 _("salt"): mask_hash(decoded["salt"]),
449 _("hash"): mask_hash(decoded["hash"]),
450 }
451
452 def must_update(self, encoded):
453 decoded = self.decode(encoded)
454 current_params = decoded["params"]
455 new_params = self.params()
456 # Set salt_len to the salt_len of the current parameters because salt
457 # is explicitly passed to argon2.
458 new_params.salt_len = current_params.salt_len
459 update_salt = must_update_salt(decoded["salt"], self.salt_entropy)
460 return (current_params != new_params) or update_salt
461
462 def harden_runtime(self, password, encoded):
463 # The runtime for Argon2 is too complicated to implement a sensible
464 # hardening algorithm.
465 pass
466
467 def params(self):
468 argon2 = self._load_library()
469 # salt_len is a noop, because we provide our own salt.
470 return argon2.Parameters(
471 type=argon2.low_level.Type.ID,
472 version=argon2.low_level.ARGON2_VERSION,
473 salt_len=argon2.DEFAULT_RANDOM_SALT_LENGTH,
474 hash_len=argon2.DEFAULT_HASH_LENGTH,
475 time_cost=self.time_cost,
476 memory_cost=self.memory_cost,
477 parallelism=self.parallelism,
478 )
479
480
481 class BCryptSHA256PasswordHasher(BasePasswordHasher):
482 """
483 Secure password hashing using the bcrypt algorithm (recommended)
484
485 This is considered by many to be the most secure algorithm but you
486 must first install the bcrypt library. Please be warned that
487 this library depends on native C code and might cause portability
488 issues.
489 """
490
491 algorithm = "bcrypt_sha256"
492 digest = hashlib.sha256
493 library = ("bcrypt", "bcrypt")
494 rounds = 12
495
496 def salt(self):
497 bcrypt = self._load_library()
498 return bcrypt.gensalt(self.rounds)
499
500 def encode(self, password, salt):
501 bcrypt = self._load_library()
502 password = password.encode()
503 # Hash the password prior to using bcrypt to prevent password
504 # truncation as described in #20138.
505 if self.digest is not None:
506 # Use binascii.hexlify() because a hex encoded bytestring is str.
507 password = binascii.hexlify(self.digest(password).digest())
508
509 data = bcrypt.hashpw(password, salt)
510 return "%s$%s" % (self.algorithm, data.decode("ascii"))
511
512 def decode(self, encoded):
513 algorithm, empty, algostr, work_factor, data = encoded.split("$", 4)
514 assert algorithm == self.algorithm
515 return {
516 "algorithm": algorithm,
517 "algostr": algostr,
518 "checksum": data[22:],
519 "salt": data[:22],
520 "work_factor": int(work_factor),
521 }
522
523 def verify(self, password, encoded):
524 algorithm, data = encoded.split("$", 1)
525 assert algorithm == self.algorithm
526 encoded_2 = self.encode(password, data.encode("ascii"))
527 return constant_time_compare(encoded, encoded_2)
528
529 def safe_summary(self, encoded):
530 decoded = self.decode(encoded)
531 return {
532 _("algorithm"): decoded["algorithm"],
533 _("work factor"): decoded["work_factor"],
534 _("salt"): mask_hash(decoded["salt"]),
535 _("checksum"): mask_hash(decoded["checksum"]),
536 }
537
538 def must_update(self, encoded):
539 decoded = self.decode(encoded)
540 return decoded["work_factor"] != self.rounds
541
542 def harden_runtime(self, password, encoded):
543 _, data = encoded.split("$", 1)
544 salt = data[:29] # Length of the salt in bcrypt.
545 rounds = data.split("$")[2]
546 # work factor is logarithmic, adding one doubles the load.
547 diff = 2 ** (self.rounds - int(rounds)) - 1
548 while diff > 0:
549 self.encode(password, salt.encode("ascii"))
550 diff -= 1
551
552
553 class BCryptPasswordHasher(BCryptSHA256PasswordHasher):
554 """
555 Secure password hashing using the bcrypt algorithm
556
557 This is considered by many to be the most secure algorithm but you
558 must first install the bcrypt library. Please be warned that
559 this library depends on native C code and might cause portability
560 issues.
561
562 This hasher does not first hash the password which means it is subject to
563 bcrypt's 72 bytes password truncation. Most use cases should prefer the
564 BCryptSHA256PasswordHasher.
565 """
566
567 algorithm = "bcrypt"
568 digest = None
569
570
571 class ScryptPasswordHasher(BasePasswordHasher):
572 """
573 Secure password hashing using the Scrypt algorithm.
574 """
575
576 algorithm = "scrypt"
577 block_size = 8
578 maxmem = 0
579 parallelism = 5
580 work_factor = 2**14
581
582 def encode(self, password, salt, n=None, r=None, p=None):
583 self._check_encode_args(password, salt)
584 n = n or self.work_factor
585 r = r or self.block_size
586 p = p or self.parallelism
587 hash_ = hashlib.scrypt(
588 password.encode(),
589 salt=salt.encode(),
590 n=n,
591 r=r,
592 p=p,
593 maxmem=self.maxmem,
594 dklen=64,
595 )
596 hash_ = base64.b64encode(hash_).decode("ascii").strip()
597 return "%s$%d$%s$%d$%d$%s" % (self.algorithm, n, salt, r, p, hash_)
598
599 def decode(self, encoded):
600 algorithm, work_factor, salt, block_size, parallelism, hash_ = encoded.split(
601 "$", 6
602 )
603 assert algorithm == self.algorithm
604 return {
605 "algorithm": algorithm,
606 "work_factor": int(work_factor),
607 "salt": salt,
608 "block_size": int(block_size),
609 "parallelism": int(parallelism),
610 "hash": hash_,
611 }
612
613 def verify(self, password, encoded):
614 decoded = self.decode(encoded)
615 encoded_2 = self.encode(
616 password,
617 decoded["salt"],
618 decoded["work_factor"],
619 decoded["block_size"],
620 decoded["parallelism"],
621 )
622 return constant_time_compare(encoded, encoded_2)
623
624 def safe_summary(self, encoded):
625 decoded = self.decode(encoded)
626 return {
627 _("algorithm"): decoded["algorithm"],
628 _("work factor"): decoded["work_factor"],
629 _("block size"): decoded["block_size"],
630 _("parallelism"): decoded["parallelism"],
631 _("salt"): mask_hash(decoded["salt"]),
632 _("hash"): mask_hash(decoded["hash"]),
633 }
634
635 def must_update(self, encoded):
636 decoded = self.decode(encoded)
637 return (
638 decoded["work_factor"] != self.work_factor
639 or decoded["block_size"] != self.block_size
640 or decoded["parallelism"] != self.parallelism
641 )
642
643 def harden_runtime(self, password, encoded):
644 # The runtime for Scrypt is too complicated to implement a sensible
645 # hardening algorithm.
646 pass
647
648
649 class MD5PasswordHasher(BasePasswordHasher):
650 """
651 The Salted MD5 password hashing algorithm (not recommended)
652 """
653
654 algorithm = "md5"
655
656 def encode(self, password, salt):
657 self._check_encode_args(password, salt)
658 hash = hashlib.md5((salt + password).encode()).hexdigest()
659 return "%s$%s$%s" % (self.algorithm, salt, hash)
660
661 def decode(self, encoded):
662 algorithm, salt, hash = encoded.split("$", 2)
663 assert algorithm == self.algorithm
664 return {
665 "algorithm": algorithm,
666 "hash": hash,
667 "salt": salt,
668 }
669
670 def verify(self, password, encoded):
671 decoded = self.decode(encoded)
672 encoded_2 = self.encode(password, decoded["salt"])
673 return constant_time_compare(encoded, encoded_2)
674
675 def safe_summary(self, encoded):
676 decoded = self.decode(encoded)
677 return {
678 _("algorithm"): decoded["algorithm"],
679 _("salt"): mask_hash(decoded["salt"], show=2),
680 _("hash"): mask_hash(decoded["hash"]),
681 }
682
683 def must_update(self, encoded):
684 decoded = self.decode(encoded)
685 return must_update_salt(decoded["salt"], self.salt_entropy)
686
687 def harden_runtime(self, password, encoded):
688 pass