__init__.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. # This file is part of Radicale Server - Calendar 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. import pkg_resources
  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. VERSION: str = pkg_resources.get_distribution("radicale").version
  49. # Combination of types.WSGIStartResponse and WSGI application return value
  50. _IntermediateResponse = Tuple[str, List[Tuple[str, str]], Iterable[bytes]]
  51. class Application(ApplicationPartDelete, ApplicationPartHead,
  52. ApplicationPartGet, ApplicationPartMkcalendar,
  53. ApplicationPartMkcol, ApplicationPartMove,
  54. ApplicationPartOptions, ApplicationPartPropfind,
  55. ApplicationPartProppatch, ApplicationPartPost,
  56. ApplicationPartPut, ApplicationPartReport, ApplicationBase):
  57. """WSGI application."""
  58. _mask_passwords: bool
  59. _auth_delay: float
  60. _internal_server: bool
  61. _max_content_length: int
  62. _auth_realm: str
  63. _extra_headers: Mapping[str, str]
  64. def __init__(self, configuration: config.Configuration) -> None:
  65. """Initialize Application.
  66. ``configuration`` see ``radicale.config`` module.
  67. The ``configuration`` must not change during the lifetime of
  68. this object, it is kept as an internal reference.
  69. """
  70. super().__init__(configuration)
  71. self._mask_passwords = configuration.get("logging", "mask_passwords")
  72. self._auth_delay = configuration.get("auth", "delay")
  73. self._internal_server = configuration.get("server", "_internal_server")
  74. self._max_content_length = configuration.get(
  75. "server", "max_content_length")
  76. self._auth_realm = configuration.get("auth", "realm")
  77. self._extra_headers = dict()
  78. for key in self.configuration.options("headers"):
  79. self._extra_headers[key] = configuration.get("headers", key)
  80. def _scrub_headers(self, environ: types.WSGIEnviron) -> types.WSGIEnviron:
  81. """Mask passwords and cookies."""
  82. headers = dict(environ)
  83. if (self._mask_passwords and
  84. headers.get("HTTP_AUTHORIZATION", "").startswith("Basic")):
  85. headers["HTTP_AUTHORIZATION"] = "Basic **masked**"
  86. if headers.get("HTTP_COOKIE"):
  87. headers["HTTP_COOKIE"] = "**masked**"
  88. return headers
  89. def __call__(self, environ: types.WSGIEnviron, start_response:
  90. types.WSGIStartResponse) -> Iterable[bytes]:
  91. with log.register_stream(environ["wsgi.errors"]):
  92. try:
  93. status_text, headers, answers = self._handle_request(environ)
  94. except Exception as e:
  95. logger.error("An exception occurred during %s request on %r: "
  96. "%s", environ.get("REQUEST_METHOD", "unknown"),
  97. environ.get("PATH_INFO", ""), e, exc_info=True)
  98. # Make minimal response
  99. status, raw_headers, raw_answer = (
  100. httputils.INTERNAL_SERVER_ERROR)
  101. assert isinstance(raw_answer, str)
  102. answer = raw_answer.encode("ascii")
  103. status_text = "%d %s" % (
  104. status, client.responses.get(status, "Unknown"))
  105. headers = [*raw_headers, ("Content-Length", str(len(answer)))]
  106. answers = [answer]
  107. start_response(status_text, headers)
  108. return answers
  109. def _handle_request(self, environ: types.WSGIEnviron
  110. ) -> _IntermediateResponse:
  111. """Manage a request."""
  112. def response(status: int, headers: types.WSGIResponseHeaders,
  113. answer: Union[None, str, bytes]) -> _IntermediateResponse:
  114. """Helper to create response from internal types.WSGIResponse"""
  115. headers = dict(headers)
  116. # Set content length
  117. answers = []
  118. if answer is not None:
  119. if isinstance(answer, str):
  120. logger.debug("Response content:\n%s", answer)
  121. headers["Content-Type"] += "; charset=%s" % self._encoding
  122. answer = answer.encode(self._encoding)
  123. accept_encoding = [
  124. encoding.strip() for encoding in
  125. environ.get("HTTP_ACCEPT_ENCODING", "").split(",")
  126. if encoding.strip()]
  127. if "gzip" in accept_encoding:
  128. zcomp = zlib.compressobj(wbits=16 + zlib.MAX_WBITS)
  129. answer = zcomp.compress(answer) + zcomp.flush()
  130. headers["Content-Encoding"] = "gzip"
  131. headers["Content-Length"] = str(len(answer))
  132. answers.append(answer)
  133. # Add extra headers set in configuration
  134. headers.update(self._extra_headers)
  135. # Start response
  136. time_end = datetime.datetime.now()
  137. status_text = "%d %s" % (
  138. status, client.responses.get(status, "Unknown"))
  139. logger.info(
  140. "%s response status for %r%s in %.3f seconds: %s",
  141. environ["REQUEST_METHOD"], environ.get("PATH_INFO", ""),
  142. depthinfo, (time_end - time_begin).total_seconds(),
  143. status_text)
  144. # Return response content
  145. return status_text, list(headers.items()), answers
  146. remote_host = "unknown"
  147. if environ.get("REMOTE_HOST"):
  148. remote_host = repr(environ["REMOTE_HOST"])
  149. elif environ.get("REMOTE_ADDR"):
  150. remote_host = environ["REMOTE_ADDR"]
  151. if environ.get("HTTP_X_FORWARDED_FOR"):
  152. remote_host = "%s (forwarded for %r)" % (
  153. remote_host, environ["HTTP_X_FORWARDED_FOR"])
  154. remote_useragent = ""
  155. if environ.get("HTTP_USER_AGENT"):
  156. remote_useragent = " using %r" % environ["HTTP_USER_AGENT"]
  157. depthinfo = ""
  158. if environ.get("HTTP_DEPTH"):
  159. depthinfo = " with depth %r" % environ["HTTP_DEPTH"]
  160. time_begin = datetime.datetime.now()
  161. logger.info(
  162. "%s request for %r%s received from %s%s",
  163. environ["REQUEST_METHOD"], environ.get("PATH_INFO", ""), depthinfo,
  164. remote_host, remote_useragent)
  165. logger.debug("Request headers:\n%s",
  166. pprint.pformat(self._scrub_headers(environ)))
  167. # Let reverse proxies overwrite SCRIPT_NAME
  168. if "HTTP_X_SCRIPT_NAME" in environ:
  169. # script_name must be removed from PATH_INFO by the client.
  170. unsafe_base_prefix = environ["HTTP_X_SCRIPT_NAME"]
  171. logger.debug("Script name overwritten by client: %r",
  172. unsafe_base_prefix)
  173. else:
  174. # SCRIPT_NAME is already removed from PATH_INFO, according to the
  175. # WSGI specification.
  176. unsafe_base_prefix = environ.get("SCRIPT_NAME", "")
  177. # Sanitize base prefix
  178. base_prefix = pathutils.sanitize_path(unsafe_base_prefix).rstrip("/")
  179. logger.debug("Sanitized script name: %r", base_prefix)
  180. # Sanitize request URI (a WSGI server indicates with an empty path,
  181. # that the URL targets the application root without a trailing slash)
  182. path = pathutils.sanitize_path(environ.get("PATH_INFO", ""))
  183. logger.debug("Sanitized path: %r", path)
  184. # Get function corresponding to method
  185. function = getattr(
  186. self, "do_%s" % environ["REQUEST_METHOD"].upper(), None)
  187. if not function:
  188. return response(*httputils.METHOD_NOT_ALLOWED)
  189. # If "/.well-known" is not available, clients query "/"
  190. if path == "/.well-known" or path.startswith("/.well-known/"):
  191. return response(*httputils.NOT_FOUND)
  192. # Ask authentication backend to check rights
  193. login = password = ""
  194. external_login = self._auth.get_external_login(environ)
  195. authorization = environ.get("HTTP_AUTHORIZATION", "")
  196. if external_login:
  197. login, password = external_login
  198. login, password = login or "", password or ""
  199. elif authorization.startswith("Basic"):
  200. authorization = authorization[len("Basic"):].strip()
  201. login, password = httputils.decode_request(
  202. self.configuration, environ, base64.b64decode(
  203. authorization.encode("ascii"))).split(":", 1)
  204. user = self._auth.login(login, password) or "" if login else ""
  205. if user and login == user:
  206. logger.info("Successful login: %r", user)
  207. elif user:
  208. logger.info("Successful login: %r -> %r", login, user)
  209. elif login:
  210. logger.warning("Failed login attempt from %s: %r",
  211. remote_host, login)
  212. # Random delay to avoid timing oracles and bruteforce attacks
  213. if self._auth_delay > 0:
  214. random_delay = self._auth_delay * (0.5 + random.random())
  215. logger.debug("Sleeping %.3f seconds", random_delay)
  216. time.sleep(random_delay)
  217. if user and not pathutils.is_safe_path_component(user):
  218. # Prevent usernames like "user/calendar.ics"
  219. logger.info("Refused unsafe username: %r", user)
  220. user = ""
  221. # Create principal collection
  222. if user:
  223. principal_path = "/%s/" % user
  224. with self._storage.acquire_lock("r", user):
  225. principal = next(iter(self._storage.discover(
  226. principal_path, depth="1")), None)
  227. if not principal:
  228. if "W" in self._rights.authorization(user, principal_path):
  229. with self._storage.acquire_lock("w", user):
  230. try:
  231. self._storage.create_collection(principal_path)
  232. except ValueError as e:
  233. logger.warning("Failed to create principal "
  234. "collection %r: %s", user, e)
  235. user = ""
  236. else:
  237. logger.warning("Access to principal path %r denied by "
  238. "rights backend", principal_path)
  239. if self._internal_server:
  240. # Verify content length
  241. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  242. if content_length:
  243. if (self._max_content_length > 0 and
  244. content_length > self._max_content_length):
  245. logger.info("Request body too large: %d", content_length)
  246. return response(*httputils.REQUEST_ENTITY_TOO_LARGE)
  247. if not login or user:
  248. status, headers, answer = function(
  249. environ, base_prefix, path, user)
  250. if (status, headers, answer) == httputils.NOT_ALLOWED:
  251. logger.info("Access to %r denied for %s", path,
  252. repr(user) if user else "anonymous user")
  253. else:
  254. status, headers, answer = httputils.NOT_ALLOWED
  255. if ((status, headers, answer) == httputils.NOT_ALLOWED and not user and
  256. not external_login):
  257. # Unknown or unauthorized user
  258. logger.debug("Asking client for authentication")
  259. status = client.UNAUTHORIZED
  260. headers = dict(headers)
  261. headers.update({
  262. "WWW-Authenticate":
  263. "Basic realm=\"%s\"" % self._auth_realm})
  264. return response(status, headers, answer)