You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

243 lines
9.0 KiB

  1. # Copyright 2018 New Vector Ltd
  2. # Copyright 2019-2021 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import logging
  16. from typing import Any, List, Set
  17. from synapse.config.sso import SsoAttributeRequirement
  18. from synapse.types import JsonDict
  19. from synapse.util.check_dependencies import check_requirements
  20. from synapse.util.module_loader import load_module, load_python_module
  21. from ._base import Config, ConfigError
  22. from ._util import validate_config
  23. logger = logging.getLogger(__name__)
  24. DEFAULT_USER_MAPPING_PROVIDER = "synapse.handlers.saml.DefaultSamlMappingProvider"
  25. # The module that DefaultSamlMappingProvider is in was renamed, we want to
  26. # transparently handle both the same.
  27. LEGACY_USER_MAPPING_PROVIDER = (
  28. "synapse.handlers.saml_handler.DefaultSamlMappingProvider"
  29. )
  30. def _dict_merge(merge_dict: dict, into_dict: dict) -> None:
  31. """Do a deep merge of two dicts
  32. Recursively merges `merge_dict` into `into_dict`:
  33. * For keys where both `merge_dict` and `into_dict` have a dict value, the values
  34. are recursively merged
  35. * For all other keys, the values in `into_dict` (if any) are overwritten with
  36. the value from `merge_dict`.
  37. Args:
  38. merge_dict: dict to merge
  39. into_dict: target dict to be modified
  40. """
  41. for k, v in merge_dict.items():
  42. if k not in into_dict:
  43. into_dict[k] = v
  44. continue
  45. current_val = into_dict[k]
  46. if isinstance(v, dict) and isinstance(current_val, dict):
  47. _dict_merge(v, current_val)
  48. continue
  49. # otherwise we just overwrite
  50. into_dict[k] = v
  51. class SAML2Config(Config):
  52. section = "saml2"
  53. def read_config(self, config: JsonDict, **kwargs: Any) -> None:
  54. self.saml2_enabled = False
  55. saml2_config = config.get("saml2_config")
  56. if not saml2_config or not saml2_config.get("enabled", True):
  57. return
  58. if not saml2_config.get("sp_config") and not saml2_config.get("config_path"):
  59. return
  60. check_requirements("saml2")
  61. self.saml2_enabled = True
  62. attribute_requirements = saml2_config.get("attribute_requirements") or []
  63. self.attribute_requirements = _parse_attribute_requirements_def(
  64. attribute_requirements
  65. )
  66. self.saml2_grandfathered_mxid_source_attribute = saml2_config.get(
  67. "grandfathered_mxid_source_attribute", "uid"
  68. )
  69. # refers to a SAML IdP entity ID
  70. self.saml2_idp_entityid = saml2_config.get("idp_entityid", None)
  71. # IdP properties for Matrix clients
  72. self.idp_name = saml2_config.get("idp_name", "SAML")
  73. self.idp_icon = saml2_config.get("idp_icon")
  74. self.idp_brand = saml2_config.get("idp_brand")
  75. # user_mapping_provider may be None if the key is present but has no value
  76. ump_dict = saml2_config.get("user_mapping_provider") or {}
  77. # Use the default user mapping provider if not set
  78. ump_dict.setdefault("module", DEFAULT_USER_MAPPING_PROVIDER)
  79. if ump_dict.get("module") == LEGACY_USER_MAPPING_PROVIDER:
  80. ump_dict["module"] = DEFAULT_USER_MAPPING_PROVIDER
  81. # Ensure a config is present
  82. ump_dict["config"] = ump_dict.get("config") or {}
  83. if ump_dict["module"] == DEFAULT_USER_MAPPING_PROVIDER:
  84. # Load deprecated options for use by the default module
  85. old_mxid_source_attribute = saml2_config.get("mxid_source_attribute")
  86. if old_mxid_source_attribute:
  87. logger.warning(
  88. "The config option saml2_config.mxid_source_attribute is deprecated. "
  89. "Please use saml2_config.user_mapping_provider.config"
  90. ".mxid_source_attribute instead."
  91. )
  92. ump_dict["config"]["mxid_source_attribute"] = old_mxid_source_attribute
  93. old_mxid_mapping = saml2_config.get("mxid_mapping")
  94. if old_mxid_mapping:
  95. logger.warning(
  96. "The config option saml2_config.mxid_mapping is deprecated. Please "
  97. "use saml2_config.user_mapping_provider.config.mxid_mapping instead."
  98. )
  99. ump_dict["config"]["mxid_mapping"] = old_mxid_mapping
  100. # Retrieve an instance of the module's class
  101. # Pass the config dictionary to the module for processing
  102. (
  103. self.saml2_user_mapping_provider_class,
  104. self.saml2_user_mapping_provider_config,
  105. ) = load_module(ump_dict, ("saml2_config", "user_mapping_provider"))
  106. # Ensure loaded user mapping module has defined all necessary methods
  107. # Note parse_config() is already checked during the call to load_module
  108. required_methods = [
  109. "get_saml_attributes",
  110. "saml_response_to_user_attributes",
  111. "get_remote_user_id",
  112. ]
  113. missing_methods = [
  114. method
  115. for method in required_methods
  116. if not hasattr(self.saml2_user_mapping_provider_class, method)
  117. ]
  118. if missing_methods:
  119. raise ConfigError(
  120. "Class specified by saml2_config."
  121. "user_mapping_provider.module is missing required "
  122. "methods: %s" % (", ".join(missing_methods),)
  123. )
  124. # Get the desired saml auth response attributes from the module
  125. saml2_config_dict = self._default_saml_config_dict(
  126. *self.saml2_user_mapping_provider_class.get_saml_attributes(
  127. self.saml2_user_mapping_provider_config
  128. )
  129. )
  130. _dict_merge(
  131. merge_dict=saml2_config.get("sp_config", {}), into_dict=saml2_config_dict
  132. )
  133. config_path = saml2_config.get("config_path", None)
  134. if config_path is not None:
  135. mod = load_python_module(config_path)
  136. config_dict_from_file = getattr(mod, "CONFIG", None)
  137. if config_dict_from_file is None:
  138. raise ConfigError(
  139. "Config path specified by saml2_config.config_path does not "
  140. "have a CONFIG property."
  141. )
  142. _dict_merge(merge_dict=config_dict_from_file, into_dict=saml2_config_dict)
  143. import saml2.config
  144. self.saml2_sp_config = saml2.config.SPConfig()
  145. self.saml2_sp_config.load(saml2_config_dict)
  146. # session lifetime: in milliseconds
  147. self.saml2_session_lifetime = self.parse_duration(
  148. saml2_config.get("saml_session_lifetime", "15m")
  149. )
  150. def _default_saml_config_dict(
  151. self, required_attributes: Set[str], optional_attributes: Set[str]
  152. ) -> JsonDict:
  153. """Generate a configuration dictionary with required and optional attributes that
  154. will be needed to process new user registration
  155. Args:
  156. required_attributes: SAML auth response attributes that are
  157. necessary to function
  158. optional_attributes: SAML auth response attributes that can be used to add
  159. additional information to Synapse user accounts, but are not required
  160. Returns:
  161. A SAML configuration dictionary
  162. """
  163. import saml2
  164. if self.saml2_grandfathered_mxid_source_attribute:
  165. optional_attributes.add(self.saml2_grandfathered_mxid_source_attribute)
  166. optional_attributes -= required_attributes
  167. public_baseurl = self.root.server.public_baseurl
  168. metadata_url = public_baseurl + "_synapse/client/saml2/metadata.xml"
  169. response_url = public_baseurl + "_synapse/client/saml2/authn_response"
  170. return {
  171. "entityid": metadata_url,
  172. "service": {
  173. "sp": {
  174. "endpoints": {
  175. "assertion_consumer_service": [
  176. (response_url, saml2.BINDING_HTTP_POST)
  177. ]
  178. },
  179. "required_attributes": list(required_attributes),
  180. "optional_attributes": list(optional_attributes),
  181. # "name_id_format": saml2.saml.NAMEID_FORMAT_PERSISTENT,
  182. }
  183. },
  184. }
  185. ATTRIBUTE_REQUIREMENTS_SCHEMA = {
  186. "type": "array",
  187. "items": SsoAttributeRequirement.JSON_SCHEMA,
  188. }
  189. def _parse_attribute_requirements_def(
  190. attribute_requirements: Any,
  191. ) -> List[SsoAttributeRequirement]:
  192. validate_config(
  193. ATTRIBUTE_REQUIREMENTS_SCHEMA,
  194. attribute_requirements,
  195. config_path=("saml2_config", "attribute_requirements"),
  196. )
  197. return [SsoAttributeRequirement(**x) for x in attribute_requirements]