1
0

__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, hook, httputils, log, pathutils, rights, storage,
  38. web, 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. self._hook = hook.load(configuration)
  73. def _headers_log(self, environ):
  74. """Sanitize headers for logging."""
  75. request_environ = dict(environ)
  76. # Mask passwords
  77. mask_passwords = self.configuration.get("logging", "mask_passwords")
  78. authorization = request_environ.get("HTTP_AUTHORIZATION", "")
  79. if mask_passwords and authorization.startswith("Basic"):
  80. request_environ["HTTP_AUTHORIZATION"] = "Basic **masked**"
  81. if request_environ.get("HTTP_COOKIE"):
  82. request_environ["HTTP_COOKIE"] = "**masked**"
  83. return request_environ
  84. def _decode(self, text, environ):
  85. """Try to magically decode ``text`` according to given ``environ``."""
  86. # List of charsets to try
  87. charsets = []
  88. # First append content charset given in the request
  89. content_type = environ.get("CONTENT_TYPE")
  90. if content_type and "charset=" in content_type:
  91. charsets.append(
  92. content_type.split("charset=")[1].split(";")[0].strip())
  93. # Then append default Radicale charset
  94. charsets.append(self._encoding)
  95. # Then append various fallbacks
  96. charsets.append("utf-8")
  97. charsets.append("iso8859-1")
  98. # Try to decode
  99. for charset in charsets:
  100. try:
  101. return text.decode(charset)
  102. except UnicodeDecodeError:
  103. pass
  104. raise UnicodeDecodeError
  105. def __call__(self, environ, start_response):
  106. with log.register_stream(environ["wsgi.errors"]):
  107. try:
  108. status, headers, answers = self._handle_request(environ)
  109. except Exception as e:
  110. try:
  111. method = str(environ["REQUEST_METHOD"])
  112. except Exception:
  113. method = "unknown"
  114. try:
  115. path = str(environ.get("PATH_INFO", ""))
  116. except Exception:
  117. path = ""
  118. logger.error("An exception occurred during %s request on %r: "
  119. "%s", method, path, e, exc_info=True)
  120. status, headers, answer = httputils.INTERNAL_SERVER_ERROR
  121. answer = answer.encode("ascii")
  122. status = "%d %s" % (
  123. status.value, client.responses.get(status, "Unknown"))
  124. headers = [
  125. ("Content-Length", str(len(answer)))] + list(headers)
  126. answers = [answer]
  127. start_response(status, headers)
  128. return answers
  129. def _handle_request(self, environ):
  130. """Manage a request."""
  131. def response(status, headers=(), answer=None):
  132. headers = dict(headers)
  133. # Set content length
  134. if answer:
  135. if hasattr(answer, "encode"):
  136. logger.debug("Response content:\n%s", answer)
  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. # Add extra headers set in configuration
  149. for key in self.configuration.options("headers"):
  150. headers[key] = self.configuration.get("headers", key)
  151. # Start response
  152. time_end = datetime.datetime.now()
  153. status = "%d %s" % (
  154. status, client.responses.get(status, "Unknown"))
  155. logger.info(
  156. "%s response status for %r%s in %.3f seconds: %s",
  157. environ["REQUEST_METHOD"], environ.get("PATH_INFO", ""),
  158. depthinfo, (time_end - time_begin).total_seconds(), status)
  159. # Return response content
  160. return status, list(headers.items()), [answer] if answer else []
  161. remote_host = "unknown"
  162. if environ.get("REMOTE_HOST"):
  163. remote_host = repr(environ["REMOTE_HOST"])
  164. elif environ.get("REMOTE_ADDR"):
  165. remote_host = environ["REMOTE_ADDR"]
  166. if environ.get("HTTP_X_FORWARDED_FOR"):
  167. remote_host = "%r (forwarded by %s)" % (
  168. environ["HTTP_X_FORWARDED_FOR"], remote_host)
  169. remote_useragent = ""
  170. if environ.get("HTTP_USER_AGENT"):
  171. remote_useragent = " using %r" % environ["HTTP_USER_AGENT"]
  172. depthinfo = ""
  173. if environ.get("HTTP_DEPTH"):
  174. depthinfo = " with depth %r" % environ["HTTP_DEPTH"]
  175. time_begin = datetime.datetime.now()
  176. logger.info(
  177. "%s request for %r%s received from %s%s",
  178. environ["REQUEST_METHOD"], environ.get("PATH_INFO", ""), depthinfo,
  179. remote_host, remote_useragent)
  180. headers = pprint.pformat(self._headers_log(environ))
  181. logger.debug("Request headers:\n%s", headers)
  182. # Let reverse proxies overwrite SCRIPT_NAME
  183. if "HTTP_X_SCRIPT_NAME" in environ:
  184. # script_name must be removed from PATH_INFO by the client.
  185. unsafe_base_prefix = environ["HTTP_X_SCRIPT_NAME"]
  186. logger.debug("Script name overwritten by client: %r",
  187. unsafe_base_prefix)
  188. else:
  189. # SCRIPT_NAME is already removed from PATH_INFO, according to the
  190. # WSGI specification.
  191. unsafe_base_prefix = environ.get("SCRIPT_NAME", "")
  192. # Sanitize base prefix
  193. base_prefix = pathutils.sanitize_path(unsafe_base_prefix).rstrip("/")
  194. logger.debug("Sanitized script name: %r", base_prefix)
  195. # Sanitize request URI (a WSGI server indicates with an empty path,
  196. # that the URL targets the application root without a trailing slash)
  197. path = pathutils.sanitize_path(environ.get("PATH_INFO", ""))
  198. logger.debug("Sanitized path: %r", path)
  199. # Get function corresponding to method
  200. function = getattr(self, "do_%s" % environ["REQUEST_METHOD"].upper())
  201. # If "/.well-known" is not available, clients query "/"
  202. if path == "/.well-known" or path.startswith("/.well-known/"):
  203. return response(*httputils.NOT_FOUND)
  204. # Ask authentication backend to check rights
  205. login = password = ""
  206. external_login = self._auth.get_external_login(environ)
  207. authorization = environ.get("HTTP_AUTHORIZATION", "")
  208. if external_login:
  209. login, password = external_login
  210. login, password = login or "", password or ""
  211. elif authorization.startswith("Basic"):
  212. authorization = authorization[len("Basic"):].strip()
  213. login, password = self._decode(base64.b64decode(
  214. authorization.encode("ascii")), environ).split(":", 1)
  215. user = self._auth.login(login, password) or "" if login else ""
  216. if user and login == user:
  217. logger.info("Successful login: %r", user)
  218. elif user:
  219. logger.info("Successful login: %r -> %r", login, user)
  220. elif login:
  221. logger.info("Failed login attempt: %r", login)
  222. # Random delay to avoid timing oracles and bruteforce attacks
  223. delay = self.configuration.get("auth", "delay")
  224. if delay > 0:
  225. random_delay = delay * (0.5 + random.random())
  226. logger.debug("Sleeping %.3f seconds", random_delay)
  227. time.sleep(random_delay)
  228. if user and not pathutils.is_safe_path_component(user):
  229. # Prevent usernames like "user/calendar.ics"
  230. logger.info("Refused unsafe username: %r", user)
  231. user = ""
  232. # Create principal collection
  233. if user:
  234. principal_path = "/%s/" % user
  235. with self._storage.acquire_lock("r", user):
  236. principal = next(self._storage.discover(
  237. principal_path, depth="1"), None)
  238. if not principal:
  239. if "W" in self._rights.authorization(user, principal_path):
  240. with self._storage.acquire_lock("w", user):
  241. try:
  242. self._storage.create_collection(principal_path)
  243. except ValueError as e:
  244. logger.warning("Failed to create principal "
  245. "collection %r: %s", user, e)
  246. user = ""
  247. else:
  248. logger.warning("Access to principal path %r denied by "
  249. "rights backend", principal_path)
  250. if self.configuration.get("server", "_internal_server"):
  251. # Verify content length
  252. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  253. if content_length:
  254. max_content_length = self.configuration.get(
  255. "server", "max_content_length")
  256. if max_content_length and content_length > max_content_length:
  257. logger.info("Request body too large: %d", content_length)
  258. return response(*httputils.REQUEST_ENTITY_TOO_LARGE)
  259. if not login or user:
  260. status, headers, answer = function(
  261. environ, base_prefix, path, user)
  262. if (status, headers, answer) == httputils.NOT_ALLOWED:
  263. logger.info("Access to %r denied for %s", path,
  264. repr(user) if user else "anonymous user")
  265. else:
  266. status, headers, answer = httputils.NOT_ALLOWED
  267. if ((status, headers, answer) == httputils.NOT_ALLOWED and not user and
  268. not external_login):
  269. # Unknown or unauthorized user
  270. logger.debug("Asking client for authentication")
  271. status = client.UNAUTHORIZED
  272. realm = self.configuration.get("auth", "realm")
  273. headers = dict(headers)
  274. headers.update({
  275. "WWW-Authenticate":
  276. "Basic realm=\"%s\"" % realm})
  277. return response(status, headers, answer)
  278. def _read_raw_content(self, environ):
  279. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  280. if not content_length:
  281. return b""
  282. content = environ["wsgi.input"].read(content_length)
  283. if len(content) < content_length:
  284. raise RuntimeError("Request body too short: %d" % len(content))
  285. return content
  286. def _read_content(self, environ):
  287. content = self._decode(self._read_raw_content(environ), environ)
  288. logger.debug("Request content:\n%s", content)
  289. return content
  290. def _read_xml_content(self, environ):
  291. content = self._decode(self._read_raw_content(environ), environ)
  292. if not content:
  293. return None
  294. try:
  295. xml_content = DefusedET.fromstring(content)
  296. except ET.ParseError as e:
  297. logger.debug("Request content (Invalid XML):\n%s", content)
  298. raise RuntimeError("Failed to parse XML: %s" % e) from e
  299. if logger.isEnabledFor(logging.DEBUG):
  300. logger.debug("Request content:\n%s",
  301. xmlutils.pretty_xml(xml_content))
  302. return xml_content
  303. def _write_xml_content(self, xml_content):
  304. if logger.isEnabledFor(logging.DEBUG):
  305. logger.debug("Response content:\n%s",
  306. xmlutils.pretty_xml(xml_content))
  307. f = io.BytesIO()
  308. ET.ElementTree(xml_content).write(f, encoding=self._encoding,
  309. xml_declaration=True)
  310. return f.getvalue()
  311. def _webdav_error_response(self, status, human_tag):
  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)))