htpasswd.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. # This file is part of Radicale Server - Calendar Server
  2. # Copyright © 2008 Nicolas Kandel
  3. # Copyright © 2008 Pascal Halter
  4. # Copyright © 2008-2017 Guillaume Ayoub
  5. # Copyright © 2017-2019 Unrud <unrud@outlook.com>
  6. #
  7. # This library is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This library is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  19. """
  20. Authentication backend that checks credentials with a htpasswd file.
  21. Apache's htpasswd command (httpd.apache.org/docs/programs/htpasswd.html)
  22. manages a file for storing user credentials. It can encrypt passwords using
  23. different methods, e.g. BCRYPT, MD5-APR1 (a version of MD5 modified for
  24. Apache), SHA1, or by using the system's CRYPT routine. The CRYPT and SHA1
  25. encryption methods implemented by htpasswd are considered as insecure. MD5-APR1
  26. provides medium security as of 2015. Only BCRYPT can be considered secure by
  27. current standards.
  28. MD5-APR1-encrypted credentials can be written by all versions of htpasswd (it
  29. is the default, in fact), whereas BCRYPT requires htpasswd 2.4.x or newer.
  30. The `is_authenticated(user, password)` function provided by this module
  31. verifies the user-given credentials by parsing the htpasswd credential file
  32. pointed to by the ``htpasswd_filename`` configuration value while assuming
  33. the password encryption method specified via the ``htpasswd_encryption``
  34. configuration value.
  35. The following htpasswd password encrpytion methods are supported by Radicale
  36. out-of-the-box:
  37. - plain-text (created by htpasswd -p...) -- INSECURE
  38. - CRYPT (created by htpasswd -d...) -- INSECURE
  39. - SHA1 (created by htpasswd -s...) -- INSECURE
  40. When passlib (https://pypi.python.org/pypi/passlib) is importable, the
  41. following significantly more secure schemes are parsable by Radicale:
  42. - MD5-APR1 (htpasswd -m...) -- htpasswd's default method
  43. - BCRYPT (htpasswd -B...) -- Requires htpasswd 2.4.x
  44. """
  45. import base64
  46. import functools
  47. import hashlib
  48. import hmac
  49. from radicale import auth
  50. class Auth(auth.BaseAuth):
  51. def __init__(self, configuration):
  52. super().__init__(configuration)
  53. self.filename = configuration.get("auth", "htpasswd_filename")
  54. self.encryption = configuration.get("auth", "htpasswd_encryption")
  55. if self.encryption == "ssha":
  56. self.verify = self._ssha
  57. elif self.encryption == "sha1":
  58. self.verify = self._sha1
  59. elif self.encryption == "plain":
  60. self.verify = self._plain
  61. elif self.encryption == "md5":
  62. try:
  63. from passlib.hash import apr_md5_crypt
  64. except ImportError as e:
  65. raise RuntimeError(
  66. "The htpasswd encryption method 'md5' requires "
  67. "the passlib module.") from e
  68. self.verify = functools.partial(self._md5apr1, apr_md5_crypt)
  69. elif self.encryption == "bcrypt":
  70. try:
  71. from passlib.hash import bcrypt
  72. except ImportError as e:
  73. raise RuntimeError(
  74. "The htpasswd encryption method 'bcrypt' requires "
  75. "the passlib module with bcrypt support.") from e
  76. # A call to `encrypt` raises passlib.exc.MissingBackendError with a
  77. # good error message if bcrypt backend is not available. Trigger
  78. # this here.
  79. bcrypt.hash("test-bcrypt-backend")
  80. self.verify = functools.partial(self._bcrypt, bcrypt)
  81. elif self.encryption == "crypt":
  82. try:
  83. import crypt
  84. except ImportError as e:
  85. raise RuntimeError(
  86. "The htpasswd encryption method 'crypt' requires "
  87. "the crypt() system support.") from e
  88. self.verify = functools.partial(self._crypt, crypt)
  89. else:
  90. raise RuntimeError(
  91. "The htpasswd encryption method %r is not "
  92. "supported." % self.encryption)
  93. def _plain(self, hash_value, password):
  94. """Check if ``hash_value`` and ``password`` match, plain method."""
  95. return hmac.compare_digest(hash_value, password)
  96. def _crypt(self, crypt, hash_value, password):
  97. """Check if ``hash_value`` and ``password`` match, crypt method."""
  98. hash_value = hash_value.strip()
  99. return hmac.compare_digest(crypt.crypt(password, hash_value),
  100. hash_value)
  101. def _sha1(self, hash_value, password):
  102. """Check if ``hash_value`` and ``password`` match, sha1 method."""
  103. hash_value = base64.b64decode(hash_value.strip().replace(
  104. "{SHA}", "").encode("ascii"))
  105. password = password.encode(self.configuration.get("encoding", "stock"))
  106. sha1 = hashlib.sha1()
  107. sha1.update(password)
  108. return hmac.compare_digest(sha1.digest(), hash_value)
  109. def _ssha(self, hash_value, password):
  110. """Check if ``hash_value`` and ``password`` match, salted sha1 method.
  111. This method is not directly supported by htpasswd, but it can be
  112. written with e.g. openssl, and nginx can parse it.
  113. """
  114. hash_value = base64.b64decode(hash_value.strip().replace(
  115. "{SSHA}", "").encode("ascii"))
  116. password = password.encode(self.configuration.get("encoding", "stock"))
  117. salt_value = hash_value[20:]
  118. hash_value = hash_value[:20]
  119. sha1 = hashlib.sha1()
  120. sha1.update(password)
  121. sha1.update(salt_value)
  122. return hmac.compare_digest(sha1.digest(), hash_value)
  123. def _bcrypt(self, bcrypt, hash_value, password):
  124. hash_value = hash_value.strip()
  125. return bcrypt.verify(password, hash_value)
  126. def _md5apr1(self, md5_apr1, hash_value, password):
  127. hash_value = hash_value.strip()
  128. return md5_apr1.verify(password, hash_value)
  129. def login(self, login, password):
  130. """Validate credentials.
  131. Iterate through htpasswd credential file until login matches, extract
  132. hash (encrypted password) and check hash against password,
  133. using the method specified in the Radicale config.
  134. The content of the file is not cached because reading is generally a
  135. very cheap operation, and it's useful to get live updates of the
  136. htpasswd file.
  137. """
  138. try:
  139. with open(self.filename) as f:
  140. for line in f:
  141. line = line.rstrip("\n")
  142. if line.lstrip() and not line.lstrip().startswith("#"):
  143. try:
  144. hash_login, hash_value = line.split(
  145. ":", maxsplit=1)
  146. # Always compare both login and password to avoid
  147. # timing attacks, see #591.
  148. login_ok = hmac.compare_digest(hash_login, login)
  149. password_ok = self.verify(hash_value, password)
  150. if login_ok and password_ok:
  151. return login
  152. except ValueError as e:
  153. raise RuntimeError("Invalid htpasswd file %r: %s" %
  154. (self.filename, e)) from e
  155. except OSError as e:
  156. raise RuntimeError("Failed to load htpasswd file %r: %s" %
  157. (self.filename, e)) from e
  158. return ""