__init__.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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-2019 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. Radicale WSGI application.
  22. Can be used with an external WSGI server (see ``radicale.application()``) or
  23. the built-in server (see ``radicale.server`` module).
  24. """
  25. import base64
  26. import datetime
  27. import pprint
  28. import random
  29. import time
  30. import zlib
  31. from http import client
  32. from typing import Iterable, List, Mapping, Tuple, Union
  33. from radicale import config, httputils, log, pathutils, types
  34. from radicale.app.base import ApplicationBase
  35. from radicale.app.delete import ApplicationPartDelete
  36. from radicale.app.get import ApplicationPartGet
  37. from radicale.app.head import ApplicationPartHead
  38. from radicale.app.mkcalendar import ApplicationPartMkcalendar
  39. from radicale.app.mkcol import ApplicationPartMkcol
  40. from radicale.app.move import ApplicationPartMove
  41. from radicale.app.options import ApplicationPartOptions
  42. from radicale.app.post import ApplicationPartPost
  43. from radicale.app.propfind import ApplicationPartPropfind
  44. from radicale.app.proppatch import ApplicationPartProppatch
  45. from radicale.app.put import ApplicationPartPut
  46. from radicale.app.report import ApplicationPartReport
  47. from radicale.log import logger
  48. # Combination of types.WSGIStartResponse and WSGI application return value
  49. _IntermediateResponse = Tuple[str, List[Tuple[str, str]], Iterable[bytes]]
  50. class Application(ApplicationPartDelete, ApplicationPartHead,
  51. ApplicationPartGet, ApplicationPartMkcalendar,
  52. ApplicationPartMkcol, ApplicationPartMove,
  53. ApplicationPartOptions, ApplicationPartPropfind,
  54. ApplicationPartProppatch, ApplicationPartPost,
  55. ApplicationPartPut, ApplicationPartReport, ApplicationBase):
  56. """WSGI application."""
  57. _mask_passwords: bool
  58. _auth_delay: float
  59. _internal_server: bool
  60. _max_content_length: int
  61. _auth_realm: str
  62. _script_name: str
  63. _extra_headers: Mapping[str, str]
  64. _permit_delete_collection: bool
  65. _permit_overwrite_collection: bool
  66. def __init__(self, configuration: config.Configuration) -> None:
  67. """Initialize Application.
  68. ``configuration`` see ``radicale.config`` module.
  69. The ``configuration`` must not change during the lifetime of
  70. this object, it is kept as an internal reference.
  71. """
  72. super().__init__(configuration)
  73. self._mask_passwords = configuration.get("logging", "mask_passwords")
  74. self._bad_put_request_content = configuration.get("logging", "bad_put_request_content")
  75. self._request_header_on_debug = configuration.get("logging", "request_header_on_debug")
  76. self._response_content_on_debug = configuration.get("logging", "response_content_on_debug")
  77. self._auth_delay = configuration.get("auth", "delay")
  78. self._internal_server = configuration.get("server", "_internal_server")
  79. self._script_name = configuration.get("server", "script_name")
  80. if self._script_name:
  81. if self._script_name[0] != "/":
  82. logger.error("server.script_name must start with '/': %r", self._script_name)
  83. raise RuntimeError("server.script_name option has to start with '/'")
  84. else:
  85. if self._script_name.endswith("/"):
  86. logger.error("server.script_name must not end with '/': %r", self._script_name)
  87. raise RuntimeError("server.script_name option must not end with '/'")
  88. else:
  89. logger.info("Provided script name to strip from URI if called by reverse proxy: %r", self._script_name)
  90. else:
  91. logger.info("Default script name to strip from URI if called by reverse proxy is taken from HTTP_X_SCRIPT_NAME or SCRIPT_NAME")
  92. self._max_content_length = configuration.get(
  93. "server", "max_content_length")
  94. self._auth_realm = configuration.get("auth", "realm")
  95. self._permit_delete_collection = configuration.get("rights", "permit_delete_collection")
  96. logger.info("permit delete of collection: %s", self._permit_delete_collection)
  97. self._permit_overwrite_collection = configuration.get("rights", "permit_overwrite_collection")
  98. logger.info("permit overwrite of collection: %s", self._permit_overwrite_collection)
  99. self._extra_headers = dict()
  100. for key in self.configuration.options("headers"):
  101. self._extra_headers[key] = configuration.get("headers", key)
  102. def _scrub_headers(self, environ: types.WSGIEnviron) -> types.WSGIEnviron:
  103. """Mask passwords and cookies."""
  104. headers = dict(environ)
  105. if (self._mask_passwords and
  106. headers.get("HTTP_AUTHORIZATION", "").startswith("Basic")):
  107. headers["HTTP_AUTHORIZATION"] = "Basic **masked**"
  108. if headers.get("HTTP_COOKIE"):
  109. headers["HTTP_COOKIE"] = "**masked**"
  110. return headers
  111. def __call__(self, environ: types.WSGIEnviron, start_response:
  112. types.WSGIStartResponse) -> Iterable[bytes]:
  113. with log.register_stream(environ["wsgi.errors"]):
  114. try:
  115. status_text, headers, answers = self._handle_request(environ)
  116. except Exception as e:
  117. logger.error("An exception occurred during %s request on %r: "
  118. "%s", environ.get("REQUEST_METHOD", "unknown"),
  119. environ.get("PATH_INFO", ""), e, exc_info=True)
  120. # Make minimal response
  121. status, raw_headers, raw_answer = (
  122. httputils.INTERNAL_SERVER_ERROR)
  123. assert isinstance(raw_answer, str)
  124. answer = raw_answer.encode("ascii")
  125. status_text = "%d %s" % (
  126. status, client.responses.get(status, "Unknown"))
  127. headers = [*raw_headers, ("Content-Length", str(len(answer)))]
  128. answers = [answer]
  129. start_response(status_text, headers)
  130. if environ.get("REQUEST_METHOD") == "HEAD":
  131. return []
  132. return answers
  133. def _handle_request(self, environ: types.WSGIEnviron
  134. ) -> _IntermediateResponse:
  135. time_begin = datetime.datetime.now()
  136. request_method = environ["REQUEST_METHOD"].upper()
  137. unsafe_path = environ.get("PATH_INFO", "")
  138. https = environ.get("HTTPS", "")
  139. """Manage a request."""
  140. def response(status: int, headers: types.WSGIResponseHeaders,
  141. answer: Union[None, str, bytes]) -> _IntermediateResponse:
  142. """Helper to create response from internal types.WSGIResponse"""
  143. headers = dict(headers)
  144. # Set content length
  145. answers = []
  146. if answer is not None:
  147. if isinstance(answer, str):
  148. if self._response_content_on_debug:
  149. logger.debug("Response content:\n%s", answer)
  150. else:
  151. logger.debug("Response content: suppressed by config/option [logging] response_content_on_debug")
  152. headers["Content-Type"] += "; charset=%s" % self._encoding
  153. answer = answer.encode(self._encoding)
  154. accept_encoding = [
  155. encoding.strip() for encoding in
  156. environ.get("HTTP_ACCEPT_ENCODING", "").split(",")
  157. if encoding.strip()]
  158. if "gzip" in accept_encoding:
  159. zcomp = zlib.compressobj(wbits=16 + zlib.MAX_WBITS)
  160. answer = zcomp.compress(answer) + zcomp.flush()
  161. headers["Content-Encoding"] = "gzip"
  162. headers["Content-Length"] = str(len(answer))
  163. answers.append(answer)
  164. # Add extra headers set in configuration
  165. headers.update(self._extra_headers)
  166. # Start response
  167. time_end = datetime.datetime.now()
  168. status_text = "%d %s" % (
  169. status, client.responses.get(status, "Unknown"))
  170. logger.info("%s response status for %r%s in %.3f seconds: %s",
  171. request_method, unsafe_path, depthinfo,
  172. (time_end - time_begin).total_seconds(), status_text)
  173. # Return response content
  174. return status_text, list(headers.items()), answers
  175. reverse_proxy = False
  176. remote_host = "unknown"
  177. if environ.get("REMOTE_HOST"):
  178. remote_host = repr(environ["REMOTE_HOST"])
  179. elif environ.get("REMOTE_ADDR"):
  180. remote_host = environ["REMOTE_ADDR"]
  181. if environ.get("HTTP_X_FORWARDED_FOR"):
  182. reverse_proxy = True
  183. remote_host = "%s (forwarded for %r)" % (
  184. remote_host, environ["HTTP_X_FORWARDED_FOR"])
  185. if environ.get("HTTP_X_FORWARDED_HOST") or environ.get("HTTP_X_FORWARDED_PROTO") or environ.get("HTTP_X_FORWARDED_SERVER"):
  186. reverse_proxy = True
  187. remote_useragent = ""
  188. if environ.get("HTTP_USER_AGENT"):
  189. remote_useragent = " using %r" % environ["HTTP_USER_AGENT"]
  190. depthinfo = ""
  191. if environ.get("HTTP_DEPTH"):
  192. depthinfo = " with depth %r" % environ["HTTP_DEPTH"]
  193. if https:
  194. https_info = " " + environ.get("SSL_PROTOCOL", "") + " " + environ.get("SSL_CIPHER", "")
  195. else:
  196. https_info = ""
  197. logger.info("%s request for %r%s received from %s%s%s",
  198. request_method, unsafe_path, depthinfo,
  199. remote_host, remote_useragent, https_info)
  200. if self._request_header_on_debug:
  201. logger.debug("Request header:\n%s",
  202. pprint.pformat(self._scrub_headers(environ)))
  203. else:
  204. logger.debug("Request header: suppressed by config/option [logging] request_header_on_debug")
  205. # SCRIPT_NAME is already removed from PATH_INFO, according to the
  206. # WSGI specification.
  207. # Reverse proxies can overwrite SCRIPT_NAME with X-SCRIPT-NAME header
  208. if self._script_name and (reverse_proxy is True):
  209. base_prefix_src = "config"
  210. base_prefix = self._script_name
  211. else:
  212. base_prefix_src = ("HTTP_X_SCRIPT_NAME" if "HTTP_X_SCRIPT_NAME" in
  213. environ else "SCRIPT_NAME")
  214. base_prefix = environ.get(base_prefix_src, "")
  215. if base_prefix and base_prefix[0] != "/":
  216. logger.error("Base prefix (from %s) must start with '/': %r",
  217. base_prefix_src, base_prefix)
  218. if base_prefix_src == "HTTP_X_SCRIPT_NAME":
  219. return response(*httputils.BAD_REQUEST)
  220. return response(*httputils.INTERNAL_SERVER_ERROR)
  221. if base_prefix.endswith("/"):
  222. logger.warning("Base prefix (from %s) must not end with '/': %r",
  223. base_prefix_src, base_prefix)
  224. base_prefix = base_prefix.rstrip("/")
  225. if base_prefix:
  226. logger.debug("Base prefix (from %s): %r", base_prefix_src, base_prefix)
  227. # Sanitize request URI (a WSGI server indicates with an empty path,
  228. # that the URL targets the application root without a trailing slash)
  229. path = pathutils.sanitize_path(unsafe_path)
  230. logger.debug("Sanitized path: %r", path)
  231. if (reverse_proxy is True) and (len(base_prefix) > 0):
  232. if path.startswith(base_prefix):
  233. path_new = path.removeprefix(base_prefix)
  234. logger.debug("Called by reverse proxy, remove base prefix %r from path: %r => %r", base_prefix, path, path_new)
  235. path = path_new
  236. else:
  237. logger.warning("Called by reverse proxy, cannot remove base prefix %r from path: %r as not matching", base_prefix, path)
  238. # Get function corresponding to method
  239. function = getattr(self, "do_%s" % request_method, None)
  240. if not function:
  241. return response(*httputils.METHOD_NOT_ALLOWED)
  242. # Redirect all "…/.well-known/{caldav,carddav}" paths to "/".
  243. # This shouldn't be necessary but some clients like TbSync require it.
  244. # Status must be MOVED PERMANENTLY using FOUND causes problems
  245. if (path.rstrip("/").endswith("/.well-known/caldav") or
  246. path.rstrip("/").endswith("/.well-known/carddav")):
  247. return response(*httputils.redirect(
  248. base_prefix + "/", client.MOVED_PERMANENTLY))
  249. # Return NOT FOUND for all other paths containing ".well-known"
  250. if path.endswith("/.well-known") or "/.well-known/" in path:
  251. return response(*httputils.NOT_FOUND)
  252. # Ask authentication backend to check rights
  253. login = password = ""
  254. external_login = self._auth.get_external_login(environ)
  255. authorization = environ.get("HTTP_AUTHORIZATION", "")
  256. if external_login:
  257. login, password = external_login
  258. login, password = login or "", password or ""
  259. elif authorization.startswith("Basic"):
  260. authorization = authorization[len("Basic"):].strip()
  261. login, password = httputils.decode_request(
  262. self.configuration, environ, base64.b64decode(
  263. authorization.encode("ascii"))).split(":", 1)
  264. (user, info) = self._auth.login(login, password) or ("", "") if login else ("", "")
  265. if self.configuration.get("auth", "type") == "ldap":
  266. try:
  267. logger.debug("Groups %r", ",".join(self._auth._ldap_groups))
  268. self._rights._user_groups = self._auth._ldap_groups
  269. except AttributeError:
  270. pass
  271. if user and login == user:
  272. logger.info("Successful login: %r (%s)", user, info)
  273. elif user:
  274. logger.info("Successful login: %r -> %r (%s)", login, user, info)
  275. elif login:
  276. logger.warning("Failed login attempt from %s: %r (%s)",
  277. remote_host, login, info)
  278. # Random delay to avoid timing oracles and bruteforce attacks
  279. if self._auth_delay > 0:
  280. random_delay = self._auth_delay * (0.5 + random.random())
  281. logger.debug("Failed login, sleeping random: %.3f sec", random_delay)
  282. time.sleep(random_delay)
  283. if user and not pathutils.is_safe_path_component(user):
  284. # Prevent usernames like "user/calendar.ics"
  285. logger.info("Refused unsafe username: %r", user)
  286. user = ""
  287. # Create principal collection
  288. if user:
  289. principal_path = "/%s/" % user
  290. with self._storage.acquire_lock("r", user):
  291. principal = next(iter(self._storage.discover(
  292. principal_path, depth="1")), None)
  293. if not principal:
  294. if "W" in self._rights.authorization(user, principal_path):
  295. with self._storage.acquire_lock("w", user):
  296. try:
  297. new_coll = self._storage.create_collection(principal_path)
  298. if new_coll:
  299. jsn_coll = self.configuration.get("storage", "predefined_collections")
  300. for (name_coll, props) in jsn_coll.items():
  301. try:
  302. self._storage.create_collection(principal_path + name_coll, props=props)
  303. except ValueError as e:
  304. logger.warning("Failed to create predefined collection %r: %s", name_coll, e)
  305. except ValueError as e:
  306. logger.warning("Failed to create principal "
  307. "collection %r: %s", user, e)
  308. user = ""
  309. else:
  310. logger.warning("Access to principal path %r denied by "
  311. "rights backend", principal_path)
  312. if self._internal_server:
  313. # Verify content length
  314. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  315. if content_length:
  316. if (self._max_content_length > 0 and
  317. content_length > self._max_content_length):
  318. logger.info("Request body too large: %d", content_length)
  319. return response(*httputils.REQUEST_ENTITY_TOO_LARGE)
  320. if not login or user:
  321. status, headers, answer = function(
  322. environ, base_prefix, path, user)
  323. if (status, headers, answer) == httputils.NOT_ALLOWED:
  324. logger.info("Access to %r denied for %s", path,
  325. repr(user) if user else "anonymous user")
  326. else:
  327. status, headers, answer = httputils.NOT_ALLOWED
  328. if ((status, headers, answer) == httputils.NOT_ALLOWED and not user and
  329. not external_login):
  330. # Unknown or unauthorized user
  331. logger.debug("Asking client for authentication")
  332. status = client.UNAUTHORIZED
  333. headers = dict(headers)
  334. headers.update({
  335. "WWW-Authenticate":
  336. "Basic realm=\"%s\"" % self._auth_realm})
  337. return response(status, headers, answer)