hashers.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. import base64
  2. import binascii
  3. import functools
  4. import hashlib
  5. import importlib
  6. import warnings
  7. from django.conf import settings
  8. from django.core.exceptions import ImproperlyConfigured
  9. from django.core.signals import setting_changed
  10. from django.dispatch import receiver
  11. from django.utils.crypto import (
  12. constant_time_compare, get_random_string, pbkdf2,
  13. )
  14. from django.utils.module_loading import import_string
  15. from django.utils.translation import gettext_noop as _
  16. UNUSABLE_PASSWORD_PREFIX = '!' # This will never be a valid encoded hash
  17. UNUSABLE_PASSWORD_SUFFIX_LENGTH = 40 # number of random chars to add after UNUSABLE_PASSWORD_PREFIX
  18. def is_password_usable(encoded):
  19. """
  20. Return True if this password wasn't generated by
  21. User.set_unusable_password(), i.e. make_password(None).
  22. """
  23. return encoded is None or not encoded.startswith(UNUSABLE_PASSWORD_PREFIX)
  24. def check_password(password, encoded, setter=None, preferred='default'):
  25. """
  26. Return a boolean of whether the raw password matches the three
  27. part encoded digest.
  28. If setter is specified, it'll be called when you need to
  29. regenerate the password.
  30. """
  31. if password is None or not is_password_usable(encoded):
  32. return False
  33. preferred = get_hasher(preferred)
  34. try:
  35. hasher = identify_hasher(encoded)
  36. except ValueError:
  37. # encoded is gibberish or uses a hasher that's no longer installed.
  38. return False
  39. hasher_changed = hasher.algorithm != preferred.algorithm
  40. must_update = hasher_changed or preferred.must_update(encoded)
  41. is_correct = hasher.verify(password, encoded)
  42. # If the hasher didn't change (we don't protect against enumeration if it
  43. # does) and the password should get updated, try to close the timing gap
  44. # between the work factor of the current encoded password and the default
  45. # work factor.
  46. if not is_correct and not hasher_changed and must_update:
  47. hasher.harden_runtime(password, encoded)
  48. if setter and is_correct and must_update:
  49. setter(password)
  50. return is_correct
  51. def make_password(password, salt=None, hasher='default'):
  52. """
  53. Turn a plain-text password into a hash for database storage
  54. Same as encode() but generate a new random salt. If password is None then
  55. return a concatenation of UNUSABLE_PASSWORD_PREFIX and a random string,
  56. which disallows logins. Additional random string reduces chances of gaining
  57. access to staff or superuser accounts. See ticket #20079 for more info.
  58. """
  59. if password is None:
  60. return UNUSABLE_PASSWORD_PREFIX + get_random_string(UNUSABLE_PASSWORD_SUFFIX_LENGTH)
  61. hasher = get_hasher(hasher)
  62. salt = salt or hasher.salt()
  63. return hasher.encode(password, salt)
  64. @functools.lru_cache()
  65. def get_hashers():
  66. hashers = []
  67. for hasher_path in settings.PASSWORD_HASHERS:
  68. hasher_cls = import_string(hasher_path)
  69. hasher = hasher_cls()
  70. if not getattr(hasher, 'algorithm'):
  71. raise ImproperlyConfigured("hasher doesn't specify an "
  72. "algorithm name: %s" % hasher_path)
  73. hashers.append(hasher)
  74. return hashers
  75. @functools.lru_cache()
  76. def get_hashers_by_algorithm():
  77. return {hasher.algorithm: hasher for hasher in get_hashers()}
  78. @receiver(setting_changed)
  79. def reset_hashers(**kwargs):
  80. if kwargs['setting'] == 'PASSWORD_HASHERS':
  81. get_hashers.cache_clear()
  82. get_hashers_by_algorithm.cache_clear()
  83. def get_hasher(algorithm='default'):
  84. """
  85. Return an instance of a loaded password hasher.
  86. If algorithm is 'default', return the default hasher. Lazily import hashers
  87. specified in the project's settings file if needed.
  88. """
  89. if hasattr(algorithm, 'algorithm'):
  90. return algorithm
  91. elif algorithm == 'default':
  92. return get_hashers()[0]
  93. else:
  94. hashers = get_hashers_by_algorithm()
  95. try:
  96. return hashers[algorithm]
  97. except KeyError:
  98. raise ValueError("Unknown password hashing algorithm '%s'. "
  99. "Did you specify it in the PASSWORD_HASHERS "
  100. "setting?" % algorithm)
  101. def identify_hasher(encoded):
  102. """
  103. Return an instance of a loaded password hasher.
  104. Identify hasher algorithm by examining encoded hash, and call
  105. get_hasher() to return hasher. Raise ValueError if
  106. algorithm cannot be identified, or if hasher is not loaded.
  107. """
  108. # Ancient versions of Django created plain MD5 passwords and accepted
  109. # MD5 passwords with an empty salt.
  110. if ((len(encoded) == 32 and '$' not in encoded) or
  111. (len(encoded) == 37 and encoded.startswith('md5$$'))):
  112. algorithm = 'unsalted_md5'
  113. # Ancient versions of Django accepted SHA1 passwords with an empty salt.
  114. elif len(encoded) == 46 and encoded.startswith('sha1$$'):
  115. algorithm = 'unsalted_sha1'
  116. else:
  117. algorithm = encoded.split('$', 1)[0]
  118. return get_hasher(algorithm)
  119. def mask_hash(hash, show=6, char="*"):
  120. """
  121. Return the given hash, with only the first ``show`` number shown. The
  122. rest are masked with ``char`` for security reasons.
  123. """
  124. masked = hash[:show]
  125. masked += char * len(hash[show:])
  126. return masked
  127. class BasePasswordHasher:
  128. """
  129. Abstract base class for password hashers
  130. When creating your own hasher, you need to override algorithm,
  131. verify(), encode() and safe_summary().
  132. PasswordHasher objects are immutable.
  133. """
  134. algorithm = None
  135. library = None
  136. def _load_library(self):
  137. if self.library is not None:
  138. if isinstance(self.library, (tuple, list)):
  139. name, mod_path = self.library
  140. else:
  141. mod_path = self.library
  142. try:
  143. module = importlib.import_module(mod_path)
  144. except ImportError as e:
  145. raise ValueError("Couldn't load %r algorithm library: %s" %
  146. (self.__class__.__name__, e))
  147. return module
  148. raise ValueError("Hasher %r doesn't specify a library attribute" %
  149. self.__class__.__name__)
  150. def salt(self):
  151. """Generate a cryptographically secure nonce salt in ASCII."""
  152. return get_random_string()
  153. def verify(self, password, encoded):
  154. """Check if the given password is correct."""
  155. raise NotImplementedError('subclasses of BasePasswordHasher must provide a verify() method')
  156. def encode(self, password, salt):
  157. """
  158. Create an encoded database value.
  159. The result is normally formatted as "algorithm$salt$hash" and
  160. must be fewer than 128 characters.
  161. """
  162. raise NotImplementedError('subclasses of BasePasswordHasher must provide an encode() method')
  163. def safe_summary(self, encoded):
  164. """
  165. Return a summary of safe values.
  166. The result is a dictionary and will be used where the password field
  167. must be displayed to construct a safe representation of the password.
  168. """
  169. raise NotImplementedError('subclasses of BasePasswordHasher must provide a safe_summary() method')
  170. def must_update(self, encoded):
  171. return False
  172. def harden_runtime(self, password, encoded):
  173. """
  174. Bridge the runtime gap between the work factor supplied in `encoded`
  175. and the work factor suggested by this hasher.
  176. Taking PBKDF2 as an example, if `encoded` contains 20000 iterations and
  177. `self.iterations` is 30000, this method should run password through
  178. another 10000 iterations of PBKDF2. Similar approaches should exist
  179. for any hasher that has a work factor. If not, this method should be
  180. defined as a no-op to silence the warning.
  181. """
  182. warnings.warn('subclasses of BasePasswordHasher should provide a harden_runtime() method')
  183. class PBKDF2PasswordHasher(BasePasswordHasher):
  184. """
  185. Secure password hashing using the PBKDF2 algorithm (recommended)
  186. Configured to use PBKDF2 + HMAC + SHA256.
  187. The result is a 64 byte binary string. Iterations may be changed
  188. safely but you must rename the algorithm if you change SHA256.
  189. """
  190. algorithm = "pbkdf2_sha256"
  191. iterations = 180000
  192. digest = hashlib.sha256
  193. def encode(self, password, salt, iterations=None):
  194. assert password is not None
  195. assert salt and '$' not in salt
  196. iterations = iterations or self.iterations
  197. hash = pbkdf2(password, salt, iterations, digest=self.digest)
  198. hash = base64.b64encode(hash).decode('ascii').strip()
  199. return "%s$%d$%s$%s" % (self.algorithm, iterations, salt, hash)
  200. def verify(self, password, encoded):
  201. algorithm, iterations, salt, hash = encoded.split('$', 3)
  202. assert algorithm == self.algorithm
  203. encoded_2 = self.encode(password, salt, int(iterations))
  204. return constant_time_compare(encoded, encoded_2)
  205. def safe_summary(self, encoded):
  206. algorithm, iterations, salt, hash = encoded.split('$', 3)
  207. assert algorithm == self.algorithm
  208. return {
  209. _('algorithm'): algorithm,
  210. _('iterations'): iterations,
  211. _('salt'): mask_hash(salt),
  212. _('hash'): mask_hash(hash),
  213. }
  214. def must_update(self, encoded):
  215. algorithm, iterations, salt, hash = encoded.split('$', 3)
  216. return int(iterations) != self.iterations
  217. def harden_runtime(self, password, encoded):
  218. algorithm, iterations, salt, hash = encoded.split('$', 3)
  219. extra_iterations = self.iterations - int(iterations)
  220. if extra_iterations > 0:
  221. self.encode(password, salt, extra_iterations)
  222. class PBKDF2SHA1PasswordHasher(PBKDF2PasswordHasher):
  223. """
  224. Alternate PBKDF2 hasher which uses SHA1, the default PRF
  225. recommended by PKCS #5. This is compatible with other
  226. implementations of PBKDF2, such as openssl's
  227. PKCS5_PBKDF2_HMAC_SHA1().
  228. """
  229. algorithm = "pbkdf2_sha1"
  230. digest = hashlib.sha1
  231. class Argon2PasswordHasher(BasePasswordHasher):
  232. """
  233. Secure password hashing using the argon2 algorithm.
  234. This is the winner of the Password Hashing Competition 2013-2015
  235. (https://password-hashing.net). It requires the argon2-cffi library which
  236. depends on native C code and might cause portability issues.
  237. """
  238. algorithm = 'argon2'
  239. library = 'argon2'
  240. time_cost = 2
  241. memory_cost = 512
  242. parallelism = 2
  243. def encode(self, password, salt):
  244. argon2 = self._load_library()
  245. data = argon2.low_level.hash_secret(
  246. password.encode(),
  247. salt.encode(),
  248. time_cost=self.time_cost,
  249. memory_cost=self.memory_cost,
  250. parallelism=self.parallelism,
  251. hash_len=argon2.DEFAULT_HASH_LENGTH,
  252. type=argon2.low_level.Type.I,
  253. )
  254. return self.algorithm + data.decode('ascii')
  255. def verify(self, password, encoded):
  256. argon2 = self._load_library()
  257. algorithm, rest = encoded.split('$', 1)
  258. assert algorithm == self.algorithm
  259. try:
  260. return argon2.low_level.verify_secret(
  261. ('$' + rest).encode('ascii'),
  262. password.encode(),
  263. type=argon2.low_level.Type.I,
  264. )
  265. except argon2.exceptions.VerificationError:
  266. return False
  267. def safe_summary(self, encoded):
  268. (algorithm, variety, version, time_cost, memory_cost, parallelism,
  269. salt, data) = self._decode(encoded)
  270. assert algorithm == self.algorithm
  271. return {
  272. _('algorithm'): algorithm,
  273. _('variety'): variety,
  274. _('version'): version,
  275. _('memory cost'): memory_cost,
  276. _('time cost'): time_cost,
  277. _('parallelism'): parallelism,
  278. _('salt'): mask_hash(salt),
  279. _('hash'): mask_hash(data),
  280. }
  281. def must_update(self, encoded):
  282. (algorithm, variety, version, time_cost, memory_cost, parallelism,
  283. salt, data) = self._decode(encoded)
  284. assert algorithm == self.algorithm
  285. argon2 = self._load_library()
  286. return (
  287. argon2.low_level.ARGON2_VERSION != version or
  288. self.time_cost != time_cost or
  289. self.memory_cost != memory_cost or
  290. self.parallelism != parallelism
  291. )
  292. def harden_runtime(self, password, encoded):
  293. # The runtime for Argon2 is too complicated to implement a sensible
  294. # hardening algorithm.
  295. pass
  296. def _decode(self, encoded):
  297. """
  298. Split an encoded hash and return: (
  299. algorithm, variety, version, time_cost, memory_cost,
  300. parallelism, salt, data,
  301. ).
  302. """
  303. bits = encoded.split('$')
  304. if len(bits) == 5:
  305. # Argon2 < 1.3
  306. algorithm, variety, raw_params, salt, data = bits
  307. version = 0x10
  308. else:
  309. assert len(bits) == 6
  310. algorithm, variety, raw_version, raw_params, salt, data = bits
  311. assert raw_version.startswith('v=')
  312. version = int(raw_version[len('v='):])
  313. params = dict(bit.split('=', 1) for bit in raw_params.split(','))
  314. assert len(params) == 3 and all(x in params for x in ('t', 'm', 'p'))
  315. time_cost = int(params['t'])
  316. memory_cost = int(params['m'])
  317. parallelism = int(params['p'])
  318. return (
  319. algorithm, variety, version, time_cost, memory_cost, parallelism,
  320. salt, data,
  321. )
  322. class BCryptSHA256PasswordHasher(BasePasswordHasher):
  323. """
  324. Secure password hashing using the bcrypt algorithm (recommended)
  325. This is considered by many to be the most secure algorithm but you
  326. must first install the bcrypt library. Please be warned that
  327. this library depends on native C code and might cause portability
  328. issues.
  329. """
  330. algorithm = "bcrypt_sha256"
  331. digest = hashlib.sha256
  332. library = ("bcrypt", "bcrypt")
  333. rounds = 12
  334. def salt(self):
  335. bcrypt = self._load_library()
  336. return bcrypt.gensalt(self.rounds)
  337. def encode(self, password, salt):
  338. bcrypt = self._load_library()
  339. password = password.encode()
  340. # Hash the password prior to using bcrypt to prevent password
  341. # truncation as described in #20138.
  342. if self.digest is not None:
  343. # Use binascii.hexlify() because a hex encoded bytestring is str.
  344. password = binascii.hexlify(self.digest(password).digest())
  345. data = bcrypt.hashpw(password, salt)
  346. return "%s$%s" % (self.algorithm, data.decode('ascii'))
  347. def verify(self, password, encoded):
  348. algorithm, data = encoded.split('$', 1)
  349. assert algorithm == self.algorithm
  350. encoded_2 = self.encode(password, data.encode('ascii'))
  351. return constant_time_compare(encoded, encoded_2)
  352. def safe_summary(self, encoded):
  353. algorithm, empty, algostr, work_factor, data = encoded.split('$', 4)
  354. assert algorithm == self.algorithm
  355. salt, checksum = data[:22], data[22:]
  356. return {
  357. _('algorithm'): algorithm,
  358. _('work factor'): work_factor,
  359. _('salt'): mask_hash(salt),
  360. _('checksum'): mask_hash(checksum),
  361. }
  362. def must_update(self, encoded):
  363. algorithm, empty, algostr, rounds, data = encoded.split('$', 4)
  364. return int(rounds) != self.rounds
  365. def harden_runtime(self, password, encoded):
  366. _, data = encoded.split('$', 1)
  367. salt = data[:29] # Length of the salt in bcrypt.
  368. rounds = data.split('$')[2]
  369. # work factor is logarithmic, adding one doubles the load.
  370. diff = 2**(self.rounds - int(rounds)) - 1
  371. while diff > 0:
  372. self.encode(password, salt.encode('ascii'))
  373. diff -= 1
  374. class BCryptPasswordHasher(BCryptSHA256PasswordHasher):
  375. """
  376. Secure password hashing using the bcrypt algorithm
  377. This is considered by many to be the most secure algorithm but you
  378. must first install the bcrypt library. Please be warned that
  379. this library depends on native C code and might cause portability
  380. issues.
  381. This hasher does not first hash the password which means it is subject to
  382. bcrypt's 72 bytes password truncation. Most use cases should prefer the
  383. BCryptSHA256PasswordHasher.
  384. """
  385. algorithm = "bcrypt"
  386. digest = None
  387. class SHA1PasswordHasher(BasePasswordHasher):
  388. """
  389. The SHA1 password hashing algorithm (not recommended)
  390. """
  391. algorithm = "sha1"
  392. def encode(self, password, salt):
  393. assert password is not None
  394. assert salt and '$' not in salt
  395. hash = hashlib.sha1((salt + password).encode()).hexdigest()
  396. return "%s$%s$%s" % (self.algorithm, salt, hash)
  397. def verify(self, password, encoded):
  398. algorithm, salt, hash = encoded.split('$', 2)
  399. assert algorithm == self.algorithm
  400. encoded_2 = self.encode(password, salt)
  401. return constant_time_compare(encoded, encoded_2)
  402. def safe_summary(self, encoded):
  403. algorithm, salt, hash = encoded.split('$', 2)
  404. assert algorithm == self.algorithm
  405. return {
  406. _('algorithm'): algorithm,
  407. _('salt'): mask_hash(salt, show=2),
  408. _('hash'): mask_hash(hash),
  409. }
  410. def harden_runtime(self, password, encoded):
  411. pass
  412. class MD5PasswordHasher(BasePasswordHasher):
  413. """
  414. The Salted MD5 password hashing algorithm (not recommended)
  415. """
  416. algorithm = "md5"
  417. def encode(self, password, salt):
  418. assert password is not None
  419. assert salt and '$' not in salt
  420. hash = hashlib.md5((salt + password).encode()).hexdigest()
  421. return "%s$%s$%s" % (self.algorithm, salt, hash)
  422. def verify(self, password, encoded):
  423. algorithm, salt, hash = encoded.split('$', 2)
  424. assert algorithm == self.algorithm
  425. encoded_2 = self.encode(password, salt)
  426. return constant_time_compare(encoded, encoded_2)
  427. def safe_summary(self, encoded):
  428. algorithm, salt, hash = encoded.split('$', 2)
  429. assert algorithm == self.algorithm
  430. return {
  431. _('algorithm'): algorithm,
  432. _('salt'): mask_hash(salt, show=2),
  433. _('hash'): mask_hash(hash),
  434. }
  435. def harden_runtime(self, password, encoded):
  436. pass
  437. class UnsaltedSHA1PasswordHasher(BasePasswordHasher):
  438. """
  439. Very insecure algorithm that you should *never* use; store SHA1 hashes
  440. with an empty salt.
  441. This class is implemented because Django used to accept such password
  442. hashes. Some older Django installs still have these values lingering
  443. around so we need to handle and upgrade them properly.
  444. """
  445. algorithm = "unsalted_sha1"
  446. def salt(self):
  447. return ''
  448. def encode(self, password, salt):
  449. assert salt == ''
  450. hash = hashlib.sha1(password.encode()).hexdigest()
  451. return 'sha1$$%s' % hash
  452. def verify(self, password, encoded):
  453. encoded_2 = self.encode(password, '')
  454. return constant_time_compare(encoded, encoded_2)
  455. def safe_summary(self, encoded):
  456. assert encoded.startswith('sha1$$')
  457. hash = encoded[6:]
  458. return {
  459. _('algorithm'): self.algorithm,
  460. _('hash'): mask_hash(hash),
  461. }
  462. def harden_runtime(self, password, encoded):
  463. pass
  464. class UnsaltedMD5PasswordHasher(BasePasswordHasher):
  465. """
  466. Incredibly insecure algorithm that you should *never* use; stores unsalted
  467. MD5 hashes without the algorithm prefix, also accepts MD5 hashes with an
  468. empty salt.
  469. This class is implemented because Django used to store passwords this way
  470. and to accept such password hashes. Some older Django installs still have
  471. these values lingering around so we need to handle and upgrade them
  472. properly.
  473. """
  474. algorithm = "unsalted_md5"
  475. def salt(self):
  476. return ''
  477. def encode(self, password, salt):
  478. assert salt == ''
  479. return hashlib.md5(password.encode()).hexdigest()
  480. def verify(self, password, encoded):
  481. if len(encoded) == 37 and encoded.startswith('md5$$'):
  482. encoded = encoded[5:]
  483. encoded_2 = self.encode(password, '')
  484. return constant_time_compare(encoded, encoded_2)
  485. def safe_summary(self, encoded):
  486. return {
  487. _('algorithm'): self.algorithm,
  488. _('hash'): mask_hash(encoded, show=3),
  489. }
  490. def harden_runtime(self, password, encoded):
  491. pass
  492. class CryptPasswordHasher(BasePasswordHasher):
  493. """
  494. Password hashing using UNIX crypt (not recommended)
  495. The crypt module is not supported on all platforms.
  496. """
  497. algorithm = "crypt"
  498. library = "crypt"
  499. def salt(self):
  500. return get_random_string(2)
  501. def encode(self, password, salt):
  502. crypt = self._load_library()
  503. assert len(salt) == 2
  504. data = crypt.crypt(password, salt)
  505. assert data is not None # A platform like OpenBSD with a dummy crypt module.
  506. # we don't need to store the salt, but Django used to do this
  507. return "%s$%s$%s" % (self.algorithm, '', data)
  508. def verify(self, password, encoded):
  509. crypt = self._load_library()
  510. algorithm, salt, data = encoded.split('$', 2)
  511. assert algorithm == self.algorithm
  512. return constant_time_compare(data, crypt.crypt(password, data))
  513. def safe_summary(self, encoded):
  514. algorithm, salt, data = encoded.split('$', 2)
  515. assert algorithm == self.algorithm
  516. return {
  517. _('algorithm'): algorithm,
  518. _('salt'): salt,
  519. _('hash'): mask_hash(data, show=3),
  520. }
  521. def harden_runtime(self, password, encoded):
  522. pass