__init__.py 16 KB

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