saml_handler.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2019 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. import re
  17. from typing import Callable, Dict, Optional, Set, Tuple
  18. import attr
  19. import saml2
  20. import saml2.response
  21. from saml2.client import Saml2Client
  22. from synapse.api.errors import SynapseError
  23. from synapse.config import ConfigError
  24. from synapse.http.servlet import parse_string
  25. from synapse.http.site import SynapseRequest
  26. from synapse.module_api import ModuleApi
  27. from synapse.types import (
  28. UserID,
  29. map_username_to_mxid_localpart,
  30. mxid_localpart_allowed_characters,
  31. )
  32. from synapse.util.async_helpers import Linearizer
  33. from synapse.util.iterutils import chunk_seq
  34. logger = logging.getLogger(__name__)
  35. @attr.s
  36. class Saml2SessionData:
  37. """Data we track about SAML2 sessions"""
  38. # time the session was created, in milliseconds
  39. creation_time = attr.ib()
  40. # The user interactive authentication session ID associated with this SAML
  41. # session (or None if this SAML session is for an initial login).
  42. ui_auth_session_id = attr.ib(type=Optional[str], default=None)
  43. class SamlHandler:
  44. def __init__(self, hs):
  45. self._saml_client = Saml2Client(hs.config.saml2_sp_config)
  46. self._auth = hs.get_auth()
  47. self._auth_handler = hs.get_auth_handler()
  48. self._registration_handler = hs.get_registration_handler()
  49. self._clock = hs.get_clock()
  50. self._datastore = hs.get_datastore()
  51. self._hostname = hs.hostname
  52. self._saml2_session_lifetime = hs.config.saml2_session_lifetime
  53. self._grandfathered_mxid_source_attribute = (
  54. hs.config.saml2_grandfathered_mxid_source_attribute
  55. )
  56. # plugin to do custom mapping from saml response to mxid
  57. self._user_mapping_provider = hs.config.saml2_user_mapping_provider_class(
  58. hs.config.saml2_user_mapping_provider_config,
  59. ModuleApi(hs, hs.get_auth_handler()),
  60. )
  61. # identifier for the external_ids table
  62. self._auth_provider_id = "saml"
  63. # a map from saml session id to Saml2SessionData object
  64. self._outstanding_requests_dict = {}
  65. # a lock on the mappings
  66. self._mapping_lock = Linearizer(name="saml_mapping", clock=self._clock)
  67. def handle_redirect_request(
  68. self, client_redirect_url: bytes, ui_auth_session_id: Optional[str] = None
  69. ) -> bytes:
  70. """Handle an incoming request to /login/sso/redirect
  71. Args:
  72. client_redirect_url: the URL that we should redirect the
  73. client to when everything is done
  74. ui_auth_session_id: The session ID of the ongoing UI Auth (or
  75. None if this is a login).
  76. Returns:
  77. URL to redirect to
  78. """
  79. reqid, info = self._saml_client.prepare_for_authenticate(
  80. relay_state=client_redirect_url
  81. )
  82. now = self._clock.time_msec()
  83. self._outstanding_requests_dict[reqid] = Saml2SessionData(
  84. creation_time=now, ui_auth_session_id=ui_auth_session_id,
  85. )
  86. for key, value in info["headers"]:
  87. if key == "Location":
  88. return value
  89. # this shouldn't happen!
  90. raise Exception("prepare_for_authenticate didn't return a Location header")
  91. async def handle_saml_response(self, request: SynapseRequest) -> None:
  92. """Handle an incoming request to /_matrix/saml2/authn_response
  93. Args:
  94. request: the incoming request from the browser. We'll
  95. respond to it with a redirect.
  96. Returns:
  97. Completes once we have handled the request.
  98. """
  99. resp_bytes = parse_string(request, "SAMLResponse", required=True)
  100. relay_state = parse_string(request, "RelayState", required=True)
  101. # expire outstanding sessions before parse_authn_request_response checks
  102. # the dict.
  103. self.expire_sessions()
  104. user_id, current_session = await self._map_saml_response_to_user(
  105. resp_bytes, relay_state
  106. )
  107. # Complete the interactive auth session or the login.
  108. if current_session and current_session.ui_auth_session_id:
  109. await self._auth_handler.complete_sso_ui_auth(
  110. user_id, current_session.ui_auth_session_id, request
  111. )
  112. else:
  113. await self._auth_handler.complete_sso_login(user_id, request, relay_state)
  114. async def _map_saml_response_to_user(
  115. self, resp_bytes: str, client_redirect_url: str
  116. ) -> Tuple[str, Optional[Saml2SessionData]]:
  117. """
  118. Given a sample response, retrieve the cached session and user for it.
  119. Args:
  120. resp_bytes: The SAML response.
  121. client_redirect_url: The redirect URL passed in by the client.
  122. Returns:
  123. Tuple of the user ID and SAML session associated with this response.
  124. Raises:
  125. SynapseError if there was a problem with the response.
  126. RedirectException: some mapping providers may raise this if they need
  127. to redirect to an interstitial page.
  128. """
  129. try:
  130. saml2_auth = self._saml_client.parse_authn_request_response(
  131. resp_bytes,
  132. saml2.BINDING_HTTP_POST,
  133. outstanding=self._outstanding_requests_dict,
  134. )
  135. except Exception as e:
  136. raise SynapseError(400, "Unable to parse SAML2 response: %s" % (e,))
  137. if saml2_auth.not_signed:
  138. raise SynapseError(400, "SAML2 response was not signed")
  139. logger.debug("SAML2 response: %s", saml2_auth.origxml)
  140. for assertion in saml2_auth.assertions:
  141. # kibana limits the length of a log field, whereas this is all rather
  142. # useful, so split it up.
  143. count = 0
  144. for part in chunk_seq(str(assertion), 10000):
  145. logger.info(
  146. "SAML2 assertion: %s%s", "(%i)..." % (count,) if count else "", part
  147. )
  148. count += 1
  149. logger.info("SAML2 mapped attributes: %s", saml2_auth.ava)
  150. current_session = self._outstanding_requests_dict.pop(
  151. saml2_auth.in_response_to, None
  152. )
  153. remote_user_id = self._user_mapping_provider.get_remote_user_id(
  154. saml2_auth, client_redirect_url
  155. )
  156. if not remote_user_id:
  157. raise Exception("Failed to extract remote user id from SAML response")
  158. with (await self._mapping_lock.queue(self._auth_provider_id)):
  159. # first of all, check if we already have a mapping for this user
  160. logger.info(
  161. "Looking for existing mapping for user %s:%s",
  162. self._auth_provider_id,
  163. remote_user_id,
  164. )
  165. registered_user_id = await self._datastore.get_user_by_external_id(
  166. self._auth_provider_id, remote_user_id
  167. )
  168. if registered_user_id is not None:
  169. logger.info("Found existing mapping %s", registered_user_id)
  170. return registered_user_id, current_session
  171. # backwards-compatibility hack: see if there is an existing user with a
  172. # suitable mapping from the uid
  173. if (
  174. self._grandfathered_mxid_source_attribute
  175. and self._grandfathered_mxid_source_attribute in saml2_auth.ava
  176. ):
  177. attrval = saml2_auth.ava[self._grandfathered_mxid_source_attribute][0]
  178. user_id = UserID(
  179. map_username_to_mxid_localpart(attrval), self._hostname
  180. ).to_string()
  181. logger.info(
  182. "Looking for existing account based on mapped %s %s",
  183. self._grandfathered_mxid_source_attribute,
  184. user_id,
  185. )
  186. users = await self._datastore.get_users_by_id_case_insensitive(user_id)
  187. if users:
  188. registered_user_id = list(users.keys())[0]
  189. logger.info("Grandfathering mapping to %s", registered_user_id)
  190. await self._datastore.record_user_external_id(
  191. self._auth_provider_id, remote_user_id, registered_user_id
  192. )
  193. return registered_user_id, current_session
  194. # Map saml response to user attributes using the configured mapping provider
  195. for i in range(1000):
  196. attribute_dict = self._user_mapping_provider.saml_response_to_user_attributes(
  197. saml2_auth, i, client_redirect_url=client_redirect_url,
  198. )
  199. logger.debug(
  200. "Retrieved SAML attributes from user mapping provider: %s "
  201. "(attempt %d)",
  202. attribute_dict,
  203. i,
  204. )
  205. localpart = attribute_dict.get("mxid_localpart")
  206. if not localpart:
  207. raise Exception(
  208. "Error parsing SAML2 response: SAML mapping provider plugin "
  209. "did not return a mxid_localpart value"
  210. )
  211. displayname = attribute_dict.get("displayname")
  212. emails = attribute_dict.get("emails", [])
  213. # Check if this mxid already exists
  214. if not await self._datastore.get_users_by_id_case_insensitive(
  215. UserID(localpart, self._hostname).to_string()
  216. ):
  217. # This mxid is free
  218. break
  219. else:
  220. # Unable to generate a username in 1000 iterations
  221. # Break and return error to the user
  222. raise SynapseError(
  223. 500, "Unable to generate a Matrix ID from the SAML response"
  224. )
  225. logger.info("Mapped SAML user to local part %s", localpart)
  226. registered_user_id = await self._registration_handler.register_user(
  227. localpart=localpart,
  228. default_display_name=displayname,
  229. bind_emails=emails,
  230. )
  231. await self._datastore.record_user_external_id(
  232. self._auth_provider_id, remote_user_id, registered_user_id
  233. )
  234. return registered_user_id, current_session
  235. def expire_sessions(self):
  236. expire_before = self._clock.time_msec() - self._saml2_session_lifetime
  237. to_expire = set()
  238. for reqid, data in self._outstanding_requests_dict.items():
  239. if data.creation_time < expire_before:
  240. to_expire.add(reqid)
  241. for reqid in to_expire:
  242. logger.debug("Expiring session id %s", reqid)
  243. del self._outstanding_requests_dict[reqid]
  244. DOT_REPLACE_PATTERN = re.compile(
  245. ("[^%s]" % (re.escape("".join(mxid_localpart_allowed_characters)),))
  246. )
  247. def dot_replace_for_mxid(username: str) -> str:
  248. """Replace any characters which are not allowed in Matrix IDs with a dot."""
  249. username = username.lower()
  250. username = DOT_REPLACE_PATTERN.sub(".", username)
  251. # regular mxids aren't allowed to start with an underscore either
  252. username = re.sub("^_", "", username)
  253. return username
  254. MXID_MAPPER_MAP = {
  255. "hexencode": map_username_to_mxid_localpart,
  256. "dotreplace": dot_replace_for_mxid,
  257. } # type: Dict[str, Callable[[str], str]]
  258. @attr.s
  259. class SamlConfig(object):
  260. mxid_source_attribute = attr.ib()
  261. mxid_mapper = attr.ib()
  262. class DefaultSamlMappingProvider(object):
  263. __version__ = "0.0.1"
  264. def __init__(self, parsed_config: SamlConfig, module_api: ModuleApi):
  265. """The default SAML user mapping provider
  266. Args:
  267. parsed_config: Module configuration
  268. module_api: module api proxy
  269. """
  270. self._mxid_source_attribute = parsed_config.mxid_source_attribute
  271. self._mxid_mapper = parsed_config.mxid_mapper
  272. self._grandfathered_mxid_source_attribute = (
  273. module_api._hs.config.saml2_grandfathered_mxid_source_attribute
  274. )
  275. def get_remote_user_id(
  276. self, saml_response: saml2.response.AuthnResponse, client_redirect_url: str
  277. ) -> str:
  278. """Extracts the remote user id from the SAML response"""
  279. try:
  280. return saml_response.ava["uid"][0]
  281. except KeyError:
  282. logger.warning("SAML2 response lacks a 'uid' attestation")
  283. raise SynapseError(400, "'uid' not in SAML2 response")
  284. def saml_response_to_user_attributes(
  285. self,
  286. saml_response: saml2.response.AuthnResponse,
  287. failures: int,
  288. client_redirect_url: str,
  289. ) -> dict:
  290. """Maps some text from a SAML response to attributes of a new user
  291. Args:
  292. saml_response: A SAML auth response object
  293. failures: How many times a call to this function with this
  294. saml_response has resulted in a failure
  295. client_redirect_url: where the client wants to redirect to
  296. Returns:
  297. dict: A dict containing new user attributes. Possible keys:
  298. * mxid_localpart (str): Required. The localpart of the user's mxid
  299. * displayname (str): The displayname of the user
  300. * emails (list[str]): Any emails for the user
  301. """
  302. try:
  303. mxid_source = saml_response.ava[self._mxid_source_attribute][0]
  304. except KeyError:
  305. logger.warning(
  306. "SAML2 response lacks a '%s' attestation", self._mxid_source_attribute,
  307. )
  308. raise SynapseError(
  309. 400, "%s not in SAML2 response" % (self._mxid_source_attribute,)
  310. )
  311. # Use the configured mapper for this mxid_source
  312. base_mxid_localpart = self._mxid_mapper(mxid_source)
  313. # Append suffix integer if last call to this function failed to produce
  314. # a usable mxid
  315. localpart = base_mxid_localpart + (str(failures) if failures else "")
  316. # Retrieve the display name from the saml response
  317. # If displayname is None, the mxid_localpart will be used instead
  318. displayname = saml_response.ava.get("displayName", [None])[0]
  319. # Retrieve any emails present in the saml response
  320. emails = saml_response.ava.get("email", [])
  321. return {
  322. "mxid_localpart": localpart,
  323. "displayname": displayname,
  324. "emails": emails,
  325. }
  326. @staticmethod
  327. def parse_config(config: dict) -> SamlConfig:
  328. """Parse the dict provided by the homeserver's config
  329. Args:
  330. config: A dictionary containing configuration options for this provider
  331. Returns:
  332. SamlConfig: A custom config object for this module
  333. """
  334. # Parse config options and use defaults where necessary
  335. mxid_source_attribute = config.get("mxid_source_attribute", "uid")
  336. mapping_type = config.get("mxid_mapping", "hexencode")
  337. # Retrieve the associating mapping function
  338. try:
  339. mxid_mapper = MXID_MAPPER_MAP[mapping_type]
  340. except KeyError:
  341. raise ConfigError(
  342. "saml2_config.user_mapping_provider.config: '%s' is not a valid "
  343. "mxid_mapping value" % (mapping_type,)
  344. )
  345. return SamlConfig(mxid_source_attribute, mxid_mapper)
  346. @staticmethod
  347. def get_saml_attributes(config: SamlConfig) -> Tuple[Set[str], Set[str]]:
  348. """Returns the required attributes of a SAML
  349. Args:
  350. config: A SamlConfig object containing configuration params for this provider
  351. Returns:
  352. The first set equates to the saml auth response
  353. attributes that are required for the module to function, whereas the
  354. second set consists of those attributes which can be used if
  355. available, but are not necessary
  356. """
  357. return {"uid", config.mxid_source_attribute}, {"displayName", "email"}