Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 
 
 

401 řádky
14 KiB

  1. # Copyright 2020 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 urllib.parse
  16. from typing import TYPE_CHECKING, Dict, List, Optional
  17. from xml.etree import ElementTree as ET
  18. import attr
  19. from twisted.web.client import PartialDownloadError
  20. from synapse.api.errors import HttpResponseException
  21. from synapse.handlers.sso import MappingException, UserAttributes
  22. from synapse.http.site import SynapseRequest
  23. from synapse.types import UserID, map_username_to_mxid_localpart
  24. if TYPE_CHECKING:
  25. from synapse.server import HomeServer
  26. logger = logging.getLogger(__name__)
  27. class CasError(Exception):
  28. """Used to catch errors when validating the CAS ticket."""
  29. def __init__(self, error: str, error_description: Optional[str] = None):
  30. self.error = error
  31. self.error_description = error_description
  32. def __str__(self) -> str:
  33. if self.error_description:
  34. return f"{self.error}: {self.error_description}"
  35. return self.error
  36. @attr.s(slots=True, frozen=True, auto_attribs=True)
  37. class CasResponse:
  38. username: str
  39. attributes: Dict[str, List[Optional[str]]]
  40. class CasHandler:
  41. """
  42. Utility class for to handle the response from a CAS SSO service.
  43. Args:
  44. hs
  45. """
  46. def __init__(self, hs: "HomeServer"):
  47. self.hs = hs
  48. self._hostname = hs.hostname
  49. self._store = hs.get_datastores().main
  50. self._auth_handler = hs.get_auth_handler()
  51. self._registration_handler = hs.get_registration_handler()
  52. self._cas_server_url = hs.config.cas.cas_server_url
  53. self._cas_service_url = hs.config.cas.cas_service_url
  54. self._cas_protocol_version = hs.config.cas.cas_protocol_version
  55. self._cas_displayname_attribute = hs.config.cas.cas_displayname_attribute
  56. self._cas_required_attributes = hs.config.cas.cas_required_attributes
  57. self._cas_enable_registration = hs.config.cas.cas_enable_registration
  58. self._http_client = hs.get_proxied_http_client()
  59. # identifier for the external_ids table
  60. self.idp_id = "cas"
  61. # user-facing name of this auth provider
  62. self.idp_name = hs.config.cas.idp_name
  63. # MXC URI for icon for this auth provider
  64. self.idp_icon = hs.config.cas.idp_icon
  65. # optional brand identifier for this auth provider
  66. self.idp_brand = hs.config.cas.idp_brand
  67. self._sso_handler = hs.get_sso_handler()
  68. self._sso_handler.register_identity_provider(self)
  69. def _build_service_param(self, args: Dict[str, str]) -> str:
  70. """
  71. Generates a value to use as the "service" parameter when redirecting or
  72. querying the CAS service.
  73. Args:
  74. args: Additional arguments to include in the final redirect URL.
  75. Returns:
  76. The URL to use as a "service" parameter.
  77. """
  78. return "%s?%s" % (
  79. self._cas_service_url,
  80. urllib.parse.urlencode(args),
  81. )
  82. async def _validate_ticket(
  83. self, ticket: str, service_args: Dict[str, str]
  84. ) -> CasResponse:
  85. """
  86. Validate a CAS ticket with the server, and return the parsed the response.
  87. Args:
  88. ticket: The CAS ticket from the client.
  89. service_args: Additional arguments to include in the service URL.
  90. Should be the same as those passed to `handle_redirect_request`.
  91. Raises:
  92. CasError: If there's an error parsing the CAS response.
  93. Returns:
  94. The parsed CAS response.
  95. """
  96. if self._cas_protocol_version == 3:
  97. uri = self._cas_server_url + "/p3/proxyValidate"
  98. else:
  99. uri = self._cas_server_url + "/proxyValidate"
  100. args = {
  101. "ticket": ticket,
  102. "service": self._build_service_param(service_args),
  103. }
  104. try:
  105. body = await self._http_client.get_raw(uri, args)
  106. except PartialDownloadError as pde:
  107. # Twisted raises this error if the connection is closed,
  108. # even if that's being used old-http style to signal end-of-data
  109. # Assertion is for mypy's benefit. Error.response is Optional[bytes],
  110. # but a PartialDownloadError should always have a non-None response.
  111. assert pde.response is not None
  112. body = pde.response
  113. except HttpResponseException as e:
  114. description = (
  115. 'Authorization server responded with a "{status}" error '
  116. "while exchanging the authorization code."
  117. ).format(status=e.code)
  118. raise CasError("server_error", description) from e
  119. return self._parse_cas_response(body)
  120. def _parse_cas_response(self, cas_response_body: bytes) -> CasResponse:
  121. """
  122. Retrieve the user and other parameters from the CAS response.
  123. Args:
  124. cas_response_body: The response from the CAS query.
  125. Raises:
  126. CasError: If there's an error parsing the CAS response.
  127. Returns:
  128. The parsed CAS response.
  129. """
  130. # Ensure the response is valid.
  131. root = ET.fromstring(cas_response_body)
  132. if not root.tag.endswith("serviceResponse"):
  133. raise CasError(
  134. "missing_service_response",
  135. "root of CAS response is not serviceResponse",
  136. )
  137. success = root[0].tag.endswith("authenticationSuccess")
  138. if not success:
  139. raise CasError("unsucessful_response", "Unsuccessful CAS response")
  140. # Iterate through the nodes and pull out the user and any extra attributes.
  141. user = None
  142. attributes: Dict[str, List[Optional[str]]] = {}
  143. for child in root[0]:
  144. if child.tag.endswith("user"):
  145. user = child.text
  146. if child.tag.endswith("attributes"):
  147. for attribute in child:
  148. # ElementTree library expands the namespace in
  149. # attribute tags to the full URL of the namespace.
  150. # We don't care about namespace here and it will always
  151. # be encased in curly braces, so we remove them.
  152. tag = attribute.tag
  153. if "}" in tag:
  154. tag = tag.split("}")[1]
  155. attributes.setdefault(tag, []).append(attribute.text)
  156. # Ensure a user was found.
  157. if user is None:
  158. raise CasError("no_user", "CAS response does not contain user")
  159. return CasResponse(user, attributes)
  160. async def handle_redirect_request(
  161. self,
  162. request: SynapseRequest,
  163. client_redirect_url: Optional[bytes],
  164. ui_auth_session_id: Optional[str] = None,
  165. ) -> str:
  166. """Generates a URL for the CAS server where the client should be redirected.
  167. Args:
  168. request: the incoming HTTP request
  169. client_redirect_url: the URL that we should redirect the
  170. client to after login (or None for UI Auth).
  171. ui_auth_session_id: The session ID of the ongoing UI Auth (or
  172. None if this is a login).
  173. Returns:
  174. URL to redirect to
  175. """
  176. if ui_auth_session_id:
  177. service_args = {"session": ui_auth_session_id}
  178. else:
  179. assert client_redirect_url
  180. service_args = {"redirectUrl": client_redirect_url.decode("utf8")}
  181. args = urllib.parse.urlencode(
  182. {"service": self._build_service_param(service_args)}
  183. )
  184. return "%s/login?%s" % (self._cas_server_url, args)
  185. async def handle_ticket(
  186. self,
  187. request: SynapseRequest,
  188. ticket: str,
  189. client_redirect_url: Optional[str],
  190. session: Optional[str],
  191. ) -> None:
  192. """
  193. Called once the user has successfully authenticated with the SSO.
  194. Validates a CAS ticket sent by the client and completes the auth process.
  195. If the user interactive authentication session is provided, marks the
  196. UI Auth session as complete, then returns an HTML page notifying the
  197. user they are done.
  198. Otherwise, this registers the user if necessary, and then returns a
  199. redirect (with a login token) to the client.
  200. Args:
  201. request: the incoming request from the browser. We'll
  202. respond to it with a redirect or an HTML page.
  203. ticket: The CAS ticket provided by the client.
  204. client_redirect_url: the redirectUrl parameter from the `/cas/ticket` HTTP request, if given.
  205. This should be the same as the redirectUrl from the original `/login/sso/redirect` request.
  206. session: The session parameter from the `/cas/ticket` HTTP request, if given.
  207. This should be the UI Auth session id.
  208. """
  209. args = {}
  210. if client_redirect_url:
  211. args["redirectUrl"] = client_redirect_url
  212. if session:
  213. args["session"] = session
  214. try:
  215. cas_response = await self._validate_ticket(ticket, args)
  216. except CasError as e:
  217. logger.exception("Could not validate ticket")
  218. self._sso_handler.render_error(request, e.error, e.error_description, 401)
  219. return
  220. await self._handle_cas_response(
  221. request, cas_response, client_redirect_url, session
  222. )
  223. async def _handle_cas_response(
  224. self,
  225. request: SynapseRequest,
  226. cas_response: CasResponse,
  227. client_redirect_url: Optional[str],
  228. session: Optional[str],
  229. ) -> None:
  230. """Handle a CAS response to a ticket request.
  231. Assumes that the response has been validated. Maps the user onto an MXID,
  232. registering them if necessary, and returns a response to the browser.
  233. Args:
  234. request: the incoming request from the browser. We'll respond to it with an
  235. HTML page or a redirect
  236. cas_response: The parsed CAS response.
  237. client_redirect_url: the redirectUrl parameter from the `/cas/ticket` HTTP request, if given.
  238. This should be the same as the redirectUrl from the original `/login/sso/redirect` request.
  239. session: The session parameter from the `/cas/ticket` HTTP request, if given.
  240. This should be the UI Auth session id.
  241. """
  242. # first check if we're doing a UIA
  243. if session:
  244. return await self._sso_handler.complete_sso_ui_auth_request(
  245. self.idp_id,
  246. cas_response.username,
  247. session,
  248. request,
  249. )
  250. # otherwise, we're handling a login request.
  251. # Ensure that the attributes of the logged in user meet the required
  252. # attributes.
  253. if not self._sso_handler.check_required_attributes(
  254. request, cas_response.attributes, self._cas_required_attributes
  255. ):
  256. return
  257. # Call the mapper to register/login the user
  258. # If this not a UI auth request than there must be a redirect URL.
  259. assert client_redirect_url is not None
  260. try:
  261. await self._complete_cas_login(cas_response, request, client_redirect_url)
  262. except MappingException as e:
  263. logger.exception("Could not map user")
  264. self._sso_handler.render_error(request, "mapping_error", str(e))
  265. async def _complete_cas_login(
  266. self,
  267. cas_response: CasResponse,
  268. request: SynapseRequest,
  269. client_redirect_url: str,
  270. ) -> None:
  271. """
  272. Given a CAS response, complete the login flow
  273. Retrieves the remote user ID, registers the user if necessary, and serves
  274. a redirect back to the client with a login-token.
  275. Args:
  276. cas_response: The parsed CAS response.
  277. request: The request to respond to
  278. client_redirect_url: The redirect URL passed in by the client.
  279. Raises:
  280. MappingException if there was a problem mapping the response to a user.
  281. RedirectException: some mapping providers may raise this if they need
  282. to redirect to an interstitial page.
  283. """
  284. # Note that CAS does not support a mapping provider, so the logic is hard-coded.
  285. localpart = map_username_to_mxid_localpart(cas_response.username)
  286. async def cas_response_to_user_attributes(failures: int) -> UserAttributes:
  287. """
  288. Map from CAS attributes to user attributes.
  289. """
  290. # Due to the grandfathering logic matching any previously registered
  291. # mxids it isn't expected for there to be any failures.
  292. if failures:
  293. raise RuntimeError("CAS is not expected to de-duplicate Matrix IDs")
  294. # Arbitrarily use the first attribute found.
  295. display_name = cas_response.attributes.get(
  296. self._cas_displayname_attribute, [None]
  297. )[0]
  298. return UserAttributes(localpart=localpart, display_name=display_name)
  299. async def grandfather_existing_users() -> Optional[str]:
  300. # Since CAS did not always use the user_external_ids table, always
  301. # to attempt to map to existing users.
  302. user_id = UserID(localpart, self._hostname).to_string()
  303. logger.debug(
  304. "Looking for existing account based on mapped %s",
  305. user_id,
  306. )
  307. users = await self._store.get_users_by_id_case_insensitive(user_id)
  308. if users:
  309. registered_user_id = list(users.keys())[0]
  310. logger.info("Grandfathering mapping to %s", registered_user_id)
  311. return registered_user_id
  312. return None
  313. await self._sso_handler.complete_sso_login_request(
  314. self.idp_id,
  315. cas_response.username,
  316. request,
  317. client_redirect_url,
  318. cas_response_to_user_attributes,
  319. grandfather_existing_users,
  320. registration_enabled=self._cas_enable_registration,
  321. )