saml_handler.py 17 KB

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