hashers.py 27 KB

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