hashers.py 29 KB

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