__init__.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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. _auth_delay: float
  52. _failed_auth_delay: float
  53. _type: str
  54. _cache_logins: bool
  55. _cache_successful: dict # login -> (digest, time_ns)
  56. _cache_successful_logins_expiry: int
  57. _cache_failed: dict # digest_failed -> (time_ns, login)
  58. _cache_failed_logins_expiry: int
  59. _cache_failed_logins_salt_ns: int # persistent over runtime
  60. _lock: threading.Lock
  61. def __init__(self, configuration: "config.Configuration") -> None:
  62. """Initialize BaseAuth.
  63. ``configuration`` see ``radicale.config`` module.
  64. The ``configuration`` must not change during the lifetime of
  65. this object, it is kept as an internal reference.
  66. """
  67. self.configuration = configuration
  68. self._lc_username = configuration.get("auth", "lc_username")
  69. self._uc_username = configuration.get("auth", "uc_username")
  70. self._strip_domain = configuration.get("auth", "strip_domain")
  71. logger.info("auth.strip_domain: %s", self._strip_domain)
  72. logger.info("auth.lc_username: %s", self._lc_username)
  73. logger.info("auth.uc_username: %s", self._uc_username)
  74. if self._lc_username is True and self._uc_username is True:
  75. raise RuntimeError("auth.lc_username and auth.uc_username cannot be enabled together")
  76. self._auth_delay = configuration.get("auth", "delay")
  77. logger.info("auth.delay: %f", self._auth_delay)
  78. self._failed_auth_delay = self._auth_delay
  79. # cache_successful_logins
  80. self._cache_logins = configuration.get("auth", "cache_logins")
  81. self._type = configuration.get("auth", "type")
  82. if (self._type in ["dovecot", "ldap", "htpasswd"]) or (self._cache_logins is False):
  83. logger.info("auth.cache_logins: %s", self._cache_logins)
  84. else:
  85. logger.info("auth.cache_logins: %s (but not required for type '%s' and disabled therefore)", self._cache_logins, self._type)
  86. self._cache_logins = False
  87. if self._cache_logins is True:
  88. self._cache_successful_logins_expiry = configuration.get("auth", "cache_successful_logins_expiry")
  89. if self._cache_successful_logins_expiry < 0:
  90. raise RuntimeError("self._cache_successful_logins_expiry cannot be < 0")
  91. self._cache_failed_logins_expiry = configuration.get("auth", "cache_failed_logins_expiry")
  92. if self._cache_failed_logins_expiry < 0:
  93. raise RuntimeError("self._cache_failed_logins_expiry cannot be < 0")
  94. logger.info("auth.cache_successful_logins_expiry: %s seconds", self._cache_successful_logins_expiry)
  95. logger.info("auth.cache_failed_logins_expiry: %s seconds", self._cache_failed_logins_expiry)
  96. # cache init
  97. self._cache_successful = dict()
  98. self._cache_failed = dict()
  99. self._cache_failed_logins_salt_ns = time.time_ns()
  100. self._lock = threading.Lock()
  101. def _cache_digest(self, login: str, password: str, salt: str) -> str:
  102. h = hashlib.sha3_512()
  103. h.update(salt.encode())
  104. h.update(login.encode())
  105. h.update(password.encode())
  106. return str(h.digest())
  107. def get_external_login(self, environ: types.WSGIEnviron) -> Union[
  108. Tuple[()], Tuple[str, str]]:
  109. """Optionally provide the login and password externally.
  110. ``environ`` a dict with the WSGI environment
  111. If ``()`` is returned, Radicale handles HTTP authentication.
  112. Otherwise, returns a tuple ``(login, password)``. For anonymous users
  113. ``login`` must be ``""``.
  114. """
  115. return ()
  116. def _login(self, login: str, password: str) -> str:
  117. """Check credentials and map login to internal user
  118. ``login`` the login name
  119. ``password`` the password
  120. Returns the username or ``""`` for invalid credentials.
  121. """
  122. raise NotImplementedError
  123. def _sleep(self, time_ns_begin):
  124. """Sleep some time to reach a constant execution time finally
  125. Increase final execution time in case initial limit exceeded
  126. """
  127. time_delta = (time.time_ns() - time_ns_begin) / 1000 / 1000 / 1000
  128. if time_delta > self._failed_auth_delay:
  129. logger.debug("Increase failed auth_delay %.3f -> %.3f seconds", self._failed_auth_delay, time_delta)
  130. with self._lock:
  131. self._failed_auth_delay = time_delta
  132. sleep = self._failed_auth_delay - time_delta
  133. logger.debug("Sleeping %.3f seconds", sleep)
  134. time.sleep(sleep)
  135. @final
  136. def login(self, login: str, password: str) -> Tuple[str, str]:
  137. time_ns_begin = time.time_ns()
  138. result_from_cache = False
  139. if self._lc_username:
  140. login = login.lower()
  141. if self._uc_username:
  142. login = login.upper()
  143. if self._strip_domain:
  144. login = login.split('@')[0]
  145. if self._cache_logins is True:
  146. # time_ns is also used as salt
  147. result = ""
  148. digest = ""
  149. time_ns = time.time_ns()
  150. # cleanup failed login cache to avoid out-of-memory
  151. cache_failed_entries = len(self._cache_failed)
  152. if cache_failed_entries > 0:
  153. logger.debug("Login failed cache investigation start (entries: %d)", cache_failed_entries)
  154. self._lock.acquire()
  155. cache_failed_cleanup = dict()
  156. for digest in self._cache_failed:
  157. (time_ns_cache, login_cache) = self._cache_failed[digest]
  158. age_failed = int((time_ns - time_ns_cache) / 1000 / 1000 / 1000)
  159. if age_failed > self._cache_failed_logins_expiry:
  160. cache_failed_cleanup[digest] = (login_cache, age_failed)
  161. cache_failed_cleanup_entries = len(cache_failed_cleanup)
  162. logger.debug("Login failed cache cleanup start (entries: %d)", cache_failed_cleanup_entries)
  163. if cache_failed_cleanup_entries > 0:
  164. for digest in cache_failed_cleanup:
  165. (login, age_failed) = cache_failed_cleanup[digest]
  166. logger.debug("Login failed cache entry for user+password expired: '%s' (age: %d > %d sec)", login_cache, age_failed, self._cache_failed_logins_expiry)
  167. del self._cache_failed[digest]
  168. self._lock.release()
  169. logger.debug("Login failed cache investigation finished")
  170. # check for cache failed login
  171. digest_failed = login + ":" + self._cache_digest(login, password, str(self._cache_failed_logins_salt_ns))
  172. if self._cache_failed.get(digest_failed):
  173. # login+password found in cache "failed" -> shortcut return
  174. (time_ns_cache, login_cache) = self._cache_failed[digest]
  175. age_failed = int((time_ns - time_ns_cache) / 1000 / 1000 / 1000)
  176. logger.debug("Login failed cache entry for user+password found: '%s' (age: %d sec)", login_cache, age_failed)
  177. self._sleep(time_ns_begin)
  178. return ("", self._type + " / cached")
  179. if self._cache_successful.get(login):
  180. # login found in cache "successful"
  181. (digest_cache, time_ns_cache) = self._cache_successful[login]
  182. digest = self._cache_digest(login, password, str(time_ns_cache))
  183. if digest == digest_cache:
  184. age_success = int((time_ns - time_ns_cache) / 1000 / 1000 / 1000)
  185. if age_success > self._cache_successful_logins_expiry:
  186. 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)
  187. # delete expired success from cache
  188. del self._cache_successful[login]
  189. digest = ""
  190. else:
  191. logger.debug("Login successful cache entry for user+password found: '%s' (age: %d sec)", login, age_success)
  192. result = login
  193. result_from_cache = True
  194. else:
  195. logger.debug("Login successful cache entry for user+password not matching: '%s'", login)
  196. else:
  197. # login not found in cache, caculate always to avoid timing attacks
  198. digest = self._cache_digest(login, password, str(time_ns))
  199. if result == "":
  200. # verify login+password via configured backend
  201. logger.debug("Login verification for user+password via backend: '%s'", login)
  202. result = self._login(login, password)
  203. if result != "":
  204. logger.debug("Login successful for user+password via backend: '%s'", login)
  205. if digest == "":
  206. # successful login, but expired, digest must be recalculated
  207. digest = self._cache_digest(login, password, str(time_ns))
  208. # store successful login in cache
  209. self._lock.acquire()
  210. self._cache_successful[login] = (digest, time_ns)
  211. self._lock.release()
  212. logger.debug("Login successful cache for user set: '%s'", login)
  213. if self._cache_failed.get(digest_failed):
  214. logger.debug("Login failed cache for user cleared: '%s'", login)
  215. del self._cache_failed[digest_failed]
  216. else:
  217. logger.debug("Login failed for user+password via backend: '%s'", login)
  218. self._lock.acquire()
  219. self._cache_failed[digest_failed] = (time_ns, login)
  220. self._lock.release()
  221. logger.debug("Login failed cache for user set: '%s'", login)
  222. if result_from_cache is True:
  223. if result == "":
  224. self._sleep(time_ns_begin)
  225. return (result, self._type + " / cached")
  226. else:
  227. if result == "":
  228. self._sleep(time_ns_begin)
  229. return (result, self._type)
  230. else:
  231. # self._cache_logins is False
  232. result = self._login(login, password)
  233. if result == "":
  234. self._sleep(time_ns_begin)
  235. return (result, self._type)