rights.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. # This file is part of Radicale Server - Calendar Server
  2. # Copyright © 2012-2016 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. import sys
  34. from configparser import ConfigParser
  35. from io import StringIO
  36. from . import config, log
  37. def _load():
  38. """Load the rights manager chosen in configuration."""
  39. rights_type = config.get("rights", "type")
  40. if rights_type == "None":
  41. sys.modules[__name__].authorized = (
  42. lambda user, collection, permission: True)
  43. elif rights_type in DEFINED_RIGHTS or rights_type == "from_file":
  44. pass # authorized is already defined
  45. else:
  46. __import__(rights_type)
  47. sys.modules[__name__].authorized = sys.modules[rights_type].authorized
  48. DEFINED_RIGHTS = {
  49. "authenticated": """
  50. [rw]
  51. user:.+
  52. collection:.*
  53. permission:rw
  54. """,
  55. "owner_write": """
  56. [w]
  57. user:.+
  58. collection:^%(login)s(/.*)?$
  59. permission:rw
  60. [r]
  61. user:.+
  62. collection:.*
  63. permission:r
  64. """,
  65. "owner_only": """
  66. [rw]
  67. user:.+
  68. collection:^%(login)s(/.*)?$
  69. permission:rw
  70. """}
  71. def _read_from_sections(user, collection_url, permission):
  72. """Get regex sections."""
  73. filename = os.path.expanduser(config.get("rights", "file"))
  74. rights_type = config.get("rights", "type").lower()
  75. # Prevent "regex injection"
  76. user_escaped = re.escape(user)
  77. collection_url_escaped = re.escape(collection_url)
  78. regex = ConfigParser({"login": user_escaped, "path": collection_url_escaped})
  79. if rights_type in DEFINED_RIGHTS:
  80. log.LOGGER.debug("Rights type '%s'" % rights_type)
  81. regex.readfp(StringIO(DEFINED_RIGHTS[rights_type]))
  82. elif rights_type == "from_file":
  83. log.LOGGER.debug("Reading rights from file %s" % filename)
  84. if not regex.read(filename):
  85. log.LOGGER.error("File '%s' not found for rights" % filename)
  86. return False
  87. else:
  88. log.LOGGER.error("Unknown rights type '%s'" % rights_type)
  89. return False
  90. for section in regex.sections():
  91. re_user = regex.get(section, "user")
  92. re_collection = regex.get(section, "collection")
  93. log.LOGGER.debug(
  94. "Test if '%s:%s' matches against '%s:%s' from section '%s'" % (
  95. user, collection_url, re_user, re_collection, section))
  96. user_match = re.match(re_user, user)
  97. if user_match:
  98. re_collection = re_collection.format(*user_match.groups())
  99. if re.match(re_collection, collection_url):
  100. log.LOGGER.debug("Section '%s' matches" % section)
  101. return permission in regex.get(section, "permission")
  102. else:
  103. log.LOGGER.debug("Section '%s' does not match" % section)
  104. return False
  105. def authorized(user, collection, permission):
  106. """Check if the user is allowed to read or write the collection.
  107. If the user is empty, check for anonymous rights.
  108. """
  109. collection_url = collection.path.rstrip("/") or "/"
  110. if collection_url in (".well-known/carddav", ".well-known/caldav"):
  111. return permission == "r"
  112. rights_type = config.get("rights", "type").lower()
  113. return (
  114. rights_type == "none" or
  115. _read_from_sections(user or "", collection_url, permission))