Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

518 lignes
19 KiB

  1. # Copyright 2019 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import logging
  15. import re
  16. from typing import TYPE_CHECKING, Callable, Dict, Optional, Set, Tuple
  17. import attr
  18. import saml2
  19. import saml2.response
  20. from saml2.client import Saml2Client
  21. from synapse.api.errors import SynapseError
  22. from synapse.config import ConfigError
  23. from synapse.handlers.sso import MappingException, UserAttributes
  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. MXID_LOCALPART_ALLOWED_CHARACTERS,
  29. UserID,
  30. map_username_to_mxid_localpart,
  31. )
  32. from synapse.util.iterutils import chunk_seq
  33. if TYPE_CHECKING:
  34. from synapse.server import HomeServer
  35. logger = logging.getLogger(__name__)
  36. @attr.s(slots=True, auto_attribs=True)
  37. class Saml2SessionData:
  38. """Data we track about SAML2 sessions"""
  39. # time the session was created, in milliseconds
  40. creation_time: int
  41. # The user interactive authentication session ID associated with this SAML
  42. # session (or None if this SAML session is for an initial login).
  43. ui_auth_session_id: Optional[str] = None
  44. class SamlHandler:
  45. def __init__(self, hs: "HomeServer"):
  46. self.store = hs.get_datastores().main
  47. self.clock = hs.get_clock()
  48. self.server_name = hs.hostname
  49. self._saml_client = Saml2Client(hs.config.saml2.saml2_sp_config)
  50. self._saml_idp_entityid = hs.config.saml2.saml2_idp_entityid
  51. self._saml2_session_lifetime = hs.config.saml2.saml2_session_lifetime
  52. self._grandfathered_mxid_source_attribute = (
  53. hs.config.saml2.saml2_grandfathered_mxid_source_attribute
  54. )
  55. self._saml2_attribute_requirements = hs.config.saml2.attribute_requirements
  56. # plugin to do custom mapping from saml response to mxid
  57. self._user_mapping_provider = hs.config.saml2.saml2_user_mapping_provider_class(
  58. hs.config.saml2.saml2_user_mapping_provider_config,
  59. ModuleApi(hs, hs.get_auth_handler()),
  60. )
  61. # identifier for the external_ids table
  62. self.idp_id = "saml"
  63. # user-facing name of this auth provider
  64. self.idp_name = hs.config.saml2.idp_name
  65. # MXC URI for icon for this auth provider
  66. self.idp_icon = hs.config.saml2.idp_icon
  67. # optional brand identifier for this auth provider
  68. self.idp_brand = hs.config.saml2.idp_brand
  69. # a map from saml session id to Saml2SessionData object
  70. self._outstanding_requests_dict: Dict[str, Saml2SessionData] = {}
  71. self._sso_handler = hs.get_sso_handler()
  72. self._sso_handler.register_identity_provider(self)
  73. async def handle_redirect_request(
  74. self,
  75. request: SynapseRequest,
  76. client_redirect_url: Optional[bytes],
  77. ui_auth_session_id: Optional[str] = None,
  78. ) -> str:
  79. """Handle an incoming request to /login/sso/redirect
  80. Args:
  81. request: the incoming HTTP request
  82. client_redirect_url: the URL that we should redirect the
  83. client to after login (or None for UI Auth).
  84. ui_auth_session_id: The session ID of the ongoing UI Auth (or
  85. None if this is a login).
  86. Returns:
  87. URL to redirect to
  88. """
  89. if not client_redirect_url:
  90. # Some SAML identity providers (e.g. Google) require a
  91. # RelayState parameter on requests, so pass in a dummy redirect URL
  92. # (which will never get used).
  93. client_redirect_url = b"unused"
  94. reqid, info = self._saml_client.prepare_for_authenticate(
  95. entityid=self._saml_idp_entityid, relay_state=client_redirect_url
  96. )
  97. # Since SAML sessions timeout it is useful to log when they were created.
  98. logger.info("Initiating a new SAML session: %s" % (reqid,))
  99. now = self.clock.time_msec()
  100. self._outstanding_requests_dict[reqid] = Saml2SessionData(
  101. creation_time=now,
  102. ui_auth_session_id=ui_auth_session_id,
  103. )
  104. for key, value in info["headers"]:
  105. if key == "Location":
  106. return value
  107. # this shouldn't happen!
  108. raise Exception("prepare_for_authenticate didn't return a Location header")
  109. async def handle_saml_response(self, request: SynapseRequest) -> None:
  110. """Handle an incoming request to /_synapse/client/saml2/authn_response
  111. Args:
  112. request: the incoming request from the browser. We'll
  113. respond to it with a redirect.
  114. Returns:
  115. Completes once we have handled the request.
  116. """
  117. resp_bytes = parse_string(request, "SAMLResponse", required=True)
  118. relay_state = parse_string(request, "RelayState", required=True)
  119. # expire outstanding sessions before parse_authn_request_response checks
  120. # the dict.
  121. self.expire_sessions()
  122. try:
  123. saml2_auth = self._saml_client.parse_authn_request_response(
  124. resp_bytes,
  125. saml2.BINDING_HTTP_POST,
  126. outstanding=self._outstanding_requests_dict,
  127. )
  128. except saml2.response.UnsolicitedResponse as e:
  129. # the pysaml2 library helpfully logs an ERROR here, but neglects to log
  130. # the session ID. I don't really want to put the full text of the exception
  131. # in the (user-visible) exception message, so let's log the exception here
  132. # so we can track down the session IDs later.
  133. logger.warning(str(e))
  134. self._sso_handler.render_error(
  135. request, "unsolicited_response", "Unexpected SAML2 login."
  136. )
  137. return
  138. except Exception as e:
  139. self._sso_handler.render_error(
  140. request,
  141. "invalid_response",
  142. "Unable to parse SAML2 response: %s." % (e,),
  143. )
  144. return
  145. if saml2_auth.not_signed:
  146. self._sso_handler.render_error(
  147. request, "unsigned_respond", "SAML2 response was not signed."
  148. )
  149. return
  150. logger.debug("SAML2 response: %s", saml2_auth.origxml)
  151. await self._handle_authn_response(request, saml2_auth, relay_state)
  152. async def _handle_authn_response(
  153. self,
  154. request: SynapseRequest,
  155. saml2_auth: saml2.response.AuthnResponse,
  156. relay_state: str,
  157. ) -> None:
  158. """Handle an AuthnResponse, having parsed it from the request params
  159. Assumes that the signature on the response object has been checked. Maps
  160. the user onto an MXID, registering them if necessary, and returns a response
  161. to the browser.
  162. Args:
  163. request: the incoming request from the browser. We'll respond to it with an
  164. HTML page or a redirect
  165. saml2_auth: the parsed AuthnResponse object
  166. relay_state: the RelayState query param, which encodes the URI to rediret
  167. back to
  168. """
  169. for assertion in saml2_auth.assertions:
  170. # kibana limits the length of a log field, whereas this is all rather
  171. # useful, so split it up.
  172. count = 0
  173. for part in chunk_seq(str(assertion), 10000):
  174. logger.info(
  175. "SAML2 assertion: %s%s", "(%i)..." % (count,) if count else "", part
  176. )
  177. count += 1
  178. logger.info("SAML2 mapped attributes: %s", saml2_auth.ava)
  179. current_session = self._outstanding_requests_dict.pop(
  180. saml2_auth.in_response_to, None
  181. )
  182. # first check if we're doing a UIA
  183. if current_session and current_session.ui_auth_session_id:
  184. try:
  185. remote_user_id = self._remote_id_from_saml_response(saml2_auth, None)
  186. except MappingException as e:
  187. logger.exception("Failed to extract remote user id from SAML response")
  188. self._sso_handler.render_error(request, "mapping_error", str(e))
  189. return
  190. return await self._sso_handler.complete_sso_ui_auth_request(
  191. self.idp_id,
  192. remote_user_id,
  193. current_session.ui_auth_session_id,
  194. request,
  195. )
  196. # otherwise, we're handling a login request.
  197. # Ensure that the attributes of the logged in user meet the required
  198. # attributes.
  199. if not self._sso_handler.check_required_attributes(
  200. request, saml2_auth.ava, self._saml2_attribute_requirements
  201. ):
  202. return
  203. # Call the mapper to register/login the user
  204. try:
  205. await self._complete_saml_login(saml2_auth, request, relay_state)
  206. except MappingException as e:
  207. logger.exception("Could not map user")
  208. self._sso_handler.render_error(request, "mapping_error", str(e))
  209. async def _complete_saml_login(
  210. self,
  211. saml2_auth: saml2.response.AuthnResponse,
  212. request: SynapseRequest,
  213. client_redirect_url: str,
  214. ) -> None:
  215. """
  216. Given a SAML response, complete the login flow
  217. Retrieves the remote user ID, registers the user if necessary, and serves
  218. a redirect back to the client with a login-token.
  219. Args:
  220. saml2_auth: The parsed SAML2 response.
  221. request: The request to respond to
  222. client_redirect_url: The redirect URL passed in by the client.
  223. Raises:
  224. MappingException if there was a problem mapping the response to a user.
  225. RedirectException: some mapping providers may raise this if they need
  226. to redirect to an interstitial page.
  227. """
  228. remote_user_id = self._remote_id_from_saml_response(
  229. saml2_auth, client_redirect_url
  230. )
  231. async def saml_response_to_remapped_user_attributes(
  232. failures: int,
  233. ) -> UserAttributes:
  234. """
  235. Call the mapping provider to map a SAML response to user attributes and coerce the result into the standard form.
  236. This is backwards compatibility for abstraction for the SSO handler.
  237. """
  238. # Call the mapping provider.
  239. result = self._user_mapping_provider.saml_response_to_user_attributes(
  240. saml2_auth, failures, client_redirect_url
  241. )
  242. # Remap some of the results.
  243. return UserAttributes(
  244. localpart=result.get("mxid_localpart"),
  245. display_name=result.get("displayname"),
  246. emails=result.get("emails", []),
  247. )
  248. async def grandfather_existing_users() -> Optional[str]:
  249. # backwards-compatibility hack: see if there is an existing user with a
  250. # suitable mapping from the uid
  251. if (
  252. self._grandfathered_mxid_source_attribute
  253. and self._grandfathered_mxid_source_attribute in saml2_auth.ava
  254. ):
  255. attrval = saml2_auth.ava[self._grandfathered_mxid_source_attribute][0]
  256. user_id = UserID(
  257. map_username_to_mxid_localpart(attrval), self.server_name
  258. ).to_string()
  259. logger.debug(
  260. "Looking for existing account based on mapped %s %s",
  261. self._grandfathered_mxid_source_attribute,
  262. user_id,
  263. )
  264. users = await self.store.get_users_by_id_case_insensitive(user_id)
  265. if users:
  266. registered_user_id = list(users.keys())[0]
  267. logger.info("Grandfathering mapping to %s", registered_user_id)
  268. return registered_user_id
  269. return None
  270. await self._sso_handler.complete_sso_login_request(
  271. self.idp_id,
  272. remote_user_id,
  273. request,
  274. client_redirect_url,
  275. saml_response_to_remapped_user_attributes,
  276. grandfather_existing_users,
  277. )
  278. def _remote_id_from_saml_response(
  279. self,
  280. saml2_auth: saml2.response.AuthnResponse,
  281. client_redirect_url: Optional[str],
  282. ) -> str:
  283. """Extract the unique remote id from a SAML2 AuthnResponse
  284. Args:
  285. saml2_auth: The parsed SAML2 response.
  286. client_redirect_url: The redirect URL passed in by the client.
  287. Returns:
  288. remote user id
  289. Raises:
  290. MappingException if there was an error extracting the user id
  291. """
  292. # It's not obvious why we need to pass in the redirect URI to the mapping
  293. # provider, but we do :/
  294. remote_user_id = self._user_mapping_provider.get_remote_user_id(
  295. saml2_auth, client_redirect_url
  296. )
  297. if not remote_user_id:
  298. raise MappingException(
  299. "Failed to extract remote user id from SAML response"
  300. )
  301. return remote_user_id
  302. def expire_sessions(self) -> None:
  303. expire_before = self.clock.time_msec() - self._saml2_session_lifetime
  304. to_expire = set()
  305. for reqid, data in self._outstanding_requests_dict.items():
  306. if data.creation_time < expire_before:
  307. to_expire.add(reqid)
  308. for reqid in to_expire:
  309. logger.debug("Expiring session id %s", reqid)
  310. del self._outstanding_requests_dict[reqid]
  311. DOT_REPLACE_PATTERN = re.compile(
  312. "[^%s]" % (re.escape("".join(MXID_LOCALPART_ALLOWED_CHARACTERS)),)
  313. )
  314. def dot_replace_for_mxid(username: str) -> str:
  315. """Replace any characters which are not allowed in Matrix IDs with a dot."""
  316. username = username.lower()
  317. username = DOT_REPLACE_PATTERN.sub(".", username)
  318. # regular mxids aren't allowed to start with an underscore either
  319. username = re.sub("^_", "", username)
  320. return username
  321. MXID_MAPPER_MAP: Dict[str, Callable[[str], str]] = {
  322. "hexencode": map_username_to_mxid_localpart,
  323. "dotreplace": dot_replace_for_mxid,
  324. }
  325. @attr.s(auto_attribs=True)
  326. class SamlConfig:
  327. mxid_source_attribute: str
  328. mxid_mapper: Callable[[str], str]
  329. class DefaultSamlMappingProvider:
  330. __version__ = "0.0.1"
  331. def __init__(self, parsed_config: SamlConfig, module_api: ModuleApi):
  332. """The default SAML user mapping provider
  333. Args:
  334. parsed_config: Module configuration
  335. module_api: module api proxy
  336. """
  337. self._mxid_source_attribute = parsed_config.mxid_source_attribute
  338. self._mxid_mapper = parsed_config.mxid_mapper
  339. self._grandfathered_mxid_source_attribute = (
  340. module_api._hs.config.saml2.saml2_grandfathered_mxid_source_attribute
  341. )
  342. def get_remote_user_id(
  343. self, saml_response: saml2.response.AuthnResponse, client_redirect_url: str
  344. ) -> str:
  345. """Extracts the remote user id from the SAML response"""
  346. try:
  347. return saml_response.ava["uid"][0]
  348. except KeyError:
  349. logger.warning("SAML2 response lacks a 'uid' attestation")
  350. raise MappingException("'uid' not in SAML2 response")
  351. def saml_response_to_user_attributes(
  352. self,
  353. saml_response: saml2.response.AuthnResponse,
  354. failures: int,
  355. client_redirect_url: str,
  356. ) -> dict:
  357. """Maps some text from a SAML response to attributes of a new user
  358. Args:
  359. saml_response: A SAML auth response object
  360. failures: How many times a call to this function with this
  361. saml_response has resulted in a failure
  362. client_redirect_url: where the client wants to redirect to
  363. Returns:
  364. A dict containing new user attributes. Possible keys:
  365. * mxid_localpart (str): Required. The localpart of the user's mxid
  366. * displayname (str): The displayname of the user
  367. * emails (list[str]): Any emails for the user
  368. """
  369. try:
  370. mxid_source = saml_response.ava[self._mxid_source_attribute][0]
  371. except KeyError:
  372. logger.warning(
  373. "SAML2 response lacks a '%s' attestation",
  374. self._mxid_source_attribute,
  375. )
  376. raise SynapseError(
  377. 400, "%s not in SAML2 response" % (self._mxid_source_attribute,)
  378. )
  379. # Use the configured mapper for this mxid_source
  380. localpart = self._mxid_mapper(mxid_source)
  381. # Append suffix integer if last call to this function failed to produce
  382. # a usable mxid.
  383. localpart += str(failures) if failures else ""
  384. # Retrieve the display name from the saml response
  385. # If displayname is None, the mxid_localpart will be used instead
  386. displayname = saml_response.ava.get("displayName", [None])[0]
  387. # Retrieve any emails present in the saml response
  388. emails = saml_response.ava.get("email", [])
  389. return {
  390. "mxid_localpart": localpart,
  391. "displayname": displayname,
  392. "emails": emails,
  393. }
  394. @staticmethod
  395. def parse_config(config: dict) -> SamlConfig:
  396. """Parse the dict provided by the homeserver's config
  397. Args:
  398. config: A dictionary containing configuration options for this provider
  399. Returns:
  400. A custom config object for this module
  401. """
  402. # Parse config options and use defaults where necessary
  403. mxid_source_attribute = config.get("mxid_source_attribute", "uid")
  404. mapping_type = config.get("mxid_mapping", "hexencode")
  405. # Retrieve the associating mapping function
  406. try:
  407. mxid_mapper = MXID_MAPPER_MAP[mapping_type]
  408. except KeyError:
  409. raise ConfigError(
  410. "saml2_config.user_mapping_provider.config: '%s' is not a valid "
  411. "mxid_mapping value" % (mapping_type,)
  412. )
  413. return SamlConfig(mxid_source_attribute, mxid_mapper)
  414. @staticmethod
  415. def get_saml_attributes(config: SamlConfig) -> Tuple[Set[str], Set[str]]:
  416. """Returns the required attributes of a SAML
  417. Args:
  418. config: A SamlConfig object containing configuration params for this provider
  419. Returns:
  420. The first set equates to the saml auth response
  421. attributes that are required for the module to function, whereas the
  422. second set consists of those attributes which can be used if
  423. available, but are not necessary
  424. """
  425. return {"uid", config.mxid_source_attribute}, {"displayName", "email"}