__init__.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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 pkg_resources
  36. from radicale import (auth, httputils, log, pathutils, rights, storage, web,
  37. xmlutils)
  38. from radicale.app.delete import ApplicationDeleteMixin
  39. from radicale.app.get import ApplicationGetMixin
  40. from radicale.app.head import ApplicationHeadMixin
  41. from radicale.app.mkcalendar import ApplicationMkcalendarMixin
  42. from radicale.app.mkcol import ApplicationMkcolMixin
  43. from radicale.app.move import ApplicationMoveMixin
  44. from radicale.app.options import ApplicationOptionsMixin
  45. from radicale.app.propfind import ApplicationPropfindMixin
  46. from radicale.app.proppatch import ApplicationProppatchMixin
  47. from radicale.app.put import ApplicationPutMixin
  48. from radicale.app.report import ApplicationReportMixin
  49. from radicale.log import logger
  50. VERSION = pkg_resources.get_distribution("radicale").version
  51. class Application(
  52. ApplicationDeleteMixin, ApplicationGetMixin, ApplicationHeadMixin,
  53. ApplicationMkcalendarMixin, ApplicationMkcolMixin,
  54. ApplicationMoveMixin, ApplicationOptionsMixin,
  55. ApplicationPropfindMixin, ApplicationProppatchMixin,
  56. ApplicationPutMixin, ApplicationReportMixin):
  57. """WSGI application."""
  58. def __init__(self, configuration):
  59. """Initialize Application.
  60. ``configuration`` see ``radicale.config`` module.
  61. The ``configuration`` must not change during the lifetime of
  62. this object, it is kept as an internal reference.
  63. """
  64. super().__init__()
  65. self.configuration = configuration
  66. self._auth = auth.load(configuration)
  67. self._storage = storage.load(configuration)
  68. self._rights = rights.load(configuration)
  69. self._web = web.load(configuration)
  70. self._encoding = configuration.get("encoding", "request")
  71. def _headers_log(self, environ):
  72. """Sanitize headers for logging."""
  73. request_environ = dict(environ)
  74. # Mask passwords
  75. mask_passwords = self.configuration.get("logging", "mask_passwords")
  76. authorization = request_environ.get("HTTP_AUTHORIZATION", "")
  77. if mask_passwords and authorization.startswith("Basic"):
  78. request_environ["HTTP_AUTHORIZATION"] = "Basic **masked**"
  79. if request_environ.get("HTTP_COOKIE"):
  80. request_environ["HTTP_COOKIE"] = "**masked**"
  81. return request_environ
  82. def decode(self, text, environ):
  83. """Try to magically decode ``text`` according to given ``environ``."""
  84. # List of charsets to try
  85. charsets = []
  86. # First append content charset given in the request
  87. content_type = environ.get("CONTENT_TYPE")
  88. if content_type and "charset=" in content_type:
  89. charsets.append(
  90. content_type.split("charset=")[1].split(";")[0].strip())
  91. # Then append default Radicale charset
  92. charsets.append(self._encoding)
  93. # Then append various fallbacks
  94. charsets.append("utf-8")
  95. charsets.append("iso8859-1")
  96. # Try to decode
  97. for charset in charsets:
  98. try:
  99. return text.decode(charset)
  100. except UnicodeDecodeError:
  101. pass
  102. raise UnicodeDecodeError
  103. def __call__(self, environ, start_response):
  104. with log.register_stream(environ["wsgi.errors"]):
  105. try:
  106. status, headers, answers = self._handle_request(environ)
  107. except Exception as e:
  108. try:
  109. method = str(environ["REQUEST_METHOD"])
  110. except Exception:
  111. method = "unknown"
  112. try:
  113. path = str(environ.get("PATH_INFO", ""))
  114. except Exception:
  115. path = ""
  116. logger.error("An exception occurred during %s request on %r: "
  117. "%s", method, path, e, exc_info=True)
  118. status, headers, answer = httputils.INTERNAL_SERVER_ERROR
  119. answer = answer.encode("ascii")
  120. status = "%d %s" % (
  121. status, client.responses.get(status, "Unknown"))
  122. headers = [
  123. ("Content-Length", str(len(answer)))] + list(headers)
  124. answers = [answer]
  125. start_response(status, headers)
  126. return answers
  127. def _handle_request(self, environ):
  128. """Manage a request."""
  129. def response(status, headers=(), answer=None):
  130. headers = dict(headers)
  131. # Set content length
  132. if answer:
  133. if hasattr(answer, "encode"):
  134. logger.debug("Response content:\n%s", answer)
  135. headers["Content-Type"] += "; charset=%s" % self._encoding
  136. answer = answer.encode(self._encoding)
  137. accept_encoding = [
  138. encoding.strip() for encoding in
  139. environ.get("HTTP_ACCEPT_ENCODING", "").split(",")
  140. if encoding.strip()]
  141. if "gzip" in accept_encoding:
  142. zcomp = zlib.compressobj(wbits=16 + zlib.MAX_WBITS)
  143. answer = zcomp.compress(answer) + zcomp.flush()
  144. headers["Content-Encoding"] = "gzip"
  145. headers["Content-Length"] = str(len(answer))
  146. # Add extra headers set in configuration
  147. for key in self.configuration.options("headers"):
  148. headers[key] = self.configuration.get("headers", key)
  149. # Start response
  150. time_end = datetime.datetime.now()
  151. status = "%d %s" % (
  152. status, client.responses.get(status, "Unknown"))
  153. logger.info(
  154. "%s response status for %r%s in %.3f seconds: %s",
  155. environ["REQUEST_METHOD"], environ.get("PATH_INFO", ""),
  156. depthinfo, (time_end - time_begin).total_seconds(), status)
  157. # Return response content
  158. return status, list(headers.items()), [answer] if answer else []
  159. remote_host = "unknown"
  160. if environ.get("REMOTE_HOST"):
  161. remote_host = repr(environ["REMOTE_HOST"])
  162. elif environ.get("REMOTE_ADDR"):
  163. remote_host = environ["REMOTE_ADDR"]
  164. if environ.get("HTTP_X_FORWARDED_FOR"):
  165. remote_host = "%r (forwarded by %s)" % (
  166. environ["HTTP_X_FORWARDED_FOR"], remote_host)
  167. remote_useragent = ""
  168. if environ.get("HTTP_USER_AGENT"):
  169. remote_useragent = " using %r" % environ["HTTP_USER_AGENT"]
  170. depthinfo = ""
  171. if environ.get("HTTP_DEPTH"):
  172. depthinfo = " with depth %r" % environ["HTTP_DEPTH"]
  173. time_begin = datetime.datetime.now()
  174. logger.info(
  175. "%s request for %r%s received from %s%s",
  176. environ["REQUEST_METHOD"], environ.get("PATH_INFO", ""), depthinfo,
  177. remote_host, remote_useragent)
  178. headers = pprint.pformat(self._headers_log(environ))
  179. logger.debug("Request headers:\n%s", headers)
  180. # Let reverse proxies overwrite SCRIPT_NAME
  181. if "HTTP_X_SCRIPT_NAME" in environ:
  182. # script_name must be removed from PATH_INFO by the client.
  183. unsafe_base_prefix = environ["HTTP_X_SCRIPT_NAME"]
  184. logger.debug("Script name overwritten by client: %r",
  185. unsafe_base_prefix)
  186. else:
  187. # SCRIPT_NAME is already removed from PATH_INFO, according to the
  188. # WSGI specification.
  189. unsafe_base_prefix = environ.get("SCRIPT_NAME", "")
  190. # Sanitize base prefix
  191. base_prefix = pathutils.sanitize_path(unsafe_base_prefix).rstrip("/")
  192. logger.debug("Sanitized script name: %r", base_prefix)
  193. # Sanitize request URI (a WSGI server indicates with an empty path,
  194. # that the URL targets the application root without a trailing slash)
  195. path = pathutils.sanitize_path(environ.get("PATH_INFO", ""))
  196. logger.debug("Sanitized path: %r", path)
  197. # Get function corresponding to method
  198. function = getattr(self, "do_%s" % environ["REQUEST_METHOD"].upper())
  199. # If "/.well-known" is not available, clients query "/"
  200. if path == "/.well-known" or path.startswith("/.well-known/"):
  201. return response(*httputils.NOT_FOUND)
  202. # Ask authentication backend to check rights
  203. login = password = ""
  204. external_login = self._auth.get_external_login(environ)
  205. authorization = environ.get("HTTP_AUTHORIZATION", "")
  206. if external_login:
  207. login, password = external_login
  208. login, password = login or "", password or ""
  209. elif authorization.startswith("Basic"):
  210. authorization = authorization[len("Basic"):].strip()
  211. login, password = self.decode(base64.b64decode(
  212. authorization.encode("ascii")), environ).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.info("Failed login attempt: %r", login)
  220. # Random delay to avoid timing oracles and bruteforce attacks
  221. delay = self.configuration.get("auth", "delay")
  222. if delay > 0:
  223. random_delay = 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. if self._rights.authorized(user, principal_path, "W"):
  234. with self._storage.acquire_lock("r", user):
  235. principal = next(
  236. self._storage.discover(principal_path, depth="1"),
  237. None)
  238. if not principal:
  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("internal", "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 access(self, user, path, permission, item=None):
  278. if permission not in "rw":
  279. raise ValueError("Invalid permission argument: %r" % permission)
  280. if not item:
  281. permissions = permission + permission.upper()
  282. parent_permissions = permission
  283. elif isinstance(item, storage.BaseCollection):
  284. if item.get_meta("tag"):
  285. permissions = permission
  286. else:
  287. permissions = permission.upper()
  288. parent_permissions = ""
  289. else:
  290. permissions = ""
  291. parent_permissions = permission
  292. if permissions and self._rights.authorized(user, path, permissions):
  293. return True
  294. if parent_permissions:
  295. parent_path = pathutils.unstrip_path(
  296. posixpath.dirname(pathutils.strip_path(path)), True)
  297. if self._rights.authorized(user, parent_path, parent_permissions):
  298. return True
  299. return False
  300. def read_raw_content(self, environ):
  301. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  302. if not content_length:
  303. return b""
  304. content = environ["wsgi.input"].read(content_length)
  305. if len(content) < content_length:
  306. raise RuntimeError("Request body too short: %d" % len(content))
  307. return content
  308. def read_content(self, environ):
  309. content = self.decode(self.read_raw_content(environ), environ)
  310. logger.debug("Request content:\n%s", content)
  311. return content
  312. def read_xml_content(self, environ):
  313. content = self.decode(self.read_raw_content(environ), environ)
  314. if not content:
  315. return None
  316. try:
  317. xml_content = ET.fromstring(content)
  318. except ET.ParseError as e:
  319. logger.debug("Request content (Invalid XML):\n%s", content)
  320. raise RuntimeError("Failed to parse XML: %s" % e) from e
  321. if logger.isEnabledFor(logging.DEBUG):
  322. logger.debug("Request content:\n%s",
  323. xmlutils.pretty_xml(xml_content))
  324. return xml_content
  325. def write_xml_content(self, xml_content):
  326. if logger.isEnabledFor(logging.DEBUG):
  327. logger.debug("Response content:\n%s",
  328. xmlutils.pretty_xml(xml_content))
  329. f = io.BytesIO()
  330. ET.ElementTree(xml_content).write(f, encoding=self._encoding,
  331. xml_declaration=True)
  332. return f.getvalue()
  333. def webdav_error_response(self, namespace, name,
  334. status=httputils.WEBDAV_PRECONDITION_FAILED[0]):
  335. """Generate XML error response."""
  336. headers = {"Content-Type": "text/xml; charset=%s" % self._encoding}
  337. content = self.write_xml_content(
  338. xmlutils.webdav_error(namespace, name))
  339. return status, headers, content