rights.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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 os.path
  32. import re
  33. from configparser import ConfigParser
  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") == "None":
  40. rights_type = "None"
  41. logger.info("Rights type is %r", rights_type)
  42. if rights_type == "None":
  43. rights_class = NoneRights
  44. elif rights_type == "authenticated":
  45. rights_class = AuthenticatedRights
  46. elif rights_type == "owner_write":
  47. rights_class = OwnerWriteRights
  48. elif rights_type == "owner_only":
  49. rights_class = OwnerOnlyRights
  50. elif rights_type == "from_file":
  51. rights_class = Rights
  52. else:
  53. rights_class = import_module(rights_type).Rights
  54. return rights_class(configuration, logger).authorized
  55. class BaseRights:
  56. def __init__(self, configuration, logger):
  57. self.configuration = configuration
  58. self.logger = logger
  59. def authorized(self, user, collection, permission):
  60. """Check if the user is allowed to read or write the collection.
  61. If the user is empty, check for anonymous rights.
  62. """
  63. raise NotImplementedError
  64. class NoneRights(BaseRights):
  65. def authorized(self, user, path, permission):
  66. return True
  67. class AuthenticatedRights(BaseRights):
  68. def authorized(self, user, path, permission):
  69. return bool(user)
  70. class OwnerWriteRights(BaseRights):
  71. def authorized(self, user, path, permission):
  72. sane_path = storage.sanitize_path(path).strip("/")
  73. return bool(user) and (permission == "r" or
  74. user == sane_path.split("/", maxsplit=1)[0])
  75. class OwnerOnlyRights(BaseRights):
  76. def authorized(self, user, path, permission):
  77. sane_path = storage.sanitize_path(path).strip("/")
  78. return bool(user) and (
  79. permission == "r" and not sane_path.strip("/") or
  80. user == sane_path.split("/", maxsplit=1)[0])
  81. class Rights(BaseRights):
  82. def __init__(self, configuration, logger):
  83. super().__init__(configuration, logger)
  84. self.filename = os.path.expanduser(configuration.get("rights", "file"))
  85. def authorized(self, user, path, permission):
  86. user = user or ""
  87. sane_path = storage.sanitize_path(path).strip("/")
  88. # Prevent "regex injection"
  89. user_escaped = re.escape(user)
  90. sane_path_escaped = re.escape(sane_path)
  91. regex = ConfigParser(
  92. {"login": user_escaped, "path": sane_path_escaped})
  93. if not regex.read(self.filename):
  94. raise RuntimeError("Failed to read rights from file %r",
  95. self.filename)
  96. return False
  97. for section in regex.sections():
  98. re_user = regex.get(section, "user")
  99. re_collection = regex.get(section, "collection")
  100. self.logger.debug(
  101. "Test if '%s:%s' matches against '%s:%s' from section '%s'",
  102. user, sane_path, re_user, re_collection, section)
  103. # Emulate fullmatch
  104. user_match = re.match(r"(?:%s)\Z" % re_user, user)
  105. if user_match:
  106. re_collection = re_collection.format(*user_match.groups())
  107. # Emulate fullmatch
  108. if re.match(r"(?:%s)\Z" % re_collection, sane_path):
  109. self.logger.debug("Section '%s' matches", section)
  110. return permission in regex.get(section, "permission")
  111. else:
  112. self.logger.debug("Section '%s' does not match", section)
  113. return False