__init__.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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-2025 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 threading
  29. import time
  30. from typing import Sequence, Set, Tuple, Union, final
  31. from radicale import config, types, utils
  32. from radicale.log import logger
  33. INTERNAL_TYPES: Sequence[str] = ("none", "remote_user", "http_x_remote_user",
  34. "denyall",
  35. "htpasswd",
  36. "ldap",
  37. "dovecot")
  38. def load(configuration: "config.Configuration") -> "BaseAuth":
  39. """Load the authentication module chosen in configuration."""
  40. if configuration.get("auth", "type") == "none":
  41. logger.warning("No user authentication is selected: '[auth] type=none' (insecure)")
  42. if configuration.get("auth", "type") == "denyall":
  43. logger.warning("All access is blocked by: '[auth] type=denyall'")
  44. return utils.load_plugin(INTERNAL_TYPES, "auth", "Auth", BaseAuth,
  45. configuration)
  46. class BaseAuth:
  47. _ldap_groups: Set[str] = set([])
  48. _lc_username: bool
  49. _uc_username: bool
  50. _strip_domain: bool
  51. _type: str
  52. _cache_logins: bool
  53. _cache_successful: dict # login -> (digest, time_ns)
  54. _cache_successful_logins_expiry: int
  55. _cache_failed: dict # digest_failed -> (time_ns, login)
  56. _cache_failed_logins_expiry: int
  57. _cache_failed_logins_salt_ns: int # persistent over runtime
  58. _lock: threading.Lock
  59. def __init__(self, configuration: "config.Configuration") -> None:
  60. """Initialize BaseAuth.
  61. ``configuration`` see ``radicale.config`` module.
  62. The ``configuration`` must not change during the lifetime of
  63. this object, it is kept as an internal reference.
  64. """
  65. self.configuration = configuration
  66. self._lc_username = configuration.get("auth", "lc_username")
  67. self._uc_username = configuration.get("auth", "uc_username")
  68. self._strip_domain = configuration.get("auth", "strip_domain")
  69. logger.info("auth.strip_domain: %s", self._strip_domain)
  70. logger.info("auth.lc_username: %s", self._lc_username)
  71. logger.info("auth.uc_username: %s", self._uc_username)
  72. if self._lc_username is True and self._uc_username is True:
  73. raise RuntimeError("auth.lc_username and auth.uc_username cannot be enabled together")
  74. # cache_successful_logins
  75. self._cache_logins = configuration.get("auth", "cache_logins")
  76. self._type = configuration.get("auth", "type")
  77. if (self._type in ["dovecot", "ldap", "htpasswd"]) or (self._cache_logins is False):
  78. logger.info("auth.cache_logins: %s", self._cache_logins)
  79. else:
  80. logger.info("auth.cache_logins: %s (but not required for type '%s' and disabled therefore)", self._cache_logins, self._type)
  81. self._cache_logins = False
  82. if self._cache_logins is True:
  83. self._cache_successful_logins_expiry = configuration.get("auth", "cache_successful_logins_expiry")
  84. if self._cache_successful_logins_expiry < 0:
  85. raise RuntimeError("self._cache_successful_logins_expiry cannot be < 0")
  86. self._cache_failed_logins_expiry = configuration.get("auth", "cache_failed_logins_expiry")
  87. if self._cache_failed_logins_expiry < 0:
  88. raise RuntimeError("self._cache_failed_logins_expiry cannot be < 0")
  89. logger.info("auth.cache_successful_logins_expiry: %s seconds", self._cache_successful_logins_expiry)
  90. logger.info("auth.cache_failed_logins_expiry: %s seconds", self._cache_failed_logins_expiry)
  91. # cache init
  92. self._cache_successful = dict()
  93. self._cache_failed = dict()
  94. self._cache_failed_logins_salt_ns = time.time_ns()
  95. self._lock = threading.Lock()
  96. def _cache_digest(self, login: str, password: str, salt: str) -> str:
  97. h = hashlib.sha3_512()
  98. h.update(salt.encode())
  99. h.update(login.encode())
  100. h.update(password.encode())
  101. return str(h.digest())
  102. def get_external_login(self, environ: types.WSGIEnviron) -> Union[
  103. Tuple[()], Tuple[str, str]]:
  104. """Optionally provide the login and password externally.
  105. ``environ`` a dict with the WSGI environment
  106. If ``()`` is returned, Radicale handles HTTP authentication.
  107. Otherwise, returns a tuple ``(login, password)``. For anonymous users
  108. ``login`` must be ``""``.
  109. """
  110. return ()
  111. def _login(self, login: str, password: str) -> str:
  112. """Check credentials and map login to internal user
  113. ``login`` the login name
  114. ``password`` the password
  115. Returns the username or ``""`` for invalid credentials.
  116. """
  117. raise NotImplementedError
  118. @final
  119. def login(self, login: str, password: str) -> str:
  120. if self._lc_username:
  121. login = login.lower()
  122. if self._uc_username:
  123. login = login.upper()
  124. if self._strip_domain:
  125. login = login.split('@')[0]
  126. if self._cache_logins is True:
  127. # time_ns is also used as salt
  128. result = ""
  129. digest = ""
  130. time_ns = time.time_ns()
  131. # cleanup failed login cache to avoid out-of-memory
  132. cache_failed_entries = len(self._cache_failed)
  133. if cache_failed_entries > 0:
  134. logger.debug("Login failed cache investigation start (entries: %d)", cache_failed_entries)
  135. self._lock.acquire()
  136. cache_failed_cleanup = dict()
  137. for digest in self._cache_failed:
  138. (time_ns_cache, login_cache) = self._cache_failed[digest]
  139. age_failed = int((time_ns - time_ns_cache) / 1000 / 1000 / 1000)
  140. if age_failed > self._cache_failed_logins_expiry:
  141. cache_failed_cleanup[digest] = (login_cache, age_failed)
  142. cache_failed_cleanup_entries = len(cache_failed_cleanup)
  143. logger.debug("Login failed cache cleanup start (entries: %d)", cache_failed_cleanup_entries)
  144. if cache_failed_cleanup_entries > 0:
  145. for digest in cache_failed_cleanup:
  146. (login, age_failed) = cache_failed_cleanup[digest]
  147. logger.debug("Login failed cache entry for user+password expired: '%s' (age: %d > %d sec)", login_cache, age_failed, self._cache_failed_logins_expiry)
  148. del self._cache_failed[digest]
  149. self._lock.release()
  150. logger.debug("Login failed cache investigation finished")
  151. # check for cache failed login
  152. digest_failed = login + ":" + self._cache_digest(login, password, str(self._cache_failed_logins_salt_ns))
  153. if self._cache_failed.get(digest_failed):
  154. # login+password found in cache "failed" -> shortcut return
  155. (time_ns_cache, login_cache) = self._cache_failed[digest]
  156. age_failed = int((time_ns - time_ns_cache) / 1000 / 1000 / 1000)
  157. logger.debug("Login failed cache entry for user+password found: '%s' (age: %d sec)", login_cache, age_failed)
  158. return ""
  159. if self._cache_successful.get(login):
  160. # login found in cache "successful"
  161. (digest_cache, time_ns_cache) = self._cache_successful[login]
  162. digest = self._cache_digest(login, password, str(time_ns_cache))
  163. if digest == digest_cache:
  164. age_success = int((time_ns - time_ns_cache) / 1000 / 1000 / 1000)
  165. if age_success > self._cache_successful_logins_expiry:
  166. 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)
  167. # delete expired success from cache
  168. del self._cache_successful[login]
  169. digest = ""
  170. else:
  171. logger.debug("Login successful cache entry for user+password found: '%s' (age: %d sec)", login, age_success)
  172. result = login
  173. else:
  174. logger.debug("Login successful cache entry for user+password not matching: '%s'", login)
  175. else:
  176. # login not found in cache, caculate always to avoid timing attacks
  177. digest = self._cache_digest(login, password, str(time_ns))
  178. if result == "":
  179. # verify login+password via configured backend
  180. logger.debug("Login verification for user+password via backend: '%s'", login)
  181. result = self._login(login, password)
  182. if result != "":
  183. logger.debug("Login successful for user+password via backend: '%s'", login)
  184. if digest == "":
  185. # successful login, but expired, digest must be recalculated
  186. digest = self._cache_digest(login, password, str(time_ns))
  187. # store successful login in cache
  188. self._lock.acquire()
  189. self._cache_successful[login] = (digest, time_ns)
  190. self._lock.release()
  191. logger.debug("Login successful cache for user set: '%s'", login)
  192. if self._cache_failed.get(digest_failed):
  193. logger.debug("Login failed cache for user cleared: '%s'", login)
  194. del self._cache_failed[digest_failed]
  195. else:
  196. logger.debug("Login failed for user+password via backend: '%s'", login)
  197. self._lock.acquire()
  198. self._cache_failed[digest_failed] = (time_ns, login)
  199. self._lock.release()
  200. logger.debug("Login failed cache for user set: '%s'", login)
  201. return result
  202. else:
  203. return self._login(login, password)