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.
 
 
 
 

555 lines
18 KiB

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