__init__.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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 io
  27. import logging
  28. import posixpath
  29. import pprint
  30. import random
  31. import time
  32. import zlib
  33. from http import client
  34. from xml.etree import ElementTree as ET
  35. import defusedxml.ElementTree as DefusedET
  36. import pkg_resources
  37. from radicale import (auth, httputils, log, pathutils, rights, storage, web,
  38. xmlutils)
  39. from radicale.app.delete import ApplicationDeleteMixin
  40. from radicale.app.get import ApplicationGetMixin
  41. from radicale.app.head import ApplicationHeadMixin
  42. from radicale.app.mkcalendar import ApplicationMkcalendarMixin
  43. from radicale.app.mkcol import ApplicationMkcolMixin
  44. from radicale.app.move import ApplicationMoveMixin
  45. from radicale.app.options import ApplicationOptionsMixin
  46. from radicale.app.propfind import ApplicationPropfindMixin
  47. from radicale.app.proppatch import ApplicationProppatchMixin
  48. from radicale.app.put import ApplicationPutMixin
  49. from radicale.app.report import ApplicationReportMixin
  50. from radicale.log import logger
  51. VERSION = pkg_resources.get_distribution("radicale").version
  52. class Application(
  53. ApplicationDeleteMixin, ApplicationGetMixin, ApplicationHeadMixin,
  54. ApplicationMkcalendarMixin, ApplicationMkcolMixin,
  55. ApplicationMoveMixin, ApplicationOptionsMixin,
  56. ApplicationPropfindMixin, ApplicationProppatchMixin,
  57. ApplicationPutMixin, ApplicationReportMixin):
  58. """WSGI application."""
  59. def __init__(self, configuration):
  60. """Initialize Application.
  61. ``configuration`` see ``radicale.config`` module.
  62. The ``configuration`` must not change during the lifetime of
  63. this object, it is kept as an internal reference.
  64. """
  65. super().__init__()
  66. self.configuration = configuration
  67. self._auth = auth.load(configuration)
  68. self._storage = storage.load(configuration)
  69. self._rights = rights.load(configuration)
  70. self._web = web.load(configuration)
  71. self._encoding = configuration.get("encoding", "request")
  72. def _headers_log(self, environ):
  73. """Sanitize headers for logging."""
  74. request_environ = dict(environ)
  75. # Mask passwords
  76. mask_passwords = self.configuration.get("logging", "mask_passwords")
  77. authorization = request_environ.get("HTTP_AUTHORIZATION", "")
  78. if mask_passwords and authorization.startswith("Basic"):
  79. request_environ["HTTP_AUTHORIZATION"] = "Basic **masked**"
  80. if request_environ.get("HTTP_COOKIE"):
  81. request_environ["HTTP_COOKIE"] = "**masked**"
  82. return request_environ
  83. def _decode(self, text, environ):
  84. """Try to magically decode ``text`` according to given ``environ``."""
  85. # List of charsets to try
  86. charsets = []
  87. # First append content charset given in the request
  88. content_type = environ.get("CONTENT_TYPE")
  89. if content_type and "charset=" in content_type:
  90. charsets.append(
  91. content_type.split("charset=")[1].split(";")[0].strip())
  92. # Then append default Radicale charset
  93. charsets.append(self._encoding)
  94. # Then append various fallbacks
  95. charsets.append("utf-8")
  96. charsets.append("iso8859-1")
  97. # Try to decode
  98. for charset in charsets:
  99. try:
  100. return text.decode(charset)
  101. except UnicodeDecodeError:
  102. pass
  103. raise UnicodeDecodeError
  104. def __call__(self, environ, start_response):
  105. with log.register_stream(environ["wsgi.errors"]):
  106. try:
  107. status, headers, answers = self._handle_request(environ)
  108. except Exception as e:
  109. try:
  110. method = str(environ["REQUEST_METHOD"])
  111. except Exception:
  112. method = "unknown"
  113. try:
  114. path = str(environ.get("PATH_INFO", ""))
  115. except Exception:
  116. path = ""
  117. logger.error("An exception occurred during %s request on %r: "
  118. "%s", method, path, e, exc_info=True)
  119. status, headers, answer = httputils.INTERNAL_SERVER_ERROR
  120. answer = answer.encode("ascii")
  121. status = "%d %s" % (
  122. status.value, client.responses.get(status, "Unknown"))
  123. headers = [
  124. ("Content-Length", str(len(answer)))] + list(headers)
  125. answers = [answer]
  126. start_response(status, headers)
  127. return answers
  128. def _handle_request(self, environ):
  129. """Manage a request."""
  130. def response(status, headers=(), answer=None):
  131. headers = dict(headers)
  132. # Set content length
  133. if answer:
  134. if hasattr(answer, "encode"):
  135. logger.debug("Response content:\n%s", answer)
  136. headers["Content-Type"] += "; charset=%s" % self._encoding
  137. answer = answer.encode(self._encoding)
  138. accept_encoding = [
  139. encoding.strip() for encoding in
  140. environ.get("HTTP_ACCEPT_ENCODING", "").split(",")
  141. if encoding.strip()]
  142. if "gzip" in accept_encoding:
  143. zcomp = zlib.compressobj(wbits=16 + zlib.MAX_WBITS)
  144. answer = zcomp.compress(answer) + zcomp.flush()
  145. headers["Content-Encoding"] = "gzip"
  146. headers["Content-Length"] = str(len(answer))
  147. # Add extra headers set in configuration
  148. for key in self.configuration.options("headers"):
  149. headers[key] = self.configuration.get("headers", key)
  150. # Start response
  151. time_end = datetime.datetime.now()
  152. status = "%d %s" % (
  153. status, client.responses.get(status, "Unknown"))
  154. logger.info(
  155. "%s response status for %r%s in %.3f seconds: %s",
  156. environ["REQUEST_METHOD"], environ.get("PATH_INFO", ""),
  157. depthinfo, (time_end - time_begin).total_seconds(), status)
  158. # Return response content
  159. return status, list(headers.items()), [answer] if answer else []
  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 = "%r (forwarded by %s)" % (
  167. environ["HTTP_X_FORWARDED_FOR"], remote_host)
  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. time_begin = datetime.datetime.now()
  175. logger.info(
  176. "%s request for %r%s received from %s%s",
  177. environ["REQUEST_METHOD"], environ.get("PATH_INFO", ""), depthinfo,
  178. remote_host, remote_useragent)
  179. headers = pprint.pformat(self._headers_log(environ))
  180. logger.debug("Request headers:\n%s", headers)
  181. # Let reverse proxies overwrite SCRIPT_NAME
  182. if "HTTP_X_SCRIPT_NAME" in environ:
  183. # script_name must be removed from PATH_INFO by the client.
  184. unsafe_base_prefix = environ["HTTP_X_SCRIPT_NAME"]
  185. logger.debug("Script name overwritten by client: %r",
  186. unsafe_base_prefix)
  187. else:
  188. # SCRIPT_NAME is already removed from PATH_INFO, according to the
  189. # WSGI specification.
  190. unsafe_base_prefix = environ.get("SCRIPT_NAME", "")
  191. # Sanitize base prefix
  192. base_prefix = pathutils.sanitize_path(unsafe_base_prefix).rstrip("/")
  193. logger.debug("Sanitized script name: %r", base_prefix)
  194. # Sanitize request URI (a WSGI server indicates with an empty path,
  195. # that the URL targets the application root without a trailing slash)
  196. path = pathutils.sanitize_path(environ.get("PATH_INFO", ""))
  197. logger.debug("Sanitized path: %r", path)
  198. # Get function corresponding to method
  199. function = getattr(self, "do_%s" % environ["REQUEST_METHOD"].upper())
  200. # If "/.well-known" is not available, clients query "/"
  201. if path == "/.well-known" or path.startswith("/.well-known/"):
  202. return response(*httputils.NOT_FOUND)
  203. # Ask authentication backend to check rights
  204. login = password = ""
  205. external_login = self._auth.get_external_login(environ)
  206. authorization = environ.get("HTTP_AUTHORIZATION", "")
  207. if external_login:
  208. login, password = external_login
  209. login, password = login or "", password or ""
  210. elif authorization.startswith("Basic"):
  211. authorization = authorization[len("Basic"):].strip()
  212. login, password = self._decode(base64.b64decode(
  213. authorization.encode("ascii")), environ).split(":", 1)
  214. user = self._auth.login(login, password) or "" if login else ""
  215. if user and login == user:
  216. logger.info("Successful login: %r", user)
  217. elif user:
  218. logger.info("Successful login: %r -> %r", login, user)
  219. elif login:
  220. logger.info("Failed login attempt: %r", login)
  221. # Random delay to avoid timing oracles and bruteforce attacks
  222. delay = self.configuration.get("auth", "delay")
  223. if delay > 0:
  224. random_delay = delay * (0.5 + random.random())
  225. logger.debug("Sleeping %.3f seconds", random_delay)
  226. time.sleep(random_delay)
  227. if user and not pathutils.is_safe_path_component(user):
  228. # Prevent usernames like "user/calendar.ics"
  229. logger.info("Refused unsafe username: %r", user)
  230. user = ""
  231. # Create principal collection
  232. if user:
  233. principal_path = "/%s/" % user
  234. with self._storage.acquire_lock("r", user):
  235. principal = next(self._storage.discover(
  236. principal_path, depth="1"), None)
  237. if not principal:
  238. if "W" in self._rights.authorization(user, principal_path):
  239. with self._storage.acquire_lock("w", user):
  240. try:
  241. self._storage.create_collection(principal_path)
  242. except ValueError as e:
  243. logger.warning("Failed to create principal "
  244. "collection %r: %s", user, e)
  245. user = ""
  246. else:
  247. logger.warning("Access to principal path %r denied by "
  248. "rights backend", principal_path)
  249. if self.configuration.get("server", "_internal_server"):
  250. # Verify content length
  251. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  252. if content_length:
  253. max_content_length = self.configuration.get(
  254. "server", "max_content_length")
  255. if max_content_length and content_length > max_content_length:
  256. logger.info("Request body too large: %d", content_length)
  257. return response(*httputils.REQUEST_ENTITY_TOO_LARGE)
  258. if not login or user:
  259. status, headers, answer = function(
  260. environ, base_prefix, path, user)
  261. if (status, headers, answer) == httputils.NOT_ALLOWED:
  262. logger.info("Access to %r denied for %s", path,
  263. repr(user) if user else "anonymous user")
  264. else:
  265. status, headers, answer = httputils.NOT_ALLOWED
  266. if ((status, headers, answer) == httputils.NOT_ALLOWED and not user and
  267. not external_login):
  268. # Unknown or unauthorized user
  269. logger.debug("Asking client for authentication")
  270. status = client.UNAUTHORIZED
  271. realm = self.configuration.get("auth", "realm")
  272. headers = dict(headers)
  273. headers.update({
  274. "WWW-Authenticate":
  275. "Basic realm=\"%s\"" % realm})
  276. return response(status, headers, answer)
  277. def _read_raw_content(self, environ):
  278. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  279. if not content_length:
  280. return b""
  281. content = environ["wsgi.input"].read(content_length)
  282. if len(content) < content_length:
  283. raise RuntimeError("Request body too short: %d" % len(content))
  284. return content
  285. def _read_content(self, environ):
  286. content = self._decode(self._read_raw_content(environ), environ)
  287. logger.debug("Request content:\n%s", content)
  288. return content
  289. def _read_xml_content(self, environ):
  290. content = self._decode(self._read_raw_content(environ), environ)
  291. if not content:
  292. return None
  293. try:
  294. xml_content = DefusedET.fromstring(content)
  295. except ET.ParseError as e:
  296. logger.debug("Request content (Invalid XML):\n%s", content)
  297. raise RuntimeError("Failed to parse XML: %s" % e) from e
  298. if logger.isEnabledFor(logging.DEBUG):
  299. logger.debug("Request content:\n%s",
  300. xmlutils.pretty_xml(xml_content))
  301. return xml_content
  302. def _write_xml_content(self, xml_content):
  303. if logger.isEnabledFor(logging.DEBUG):
  304. logger.debug("Response content:\n%s",
  305. xmlutils.pretty_xml(xml_content))
  306. f = io.BytesIO()
  307. ET.ElementTree(xml_content).write(f, encoding=self._encoding,
  308. xml_declaration=True)
  309. return f.getvalue()
  310. def _webdav_error_response(self, human_tag,
  311. status=httputils.WEBDAV_PRECONDITION_FAILED[0]):
  312. """Generate XML error response."""
  313. headers = {"Content-Type": "text/xml; charset=%s" % self._encoding}
  314. content = self._write_xml_content(xmlutils.webdav_error(human_tag))
  315. return status, headers, content
  316. class Access:
  317. """Helper class to check access rights of an item"""
  318. def __init__(self, rights, user, path):
  319. self._rights = rights
  320. self.user = user
  321. self.path = path
  322. self.parent_path = pathutils.unstrip_path(
  323. posixpath.dirname(pathutils.strip_path(path)), True)
  324. self.permissions = self._rights.authorization(self.user, self.path)
  325. self._parent_permissions = None
  326. @property
  327. def parent_permissions(self):
  328. if self.path == self.parent_path:
  329. return self.permissions
  330. if self._parent_permissions is None:
  331. self._parent_permissions = self._rights.authorization(
  332. self.user, self.parent_path)
  333. return self._parent_permissions
  334. def check(self, permission, item=None):
  335. if permission not in "rw":
  336. raise ValueError("Invalid permission argument: %r" % permission)
  337. if not item:
  338. permissions = permission + permission.upper()
  339. parent_permissions = permission
  340. elif isinstance(item, storage.BaseCollection):
  341. if item.get_meta("tag"):
  342. permissions = permission
  343. else:
  344. permissions = permission.upper()
  345. parent_permissions = ""
  346. else:
  347. permissions = ""
  348. parent_permissions = permission
  349. return bool(rights.intersect(self.permissions, permissions) or (
  350. self.path != self.parent_path and
  351. rights.intersect(self.parent_permissions, parent_permissions)))