Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

hashers.py 28KB

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