__init__.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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. "imap",
  38. "oauth2",
  39. "pam",
  40. "dovecot")
  41. CACHE_LOGIN_TYPES: Sequence[str] = (
  42. "dovecot",
  43. "ldap",
  44. "htpasswd",
  45. "imap",
  46. "oauth2",
  47. "pam",
  48. )
  49. INSECURE_IF_NO_LOOPBACK_TYPES: Sequence[str] = (
  50. "remote_user",
  51. "http_x_remote_user",
  52. )
  53. AUTH_SOCKET_FAMILY: Sequence[str] = ("AF_UNIX", "AF_INET", "AF_INET6")
  54. def load(configuration: "config.Configuration") -> "BaseAuth":
  55. """Load the authentication module chosen in configuration."""
  56. _type = configuration.get("auth", "type")
  57. if _type == "none":
  58. logger.warning("No user authentication is selected: '[auth] type=none' (INSECURE)")
  59. elif _type == "denyall":
  60. logger.warning("All user authentication is blocked by: '[auth] type=denyall'")
  61. elif _type in INSECURE_IF_NO_LOOPBACK_TYPES:
  62. hosts: List[Tuple[str, int]] = configuration.get("server", "hosts")
  63. localhost_only = True
  64. address_lo = []
  65. address = []
  66. for address_port in hosts:
  67. if address_port[0] in [ "localhost", "localhost6", "127.0.0.1", "::1" ]:
  68. address_lo.append(utils.format_address(address_port))
  69. else:
  70. address.append(utils.format_address(address_port))
  71. localhost_only = False
  72. if localhost_only is False:
  73. logger.warning("User authentication '[auth] type=%s' is selected but server is not only listen on loopback address (potentially INSECURE): %s", _type, " ".join(address))
  74. return utils.load_plugin(INTERNAL_TYPES, "auth", "Auth", BaseAuth,
  75. configuration)
  76. class BaseAuth:
  77. _ldap_groups: Set[str] = set([])
  78. _lc_username: bool
  79. _uc_username: bool
  80. _strip_domain: bool
  81. _auth_delay: float
  82. _failed_auth_delay: float
  83. _type: str
  84. _cache_logins: bool
  85. _cache_successful: dict # login -> (digest, time_ns)
  86. _cache_successful_logins_expiry: int
  87. _cache_failed: dict # digest_failed -> (time_ns, login)
  88. _cache_failed_logins_expiry: int
  89. _cache_failed_logins_salt_ns: int # persistent over runtime
  90. _lock: threading.Lock
  91. def __init__(self, configuration: "config.Configuration") -> None:
  92. """Initialize BaseAuth.
  93. ``configuration`` see ``radicale.config`` module.
  94. The ``configuration`` must not change during the lifetime of
  95. this object, it is kept as an internal reference.
  96. """
  97. self.configuration = configuration
  98. self._lc_username = configuration.get("auth", "lc_username")
  99. self._uc_username = configuration.get("auth", "uc_username")
  100. self._strip_domain = configuration.get("auth", "strip_domain")
  101. logger.info("auth.strip_domain: %s", self._strip_domain)
  102. logger.info("auth.lc_username: %s", self._lc_username)
  103. logger.info("auth.uc_username: %s", self._uc_username)
  104. if self._lc_username is True and self._uc_username is True:
  105. raise RuntimeError("auth.lc_username and auth.uc_username cannot be enabled together")
  106. self._auth_delay = configuration.get("auth", "delay")
  107. logger.info("auth.delay: %f", self._auth_delay)
  108. self._failed_auth_delay = 0
  109. self._lock = threading.Lock()
  110. # cache_successful_logins
  111. self._cache_logins = configuration.get("auth", "cache_logins")
  112. self._type = configuration.get("auth", "type")
  113. if (self._type in CACHE_LOGIN_TYPES) or (self._cache_logins is False):
  114. logger.info("auth.cache_logins: %s", self._cache_logins)
  115. else:
  116. logger.info("auth.cache_logins: %s (but not required for type '%s' and disabled therefore)", self._cache_logins, self._type)
  117. self._cache_logins = False
  118. if self._cache_logins is True:
  119. self._cache_successful_logins_expiry = configuration.get("auth", "cache_successful_logins_expiry")
  120. if self._cache_successful_logins_expiry < 0:
  121. raise RuntimeError("self._cache_successful_logins_expiry cannot be < 0")
  122. self._cache_failed_logins_expiry = configuration.get("auth", "cache_failed_logins_expiry")
  123. if self._cache_failed_logins_expiry < 0:
  124. raise RuntimeError("self._cache_failed_logins_expiry cannot be < 0")
  125. logger.info("auth.cache_successful_logins_expiry: %s seconds", self._cache_successful_logins_expiry)
  126. logger.info("auth.cache_failed_logins_expiry: %s seconds", self._cache_failed_logins_expiry)
  127. # cache init
  128. self._cache_successful = dict()
  129. self._cache_failed = dict()
  130. self._cache_failed_logins_salt_ns = time.time_ns()
  131. def _cache_digest(self, login: str, password: str, salt: str) -> str:
  132. h = hashlib.sha3_512()
  133. h.update(salt.encode())
  134. h.update(login.encode())
  135. h.update(password.encode())
  136. return str(h.digest())
  137. def get_external_login(self, environ: types.WSGIEnviron) -> Union[
  138. Tuple[()], Tuple[str, str]]:
  139. """Optionally provide the login and password externally.
  140. ``environ`` a dict with the WSGI environment
  141. If ``()`` is returned, Radicale handles HTTP authentication.
  142. Otherwise, returns a tuple ``(login, password)``. For anonymous users
  143. ``login`` must be ``""``.
  144. """
  145. return ()
  146. def _login(self, login: str, password: str) -> str:
  147. """Check credentials and map login to internal user
  148. ``login`` the login name
  149. ``password`` the password
  150. Returns the username or ``""`` for invalid credentials.
  151. """
  152. raise NotImplementedError
  153. def _sleep_for_constant_exec_time(self, time_ns_begin: int):
  154. """Sleep some time to reach a constant execution time for failed logins
  155. Independent of time required by external backend or used digest methods
  156. Increase final execution time in case initial limit exceeded
  157. See also issue 591
  158. """
  159. time_delta = (time.time_ns() - time_ns_begin) / 1000 / 1000 / 1000
  160. with self._lock:
  161. # avoid that another thread is changing global value at the same time
  162. failed_auth_delay = self._failed_auth_delay
  163. failed_auth_delay_old = failed_auth_delay
  164. if time_delta > failed_auth_delay:
  165. # set new
  166. failed_auth_delay = time_delta
  167. # store globally
  168. self._failed_auth_delay = failed_auth_delay
  169. if (failed_auth_delay_old != failed_auth_delay):
  170. logger.debug("Failed login constant execution time need increase of failed_auth_delay: %.9f -> %.9f sec", failed_auth_delay_old, failed_auth_delay)
  171. # sleep == 0
  172. else:
  173. sleep = failed_auth_delay - time_delta
  174. logger.debug("Failed login constant exection time alignment, sleeping: %.9f sec", sleep)
  175. time.sleep(sleep)
  176. @final
  177. def login(self, login: str, password: str) -> Tuple[str, str]:
  178. time_ns_begin = time.time_ns()
  179. result_from_cache = False
  180. if self._lc_username:
  181. login = login.lower()
  182. if self._uc_username:
  183. login = login.upper()
  184. if self._strip_domain:
  185. login = login.split('@')[0]
  186. if self._cache_logins is True:
  187. # time_ns is also used as salt
  188. result = ""
  189. digest = ""
  190. time_ns = time.time_ns()
  191. # cleanup failed login cache to avoid out-of-memory
  192. cache_failed_entries = len(self._cache_failed)
  193. if cache_failed_entries > 0:
  194. logger.debug("Login failed cache investigation start (entries: %d)", cache_failed_entries)
  195. self._lock.acquire()
  196. cache_failed_cleanup = dict()
  197. for digest in self._cache_failed:
  198. (time_ns_cache, login_cache) = self._cache_failed[digest]
  199. age_failed = int((time_ns - time_ns_cache) / 1000 / 1000 / 1000)
  200. if age_failed > self._cache_failed_logins_expiry:
  201. cache_failed_cleanup[digest] = (login_cache, age_failed)
  202. cache_failed_cleanup_entries = len(cache_failed_cleanup)
  203. logger.debug("Login failed cache cleanup start (entries: %d)", cache_failed_cleanup_entries)
  204. if cache_failed_cleanup_entries > 0:
  205. for digest in cache_failed_cleanup:
  206. (login, age_failed) = cache_failed_cleanup[digest]
  207. logger.debug("Login failed cache entry for user+password expired: '%s' (age: %d > %d sec)", login_cache, age_failed, self._cache_failed_logins_expiry)
  208. del self._cache_failed[digest]
  209. self._lock.release()
  210. logger.debug("Login failed cache investigation finished")
  211. # check for cache failed login
  212. digest_failed = login + ":" + self._cache_digest(login, password, str(self._cache_failed_logins_salt_ns))
  213. if self._cache_failed.get(digest_failed):
  214. # login+password found in cache "failed" -> shortcut return
  215. (time_ns_cache, login_cache) = self._cache_failed[digest]
  216. age_failed = int((time_ns - time_ns_cache) / 1000 / 1000 / 1000)
  217. logger.debug("Login failed cache entry for user+password found: '%s' (age: %d sec)", login_cache, age_failed)
  218. self._sleep_for_constant_exec_time(time_ns_begin)
  219. return ("", self._type + " / cached")
  220. if self._cache_successful.get(login):
  221. # login found in cache "successful"
  222. (digest_cache, time_ns_cache) = self._cache_successful[login]
  223. digest = self._cache_digest(login, password, str(time_ns_cache))
  224. if digest == digest_cache:
  225. age_success = int((time_ns - time_ns_cache) / 1000 / 1000 / 1000)
  226. if age_success > self._cache_successful_logins_expiry:
  227. 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)
  228. # delete expired success from cache
  229. del self._cache_successful[login]
  230. digest = ""
  231. else:
  232. logger.debug("Login successful cache entry for user+password found: '%s' (age: %d sec)", login, age_success)
  233. result = login
  234. result_from_cache = True
  235. else:
  236. logger.debug("Login successful cache entry for user+password not matching: '%s'", login)
  237. else:
  238. # login not found in cache, caculate always to avoid timing attacks
  239. digest = self._cache_digest(login, password, str(time_ns))
  240. if result == "":
  241. # verify login+password via configured backend
  242. logger.debug("Login verification for user+password via backend: '%s'", login)
  243. result = self._login(login, password)
  244. if result != "":
  245. logger.debug("Login successful for user+password via backend: '%s'", login)
  246. if digest == "":
  247. # successful login, but expired, digest must be recalculated
  248. digest = self._cache_digest(login, password, str(time_ns))
  249. # store successful login in cache
  250. self._lock.acquire()
  251. self._cache_successful[login] = (digest, time_ns)
  252. self._lock.release()
  253. logger.debug("Login successful cache for user set: '%s'", login)
  254. if self._cache_failed.get(digest_failed):
  255. logger.debug("Login failed cache for user cleared: '%s'", login)
  256. del self._cache_failed[digest_failed]
  257. else:
  258. logger.debug("Login failed for user+password via backend: '%s'", login)
  259. self._lock.acquire()
  260. self._cache_failed[digest_failed] = (time_ns, login)
  261. self._lock.release()
  262. logger.debug("Login failed cache for user set: '%s'", login)
  263. if result_from_cache is True:
  264. if result == "":
  265. self._sleep_for_constant_exec_time(time_ns_begin)
  266. return (result, self._type + " / cached")
  267. else:
  268. if result == "":
  269. self._sleep_for_constant_exec_time(time_ns_begin)
  270. return (result, self._type)
  271. else:
  272. # self._cache_logins is False
  273. result = self._login(login, password)
  274. if result == "":
  275. self._sleep_for_constant_exec_time(time_ns_begin)
  276. return (result, self._type)