rights.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. # This file is part of Radicale Server - Calendar Server
  2. # Copyright © 2012-2017 Guillaume Ayoub
  3. #
  4. # This library is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This library is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  16. """
  17. Rights backends.
  18. This module loads the rights backend, according to the rights
  19. configuration.
  20. Default rights are based on a regex-based file whose name is specified in the
  21. config (section "right", key "file").
  22. Authentication login is matched against the "user" key, and collection's path
  23. is matched against the "collection" key. You can use Python's ConfigParser
  24. interpolation values %(login)s and %(path)s. You can also get groups from the
  25. user regex in the collection with {0}, {1}, etc.
  26. For example, for the "user" key, ".+" means "authenticated user" and ".*"
  27. means "anybody" (including anonymous users).
  28. Section names are only used for naming the rule.
  29. Leading or ending slashes are trimmed from collection's path.
  30. """
  31. import configparser
  32. import os.path
  33. import re
  34. from importlib import import_module
  35. from . import storage
  36. def load(configuration, logger):
  37. """Load the rights manager chosen in configuration."""
  38. rights_type = configuration.get("rights", "type")
  39. if configuration.get("auth", "type") in ("None", "none"): # DEPRECATED
  40. rights_type = "None"
  41. if rights_type in ("None", "none"): # DEPRECATED: use "none"
  42. rights_class = NoneRights
  43. elif rights_type == "authenticated":
  44. rights_class = AuthenticatedRights
  45. elif rights_type == "owner_write":
  46. rights_class = OwnerWriteRights
  47. elif rights_type == "owner_only":
  48. rights_class = OwnerOnlyRights
  49. elif rights_type == "from_file":
  50. rights_class = Rights
  51. else:
  52. try:
  53. rights_class = import_module(rights_type).Rights
  54. except ImportError as e:
  55. raise RuntimeError("Rights module %r not found" %
  56. rights_type) from e
  57. logger.info("Rights type is %r", rights_type)
  58. return rights_class(configuration, logger).authorized
  59. class BaseRights:
  60. def __init__(self, configuration, logger):
  61. self.configuration = configuration
  62. self.logger = logger
  63. def authorized(self, user, collection, permission):
  64. """Check if the user is allowed to read or write the collection.
  65. If the user is empty, check for anonymous rights.
  66. """
  67. raise NotImplementedError
  68. class NoneRights(BaseRights):
  69. def authorized(self, user, path, permission):
  70. return True
  71. class AuthenticatedRights(BaseRights):
  72. def authorized(self, user, path, permission):
  73. return bool(user)
  74. class OwnerWriteRights(BaseRights):
  75. def authorized(self, user, path, permission):
  76. sane_path = storage.sanitize_path(path).strip("/")
  77. return bool(user) and (permission == "r" or
  78. user == sane_path.split("/", maxsplit=1)[0])
  79. class OwnerOnlyRights(BaseRights):
  80. def authorized(self, user, path, permission):
  81. sane_path = storage.sanitize_path(path).strip("/")
  82. return bool(user) and (
  83. permission == "r" and not sane_path.strip("/") or
  84. user == sane_path.split("/", maxsplit=1)[0])
  85. class Rights(BaseRights):
  86. def __init__(self, configuration, logger):
  87. super().__init__(configuration, logger)
  88. self.filename = os.path.expanduser(configuration.get("rights", "file"))
  89. def authorized(self, user, path, permission):
  90. user = user or ""
  91. sane_path = storage.sanitize_path(path).strip("/")
  92. # Prevent "regex injection"
  93. user_escaped = re.escape(user)
  94. sane_path_escaped = re.escape(sane_path)
  95. regex = configparser.ConfigParser(
  96. {"login": user_escaped, "path": sane_path_escaped})
  97. try:
  98. if not regex.read(self.filename):
  99. raise RuntimeError("No such file: %r" %
  100. self.filename)
  101. except Exception as e:
  102. raise RuntimeError("Failed to load rights file %r: %s" %
  103. (self.filename, e)) from e
  104. for section in regex.sections():
  105. try:
  106. re_user_pattern = regex.get(section, "user")
  107. re_collection_pattern = regex.get(section, "collection")
  108. # Emulate fullmatch
  109. user_match = re.match(r"(?:%s)\Z" % re_user_pattern, user)
  110. collection_match = user_match and re.match(
  111. r"(?:%s)\Z" % re_collection_pattern.format(
  112. *map(re.escape, user_match.groups())), sane_path)
  113. except Exception as e:
  114. raise RuntimeError("Error in section %r of rights file %r: "
  115. "%s" % (section, self.filename, e)) from e
  116. if user_match and collection_match:
  117. self.logger.debug("Rule %r:%r matches %r:%r from section %r",
  118. user, sane_path, re_user_pattern,
  119. re_collection_pattern, section)
  120. return permission in regex.get(section, "permission")
  121. else:
  122. self.logger.debug("Rule %r:%r doesn't match %r:%r from section"
  123. " %r", user, sane_path, re_user_pattern,
  124. re_collection_pattern, section)
  125. self.logger.info(
  126. "Rights: %r:%r doesn't match any section", user, sane_path)
  127. return False