passwords.txt 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. =============================
  2. Password management in Django
  3. =============================
  4. Password management is something that should generally not be reinvented
  5. unnecessarily, and Django endeavors to provide a secure and flexible set of
  6. tools for managing user passwords. This document describes how Django stores
  7. passwords, how the storage hashing can be configured, and some utilities to
  8. work with hashed passwords.
  9. .. seealso::
  10. Even though users may use strong passwords, attackers might be able to
  11. eavesdrop on their connections. Use :ref:`HTTPS
  12. <security-recommendation-ssl>` to avoid sending passwords (or any other
  13. sensitive data) over plain HTTP connections because they will be vulnerable
  14. to password sniffing.
  15. .. _auth_password_storage:
  16. How Django stores passwords
  17. ===========================
  18. Django provides a flexible password storage system and uses PBKDF2 by default.
  19. The :attr:`~django.contrib.auth.models.User.password` attribute of a
  20. :class:`~django.contrib.auth.models.User` object is a string in this format::
  21. <algorithm>$<iterations>$<salt>$<hash>
  22. Those are the components used for storing a User's password, separated by the
  23. dollar-sign character and consist of: the hashing algorithm, the number of
  24. algorithm iterations (work factor), the random salt, and the resulting password
  25. hash. The algorithm is one of a number of one-way hashing or password storage
  26. algorithms Django can use; see below. Iterations describe the number of times
  27. the algorithm is run over the hash. Salt is the random seed used and the hash
  28. is the result of the one-way function.
  29. By default, Django uses the PBKDF2_ algorithm with a SHA256 hash, a
  30. password stretching mechanism recommended by NIST_. This should be
  31. sufficient for most users: it's quite secure, requiring massive
  32. amounts of computing time to break.
  33. However, depending on your requirements, you may choose a different
  34. algorithm, or even use a custom algorithm to match your specific
  35. security situation. Again, most users shouldn't need to do this -- if
  36. you're not sure, you probably don't. If you do, please read on:
  37. Django chooses the algorithm to use by consulting the
  38. :setting:`PASSWORD_HASHERS` setting. This is a list of hashing algorithm
  39. classes that this Django installation supports. The first entry in this list
  40. (that is, ``settings.PASSWORD_HASHERS[0]``) will be used to store passwords,
  41. and all the other entries are valid hashers that can be used to check existing
  42. passwords. This means that if you want to use a different algorithm, you'll
  43. need to modify :setting:`PASSWORD_HASHERS` to list your preferred algorithm
  44. first in the list.
  45. The default for :setting:`PASSWORD_HASHERS` is::
  46. PASSWORD_HASHERS = [
  47. 'django.contrib.auth.hashers.PBKDF2PasswordHasher',
  48. 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
  49. 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
  50. 'django.contrib.auth.hashers.BCryptPasswordHasher',
  51. 'django.contrib.auth.hashers.SHA1PasswordHasher',
  52. 'django.contrib.auth.hashers.MD5PasswordHasher',
  53. 'django.contrib.auth.hashers.CryptPasswordHasher',
  54. ]
  55. This means that Django will use PBKDF2_ to store all passwords, but will support
  56. checking passwords stored with PBKDF2SHA1, bcrypt_, SHA1_, etc. The next few
  57. sections describe a couple of common ways advanced users may want to modify this
  58. setting.
  59. .. _bcrypt_usage:
  60. Using ``bcrypt`` with Django
  61. ----------------------------
  62. Bcrypt_ is a popular password storage algorithm that's specifically designed
  63. for long-term password storage. It's not the default used by Django since it
  64. requires the use of third-party libraries, but since many people may want to
  65. use it Django supports bcrypt with minimal effort.
  66. To use Bcrypt as your default storage algorithm, do the following:
  67. 1. Install the `bcrypt library`_. This can be done by running ``pip install
  68. django[bcrypt]``, or by downloading the library and installing it with
  69. ``python setup.py install``.
  70. 2. Modify :setting:`PASSWORD_HASHERS` to list ``BCryptSHA256PasswordHasher``
  71. first. That is, in your settings file, you'd put::
  72. PASSWORD_HASHERS = [
  73. 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
  74. 'django.contrib.auth.hashers.BCryptPasswordHasher',
  75. 'django.contrib.auth.hashers.PBKDF2PasswordHasher',
  76. 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
  77. 'django.contrib.auth.hashers.SHA1PasswordHasher',
  78. 'django.contrib.auth.hashers.MD5PasswordHasher',
  79. 'django.contrib.auth.hashers.CryptPasswordHasher',
  80. ]
  81. (You need to keep the other entries in this list, or else Django won't
  82. be able to upgrade passwords; see below).
  83. That's it -- now your Django install will use Bcrypt as the default storage
  84. algorithm.
  85. .. admonition:: Password truncation with BCryptPasswordHasher
  86. The designers of bcrypt truncate all passwords at 72 characters which means
  87. that ``bcrypt(password_with_100_chars) == bcrypt(password_with_100_chars[:72])``.
  88. The original ``BCryptPasswordHasher`` does not have any special handling and
  89. thus is also subject to this hidden password length limit.
  90. ``BCryptSHA256PasswordHasher`` fixes this by first first hashing the
  91. password using sha256. This prevents the password truncation and so should
  92. be preferred over the ``BCryptPasswordHasher``. The practical ramification
  93. of this truncation is pretty marginal as the average user does not have a
  94. password greater than 72 characters in length and even being truncated at 72
  95. the compute powered required to brute force bcrypt in any useful amount of
  96. time is still astronomical. Nonetheless, we recommend you use
  97. ``BCryptSHA256PasswordHasher`` anyway on the principle of "better safe than
  98. sorry".
  99. .. admonition:: Other bcrypt implementations
  100. There are several other implementations that allow bcrypt to be
  101. used with Django. Django's bcrypt support is NOT directly
  102. compatible with these. To upgrade, you will need to modify the
  103. hashes in your database to be in the form ``bcrypt$(raw bcrypt
  104. output)``. For example:
  105. ``bcrypt$$2a$12$NT0I31Sa7ihGEWpka9ASYrEFkhuTNeBQ2xfZskIiiJeyFXhRgS.Sy``.
  106. .. _increasing-password-algorithm-work-factor:
  107. Increasing the work factor
  108. --------------------------
  109. The PBKDF2 and bcrypt algorithms use a number of iterations or rounds of
  110. hashing. This deliberately slows down attackers, making attacks against hashed
  111. passwords harder. However, as computing power increases, the number of
  112. iterations needs to be increased. We've chosen a reasonable default (and will
  113. increase it with each release of Django), but you may wish to tune it up or
  114. down, depending on your security needs and available processing power. To do so,
  115. you'll subclass the appropriate algorithm and override the ``iterations``
  116. parameters. For example, to increase the number of iterations used by the
  117. default PBKDF2 algorithm:
  118. 1. Create a subclass of ``django.contrib.auth.hashers.PBKDF2PasswordHasher``::
  119. from django.contrib.auth.hashers import PBKDF2PasswordHasher
  120. class MyPBKDF2PasswordHasher(PBKDF2PasswordHasher):
  121. """
  122. A subclass of PBKDF2PasswordHasher that uses 100 times more iterations.
  123. """
  124. iterations = PBKDF2PasswordHasher.iterations * 100
  125. Save this somewhere in your project. For example, you might put this in
  126. a file like ``myproject/hashers.py``.
  127. 2. Add your new hasher as the first entry in :setting:`PASSWORD_HASHERS`::
  128. PASSWORD_HASHERS = [
  129. 'myproject.hashers.MyPBKDF2PasswordHasher',
  130. 'django.contrib.auth.hashers.PBKDF2PasswordHasher',
  131. 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
  132. 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
  133. 'django.contrib.auth.hashers.BCryptPasswordHasher',
  134. 'django.contrib.auth.hashers.SHA1PasswordHasher',
  135. 'django.contrib.auth.hashers.MD5PasswordHasher',
  136. 'django.contrib.auth.hashers.CryptPasswordHasher',
  137. ]
  138. That's it -- now your Django install will use more iterations when it
  139. stores passwords using PBKDF2.
  140. .. _password-upgrades:
  141. Password upgrading
  142. ------------------
  143. When users log in, if their passwords are stored with anything other than
  144. the preferred algorithm, Django will automatically upgrade the algorithm
  145. to the preferred one. This means that old installs of Django will get
  146. automatically more secure as users log in, and it also means that you
  147. can switch to new (and better) storage algorithms as they get invented.
  148. However, Django can only upgrade passwords that use algorithms mentioned in
  149. :setting:`PASSWORD_HASHERS`, so as you upgrade to new systems you should make
  150. sure never to *remove* entries from this list. If you do, users using
  151. unmentioned algorithms won't be able to upgrade. Hashed passwords will be
  152. updated when increasing (or decreasing) the number of PBKDF2 iterations or
  153. bcrypt rounds.
  154. .. versionchanged:: 1.9
  155. Passwords updates when changing the number of bcrypt rounds was added.
  156. .. _sha1: https://en.wikipedia.org/wiki/SHA1
  157. .. _pbkdf2: https://en.wikipedia.org/wiki/PBKDF2
  158. .. _nist: http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf
  159. .. _bcrypt: https://en.wikipedia.org/wiki/Bcrypt
  160. .. _`bcrypt library`: https://pypi.python.org/pypi/bcrypt/
  161. Manually managing a user's password
  162. ===================================
  163. .. module:: django.contrib.auth.hashers
  164. The :mod:`django.contrib.auth.hashers` module provides a set of functions
  165. to create and validate hashed password. You can use them independently
  166. from the ``User`` model.
  167. .. function:: check_password(password, encoded)
  168. If you'd like to manually authenticate a user by comparing a plain-text
  169. password to the hashed password in the database, use the convenience
  170. function :func:`check_password`. It takes two arguments: the plain-text
  171. password to check, and the full value of a user's ``password`` field in the
  172. database to check against, and returns ``True`` if they match, ``False``
  173. otherwise.
  174. .. function:: make_password(password, salt=None, hasher='default')
  175. Creates a hashed password in the format used by this application. It takes
  176. one mandatory argument: the password in plain-text. Optionally, you can
  177. provide a salt and a hashing algorithm to use, if you don't want to use the
  178. defaults (first entry of ``PASSWORD_HASHERS`` setting).
  179. Currently supported algorithms are: ``'pbkdf2_sha256'``, ``'pbkdf2_sha1'``,
  180. ``'bcrypt_sha256'`` (see :ref:`bcrypt_usage`), ``'bcrypt'``, ``'sha1'``,
  181. ``'md5'``, ``'unsalted_md5'`` (only for backward compatibility) and ``'crypt'``
  182. if you have the ``crypt`` library installed. If the password argument is
  183. ``None``, an unusable password is returned (a one that will be never
  184. accepted by :func:`check_password`).
  185. .. function:: is_password_usable(encoded_password)
  186. Checks if the given string is a hashed password that has a chance
  187. of being verified against :func:`check_password`.
  188. .. _password-validation:
  189. Password validation
  190. ===================
  191. .. module:: django.contrib.auth.password_validation
  192. .. versionadded:: 1.9
  193. Users often choose poor passwords. To help mitigate this problem, Django
  194. offers pluggable password validation. You can configure multiple password
  195. validators at the same time. A few validators are included in Django, but it's
  196. simple to write your own as well.
  197. Each password validator must provide a help text to explain the requirements to
  198. the user, validate a given password and return an error message if it does not
  199. meet the requirements, and optionally receive passwords that have been set.
  200. Validators can also have optional settings to fine tune their behavior.
  201. Validation is controlled by the :setting:`AUTH_PASSWORD_VALIDATORS` setting.
  202. By default, validators are used in the forms to reset or change passwords.
  203. The default for the setting is an empty list, which means no validators are
  204. applied. In new projects created with the default :djadmin:`startproject`
  205. template, a simple set of validators is enabled.
  206. .. note::
  207. Password validation can prevent the use of many types of weak passwords.
  208. However, the fact that a password passes all the validators doesn't
  209. guarantee that it is a strong password. There are many factors that can
  210. weaken a password that are not detectable by even the most advanced
  211. password validators.
  212. Enabling password validation
  213. ----------------------------
  214. Password validation is configured in the
  215. :setting:`AUTH_PASSWORD_VALIDATORS` setting::
  216. AUTH_PASSWORD_VALIDATORS = [
  217. {
  218. 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
  219. },
  220. {
  221. 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
  222. 'OPTIONS': {
  223. 'min_length': 9,
  224. }
  225. },
  226. {
  227. 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
  228. },
  229. {
  230. 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
  231. },
  232. ]
  233. This example enables all four included validators:
  234. * ``UserAttributeSimilarityValidator``, which checks the similarity between
  235. the password and a set of attributes of the user.
  236. * ``MinimumLengthValidator``, which simply checks whether the password meets a
  237. minimum length. This validator is configured with a custom option: it now
  238. requires the minimum length to be nine characters, instead of the default
  239. eight.
  240. * ``CommonPasswordValidator``, which checks whether the password occurs in a
  241. list of common passwords. By default, it compares to an included list of
  242. 1000 common passwords.
  243. * ``NumericPasswordValidator``, which checks whether the password isn't
  244. entirely numeric.
  245. For ``UserAttributeSimilarityValidator`` and ``CommonPasswordValidator``,
  246. we're simply using the default settings in this example.
  247. ``NumericPasswordValidator`` has no settings.
  248. The help texts and any errors from password validators are always returned in
  249. the order they are listed in :setting:`AUTH_PASSWORD_VALIDATORS`.
  250. Included validators
  251. -------------------
  252. Django includes four validators:
  253. .. class:: MinimumLengthValidator(min_length=8)
  254. Validates whether the password meets a minimum length.
  255. The minimum length can be customized with the ``min_length`` parameter.
  256. .. class:: UserAttributeSimilarityValidator(user_attributes=DEFAULT_USER_ATTRIBUTES, max_similarity=0.7)
  257. Validates whether the password is sufficiently different from certain
  258. attributes of the user.
  259. The ``user_attributes`` parameter should be an iterable of names of user
  260. attributes to compare to. If this argument is not provided, the default
  261. is used: ``'username', 'first_name', 'last_name', 'email'``.
  262. Attributes that don't exist are ignored.
  263. The maximum similarity the password can have, before it is rejected, can
  264. be set with the ``max_similarity`` parameter, on a scale of 0 to 1.
  265. A setting of 0 will cause all passwords to be rejected, whereas a setting
  266. of 1 will cause it to only reject passwords that are identical to an
  267. attribute's value.
  268. .. class:: CommonPasswordValidator(password_list_path=DEFAULT_PASSWORD_LIST_PATH)
  269. Validates whether the password is not a common password. By default, this
  270. checks against a list of 1000 common password created by
  271. `Mark Burnett <https://web.archive.org/web/20150315154609/https://xato.net/passwords/more-top-worst-passwords/>`_.
  272. The ``password_list_path`` can be set to the path of a custom file of
  273. common passwords. This file should contain one password per line and
  274. may be plain text or gzipped.
  275. .. class:: NumericPasswordValidator()
  276. Validates whether the password is not entirely numeric.
  277. Integrating validation
  278. -----------------------
  279. There are a few functions in ``django.contrib.auth.password_validation`` that
  280. you can call from your own forms or other code to integrate password
  281. validation. This can be useful if you use custom forms for password setting,
  282. or if you have API calls that allow passwords to be set, for example.
  283. .. function:: validate_password(password, user=None, password_validators=None)
  284. Validates a password. If all validators find the password valid, returns
  285. ``None``. If one or more validators reject the password, raises a
  286. :exc:`~django.core.exceptions.ValidationError` with all the error messages
  287. from the validators.
  288. The ``user`` object is optional: if it's not provided, some validators may
  289. not be able to perform any validation and will accept any password.
  290. .. function:: password_changed(password, user=None, password_validators=None)
  291. Informs all validators that the password has been changed. This can be used
  292. by validators such as one that prevents password reuse. This should be
  293. called once the password has been successfully changed.
  294. For subclasses of :class:`~django.contrib.auth.models.AbstractBaseUser`,
  295. the password field will be marked as "dirty" when calling
  296. :meth:`~django.contrib.auth.models.AbstractBaseUser.set_password` which
  297. triggers a call to ``password_changed()`` after the user is saved.
  298. .. function:: password_validators_help_texts(password_validators=None)
  299. Returns a list of the help texts of all validators. These explain the
  300. password requirements to the user.
  301. .. function:: password_validators_help_text_html(password_validators=None)
  302. Returns an HTML string with all help texts in an ``<ul>``. This is
  303. helpful when adding password validation to forms, as you can pass the
  304. output directly to the ``help_text`` parameter of a form field.
  305. .. function:: get_password_validators(validator_config)
  306. Returns a set of validator objects based on the ``validator_config``
  307. parameter. By default, all functions use the validators defined in
  308. :setting:`AUTH_PASSWORD_VALIDATORS`, but by calling this function with an
  309. alternate set of validators and then passing the result into the
  310. ``password_validators`` parameter of the other functions, your custom set
  311. of validators will be used instead. This is useful when you have a typical
  312. set of validators to use for most scenarios, but also have a special
  313. situation that requires a custom set. If you always use the same set
  314. of validators, there is no need to use this function, as the configuration
  315. from :setting:`AUTH_PASSWORD_VALIDATORS` is used by default.
  316. The structure of ``validator_config`` is identical to the
  317. structure of :setting:`AUTH_PASSWORD_VALIDATORS`. The return value of
  318. this function can be passed into the ``password_validators`` parameter
  319. of the functions listed above.
  320. Note that where the password is passed to one of these functions, this should
  321. always be the clear text password - not a hashed password.
  322. Writing your own validator
  323. --------------------------
  324. If Django's built-in validators are not sufficient, you can write your own
  325. password validators. Validators are fairly simple classes. They must implement
  326. two methods:
  327. * ``validate(self, password, user=None)``: validate a password. Return
  328. ``None`` if the password is valid, or raise a
  329. :exc:`~django.core.exceptions.ValidationError` with an error message if the
  330. password is not valid. You must be able to deal with ``user`` being
  331. ``None`` - if that means your validator can't run, simply return ``None``
  332. for no error.
  333. * ``get_help_text()``: provide a help text to explain the requirements to
  334. the user.
  335. Any items in the ``OPTIONS`` in :setting:`AUTH_PASSWORD_VALIDATORS` for your
  336. validator will be passed to the constructor. All constructor arguments should
  337. have a default value.
  338. Here's a basic example of a validator, with one optional setting::
  339. from django.core.exceptions import ValidationError
  340. from django.utils.translation import ugettext as _
  341. class MinimumLengthValidator(object):
  342. def __init__(self, min_length=8):
  343. self.min_length = min_length
  344. def validate(self, password, user=None):
  345. if len(password) < self.min_length:
  346. raise ValidationError(
  347. _("This password must contain at least %(min_length)d characters."),
  348. code='password_too_short',
  349. params={'min_length': self.min_length},
  350. )
  351. def get_help_text(self):
  352. return _(
  353. "Your password must contain at least %(min_length)d characters."
  354. % {'min_length': self.min_length}
  355. )
  356. You can also implement ``password_changed(password, user=None``), which will
  357. be called after a successful password change. That can be used to prevent
  358. password reuse, for example. However, if you decide to store a user's previous
  359. passwords, you should never do so in clear text.