__init__.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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. #
  7. # This library is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This library is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  19. """
  20. Radicale WSGI application.
  21. Can be used with an external WSGI server (see ``radicale.application()``) or
  22. the built-in server (see ``radicale.server`` module).
  23. """
  24. import base64
  25. import datetime
  26. import pprint
  27. import random
  28. import time
  29. import zlib
  30. from http import client
  31. from typing import Iterable, List, Mapping, Tuple, Union
  32. from radicale import config, httputils, log, pathutils, types
  33. from radicale.app.base import ApplicationBase
  34. from radicale.app.delete import ApplicationPartDelete
  35. from radicale.app.get import ApplicationPartGet
  36. from radicale.app.head import ApplicationPartHead
  37. from radicale.app.mkcalendar import ApplicationPartMkcalendar
  38. from radicale.app.mkcol import ApplicationPartMkcol
  39. from radicale.app.move import ApplicationPartMove
  40. from radicale.app.options import ApplicationPartOptions
  41. from radicale.app.post import ApplicationPartPost
  42. from radicale.app.propfind import ApplicationPartPropfind
  43. from radicale.app.proppatch import ApplicationPartProppatch
  44. from radicale.app.put import ApplicationPartPut
  45. from radicale.app.report import ApplicationPartReport
  46. from radicale.log import logger
  47. # Combination of types.WSGIStartResponse and WSGI application return value
  48. _IntermediateResponse = Tuple[str, List[Tuple[str, str]], Iterable[bytes]]
  49. class Application(ApplicationPartDelete, ApplicationPartHead,
  50. ApplicationPartGet, ApplicationPartMkcalendar,
  51. ApplicationPartMkcol, ApplicationPartMove,
  52. ApplicationPartOptions, ApplicationPartPropfind,
  53. ApplicationPartProppatch, ApplicationPartPost,
  54. ApplicationPartPut, ApplicationPartReport, ApplicationBase):
  55. """WSGI application."""
  56. _mask_passwords: bool
  57. _auth_delay: float
  58. _internal_server: bool
  59. _max_content_length: int
  60. _auth_realm: str
  61. _extra_headers: Mapping[str, str]
  62. def __init__(self, configuration: config.Configuration) -> None:
  63. """Initialize Application.
  64. ``configuration`` see ``radicale.config`` module.
  65. The ``configuration`` must not change during the lifetime of
  66. this object, it is kept as an internal reference.
  67. """
  68. super().__init__(configuration)
  69. self._mask_passwords = configuration.get("logging", "mask_passwords")
  70. self._auth_delay = configuration.get("auth", "delay")
  71. self._internal_server = configuration.get("server", "_internal_server")
  72. self._max_content_length = configuration.get(
  73. "server", "max_content_length")
  74. self._auth_realm = configuration.get("auth", "realm")
  75. self._extra_headers = dict()
  76. for key in self.configuration.options("headers"):
  77. self._extra_headers[key] = configuration.get("headers", key)
  78. def _scrub_headers(self, environ: types.WSGIEnviron) -> types.WSGIEnviron:
  79. """Mask passwords and cookies."""
  80. headers = dict(environ)
  81. if (self._mask_passwords and
  82. headers.get("HTTP_AUTHORIZATION", "").startswith("Basic")):
  83. headers["HTTP_AUTHORIZATION"] = "Basic **masked**"
  84. if headers.get("HTTP_COOKIE"):
  85. headers["HTTP_COOKIE"] = "**masked**"
  86. return headers
  87. def __call__(self, environ: types.WSGIEnviron, start_response:
  88. types.WSGIStartResponse) -> Iterable[bytes]:
  89. with log.register_stream(environ["wsgi.errors"]):
  90. try:
  91. status_text, headers, answers = self._handle_request(environ)
  92. except Exception as e:
  93. logger.error("An exception occurred during %s request on %r: "
  94. "%s", environ.get("REQUEST_METHOD", "unknown"),
  95. environ.get("PATH_INFO", ""), e, exc_info=True)
  96. # Make minimal response
  97. status, raw_headers, raw_answer = (
  98. httputils.INTERNAL_SERVER_ERROR)
  99. assert isinstance(raw_answer, str)
  100. answer = raw_answer.encode("ascii")
  101. status_text = "%d %s" % (
  102. status, client.responses.get(status, "Unknown"))
  103. headers = [*raw_headers, ("Content-Length", str(len(answer)))]
  104. answers = [answer]
  105. start_response(status_text, headers)
  106. if environ.get("REQUEST_METHOD") == "HEAD":
  107. return []
  108. return answers
  109. def _handle_request(self, environ: types.WSGIEnviron
  110. ) -> _IntermediateResponse:
  111. time_begin = datetime.datetime.now()
  112. request_method = environ["REQUEST_METHOD"].upper()
  113. unsafe_path = environ.get("PATH_INFO", "")
  114. """Manage a request."""
  115. def response(status: int, headers: types.WSGIResponseHeaders,
  116. answer: Union[None, str, bytes]) -> _IntermediateResponse:
  117. """Helper to create response from internal types.WSGIResponse"""
  118. headers = dict(headers)
  119. # Set content length
  120. answers = []
  121. if answer is not None:
  122. if isinstance(answer, str):
  123. logger.debug("Response content:\n%s", answer)
  124. headers["Content-Type"] += "; charset=%s" % self._encoding
  125. answer = answer.encode(self._encoding)
  126. accept_encoding = [
  127. encoding.strip() for encoding in
  128. environ.get("HTTP_ACCEPT_ENCODING", "").split(",")
  129. if encoding.strip()]
  130. if "gzip" in accept_encoding:
  131. zcomp = zlib.compressobj(wbits=16 + zlib.MAX_WBITS)
  132. answer = zcomp.compress(answer) + zcomp.flush()
  133. headers["Content-Encoding"] = "gzip"
  134. headers["Content-Length"] = str(len(answer))
  135. answers.append(answer)
  136. # Add extra headers set in configuration
  137. headers.update(self._extra_headers)
  138. # Start response
  139. time_end = datetime.datetime.now()
  140. status_text = "%d %s" % (
  141. status, client.responses.get(status, "Unknown"))
  142. logger.info("%s response status for %r%s in %.3f seconds: %s",
  143. request_method, unsafe_path, depthinfo,
  144. (time_end - time_begin).total_seconds(), status_text)
  145. # Return response content
  146. return status_text, list(headers.items()), answers
  147. remote_host = "unknown"
  148. if environ.get("REMOTE_HOST"):
  149. remote_host = repr(environ["REMOTE_HOST"])
  150. elif environ.get("REMOTE_ADDR"):
  151. remote_host = environ["REMOTE_ADDR"]
  152. if environ.get("HTTP_X_FORWARDED_FOR"):
  153. remote_host = "%s (forwarded for %r)" % (
  154. remote_host, environ["HTTP_X_FORWARDED_FOR"])
  155. remote_useragent = ""
  156. if environ.get("HTTP_USER_AGENT"):
  157. remote_useragent = " using %r" % environ["HTTP_USER_AGENT"]
  158. depthinfo = ""
  159. if environ.get("HTTP_DEPTH"):
  160. depthinfo = " with depth %r" % environ["HTTP_DEPTH"]
  161. logger.info("%s request for %r%s received from %s%s",
  162. request_method, unsafe_path, depthinfo,
  163. remote_host, remote_useragent)
  164. logger.debug("Request headers:\n%s",
  165. pprint.pformat(self._scrub_headers(environ)))
  166. # SCRIPT_NAME is already removed from PATH_INFO, according to the
  167. # WSGI specification.
  168. # Reverse proxies can overwrite SCRIPT_NAME with X-SCRIPT-NAME header
  169. base_prefix_src = ("HTTP_X_SCRIPT_NAME" if "HTTP_X_SCRIPT_NAME" in
  170. environ else "SCRIPT_NAME")
  171. base_prefix = environ.get(base_prefix_src, "")
  172. if base_prefix and base_prefix[0] != "/":
  173. logger.error("Base prefix (from %s) must start with '/': %r",
  174. base_prefix_src, base_prefix)
  175. if base_prefix_src == "HTTP_X_SCRIPT_NAME":
  176. return response(*httputils.BAD_REQUEST)
  177. return response(*httputils.INTERNAL_SERVER_ERROR)
  178. if base_prefix.endswith("/"):
  179. logger.warning("Base prefix (from %s) must not end with '/': %r",
  180. base_prefix_src, base_prefix)
  181. base_prefix = base_prefix.rstrip("/")
  182. logger.debug("Base prefix (from %s): %r", base_prefix_src, base_prefix)
  183. # Sanitize request URI (a WSGI server indicates with an empty path,
  184. # that the URL targets the application root without a trailing slash)
  185. path = pathutils.sanitize_path(unsafe_path)
  186. logger.debug("Sanitized path: %r", path)
  187. # Get function corresponding to method
  188. function = getattr(self, "do_%s" % request_method, None)
  189. if not function:
  190. return response(*httputils.METHOD_NOT_ALLOWED)
  191. # Redirect all "…/.well-known/{caldav,carddav}" paths to "/".
  192. # This shouldn't be necessary but some clients like TbSync require it.
  193. # Status must be MOVED PERMANENTLY using FOUND causes problems
  194. if (path.rstrip("/").endswith("/.well-known/caldav") or
  195. path.rstrip("/").endswith("/.well-known/carddav")):
  196. return response(*httputils.redirect(
  197. base_prefix + "/", client.MOVED_PERMANENTLY))
  198. # Return NOT FOUND for all other paths containing ".well-knwon"
  199. if path.endswith("/.well-known") or "/.well-known/" in path:
  200. return response(*httputils.NOT_FOUND)
  201. # Ask authentication backend to check rights
  202. login = password = ""
  203. external_login = self._auth.get_external_login(environ)
  204. authorization = environ.get("HTTP_AUTHORIZATION", "")
  205. if external_login:
  206. login, password = external_login
  207. login, password = login or "", password or ""
  208. elif authorization.startswith("Basic"):
  209. authorization = authorization[len("Basic"):].strip()
  210. login, password = httputils.decode_request(
  211. self.configuration, environ, base64.b64decode(
  212. authorization.encode("ascii"))).split(":", 1)
  213. user = self._auth.login(login, password) or "" if login else ""
  214. if user and login == user:
  215. logger.info("Successful login: %r", user)
  216. elif user:
  217. logger.info("Successful login: %r -> %r", login, user)
  218. elif login:
  219. logger.warning("Failed login attempt from %s: %r",
  220. remote_host, login)
  221. # Random delay to avoid timing oracles and bruteforce attacks
  222. if self._auth_delay > 0:
  223. random_delay = self._auth_delay * (0.5 + random.random())
  224. logger.debug("Sleeping %.3f seconds", random_delay)
  225. time.sleep(random_delay)
  226. if user and not pathutils.is_safe_path_component(user):
  227. # Prevent usernames like "user/calendar.ics"
  228. logger.info("Refused unsafe username: %r", user)
  229. user = ""
  230. # Create principal collection
  231. if user:
  232. principal_path = "/%s/" % user
  233. with self._storage.acquire_lock("r", user):
  234. principal = next(iter(self._storage.discover(
  235. principal_path, depth="1")), None)
  236. if not principal:
  237. if "W" in self._rights.authorization(user, principal_path):
  238. with self._storage.acquire_lock("w", user):
  239. try:
  240. self._storage.create_collection(principal_path)
  241. except ValueError as e:
  242. logger.warning("Failed to create principal "
  243. "collection %r: %s", user, e)
  244. user = ""
  245. else:
  246. logger.warning("Access to principal path %r denied by "
  247. "rights backend", principal_path)
  248. if self._internal_server:
  249. # Verify content length
  250. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  251. if content_length:
  252. if (self._max_content_length > 0 and
  253. content_length > self._max_content_length):
  254. logger.info("Request body too large: %d", content_length)
  255. return response(*httputils.REQUEST_ENTITY_TOO_LARGE)
  256. if not login or user:
  257. status, headers, answer = function(
  258. environ, base_prefix, path, user)
  259. if (status, headers, answer) == httputils.NOT_ALLOWED:
  260. logger.info("Access to %r denied for %s", path,
  261. repr(user) if user else "anonymous user")
  262. else:
  263. status, headers, answer = httputils.NOT_ALLOWED
  264. if ((status, headers, answer) == httputils.NOT_ALLOWED and not user and
  265. not external_login):
  266. # Unknown or unauthorized user
  267. logger.debug("Asking client for authentication")
  268. status = client.UNAUTHORIZED
  269. headers = dict(headers)
  270. headers.update({
  271. "WWW-Authenticate":
  272. "Basic realm=\"%s\"" % self._auth_realm})
  273. return response(status, headers, answer)