2019-06-26 15:52:02 -06:00
|
|
|
# Copyright 2019 The Matrix.org Foundation C.I.C.
|
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
|
|
|
import logging
|
2019-12-10 10:30:16 -07:00
|
|
|
import re
|
2020-08-11 09:08:10 -06:00
|
|
|
from typing import TYPE_CHECKING, Callable, Dict, Optional, Set, Tuple
|
2019-06-26 15:52:02 -06:00
|
|
|
|
2019-06-26 16:50:55 -06:00
|
|
|
import attr
|
2019-06-26 15:52:02 -06:00
|
|
|
import saml2
|
2019-12-10 10:30:16 -07:00
|
|
|
import saml2.response
|
2019-06-26 15:52:02 -06:00
|
|
|
from saml2.client import Saml2Client
|
|
|
|
|
2020-09-14 07:05:36 -06:00
|
|
|
from synapse.api.errors import SynapseError
|
2019-12-10 10:30:16 -07:00
|
|
|
from synapse.config import ConfigError
|
2020-11-25 08:04:22 -07:00
|
|
|
from synapse.handlers.sso import MappingException, UserAttributes
|
2019-06-26 15:52:02 -06:00
|
|
|
from synapse.http.servlet import parse_string
|
2020-05-07 07:30:45 -06:00
|
|
|
from synapse.http.site import SynapseRequest
|
2020-01-11 04:48:43 -07:00
|
|
|
from synapse.module_api import ModuleApi
|
2019-12-10 10:30:16 -07:00
|
|
|
from synapse.types import (
|
2023-07-11 10:21:00 -06:00
|
|
|
MXID_LOCALPART_ALLOWED_CHARACTERS,
|
2019-12-10 10:30:16 -07:00
|
|
|
UserID,
|
|
|
|
map_username_to_mxid_localpart,
|
|
|
|
)
|
2020-01-16 15:26:34 -07:00
|
|
|
from synapse.util.iterutils import chunk_seq
|
2019-06-26 15:52:02 -06:00
|
|
|
|
2020-08-11 09:08:10 -06:00
|
|
|
if TYPE_CHECKING:
|
2020-11-23 11:28:03 -07:00
|
|
|
from synapse.server import HomeServer
|
2020-08-11 09:08:10 -06:00
|
|
|
|
2019-06-26 15:52:02 -06:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
2021-09-20 06:56:23 -06:00
|
|
|
@attr.s(slots=True, auto_attribs=True)
|
2019-12-10 10:30:16 -07:00
|
|
|
class Saml2SessionData:
|
|
|
|
"""Data we track about SAML2 sessions"""
|
|
|
|
|
|
|
|
# time the session was created, in milliseconds
|
2021-09-20 06:56:23 -06:00
|
|
|
creation_time: int
|
2020-04-01 06:48:00 -06:00
|
|
|
# The user interactive authentication session ID associated with this SAML
|
|
|
|
# session (or None if this SAML session is for an initial login).
|
2021-09-20 06:56:23 -06:00
|
|
|
ui_auth_session_id: Optional[str] = None
|
2019-12-10 10:30:16 -07:00
|
|
|
|
|
|
|
|
2021-10-08 05:44:43 -06:00
|
|
|
class SamlHandler:
|
2020-11-23 11:28:03 -07:00
|
|
|
def __init__(self, hs: "HomeServer"):
|
2022-02-23 04:04:02 -07:00
|
|
|
self.store = hs.get_datastores().main
|
2021-10-08 05:44:43 -06:00
|
|
|
self.clock = hs.get_clock()
|
|
|
|
self.server_name = hs.hostname
|
2021-09-24 05:25:21 -06:00
|
|
|
self._saml_client = Saml2Client(hs.config.saml2.saml2_sp_config)
|
|
|
|
self._saml_idp_entityid = hs.config.saml2.saml2_idp_entityid
|
2019-09-13 08:20:49 -06:00
|
|
|
|
2021-09-24 05:25:21 -06:00
|
|
|
self._saml2_session_lifetime = hs.config.saml2.saml2_session_lifetime
|
2019-09-13 08:20:49 -06:00
|
|
|
self._grandfathered_mxid_source_attribute = (
|
2021-09-24 05:25:21 -06:00
|
|
|
hs.config.saml2.saml2_grandfathered_mxid_source_attribute
|
2019-09-13 08:20:49 -06:00
|
|
|
)
|
2020-08-11 09:08:10 -06:00
|
|
|
self._saml2_attribute_requirements = hs.config.saml2.attribute_requirements
|
2019-12-10 10:30:16 -07:00
|
|
|
|
|
|
|
# plugin to do custom mapping from saml response to mxid
|
2021-09-24 05:25:21 -06:00
|
|
|
self._user_mapping_provider = hs.config.saml2.saml2_user_mapping_provider_class(
|
|
|
|
hs.config.saml2.saml2_user_mapping_provider_config,
|
2020-01-11 04:48:43 -07:00
|
|
|
ModuleApi(hs, hs.get_auth_handler()),
|
2019-12-10 10:30:16 -07:00
|
|
|
)
|
2019-09-13 08:20:49 -06:00
|
|
|
|
|
|
|
# identifier for the external_ids table
|
2021-01-04 11:13:49 -07:00
|
|
|
self.idp_id = "saml"
|
2019-06-26 15:52:02 -06:00
|
|
|
|
2021-01-05 04:25:28 -07:00
|
|
|
# user-facing name of this auth provider
|
2023-08-11 14:15:17 -06:00
|
|
|
self.idp_name = hs.config.saml2.idp_name
|
2021-01-05 04:25:28 -07:00
|
|
|
|
2023-08-11 14:15:17 -06:00
|
|
|
# MXC URI for icon for this auth provider
|
|
|
|
self.idp_icon = hs.config.saml2.idp_icon
|
|
|
|
|
|
|
|
# optional brand identifier for this auth provider
|
|
|
|
self.idp_brand = hs.config.saml2.idp_brand
|
2021-01-20 06:15:14 -07:00
|
|
|
|
2019-06-26 16:50:55 -06:00
|
|
|
# a map from saml session id to Saml2SessionData object
|
2021-07-16 11:22:36 -06:00
|
|
|
self._outstanding_requests_dict: Dict[str, Saml2SessionData] = {}
|
2019-06-26 16:50:55 -06:00
|
|
|
|
2020-11-17 07:46:23 -07:00
|
|
|
self._sso_handler = hs.get_sso_handler()
|
2021-01-04 11:13:49 -07:00
|
|
|
self._sso_handler.register_identity_provider(self)
|
2020-09-14 07:05:36 -06:00
|
|
|
|
2021-01-04 11:13:49 -07:00
|
|
|
async def handle_redirect_request(
|
|
|
|
self,
|
|
|
|
request: SynapseRequest,
|
|
|
|
client_redirect_url: Optional[bytes],
|
|
|
|
ui_auth_session_id: Optional[str] = None,
|
|
|
|
) -> str:
|
2019-06-26 15:52:02 -06:00
|
|
|
"""Handle an incoming request to /login/sso/redirect
|
|
|
|
|
|
|
|
Args:
|
2021-01-04 11:13:49 -07:00
|
|
|
request: the incoming HTTP request
|
2020-05-07 07:30:45 -06:00
|
|
|
client_redirect_url: the URL that we should redirect the
|
2021-01-04 11:13:49 -07:00
|
|
|
client to after login (or None for UI Auth).
|
2020-05-07 07:30:45 -06:00
|
|
|
ui_auth_session_id: The session ID of the ongoing UI Auth (or
|
2020-04-01 06:48:00 -06:00
|
|
|
None if this is a login).
|
2019-06-26 15:52:02 -06:00
|
|
|
|
|
|
|
Returns:
|
2020-05-07 07:30:45 -06:00
|
|
|
URL to redirect to
|
2019-06-26 15:52:02 -06:00
|
|
|
"""
|
2021-01-04 11:13:49 -07:00
|
|
|
if not client_redirect_url:
|
|
|
|
# Some SAML identity providers (e.g. Google) require a
|
|
|
|
# RelayState parameter on requests, so pass in a dummy redirect URL
|
|
|
|
# (which will never get used).
|
|
|
|
client_redirect_url = b"unused"
|
|
|
|
|
2019-06-26 15:52:02 -06:00
|
|
|
reqid, info = self._saml_client.prepare_for_authenticate(
|
2020-11-19 07:57:13 -07:00
|
|
|
entityid=self._saml_idp_entityid, relay_state=client_redirect_url
|
2019-06-26 15:52:02 -06:00
|
|
|
)
|
|
|
|
|
2020-07-29 11:54:44 -06:00
|
|
|
# Since SAML sessions timeout it is useful to log when they were created.
|
|
|
|
logger.info("Initiating a new SAML session: %s" % (reqid,))
|
|
|
|
|
2020-11-17 07:46:23 -07:00
|
|
|
now = self.clock.time_msec()
|
2020-04-01 06:48:00 -06:00
|
|
|
self._outstanding_requests_dict[reqid] = Saml2SessionData(
|
|
|
|
creation_time=now,
|
|
|
|
ui_auth_session_id=ui_auth_session_id,
|
|
|
|
)
|
2019-06-26 16:50:55 -06:00
|
|
|
|
2019-06-26 15:52:02 -06:00
|
|
|
for key, value in info["headers"]:
|
|
|
|
if key == "Location":
|
|
|
|
return value
|
|
|
|
|
|
|
|
# this shouldn't happen!
|
|
|
|
raise Exception("prepare_for_authenticate didn't return a Location header")
|
|
|
|
|
2020-05-07 07:30:45 -06:00
|
|
|
async def handle_saml_response(self, request: SynapseRequest) -> None:
|
2021-02-02 02:43:50 -07:00
|
|
|
"""Handle an incoming request to /_synapse/client/saml2/authn_response
|
2019-06-26 15:52:02 -06:00
|
|
|
|
|
|
|
Args:
|
2020-05-07 07:30:45 -06:00
|
|
|
request: the incoming request from the browser. We'll
|
2019-06-26 15:52:02 -06:00
|
|
|
respond to it with a redirect.
|
|
|
|
|
|
|
|
Returns:
|
2020-05-07 07:30:45 -06:00
|
|
|
Completes once we have handled the request.
|
2019-06-26 15:52:02 -06:00
|
|
|
"""
|
|
|
|
resp_bytes = parse_string(request, "SAMLResponse", required=True)
|
|
|
|
relay_state = parse_string(request, "RelayState", required=True)
|
|
|
|
|
2019-06-26 16:50:55 -06:00
|
|
|
# expire outstanding sessions before parse_authn_request_response checks
|
|
|
|
# the dict.
|
|
|
|
self.expire_sessions()
|
|
|
|
|
2019-06-26 15:52:02 -06:00
|
|
|
try:
|
|
|
|
saml2_auth = self._saml_client.parse_authn_request_response(
|
2019-06-26 16:50:55 -06:00
|
|
|
resp_bytes,
|
|
|
|
saml2.BINDING_HTTP_POST,
|
|
|
|
outstanding=self._outstanding_requests_dict,
|
2019-06-26 15:52:02 -06:00
|
|
|
)
|
2020-08-11 09:08:10 -06:00
|
|
|
except saml2.response.UnsolicitedResponse as e:
|
|
|
|
# the pysaml2 library helpfully logs an ERROR here, but neglects to log
|
|
|
|
# the session ID. I don't really want to put the full text of the exception
|
|
|
|
# in the (user-visible) exception message, so let's log the exception here
|
|
|
|
# so we can track down the session IDs later.
|
|
|
|
logger.warning(str(e))
|
2020-11-17 07:46:23 -07:00
|
|
|
self._sso_handler.render_error(
|
2020-09-14 07:05:36 -06:00
|
|
|
request, "unsolicited_response", "Unexpected SAML2 login."
|
|
|
|
)
|
|
|
|
return
|
2019-06-26 15:52:02 -06:00
|
|
|
except Exception as e:
|
2020-11-17 07:46:23 -07:00
|
|
|
self._sso_handler.render_error(
|
2020-09-14 07:05:36 -06:00
|
|
|
request,
|
|
|
|
"invalid_response",
|
|
|
|
"Unable to parse SAML2 response: %s." % (e,),
|
|
|
|
)
|
|
|
|
return
|
2019-06-26 15:52:02 -06:00
|
|
|
|
|
|
|
if saml2_auth.not_signed:
|
2020-11-17 07:46:23 -07:00
|
|
|
self._sso_handler.render_error(
|
2020-09-14 07:05:36 -06:00
|
|
|
request, "unsigned_respond", "SAML2 response was not signed."
|
|
|
|
)
|
|
|
|
return
|
2019-06-26 15:52:02 -06:00
|
|
|
|
2020-01-16 15:26:34 -07:00
|
|
|
logger.debug("SAML2 response: %s", saml2_auth.origxml)
|
2020-12-15 13:56:10 -07:00
|
|
|
|
|
|
|
await self._handle_authn_response(request, saml2_auth, relay_state)
|
|
|
|
|
|
|
|
async def _handle_authn_response(
|
|
|
|
self,
|
|
|
|
request: SynapseRequest,
|
|
|
|
saml2_auth: saml2.response.AuthnResponse,
|
|
|
|
relay_state: str,
|
|
|
|
) -> None:
|
|
|
|
"""Handle an AuthnResponse, having parsed it from the request params
|
|
|
|
|
|
|
|
Assumes that the signature on the response object has been checked. Maps
|
|
|
|
the user onto an MXID, registering them if necessary, and returns a response
|
|
|
|
to the browser.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
request: the incoming request from the browser. We'll respond to it with an
|
|
|
|
HTML page or a redirect
|
|
|
|
saml2_auth: the parsed AuthnResponse object
|
|
|
|
relay_state: the RelayState query param, which encodes the URI to rediret
|
|
|
|
back to
|
|
|
|
"""
|
|
|
|
|
2020-01-16 15:26:34 -07:00
|
|
|
for assertion in saml2_auth.assertions:
|
|
|
|
# kibana limits the length of a log field, whereas this is all rather
|
|
|
|
# useful, so split it up.
|
|
|
|
count = 0
|
|
|
|
for part in chunk_seq(str(assertion), 10000):
|
|
|
|
logger.info(
|
|
|
|
"SAML2 assertion: %s%s", "(%i)..." % (count,) if count else "", part
|
|
|
|
)
|
|
|
|
count += 1
|
|
|
|
|
2019-09-20 04:15:14 -06:00
|
|
|
logger.info("SAML2 mapped attributes: %s", saml2_auth.ava)
|
2019-09-19 10:16:50 -06:00
|
|
|
|
2020-04-01 06:48:00 -06:00
|
|
|
current_session = self._outstanding_requests_dict.pop(
|
|
|
|
saml2_auth.in_response_to, None
|
|
|
|
)
|
2019-06-26 15:52:02 -06:00
|
|
|
|
2020-12-08 07:03:38 -07:00
|
|
|
# first check if we're doing a UIA
|
|
|
|
if current_session and current_session.ui_auth_session_id:
|
|
|
|
try:
|
|
|
|
remote_user_id = self._remote_id_from_saml_response(saml2_auth, None)
|
|
|
|
except MappingException as e:
|
|
|
|
logger.exception("Failed to extract remote user id from SAML response")
|
|
|
|
self._sso_handler.render_error(request, "mapping_error", str(e))
|
|
|
|
return
|
|
|
|
|
|
|
|
return await self._sso_handler.complete_sso_ui_auth_request(
|
2021-01-04 11:13:49 -07:00
|
|
|
self.idp_id,
|
2020-12-08 07:03:38 -07:00
|
|
|
remote_user_id,
|
|
|
|
current_session.ui_auth_session_id,
|
|
|
|
request,
|
|
|
|
)
|
|
|
|
|
|
|
|
# otherwise, we're handling a login request.
|
|
|
|
|
2020-09-14 07:05:36 -06:00
|
|
|
# Ensure that the attributes of the logged in user meet the required
|
|
|
|
# attributes.
|
2021-02-11 08:05:15 -07:00
|
|
|
if not self._sso_handler.check_required_attributes(
|
|
|
|
request, saml2_auth.ava, self._saml2_attribute_requirements
|
|
|
|
):
|
|
|
|
return
|
2020-09-14 07:05:36 -06:00
|
|
|
|
|
|
|
# Call the mapper to register/login the user
|
|
|
|
try:
|
2020-12-16 13:01:53 -07:00
|
|
|
await self._complete_saml_login(saml2_auth, request, relay_state)
|
2020-09-14 07:05:36 -06:00
|
|
|
except MappingException as e:
|
|
|
|
logger.exception("Could not map user")
|
2020-11-17 07:46:23 -07:00
|
|
|
self._sso_handler.render_error(request, "mapping_error", str(e))
|
2020-09-14 07:05:36 -06:00
|
|
|
|
2020-12-16 13:01:53 -07:00
|
|
|
async def _complete_saml_login(
|
2020-09-14 07:05:36 -06:00
|
|
|
self,
|
|
|
|
saml2_auth: saml2.response.AuthnResponse,
|
2020-12-16 13:01:53 -07:00
|
|
|
request: SynapseRequest,
|
2020-09-14 07:05:36 -06:00
|
|
|
client_redirect_url: str,
|
2020-12-16 13:01:53 -07:00
|
|
|
) -> None:
|
2020-09-14 07:05:36 -06:00
|
|
|
"""
|
2020-12-16 13:01:53 -07:00
|
|
|
Given a SAML response, complete the login flow
|
|
|
|
|
|
|
|
Retrieves the remote user ID, registers the user if necessary, and serves
|
|
|
|
a redirect back to the client with a login-token.
|
2020-09-14 07:05:36 -06:00
|
|
|
|
|
|
|
Args:
|
|
|
|
saml2_auth: The parsed SAML2 response.
|
2020-12-16 13:01:53 -07:00
|
|
|
request: The request to respond to
|
2020-09-14 07:05:36 -06:00
|
|
|
client_redirect_url: The redirect URL passed in by the client.
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
MappingException if there was a problem mapping the response to a user.
|
|
|
|
RedirectException: some mapping providers may raise this if they need
|
|
|
|
to redirect to an interstitial page.
|
|
|
|
"""
|
2020-12-08 07:03:38 -07:00
|
|
|
remote_user_id = self._remote_id_from_saml_response(
|
2020-01-17 03:32:47 -07:00
|
|
|
saml2_auth, client_redirect_url
|
|
|
|
)
|
|
|
|
|
2020-11-25 08:04:22 -07:00
|
|
|
async def saml_response_to_remapped_user_attributes(
|
|
|
|
failures: int,
|
|
|
|
) -> UserAttributes:
|
|
|
|
"""
|
|
|
|
Call the mapping provider to map a SAML response to user attributes and coerce the result into the standard form.
|
|
|
|
|
|
|
|
This is backwards compatibility for abstraction for the SSO handler.
|
|
|
|
"""
|
|
|
|
# Call the mapping provider.
|
|
|
|
result = self._user_mapping_provider.saml_response_to_user_attributes(
|
|
|
|
saml2_auth, failures, client_redirect_url
|
|
|
|
)
|
|
|
|
# Remap some of the results.
|
|
|
|
return UserAttributes(
|
|
|
|
localpart=result.get("mxid_localpart"),
|
|
|
|
display_name=result.get("displayname"),
|
2020-12-02 05:09:21 -07:00
|
|
|
emails=result.get("emails", []),
|
2019-09-13 08:20:49 -06:00
|
|
|
)
|
|
|
|
|
2020-12-02 05:45:42 -07:00
|
|
|
async def grandfather_existing_users() -> Optional[str]:
|
2019-09-13 08:20:49 -06:00
|
|
|
# backwards-compatibility hack: see if there is an existing user with a
|
|
|
|
# suitable mapping from the uid
|
|
|
|
if (
|
|
|
|
self._grandfathered_mxid_source_attribute
|
|
|
|
and self._grandfathered_mxid_source_attribute in saml2_auth.ava
|
|
|
|
):
|
|
|
|
attrval = saml2_auth.ava[self._grandfathered_mxid_source_attribute][0]
|
|
|
|
user_id = UserID(
|
2020-11-17 07:46:23 -07:00
|
|
|
map_username_to_mxid_localpart(attrval), self.server_name
|
2019-09-13 08:20:49 -06:00
|
|
|
).to_string()
|
2020-11-23 06:45:23 -07:00
|
|
|
|
|
|
|
logger.debug(
|
2019-09-13 08:20:49 -06:00
|
|
|
"Looking for existing account based on mapped %s %s",
|
|
|
|
self._grandfathered_mxid_source_attribute,
|
|
|
|
user_id,
|
|
|
|
)
|
|
|
|
|
2020-11-17 07:46:23 -07:00
|
|
|
users = await self.store.get_users_by_id_case_insensitive(user_id)
|
2019-09-13 08:20:49 -06:00
|
|
|
if users:
|
|
|
|
registered_user_id = list(users.keys())[0]
|
|
|
|
logger.info("Grandfathering mapping to %s", registered_user_id)
|
2020-09-14 07:05:36 -06:00
|
|
|
return registered_user_id
|
2019-09-13 08:20:49 -06:00
|
|
|
|
2020-12-02 05:45:42 -07:00
|
|
|
return None
|
|
|
|
|
2020-12-16 13:01:53 -07:00
|
|
|
await self._sso_handler.complete_sso_login_request(
|
2021-01-04 11:13:49 -07:00
|
|
|
self.idp_id,
|
2020-12-10 05:43:58 -07:00
|
|
|
remote_user_id,
|
2020-12-16 13:01:53 -07:00
|
|
|
request,
|
|
|
|
client_redirect_url,
|
2020-12-10 05:43:58 -07:00
|
|
|
saml_response_to_remapped_user_attributes,
|
|
|
|
grandfather_existing_users,
|
|
|
|
)
|
2019-06-26 16:50:55 -06:00
|
|
|
|
2020-12-08 07:03:38 -07:00
|
|
|
def _remote_id_from_saml_response(
|
|
|
|
self,
|
|
|
|
saml2_auth: saml2.response.AuthnResponse,
|
|
|
|
client_redirect_url: Optional[str],
|
|
|
|
) -> str:
|
|
|
|
"""Extract the unique remote id from a SAML2 AuthnResponse
|
|
|
|
|
|
|
|
Args:
|
|
|
|
saml2_auth: The parsed SAML2 response.
|
|
|
|
client_redirect_url: The redirect URL passed in by the client.
|
|
|
|
Returns:
|
|
|
|
remote user id
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
MappingException if there was an error extracting the user id
|
|
|
|
"""
|
|
|
|
# It's not obvious why we need to pass in the redirect URI to the mapping
|
|
|
|
# provider, but we do :/
|
|
|
|
remote_user_id = self._user_mapping_provider.get_remote_user_id(
|
|
|
|
saml2_auth, client_redirect_url
|
|
|
|
)
|
|
|
|
|
|
|
|
if not remote_user_id:
|
|
|
|
raise MappingException(
|
|
|
|
"Failed to extract remote user id from SAML response"
|
|
|
|
)
|
|
|
|
|
|
|
|
return remote_user_id
|
|
|
|
|
2021-09-20 06:56:23 -06:00
|
|
|
def expire_sessions(self) -> None:
|
2020-11-17 07:46:23 -07:00
|
|
|
expire_before = self.clock.time_msec() - self._saml2_session_lifetime
|
2019-06-26 16:50:55 -06:00
|
|
|
to_expire = set()
|
|
|
|
for reqid, data in self._outstanding_requests_dict.items():
|
|
|
|
if data.creation_time < expire_before:
|
|
|
|
to_expire.add(reqid)
|
|
|
|
for reqid in to_expire:
|
|
|
|
logger.debug("Expiring session id %s", reqid)
|
|
|
|
del self._outstanding_requests_dict[reqid]
|
|
|
|
|
|
|
|
|
2019-12-10 10:30:16 -07:00
|
|
|
DOT_REPLACE_PATTERN = re.compile(
|
2023-07-11 10:21:00 -06:00
|
|
|
"[^%s]" % (re.escape("".join(MXID_LOCALPART_ALLOWED_CHARACTERS)),)
|
2019-12-10 10:30:16 -07:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
def dot_replace_for_mxid(username: str) -> str:
|
2020-05-07 07:30:45 -06:00
|
|
|
"""Replace any characters which are not allowed in Matrix IDs with a dot."""
|
2019-12-10 10:30:16 -07:00
|
|
|
username = username.lower()
|
|
|
|
username = DOT_REPLACE_PATTERN.sub(".", username)
|
|
|
|
|
|
|
|
# regular mxids aren't allowed to start with an underscore either
|
|
|
|
username = re.sub("^_", "", username)
|
|
|
|
return username
|
|
|
|
|
|
|
|
|
2021-07-16 11:22:36 -06:00
|
|
|
MXID_MAPPER_MAP: Dict[str, Callable[[str], str]] = {
|
2019-12-10 10:30:16 -07:00
|
|
|
"hexencode": map_username_to_mxid_localpart,
|
|
|
|
"dotreplace": dot_replace_for_mxid,
|
2021-07-16 11:22:36 -06:00
|
|
|
}
|
2019-12-10 10:30:16 -07:00
|
|
|
|
|
|
|
|
2021-09-20 06:56:23 -06:00
|
|
|
@attr.s(auto_attribs=True)
|
2020-09-04 04:54:56 -06:00
|
|
|
class SamlConfig:
|
2021-09-20 06:56:23 -06:00
|
|
|
mxid_source_attribute: str
|
|
|
|
mxid_mapper: Callable[[str], str]
|
2019-06-26 16:50:55 -06:00
|
|
|
|
2019-12-10 10:30:16 -07:00
|
|
|
|
2020-09-04 04:54:56 -06:00
|
|
|
class DefaultSamlMappingProvider:
|
2019-12-10 10:30:16 -07:00
|
|
|
__version__ = "0.0.1"
|
|
|
|
|
2020-01-11 04:48:43 -07:00
|
|
|
def __init__(self, parsed_config: SamlConfig, module_api: ModuleApi):
|
2019-12-10 10:30:16 -07:00
|
|
|
"""The default SAML user mapping provider
|
|
|
|
|
|
|
|
Args:
|
|
|
|
parsed_config: Module configuration
|
2020-01-11 04:48:43 -07:00
|
|
|
module_api: module api proxy
|
2019-12-10 10:30:16 -07:00
|
|
|
"""
|
|
|
|
self._mxid_source_attribute = parsed_config.mxid_source_attribute
|
|
|
|
self._mxid_mapper = parsed_config.mxid_mapper
|
|
|
|
|
2020-01-17 03:32:47 -07:00
|
|
|
self._grandfathered_mxid_source_attribute = (
|
2021-09-24 05:25:21 -06:00
|
|
|
module_api._hs.config.saml2.saml2_grandfathered_mxid_source_attribute
|
2020-01-17 03:32:47 -07:00
|
|
|
)
|
|
|
|
|
|
|
|
def get_remote_user_id(
|
|
|
|
self, saml_response: saml2.response.AuthnResponse, client_redirect_url: str
|
2020-05-07 07:30:45 -06:00
|
|
|
) -> str:
|
2020-01-17 03:32:47 -07:00
|
|
|
"""Extracts the remote user id from the SAML response"""
|
|
|
|
try:
|
|
|
|
return saml_response.ava["uid"][0]
|
|
|
|
except KeyError:
|
|
|
|
logger.warning("SAML2 response lacks a 'uid' attestation")
|
2020-09-14 07:05:36 -06:00
|
|
|
raise MappingException("'uid' not in SAML2 response")
|
2020-01-17 03:32:47 -07:00
|
|
|
|
2019-12-10 10:30:16 -07:00
|
|
|
def saml_response_to_user_attributes(
|
2020-01-10 18:01:53 -07:00
|
|
|
self,
|
|
|
|
saml_response: saml2.response.AuthnResponse,
|
|
|
|
failures: int,
|
|
|
|
client_redirect_url: str,
|
2019-12-10 10:30:16 -07:00
|
|
|
) -> dict:
|
|
|
|
"""Maps some text from a SAML response to attributes of a new user
|
|
|
|
|
|
|
|
Args:
|
|
|
|
saml_response: A SAML auth response object
|
|
|
|
|
|
|
|
failures: How many times a call to this function with this
|
|
|
|
saml_response has resulted in a failure
|
|
|
|
|
2020-01-10 18:01:53 -07:00
|
|
|
client_redirect_url: where the client wants to redirect to
|
|
|
|
|
2019-12-10 10:30:16 -07:00
|
|
|
Returns:
|
2022-11-16 08:25:24 -07:00
|
|
|
A dict containing new user attributes. Possible keys:
|
2019-12-10 10:30:16 -07:00
|
|
|
* mxid_localpart (str): Required. The localpart of the user's mxid
|
|
|
|
* displayname (str): The displayname of the user
|
2020-05-27 10:40:08 -06:00
|
|
|
* emails (list[str]): Any emails for the user
|
2019-12-10 10:30:16 -07:00
|
|
|
"""
|
|
|
|
try:
|
|
|
|
mxid_source = saml_response.ava[self._mxid_source_attribute][0]
|
|
|
|
except KeyError:
|
|
|
|
logger.warning(
|
|
|
|
"SAML2 response lacks a '%s' attestation",
|
|
|
|
self._mxid_source_attribute,
|
|
|
|
)
|
|
|
|
raise SynapseError(
|
|
|
|
400, "%s not in SAML2 response" % (self._mxid_source_attribute,)
|
|
|
|
)
|
|
|
|
|
|
|
|
# Use the configured mapper for this mxid_source
|
2020-11-25 08:04:22 -07:00
|
|
|
localpart = self._mxid_mapper(mxid_source)
|
2019-12-10 10:30:16 -07:00
|
|
|
|
|
|
|
# Append suffix integer if last call to this function failed to produce
|
2020-11-25 08:04:22 -07:00
|
|
|
# a usable mxid.
|
|
|
|
localpart += str(failures) if failures else ""
|
2019-12-10 10:30:16 -07:00
|
|
|
|
|
|
|
# Retrieve the display name from the saml response
|
|
|
|
# If displayname is None, the mxid_localpart will be used instead
|
|
|
|
displayname = saml_response.ava.get("displayName", [None])[0]
|
|
|
|
|
2020-05-27 10:40:08 -06:00
|
|
|
# Retrieve any emails present in the saml response
|
|
|
|
emails = saml_response.ava.get("email", [])
|
|
|
|
|
2019-12-10 10:30:16 -07:00
|
|
|
return {
|
|
|
|
"mxid_localpart": localpart,
|
|
|
|
"displayname": displayname,
|
2020-05-27 10:40:08 -06:00
|
|
|
"emails": emails,
|
2019-12-10 10:30:16 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def parse_config(config: dict) -> SamlConfig:
|
|
|
|
"""Parse the dict provided by the homeserver's config
|
|
|
|
Args:
|
|
|
|
config: A dictionary containing configuration options for this provider
|
|
|
|
Returns:
|
2022-11-16 08:25:24 -07:00
|
|
|
A custom config object for this module
|
2019-12-10 10:30:16 -07:00
|
|
|
"""
|
|
|
|
# Parse config options and use defaults where necessary
|
|
|
|
mxid_source_attribute = config.get("mxid_source_attribute", "uid")
|
|
|
|
mapping_type = config.get("mxid_mapping", "hexencode")
|
|
|
|
|
|
|
|
# Retrieve the associating mapping function
|
|
|
|
try:
|
|
|
|
mxid_mapper = MXID_MAPPER_MAP[mapping_type]
|
|
|
|
except KeyError:
|
|
|
|
raise ConfigError(
|
|
|
|
"saml2_config.user_mapping_provider.config: '%s' is not a valid "
|
|
|
|
"mxid_mapping value" % (mapping_type,)
|
|
|
|
)
|
|
|
|
|
|
|
|
return SamlConfig(mxid_source_attribute, mxid_mapper)
|
|
|
|
|
|
|
|
@staticmethod
|
2020-05-07 07:30:45 -06:00
|
|
|
def get_saml_attributes(config: SamlConfig) -> Tuple[Set[str], Set[str]]:
|
2019-12-10 10:30:16 -07:00
|
|
|
"""Returns the required attributes of a SAML
|
|
|
|
|
|
|
|
Args:
|
|
|
|
config: A SamlConfig object containing configuration params for this provider
|
|
|
|
|
|
|
|
Returns:
|
2020-05-07 07:30:45 -06:00
|
|
|
The first set equates to the saml auth response
|
2019-12-10 10:30:16 -07:00
|
|
|
attributes that are required for the module to function, whereas the
|
|
|
|
second set consists of those attributes which can be used if
|
|
|
|
available, but are not necessary
|
|
|
|
"""
|
2020-05-27 10:40:08 -06:00
|
|
|
return {"uid", config.mxid_source_attribute}, {"displayName", "email"}
|