auth.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. # This file is part of Radicale Server - Calendar Server
  2. # Copyright © 2008 Nicolas Kandel
  3. # Copyright © 2008 Pascal Halter
  4. # Copyright © 2008-2016 Guillaume Ayoub
  5. #
  6. # This library is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This library is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. Authentication management.
  20. Default is htpasswd authentication.
  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. import os
  50. import random
  51. import time
  52. from importlib import import_module
  53. def load(configuration, logger):
  54. """Load the authentication manager chosen in configuration."""
  55. auth_type = configuration.get("auth", "type")
  56. logger.debug("Authentication type is %s", auth_type)
  57. if auth_type == "None":
  58. class_ = NoneAuth
  59. elif auth_type == "htpasswd":
  60. class_ = Auth
  61. else:
  62. class_ = import_module(auth_type).Auth
  63. return class_(configuration, logger)
  64. class BaseAuth:
  65. def __init__(self, configuration, logger):
  66. self.configuration = configuration
  67. self.logger = logger
  68. def is_authenticated(self, user, password):
  69. """Validate credentials.
  70. Iterate through htpasswd credential file until user matches, extract
  71. hash (encrypted password) and check hash against user-given password,
  72. using the method specified in the Radicale config.
  73. """
  74. raise NotImplementedError
  75. def map_login_to_user(self, login):
  76. """Map login to internal username."""
  77. return login
  78. class NoneAuth(BaseAuth):
  79. def is_authenticated(self, user, password):
  80. return True
  81. class Auth(BaseAuth):
  82. def __init__(self, configuration, logger):
  83. super().__init__(configuration, logger)
  84. self.filename = os.path.expanduser(
  85. configuration.get("auth", "htpasswd_filename"))
  86. self.encryption = configuration.get("auth", "htpasswd_encryption")
  87. if self.encryption == "ssha":
  88. self.verify = self._ssha
  89. elif self.encryption == "sha1":
  90. self.verify = self._sha1
  91. elif self.encryption == "plain":
  92. self.verify = self._plain
  93. elif self.encryption == "md5":
  94. try:
  95. from passlib.hash import apr_md5_crypt
  96. except ImportError:
  97. raise RuntimeError(
  98. "The htpasswd encryption method 'md5' requires "
  99. "the passlib module.")
  100. self.verify = functools.partial(self._md5apr1, apr_md5_crypt)
  101. elif self.encryption == "bcrypt":
  102. try:
  103. from passlib.hash import bcrypt
  104. except ImportError:
  105. raise RuntimeError(
  106. "The htpasswd encryption method 'bcrypt' requires "
  107. "the passlib module with bcrypt support.")
  108. # A call to `encrypt` raises passlib.exc.MissingBackendError with a
  109. # good error message if bcrypt backend is not available. Trigger
  110. # this here.
  111. bcrypt.encrypt("test-bcrypt-backend")
  112. self.verify = functools.partial(self._bcrypt, bcrypt)
  113. elif self.encryption == "crypt":
  114. try:
  115. import crypt
  116. except ImportError:
  117. raise RuntimeError(
  118. "The htpasswd encryption method 'crypt' requires "
  119. "the crypt() system support.")
  120. self.verify = functools.partial(self._crypt, crypt)
  121. else:
  122. raise RuntimeError(
  123. "The htpasswd encryption method '%s' is not "
  124. "supported." % self.encryption)
  125. def _plain(self, hash_value, password):
  126. """Check if ``hash_value`` and ``password`` match, plain method."""
  127. return hmac.compare_digest(hash_value, password)
  128. def _crypt(self, crypt, hash_value, password):
  129. """Check if ``hash_value`` and ``password`` match, crypt method."""
  130. return hmac.compare_digest(crypt.crypt(password, hash_value),
  131. hash_value)
  132. def _sha1(self, hash_value, password):
  133. """Check if ``hash_value`` and ``password`` match, sha1 method."""
  134. hash_value = hash_value.replace("{SHA}", "").encode("ascii")
  135. password = password.encode(self.configuration.get("encoding", "stock"))
  136. sha1 = hashlib.sha1()
  137. sha1.update(password)
  138. return hmac.compare_digest(sha1.digest(), base64.b64decode(hash_value))
  139. def _ssha(self, hash_value, password):
  140. """Check if ``hash_value`` and ``password`` match, salted sha1 method.
  141. This method is not directly supported by htpasswd, but it can be
  142. written with e.g. openssl, and nginx can parse it.
  143. """
  144. hash_value = base64.b64decode(hash_value.replace(
  145. "{SSHA}", "").encode("ascii"))
  146. password = password.encode(self.configuration.get("encoding", "stock"))
  147. salt_value = hash_value[20:]
  148. hash_value = hash_value[:20]
  149. sha1 = hashlib.sha1()
  150. sha1.update(password)
  151. sha1.update(salt_value)
  152. return hmac.compare_digest(sha1.digest(), hash_value)
  153. def _bcrypt(self, bcrypt, hash_value, password):
  154. return bcrypt.verify(password, hash_value)
  155. def _md5apr1(self, md5_apr1, hash_value, password):
  156. return md5_apr1.verify(password, hash_value)
  157. def is_authenticated(self, user, password):
  158. # The content of the file is not cached because reading is generally a
  159. # very cheap operation, and it's useful to get live updates of the
  160. # htpasswd file.
  161. with open(self.filename) as fd:
  162. for line in fd:
  163. line = line.strip()
  164. if line:
  165. login, hash_value = line.split(":")
  166. if login == user and self.verify(hash_value, password):
  167. return True
  168. # Random timer to avoid timing oracles and simple bruteforce attacks
  169. time.sleep(1 + random.random())
  170. return False