auth.py 7.5 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-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) manages
  22. a file for storing user credentials. It can encrypt passwords using different
  23. methods, e.g. BCRYPT, MD5-APR1 (a version of MD5 modified for Apache), SHA1, or
  24. by using the system's CRYPT routine. The CRYPT and SHA1 encryption methods
  25. implemented by htpasswd are considered as insecure. MD5-APR1 provides medium
  26. security as of 2015. Only BCRYPT can be considered secure by current standards.
  27. MD5-APR1-encrypted credentials can be written by all versions of htpasswd (it
  28. is the default, in fact), whereas BCRYPT requires htpasswd 2.4.x or newer.
  29. The `is_authenticated(user, password)` function provided by this module
  30. verifies the user-given credentials by parsing the htpasswd credential file
  31. pointed to by the ``htpasswd_filename`` configuration value while assuming
  32. the password encryption method specified via the ``htpasswd_encryption``
  33. configuration value.
  34. The following htpasswd password encrpytion methods are supported by Radicale
  35. out-of-the-box:
  36. - plain-text (created by htpasswd -p...) -- INSECURE
  37. - CRYPT (created by htpasswd -d...) -- INSECURE
  38. - SHA1 (created by htpasswd -s...) -- INSECURE
  39. When passlib (https://pypi.python.org/pypi/passlib) is importable, the
  40. following significantly more secure schemes are parsable by Radicale:
  41. - MD5-APR1 (htpasswd -m...) -- htpasswd's default method
  42. - BCRYPT (htpasswd -B...) -- Requires htpasswd 2.4.x
  43. """
  44. import functools
  45. import base64
  46. import hashlib
  47. import os
  48. from importlib import import_module
  49. def load(configuration, logger):
  50. """Load the authentication manager chosen in configuration."""
  51. auth_type = configuration.get("auth", "type")
  52. logger.debug("Authentication type is %s" % auth_type)
  53. if auth_type == "None":
  54. return lambda user, password: True
  55. elif auth_type == "htpasswd":
  56. return Auth(configuration, logger).is_authenticated
  57. else:
  58. module = import_module(auth_type)
  59. return module.Auth(configuration, logger).is_authenticated
  60. class BaseAuth:
  61. def __init__(self, configuration, logger):
  62. self.configuration = configuration
  63. self.logger = logger
  64. def is_authenticated(self, user, password):
  65. """Validate credentials.
  66. Iterate through htpasswd credential file until user matches, extract hash
  67. (encrypted password) and check hash against user-given password, using the
  68. method specified in the Radicale config.
  69. """
  70. raise NotImplementedError
  71. class Auth(BaseAuth):
  72. def __init__(self, configuration, logger):
  73. super().__init__(configuration, logger)
  74. self.filename = os.path.expanduser(
  75. configuration.get("auth", "htpasswd_filename"))
  76. self.encryption = configuration.get("auth", "htpasswd_encryption")
  77. if self.encryption == "ssha":
  78. self.verify = self._ssha
  79. elif self.encryption == "sha1":
  80. self.verify = self._sha1
  81. elif self.encryption == "plain":
  82. self.verify = self._plain
  83. elif self.encryption == "md5":
  84. try:
  85. from passlib.hash import apr_md5_crypt
  86. except ImportError:
  87. raise RuntimeError(
  88. "The htpasswd encryption method 'md5' requires "
  89. "the passlib module.")
  90. self.verify = functools.partial(self._md5apr1, apr_md5_crypt)
  91. elif self.encryption == "bcrypt":
  92. try:
  93. from passlib.hash import bcrypt
  94. except ImportError:
  95. raise RuntimeError(
  96. "The htpasswd encryption method 'bcrypt' requires "
  97. "the passlib module with bcrypt support.")
  98. # A call to `encrypt` raises passlib.exc.MissingBackendError with a
  99. # good error message if bcrypt backend is not available. Trigger
  100. # this here.
  101. bcrypt.encrypt("test-bcrypt-backend")
  102. self.verify = functools.partial(self._bcrypt, bcrypt)
  103. elif self.encryption == "crypt":
  104. try:
  105. import crypt
  106. except ImportError:
  107. raise RuntimeError(
  108. "The htpasswd encryption method 'crypt' requires "
  109. "the crypt() system support.")
  110. self.verify = functools.partial(self._crypt, crypt)
  111. else:
  112. raise RuntimeError(
  113. "The htpasswd encryption method '%s' is not "
  114. "supported." % self.encryption)
  115. def _plain(self, hash_value, password):
  116. """Check if ``hash_value`` and ``password`` match, using plain method."""
  117. return hash_value == password
  118. def _crypt(self, crypt, hash_value, password):
  119. """Check if ``hash_value`` and ``password`` match, using crypt method."""
  120. return crypt.crypt(password, hash_value) == hash_value
  121. def _sha1(self, hash_value, password):
  122. """Check if ``hash_value`` and ``password`` match, using sha1 method."""
  123. hash_value = hash_value.replace("{SHA}", "").encode("ascii")
  124. password = password.encode(self.configuration.get("encoding", "stock"))
  125. sha1 = hashlib.sha1() # pylint: disable=E1101
  126. sha1.update(password)
  127. return sha1.digest() == base64.b64decode(hash_value)
  128. def _ssha(self, hash_salt_value, password):
  129. """Check if ``hash_salt_value`` and ``password`` match, using salted sha1
  130. method. This method is not directly supported by htpasswd, but it can be
  131. written with e.g. openssl, and nginx can parse it."""
  132. hash_salt_value = hash_salt_value.replace(
  133. "{SSHA}", "").encode("ascii").decode('base64')
  134. password = password.encode(self.configuration.get("encoding", "stock"))
  135. hash_value = hash_salt_value[:20]
  136. salt_value = hash_salt_value[20:]
  137. sha1 = hashlib.sha1() # pylint: disable=E1101
  138. sha1.update(password)
  139. sha1.update(salt_value)
  140. return sha1.digest() == hash_value
  141. def _bcrypt(self, bcrypt, hash_value, password):
  142. return bcrypt.verify(password, hash_value)
  143. def _md5apr1(self, md5_apr1, hash_value, password):
  144. return md5_apr1.verify(password, hash_value)
  145. def is_authenticated(self, user, password):
  146. # The content of the file is not cached because reading is generally a
  147. # very cheap operation, and it's useful to get live updates of the
  148. # htpasswd file.
  149. with open(self.filename) as fd:
  150. for line in fd:
  151. line = line.strip()
  152. if line:
  153. login, hash_value = line.split(":")
  154. if login == user:
  155. return self.verify(hash_value, password)
  156. return False