__init__.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. # This file is part of Radicale - CalDAV and CardDAV server
  2. # Copyright © 2008 Nicolas Kandel
  3. # Copyright © 2008 Pascal Halter
  4. # Copyright © 2008-2017 Guillaume Ayoub
  5. # Copyright © 2017-2022 Unrud <unrud@outlook.com>
  6. # Copyright © 2024-2024 Peter Bieringer <pb@bieringer.de>
  7. #
  8. # This library is free software: you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation, either version 3 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This library is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License
  19. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  20. """
  21. Authentication module.
  22. Authentication is based on usernames and passwords. If something more
  23. advanced is needed an external WSGI server or reverse proxy can be used
  24. (see ``remote_user`` or ``http_x_remote_user`` backend).
  25. Take a look at the class ``BaseAuth`` if you want to implement your own.
  26. """
  27. import hashlib
  28. import time
  29. from typing import Sequence, Set, Tuple, Union, final
  30. from radicale import config, types, utils
  31. from radicale.log import logger
  32. INTERNAL_TYPES: Sequence[str] = ("none", "remote_user", "http_x_remote_user",
  33. "denyall",
  34. "htpasswd",
  35. "ldap",
  36. "dovecot")
  37. def load(configuration: "config.Configuration") -> "BaseAuth":
  38. """Load the authentication module chosen in configuration."""
  39. if configuration.get("auth", "type") == "none":
  40. logger.warning("No user authentication is selected: '[auth] type=none' (insecure)")
  41. if configuration.get("auth", "type") == "denyall":
  42. logger.warning("All access is blocked by: '[auth] type=denyall'")
  43. return utils.load_plugin(INTERNAL_TYPES, "auth", "Auth", BaseAuth,
  44. configuration)
  45. class BaseAuth:
  46. _ldap_groups: Set[str] = set([])
  47. _lc_username: bool
  48. _uc_username: bool
  49. _strip_domain: bool
  50. _cache_logins: bool
  51. _cache_successful: dict # login -> (digest, time_ns)
  52. _cache_successful_logins_expiry: int
  53. _cache_failed: dict # digest_failed -> (time_ns)
  54. _cache_failed_logins_expiry: int
  55. _cache_failed_logins_salt_ns: int # persistent over runtime
  56. def __init__(self, configuration: "config.Configuration") -> None:
  57. """Initialize BaseAuth.
  58. ``configuration`` see ``radicale.config`` module.
  59. The ``configuration`` must not change during the lifetime of
  60. this object, it is kept as an internal reference.
  61. """
  62. self.configuration = configuration
  63. self._lc_username = configuration.get("auth", "lc_username")
  64. self._uc_username = configuration.get("auth", "uc_username")
  65. self._strip_domain = configuration.get("auth", "strip_domain")
  66. self._cache_logins = configuration.get("auth", "cache_logins")
  67. self._cache_successful_logins_expiry = configuration.get("auth", "cache_successful_logins_expiry")
  68. if self._cache_successful_logins_expiry < 0:
  69. raise RuntimeError("self._cache_successful_logins_expiry cannot be < 0")
  70. self._cache_failed_logins_expiry = configuration.get("auth", "cache_failed_logins_expiry")
  71. if self._cache_failed_logins_expiry < 0:
  72. raise RuntimeError("self._cache_failed_logins_expiry cannot be < 0")
  73. logger.info("auth.strip_domain: %s", self._strip_domain)
  74. logger.info("auth.lc_username: %s", self._lc_username)
  75. logger.info("auth.uc_username: %s", self._uc_username)
  76. if self._lc_username is True and self._uc_username is True:
  77. raise RuntimeError("auth.lc_username and auth.uc_username cannot be enabled together")
  78. # cache_successful_logins
  79. logger.info("auth.cache_logins: %s", self._cache_logins)
  80. self._cache_successful = dict()
  81. self._cache_failed = dict()
  82. self._cache_failed_logins_salt_ns = time.time_ns()
  83. if self._cache_logins is True:
  84. logger.info("auth.cache_successful_logins_expiry: %s seconds", self._cache_successful_logins_expiry)
  85. logger.info("auth.cache_failed_logins_expiry: %s seconds", self._cache_failed_logins_expiry)
  86. def _cache_digest(self, login: str, password: str, salt: str) -> str:
  87. h = hashlib.sha3_512()
  88. h.update(salt.encode())
  89. h.update(login.encode())
  90. h.update(password.encode())
  91. return str(h.digest())
  92. def get_external_login(self, environ: types.WSGIEnviron) -> Union[
  93. Tuple[()], Tuple[str, str]]:
  94. """Optionally provide the login and password externally.
  95. ``environ`` a dict with the WSGI environment
  96. If ``()`` is returned, Radicale handles HTTP authentication.
  97. Otherwise, returns a tuple ``(login, password)``. For anonymous users
  98. ``login`` must be ``""``.
  99. """
  100. return ()
  101. def _login(self, login: str, password: str) -> str:
  102. """Check credentials and map login to internal user
  103. ``login`` the login name
  104. ``password`` the password
  105. Returns the username or ``""`` for invalid credentials.
  106. """
  107. raise NotImplementedError
  108. @final
  109. def login(self, login: str, password: str) -> str:
  110. if self._lc_username:
  111. login = login.lower()
  112. if self._uc_username:
  113. login = login.upper()
  114. if self._strip_domain:
  115. login = login.split('@')[0]
  116. if self._cache_logins is True:
  117. # time_ns is also used as salt
  118. result = ""
  119. digest = ""
  120. time_ns = time.time_ns()
  121. digest_failed = login + ":" + self._cache_digest(login, password, str(self._cache_failed_logins_salt_ns))
  122. if self._cache_failed.get(digest_failed):
  123. # login+password found in cache "failed"
  124. time_ns_cache = self._cache_failed[digest_failed]
  125. age_failed = int((time_ns - time_ns_cache) / 1000 / 1000 / 1000)
  126. if age_failed > self._cache_failed_logins_expiry:
  127. logger.debug("Login failed cache entry for user+password found but expired: '%s' (age: %d > %d sec)", login, age_failed, self._cache_failed_logins_expiry)
  128. # delete expired failed from cache
  129. del self._cache_failed[digest_failed]
  130. else:
  131. # shortcut return
  132. logger.debug("Login failed cache entry for user+password found: '%s' (age: %d sec)", login, age_failed)
  133. return ""
  134. if self._cache_successful.get(login):
  135. # login found in cache "successful"
  136. (digest_cache, time_ns_cache) = self._cache_successful[login]
  137. digest = self._cache_digest(login, password, str(time_ns_cache))
  138. if digest == digest_cache:
  139. age_success = int((time_ns - time_ns_cache) / 1000 / 1000 / 1000)
  140. if age_success > self._cache_successful_logins_expiry:
  141. logger.debug("Login successful cache entry for user+password found but expired: '%s' (age: %d > %d sec)", login, age_success, self._cache_successful_logins_expiry)
  142. # delete expired success from cache
  143. del self._cache_successful[login]
  144. digest = ""
  145. else:
  146. logger.debug("Login successful cache entry for user+password found: '%s' (age: %d sec)", login, age_success)
  147. result = login
  148. else:
  149. logger.debug("Login successful cache entry for user+password not matching: '%s'", login)
  150. else:
  151. # login not found in cache, caculate always to avoid timing attacks
  152. digest = self._cache_digest(login, password, str(time_ns))
  153. if result == "":
  154. # verify login+password via configured backend
  155. logger.debug("Login verification for user+password via backend: '%s'", login)
  156. result = self._login(login, password)
  157. if result != "":
  158. logger.debug("Login successful for user+password via backend: '%s'", login)
  159. if digest == "":
  160. # successful login, but expired, digest must be recalculated
  161. digest = self._cache_digest(login, password, str(time_ns))
  162. # store successful login in cache
  163. self._cache_successful[login] = (digest, time_ns)
  164. logger.debug("Login successful cache for user set: '%s'", login)
  165. if self._cache_failed.get(digest_failed):
  166. logger.debug("Login failed cache for user cleared: '%s'", login)
  167. del self._cache_failed[digest_failed]
  168. else:
  169. logger.debug("Login failed for user+password via backend: '%s'", login)
  170. self._cache_failed[digest_failed] = time_ns
  171. logger.debug("Login failed cache for user set: '%s'", login)
  172. return result
  173. else:
  174. return self._login(login, password)