__init__.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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. """
  62. super().__init__()
  63. self.configuration = configuration
  64. self.auth = auth.load(configuration)
  65. self.storage = storage.load(configuration)
  66. self.rights = rights.load(configuration)
  67. self.Web = web.load(configuration)
  68. self.encoding = configuration.get("encoding", "request")
  69. def _headers_log(self, environ):
  70. """Sanitize headers for logging."""
  71. request_environ = dict(environ)
  72. # Mask passwords
  73. mask_passwords = self.configuration.get("logging", "mask_passwords")
  74. authorization = request_environ.get("HTTP_AUTHORIZATION", "")
  75. if mask_passwords and authorization.startswith("Basic"):
  76. request_environ["HTTP_AUTHORIZATION"] = "Basic **masked**"
  77. if request_environ.get("HTTP_COOKIE"):
  78. request_environ["HTTP_COOKIE"] = "**masked**"
  79. return request_environ
  80. def decode(self, text, environ):
  81. """Try to magically decode ``text`` according to given ``environ``."""
  82. # List of charsets to try
  83. charsets = []
  84. # First append content charset given in the request
  85. content_type = environ.get("CONTENT_TYPE")
  86. if content_type and "charset=" in content_type:
  87. charsets.append(
  88. content_type.split("charset=")[1].split(";")[0].strip())
  89. # Then append default Radicale charset
  90. charsets.append(self.encoding)
  91. # Then append various fallbacks
  92. charsets.append("utf-8")
  93. charsets.append("iso8859-1")
  94. # Try to decode
  95. for charset in charsets:
  96. try:
  97. return text.decode(charset)
  98. except UnicodeDecodeError:
  99. pass
  100. raise UnicodeDecodeError
  101. def __call__(self, environ, start_response):
  102. with log.register_stream(environ["wsgi.errors"]):
  103. try:
  104. status, headers, answers = self._handle_request(environ)
  105. except Exception as e:
  106. try:
  107. method = str(environ["REQUEST_METHOD"])
  108. except Exception:
  109. method = "unknown"
  110. try:
  111. path = str(environ.get("PATH_INFO", ""))
  112. except Exception:
  113. path = ""
  114. logger.error("An exception occurred during %s request on %r: "
  115. "%s", method, path, e, exc_info=True)
  116. status, headers, answer = httputils.INTERNAL_SERVER_ERROR
  117. answer = answer.encode("ascii")
  118. status = "%d %s" % (
  119. status, client.responses.get(status, "Unknown"))
  120. headers = [
  121. ("Content-Length", str(len(answer)))] + list(headers)
  122. answers = [answer]
  123. start_response(status, headers)
  124. return answers
  125. def _handle_request(self, environ):
  126. """Manage a request."""
  127. def response(status, headers=(), answer=None):
  128. headers = dict(headers)
  129. # Set content length
  130. if answer:
  131. if hasattr(answer, "encode"):
  132. logger.debug("Response content:\n%s", answer)
  133. headers["Content-Type"] += "; charset=%s" % self.encoding
  134. answer = answer.encode(self.encoding)
  135. accept_encoding = [
  136. encoding.strip() for encoding in
  137. environ.get("HTTP_ACCEPT_ENCODING", "").split(",")
  138. if encoding.strip()]
  139. if "gzip" in accept_encoding:
  140. zcomp = zlib.compressobj(wbits=16 + zlib.MAX_WBITS)
  141. answer = zcomp.compress(answer) + zcomp.flush()
  142. headers["Content-Encoding"] = "gzip"
  143. headers["Content-Length"] = str(len(answer))
  144. # Add extra headers set in configuration
  145. for key in self.configuration.options("headers"):
  146. headers[key] = self.configuration.get("headers", key)
  147. # Start response
  148. time_end = datetime.datetime.now()
  149. status = "%d %s" % (
  150. status, client.responses.get(status, "Unknown"))
  151. logger.info(
  152. "%s response status for %r%s in %.3f seconds: %s",
  153. environ["REQUEST_METHOD"], environ.get("PATH_INFO", ""),
  154. depthinfo, (time_end - time_begin).total_seconds(), status)
  155. # Return response content
  156. return status, list(headers.items()), [answer] if answer else []
  157. remote_host = "unknown"
  158. if environ.get("REMOTE_HOST"):
  159. remote_host = repr(environ["REMOTE_HOST"])
  160. elif environ.get("REMOTE_ADDR"):
  161. remote_host = environ["REMOTE_ADDR"]
  162. if environ.get("HTTP_X_FORWARDED_FOR"):
  163. remote_host = "%r (forwarded by %s)" % (
  164. environ["HTTP_X_FORWARDED_FOR"], remote_host)
  165. remote_useragent = ""
  166. if environ.get("HTTP_USER_AGENT"):
  167. remote_useragent = " using %r" % environ["HTTP_USER_AGENT"]
  168. depthinfo = ""
  169. if environ.get("HTTP_DEPTH"):
  170. depthinfo = " with depth %r" % environ["HTTP_DEPTH"]
  171. time_begin = datetime.datetime.now()
  172. logger.info(
  173. "%s request for %r%s received from %s%s",
  174. environ["REQUEST_METHOD"], environ.get("PATH_INFO", ""), depthinfo,
  175. remote_host, remote_useragent)
  176. headers = pprint.pformat(self._headers_log(environ))
  177. logger.debug("Request headers:\n%s", headers)
  178. # Let reverse proxies overwrite SCRIPT_NAME
  179. if "HTTP_X_SCRIPT_NAME" in environ:
  180. # script_name must be removed from PATH_INFO by the client.
  181. unsafe_base_prefix = environ["HTTP_X_SCRIPT_NAME"]
  182. logger.debug("Script name overwritten by client: %r",
  183. unsafe_base_prefix)
  184. else:
  185. # SCRIPT_NAME is already removed from PATH_INFO, according to the
  186. # WSGI specification.
  187. unsafe_base_prefix = environ.get("SCRIPT_NAME", "")
  188. # Sanitize base prefix
  189. base_prefix = pathutils.sanitize_path(unsafe_base_prefix).rstrip("/")
  190. logger.debug("Sanitized script name: %r", base_prefix)
  191. # Sanitize request URI (a WSGI server indicates with an empty path,
  192. # that the URL targets the application root without a trailing slash)
  193. path = pathutils.sanitize_path(environ.get("PATH_INFO", ""))
  194. logger.debug("Sanitized path: %r", path)
  195. # Get function corresponding to method
  196. function = getattr(self, "do_%s" % environ["REQUEST_METHOD"].upper())
  197. # If "/.well-known" is not available, clients query "/"
  198. if path == "/.well-known" or path.startswith("/.well-known/"):
  199. return response(*httputils.NOT_FOUND)
  200. # Ask authentication backend to check rights
  201. login = password = ""
  202. external_login = self.auth.get_external_login(environ)
  203. authorization = environ.get("HTTP_AUTHORIZATION", "")
  204. if external_login:
  205. login, password = external_login
  206. login, password = login or "", password or ""
  207. elif authorization.startswith("Basic"):
  208. authorization = authorization[len("Basic"):].strip()
  209. login, password = self.decode(base64.b64decode(
  210. authorization.encode("ascii")), environ).split(":", 1)
  211. user = self.auth.login(login, password) or "" if login else ""
  212. if user and login == user:
  213. logger.info("Successful login: %r", user)
  214. elif user:
  215. logger.info("Successful login: %r -> %r", login, user)
  216. elif login:
  217. logger.info("Failed login attempt: %r", login)
  218. # Random delay to avoid timing oracles and bruteforce attacks
  219. delay = self.configuration.get("auth", "delay")
  220. if delay > 0:
  221. random_delay = delay * (0.5 + random.random())
  222. logger.debug("Sleeping %.3f seconds", random_delay)
  223. time.sleep(random_delay)
  224. if user and not pathutils.is_safe_path_component(user):
  225. # Prevent usernames like "user/calendar.ics"
  226. logger.info("Refused unsafe username: %r", user)
  227. user = ""
  228. # Create principal collection
  229. if user:
  230. principal_path = "/%s/" % user
  231. if self.rights.authorized(user, principal_path, "W"):
  232. with self.storage.acquire_lock("r", user):
  233. principal = next(
  234. self.storage.discover(principal_path, depth="1"),
  235. None)
  236. if not principal:
  237. with self.storage.acquire_lock("w", user):
  238. try:
  239. self.storage.create_collection(principal_path)
  240. except ValueError as e:
  241. logger.warning("Failed to create principal "
  242. "collection %r: %s", user, e)
  243. user = ""
  244. else:
  245. logger.warning("Access to principal path %r denied by "
  246. "rights backend", principal_path)
  247. if self.configuration.get("internal", "internal_server"):
  248. # Verify content length
  249. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  250. if content_length:
  251. max_content_length = self.configuration.get(
  252. "server", "max_content_length")
  253. if max_content_length and content_length > 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. realm = self.configuration.get("auth", "realm")
  270. headers = dict(headers)
  271. headers.update({
  272. "WWW-Authenticate":
  273. "Basic realm=\"%s\"" % realm})
  274. return response(status, headers, answer)
  275. def access(self, user, path, permission, item=None):
  276. if permission not in "rw":
  277. raise ValueError("Invalid permission argument: %r" % permission)
  278. if not item:
  279. permissions = permission + permission.upper()
  280. parent_permissions = permission
  281. elif isinstance(item, storage.BaseCollection):
  282. if item.get_meta("tag"):
  283. permissions = permission
  284. else:
  285. permissions = permission.upper()
  286. parent_permissions = ""
  287. else:
  288. permissions = ""
  289. parent_permissions = permission
  290. if permissions and self.rights.authorized(user, path, permissions):
  291. return True
  292. if parent_permissions:
  293. parent_path = pathutils.unstrip_path(
  294. posixpath.dirname(pathutils.strip_path(path)), True)
  295. if self.rights.authorized(user, parent_path, parent_permissions):
  296. return True
  297. return False
  298. def read_raw_content(self, environ):
  299. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  300. if not content_length:
  301. return b""
  302. content = environ["wsgi.input"].read(content_length)
  303. if len(content) < content_length:
  304. raise RuntimeError("Request body too short: %d" % len(content))
  305. return content
  306. def read_content(self, environ):
  307. content = self.decode(self.read_raw_content(environ), environ)
  308. logger.debug("Request content:\n%s", content)
  309. return content
  310. def read_xml_content(self, environ):
  311. content = self.decode(self.read_raw_content(environ), environ)
  312. if not content:
  313. return None
  314. try:
  315. xml_content = ET.fromstring(content)
  316. except ET.ParseError as e:
  317. logger.debug("Request content (Invalid XML):\n%s", content)
  318. raise RuntimeError("Failed to parse XML: %s" % e) from e
  319. if logger.isEnabledFor(logging.DEBUG):
  320. logger.debug("Request content:\n%s",
  321. xmlutils.pretty_xml(xml_content))
  322. return xml_content
  323. def write_xml_content(self, xml_content):
  324. if logger.isEnabledFor(logging.DEBUG):
  325. logger.debug("Response content:\n%s",
  326. xmlutils.pretty_xml(xml_content))
  327. f = io.BytesIO()
  328. ET.ElementTree(xml_content).write(f, encoding=self.encoding,
  329. xml_declaration=True)
  330. return f.getvalue()
  331. def webdav_error_response(self, namespace, name,
  332. status=httputils.WEBDAV_PRECONDITION_FAILED[0]):
  333. """Generate XML error response."""
  334. headers = {"Content-Type": "text/xml; charset=%s" % self.encoding}
  335. content = self.write_xml_content(
  336. xmlutils.webdav_error(namespace, name))
  337. return status, headers, content