You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

2398 lines
95 KiB

  1. # Copyright 2014 - 2016 OpenMarket Ltd
  2. # Copyright 2017 Vector Creations Ltd
  3. # Copyright 2019 - 2020 The Matrix.org Foundation C.I.C.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import logging
  17. import time
  18. import unicodedata
  19. import urllib.parse
  20. from binascii import crc32
  21. from http import HTTPStatus
  22. from typing import (
  23. TYPE_CHECKING,
  24. Any,
  25. Awaitable,
  26. Callable,
  27. Dict,
  28. Iterable,
  29. List,
  30. Mapping,
  31. Optional,
  32. Tuple,
  33. Type,
  34. Union,
  35. cast,
  36. )
  37. import attr
  38. import bcrypt
  39. import unpaddedbase64
  40. from prometheus_client import Counter
  41. from twisted.internet.defer import CancelledError
  42. from twisted.web.server import Request
  43. from synapse.api.constants import LoginType
  44. from synapse.api.errors import (
  45. AuthError,
  46. Codes,
  47. InteractiveAuthIncompleteError,
  48. LoginError,
  49. NotFoundError,
  50. StoreError,
  51. SynapseError,
  52. UserDeactivatedError,
  53. )
  54. from synapse.api.ratelimiting import Ratelimiter
  55. from synapse.handlers.ui_auth import (
  56. INTERACTIVE_AUTH_CHECKERS,
  57. UIAuthSessionDataConstants,
  58. )
  59. from synapse.handlers.ui_auth.checkers import UserInteractiveAuthChecker
  60. from synapse.http import get_request_user_agent
  61. from synapse.http.server import finish_request, respond_with_html
  62. from synapse.http.site import SynapseRequest
  63. from synapse.logging.context import defer_to_thread
  64. from synapse.metrics.background_process_metrics import run_as_background_process
  65. from synapse.storage.databases.main.registration import (
  66. LoginTokenExpired,
  67. LoginTokenLookupResult,
  68. LoginTokenReused,
  69. )
  70. from synapse.types import JsonDict, Requester, UserID
  71. from synapse.util import stringutils as stringutils
  72. from synapse.util.async_helpers import delay_cancellation, maybe_awaitable
  73. from synapse.util.msisdn import phone_number_to_msisdn
  74. from synapse.util.stringutils import base62_encode
  75. from synapse.util.threepids import canonicalise_email
  76. if TYPE_CHECKING:
  77. from synapse.module_api import ModuleApi
  78. from synapse.rest.client.login import LoginResponse
  79. from synapse.server import HomeServer
  80. logger = logging.getLogger(__name__)
  81. INVALID_USERNAME_OR_PASSWORD = "Invalid username or password"
  82. invalid_login_token_counter = Counter(
  83. "synapse_user_login_invalid_login_tokens",
  84. "Counts the number of rejected m.login.token on /login",
  85. ["reason"],
  86. )
  87. def convert_client_dict_legacy_fields_to_identifier(
  88. submission: JsonDict,
  89. ) -> Dict[str, str]:
  90. """
  91. Convert a legacy-formatted login submission to an identifier dict.
  92. Legacy login submissions (used in both login and user-interactive authentication)
  93. provide user-identifying information at the top-level instead.
  94. These are now deprecated and replaced with identifiers:
  95. https://matrix.org/docs/spec/client_server/r0.6.1#identifier-types
  96. Args:
  97. submission: The client dict to convert
  98. Returns:
  99. The matching identifier dict
  100. Raises:
  101. SynapseError: If the format of the client dict is invalid
  102. """
  103. identifier = submission.get("identifier", {})
  104. # Generate an m.id.user identifier if "user" parameter is present
  105. user = submission.get("user")
  106. if user:
  107. identifier = {"type": "m.id.user", "user": user}
  108. # Generate an m.id.thirdparty identifier if "medium" and "address" parameters are present
  109. medium = submission.get("medium")
  110. address = submission.get("address")
  111. if medium and address:
  112. identifier = {
  113. "type": "m.id.thirdparty",
  114. "medium": medium,
  115. "address": address,
  116. }
  117. # We've converted valid, legacy login submissions to an identifier. If the
  118. # submission still doesn't have an identifier, it's invalid
  119. if not identifier:
  120. raise SynapseError(400, "Invalid login submission", Codes.INVALID_PARAM)
  121. # Ensure the identifier has a type
  122. if "type" not in identifier:
  123. raise SynapseError(
  124. 400,
  125. "'identifier' dict has no key 'type'",
  126. errcode=Codes.MISSING_PARAM,
  127. )
  128. return identifier
  129. def login_id_phone_to_thirdparty(identifier: JsonDict) -> Dict[str, str]:
  130. """
  131. Convert a phone login identifier type to a generic threepid identifier.
  132. Args:
  133. identifier: Login identifier dict of type 'm.id.phone'
  134. Returns:
  135. An equivalent m.id.thirdparty identifier dict
  136. """
  137. if "country" not in identifier or (
  138. # The specification requires a "phone" field, while Synapse used to require a "number"
  139. # field. Accept both for backwards compatibility.
  140. "phone" not in identifier
  141. and "number" not in identifier
  142. ):
  143. raise SynapseError(
  144. 400, "Invalid phone-type identifier", errcode=Codes.INVALID_PARAM
  145. )
  146. # Accept both "phone" and "number" as valid keys in m.id.phone
  147. phone_number = identifier.get("phone", identifier["number"])
  148. # Convert user-provided phone number to a consistent representation
  149. msisdn = phone_number_to_msisdn(identifier["country"], phone_number)
  150. return {
  151. "type": "m.id.thirdparty",
  152. "medium": "msisdn",
  153. "address": msisdn,
  154. }
  155. @attr.s(slots=True, auto_attribs=True)
  156. class SsoLoginExtraAttributes:
  157. """Data we track about SAML2 sessions"""
  158. # time the session was created, in milliseconds
  159. creation_time: int
  160. extra_attributes: JsonDict
  161. class AuthHandler:
  162. SESSION_EXPIRE_MS = 48 * 60 * 60 * 1000
  163. def __init__(self, hs: "HomeServer"):
  164. self.store = hs.get_datastores().main
  165. self.auth = hs.get_auth()
  166. self.auth_blocking = hs.get_auth_blocking()
  167. self.clock = hs.get_clock()
  168. self.checkers: Dict[str, UserInteractiveAuthChecker] = {}
  169. for auth_checker_class in INTERACTIVE_AUTH_CHECKERS:
  170. inst = auth_checker_class(hs)
  171. if inst.is_enabled():
  172. self.checkers[inst.AUTH_TYPE] = inst
  173. self.bcrypt_rounds = hs.config.registration.bcrypt_rounds
  174. self.password_auth_provider = hs.get_password_auth_provider()
  175. self.hs = hs # FIXME better possibility to access registrationHandler later?
  176. self.macaroon_gen = hs.get_macaroon_generator()
  177. self._password_enabled_for_login = hs.config.auth.password_enabled_for_login
  178. self._password_enabled_for_reauth = hs.config.auth.password_enabled_for_reauth
  179. self._password_localdb_enabled = hs.config.auth.password_localdb_enabled
  180. self._third_party_rules = hs.get_third_party_event_rules()
  181. # Ratelimiter for failed auth during UIA. Uses same ratelimit config
  182. # as per `rc_login.failed_attempts`.
  183. self._failed_uia_attempts_ratelimiter = Ratelimiter(
  184. store=self.store,
  185. clock=self.clock,
  186. rate_hz=self.hs.config.ratelimiting.rc_login_failed_attempts.per_second,
  187. burst_count=self.hs.config.ratelimiting.rc_login_failed_attempts.burst_count,
  188. )
  189. # The number of seconds to keep a UI auth session active.
  190. self._ui_auth_session_timeout = hs.config.auth.ui_auth_session_timeout
  191. # Ratelimitier for failed /login attempts
  192. self._failed_login_attempts_ratelimiter = Ratelimiter(
  193. store=self.store,
  194. clock=hs.get_clock(),
  195. rate_hz=self.hs.config.ratelimiting.rc_login_failed_attempts.per_second,
  196. burst_count=self.hs.config.ratelimiting.rc_login_failed_attempts.burst_count,
  197. )
  198. self._clock = self.hs.get_clock()
  199. # Expire old UI auth sessions after a period of time.
  200. if hs.config.worker.run_background_tasks:
  201. self._clock.looping_call(
  202. run_as_background_process,
  203. 5 * 60 * 1000,
  204. "expire_old_sessions",
  205. self._expire_old_sessions,
  206. )
  207. # Load the SSO HTML templates.
  208. # The following template is shown to the user during a client login via SSO,
  209. # after the SSO completes and before redirecting them back to their client.
  210. # It notifies the user they are about to give access to their matrix account
  211. # to the client.
  212. self._sso_redirect_confirm_template = (
  213. hs.config.sso.sso_redirect_confirm_template
  214. )
  215. # The following template is shown during user interactive authentication
  216. # in the fallback auth scenario. It notifies the user that they are
  217. # authenticating for an operation to occur on their account.
  218. self._sso_auth_confirm_template = hs.config.sso.sso_auth_confirm_template
  219. # The following template is shown during the SSO authentication process if
  220. # the account is deactivated.
  221. self._sso_account_deactivated_template = (
  222. hs.config.sso.sso_account_deactivated_template
  223. )
  224. self._server_name = hs.config.server.server_name
  225. # cast to tuple for use with str.startswith
  226. self._whitelisted_sso_clients = tuple(hs.config.sso.sso_client_whitelist)
  227. # A mapping of user ID to extra attributes to include in the login
  228. # response.
  229. self._extra_attributes: Dict[str, SsoLoginExtraAttributes] = {}
  230. async def validate_user_via_ui_auth(
  231. self,
  232. requester: Requester,
  233. request: SynapseRequest,
  234. request_body: Dict[str, Any],
  235. description: str,
  236. can_skip_ui_auth: bool = False,
  237. ) -> Tuple[dict, Optional[str]]:
  238. """
  239. Checks that the user is who they claim to be, via a UI auth.
  240. This is used for things like device deletion and password reset where
  241. the user already has a valid access token, but we want to double-check
  242. that it isn't stolen by re-authenticating them.
  243. Args:
  244. requester: The user making the request, according to the access token.
  245. request: The request sent by the client.
  246. request_body: The body of the request sent by the client
  247. description: A human readable string to be displayed to the user that
  248. describes the operation happening on their account.
  249. can_skip_ui_auth: True if the UI auth session timeout applies this
  250. action. Should be set to False for any "dangerous"
  251. actions (e.g. deactivating an account).
  252. Returns:
  253. A tuple of (params, session_id).
  254. 'params' contains the parameters for this request (which may
  255. have been given only in a previous call).
  256. 'session_id' is the ID of this session, either passed in by the
  257. client or assigned by this call. This is None if UI auth was
  258. skipped (by re-using a previous validation).
  259. Raises:
  260. InteractiveAuthIncompleteError if the client has not yet completed
  261. any of the permitted login flows
  262. AuthError if the client has completed a login flow, and it gives
  263. a different user to `requester`
  264. LimitExceededError if the ratelimiter's failed request count for this
  265. user is too high to proceed
  266. """
  267. if not requester.access_token_id:
  268. raise ValueError("Cannot validate a user without an access token")
  269. if can_skip_ui_auth and self._ui_auth_session_timeout:
  270. last_validated = await self.store.get_access_token_last_validated(
  271. requester.access_token_id
  272. )
  273. if self.clock.time_msec() - last_validated < self._ui_auth_session_timeout:
  274. # Return the input parameters, minus the auth key, which matches
  275. # the logic in check_ui_auth.
  276. request_body.pop("auth", None)
  277. return request_body, None
  278. requester_user_id = requester.user.to_string()
  279. # Check if we should be ratelimited due to too many previous failed attempts
  280. await self._failed_uia_attempts_ratelimiter.ratelimit(requester, update=False)
  281. # build a list of supported flows
  282. supported_ui_auth_types = await self._get_available_ui_auth_types(
  283. requester.user
  284. )
  285. flows = [[login_type] for login_type in supported_ui_auth_types]
  286. def get_new_session_data() -> JsonDict:
  287. return {UIAuthSessionDataConstants.REQUEST_USER_ID: requester_user_id}
  288. try:
  289. result, params, session_id = await self.check_ui_auth(
  290. flows,
  291. request,
  292. request_body,
  293. description,
  294. get_new_session_data,
  295. )
  296. except LoginError:
  297. # Update the ratelimiter to say we failed (`can_do_action` doesn't raise).
  298. await self._failed_uia_attempts_ratelimiter.can_do_action(
  299. requester,
  300. )
  301. raise
  302. # find the completed login type
  303. for login_type in supported_ui_auth_types:
  304. if login_type not in result:
  305. continue
  306. validated_user_id = result[login_type]
  307. break
  308. else:
  309. # this can't happen
  310. raise Exception("check_auth returned True but no successful login type")
  311. # check that the UI auth matched the access token
  312. if validated_user_id != requester_user_id:
  313. raise AuthError(403, "Invalid auth")
  314. # Note that the access token has been validated.
  315. await self.store.update_access_token_last_validated(requester.access_token_id)
  316. return params, session_id
  317. async def _get_available_ui_auth_types(self, user: UserID) -> Iterable[str]:
  318. """Get a list of the user-interactive authentication types this user can use."""
  319. ui_auth_types = set()
  320. # if the HS supports password auth, and the user has a non-null password, we
  321. # support password auth
  322. if self._password_localdb_enabled and self._password_enabled_for_reauth:
  323. lookupres = await self._find_user_id_and_pwd_hash(user.to_string())
  324. if lookupres:
  325. _, password_hash = lookupres
  326. if password_hash:
  327. ui_auth_types.add(LoginType.PASSWORD)
  328. # also allow auth from password providers
  329. for t in self.password_auth_provider.get_supported_login_types().keys():
  330. if t == LoginType.PASSWORD and not self._password_enabled_for_reauth:
  331. continue
  332. ui_auth_types.add(t)
  333. # if sso is enabled, allow the user to log in via SSO iff they have a mapping
  334. # from sso to mxid.
  335. if await self.hs.get_sso_handler().get_identity_providers_for_user(
  336. user.to_string()
  337. ):
  338. ui_auth_types.add(LoginType.SSO)
  339. return ui_auth_types
  340. def get_enabled_auth_types(self) -> Iterable[str]:
  341. """Return the enabled user-interactive authentication types
  342. Returns the UI-Auth types which are supported by the homeserver's current
  343. config.
  344. """
  345. return self.checkers.keys()
  346. async def check_ui_auth(
  347. self,
  348. flows: List[List[str]],
  349. request: SynapseRequest,
  350. clientdict: Dict[str, Any],
  351. description: str,
  352. get_new_session_data: Optional[Callable[[], JsonDict]] = None,
  353. ) -> Tuple[dict, dict, str]:
  354. """
  355. Takes a dictionary sent by the client in the login / registration
  356. protocol and handles the User-Interactive Auth flow.
  357. If no auth flows have been completed successfully, raises an
  358. InteractiveAuthIncompleteError. To handle this, you can use
  359. synapse.rest.client._base.interactive_auth_handler as a
  360. decorator.
  361. Args:
  362. flows: A list of login flows. Each flow is an ordered list of
  363. strings representing auth-types. At least one full
  364. flow must be completed in order for auth to be successful.
  365. request: The request sent by the client.
  366. clientdict: The dictionary from the client root level, not the
  367. 'auth' key: this method prompts for auth if none is sent.
  368. description: A human readable string to be displayed to the user that
  369. describes the operation happening on their account.
  370. get_new_session_data:
  371. an optional callback which will be called when starting a new session.
  372. it should return data to be stored as part of the session.
  373. The keys of the returned data should be entries in
  374. UIAuthSessionDataConstants.
  375. Returns:
  376. A tuple of (creds, params, session_id).
  377. 'creds' contains the authenticated credentials of each stage.
  378. 'params' contains the parameters for this request (which may
  379. have been given only in a previous call).
  380. 'session_id' is the ID of this session, either passed in by the
  381. client or assigned by this call
  382. Raises:
  383. InteractiveAuthIncompleteError if the client has not yet completed
  384. all the stages in any of the permitted flows.
  385. """
  386. sid: Optional[str] = None
  387. authdict = clientdict.pop("auth", {})
  388. if "session" in authdict:
  389. sid = authdict["session"]
  390. # Convert the URI and method to strings.
  391. uri = request.uri.decode("utf-8")
  392. method = request.method.decode("utf-8")
  393. # If there's no session ID, create a new session.
  394. if not sid:
  395. new_session_data = get_new_session_data() if get_new_session_data else {}
  396. session = await self.store.create_ui_auth_session(
  397. clientdict, uri, method, description
  398. )
  399. for k, v in new_session_data.items():
  400. await self.set_session_data(session.session_id, k, v)
  401. else:
  402. try:
  403. session = await self.store.get_ui_auth_session(sid)
  404. except StoreError:
  405. raise SynapseError(400, "Unknown session ID: %s" % (sid,))
  406. # If the client provides parameters, update what is persisted,
  407. # otherwise use whatever was last provided.
  408. #
  409. # This was designed to allow the client to omit the parameters
  410. # and just supply the session in subsequent calls so it split
  411. # auth between devices by just sharing the session, (eg. so you
  412. # could continue registration from your phone having clicked the
  413. # email auth link on there). It's probably too open to abuse
  414. # because it lets unauthenticated clients store arbitrary objects
  415. # on a homeserver.
  416. #
  417. # Revisit: Assuming the REST APIs do sensible validation, the data
  418. # isn't arbitrary.
  419. #
  420. # Note that the registration endpoint explicitly removes the
  421. # "initial_device_display_name" parameter if it is provided
  422. # without a "password" parameter. See the changes to
  423. # synapse.rest.client.register.RegisterRestServlet.on_POST
  424. # in commit 544722bad23fc31056b9240189c3cbbbf0ffd3f9.
  425. if not clientdict:
  426. clientdict = session.clientdict
  427. # Ensure that the queried operation does not vary between stages of
  428. # the UI authentication session. This is done by generating a stable
  429. # comparator and storing it during the initial query. Subsequent
  430. # queries ensure that this comparator has not changed.
  431. #
  432. # The comparator is based on the requested URI and HTTP method. The
  433. # client dict (minus the auth dict) should also be checked, but some
  434. # clients are not spec compliant, just warn for now if the client
  435. # dict changes.
  436. if (session.uri, session.method) != (uri, method):
  437. raise SynapseError(
  438. 403,
  439. "Requested operation has changed during the UI authentication session.",
  440. )
  441. if session.clientdict != clientdict:
  442. logger.warning(
  443. "Requested operation has changed during the UI "
  444. "authentication session. A future version of Synapse "
  445. "will remove this capability."
  446. )
  447. # For backwards compatibility, changes to the client dict are
  448. # persisted as clients modify them throughout their user interactive
  449. # authentication flow.
  450. await self.store.set_ui_auth_clientdict(sid, clientdict)
  451. user_agent = get_request_user_agent(request)
  452. clientip = request.getClientAddress().host
  453. await self.store.add_user_agent_ip_to_ui_auth_session(
  454. session.session_id, user_agent, clientip
  455. )
  456. if not authdict:
  457. raise InteractiveAuthIncompleteError(
  458. session.session_id, self._auth_dict_for_flows(flows, session.session_id)
  459. )
  460. # check auth type currently being presented
  461. errordict: Dict[str, Any] = {}
  462. if "type" in authdict:
  463. login_type: str = authdict["type"]
  464. try:
  465. result = await self._check_auth_dict(authdict, clientip)
  466. if result:
  467. await self.store.mark_ui_auth_stage_complete(
  468. session.session_id, login_type, result
  469. )
  470. except LoginError as e:
  471. # this step failed. Merge the error dict into the response
  472. # so that the client can have another go.
  473. errordict = e.error_dict(self.hs.config)
  474. creds = await self.store.get_completed_ui_auth_stages(session.session_id)
  475. for f in flows:
  476. # If all the required credentials have been supplied, the user has
  477. # successfully completed the UI auth process!
  478. if len(set(f) - set(creds)) == 0:
  479. # it's very useful to know what args are stored, but this can
  480. # include the password in the case of registering, so only log
  481. # the keys (confusingly, clientdict may contain a password
  482. # param, creds is just what the user authed as for UI auth
  483. # and is not sensitive).
  484. logger.info(
  485. "Auth completed with creds: %r. Client dict has keys: %r",
  486. creds,
  487. list(clientdict),
  488. )
  489. return creds, clientdict, session.session_id
  490. ret = self._auth_dict_for_flows(flows, session.session_id)
  491. ret["completed"] = list(creds)
  492. ret.update(errordict)
  493. raise InteractiveAuthIncompleteError(session.session_id, ret)
  494. async def add_oob_auth(
  495. self, stagetype: str, authdict: Dict[str, Any], clientip: str
  496. ) -> None:
  497. """
  498. Adds the result of out-of-band authentication into an existing auth
  499. session. Currently used for adding the result of fallback auth.
  500. Raises:
  501. LoginError if the stagetype is unknown or the session is missing.
  502. LoginError is raised by check_auth if authentication fails.
  503. """
  504. if stagetype not in self.checkers:
  505. raise LoginError(
  506. 400, f"Unknown UIA stage type: {stagetype}", Codes.INVALID_PARAM
  507. )
  508. if "session" not in authdict:
  509. raise LoginError(400, "Missing session ID", Codes.MISSING_PARAM)
  510. # If authentication fails a LoginError is raised. Otherwise, store
  511. # the successful result.
  512. result = await self.checkers[stagetype].check_auth(authdict, clientip)
  513. await self.store.mark_ui_auth_stage_complete(
  514. authdict["session"], stagetype, result
  515. )
  516. def get_session_id(self, clientdict: Dict[str, Any]) -> Optional[str]:
  517. """
  518. Gets the session ID for a client given the client dictionary
  519. Args:
  520. clientdict: The dictionary sent by the client in the request
  521. Returns:
  522. The string session ID the client sent. If the client did
  523. not send a session ID, returns None.
  524. """
  525. sid = None
  526. if clientdict and "auth" in clientdict:
  527. authdict = clientdict["auth"]
  528. if "session" in authdict:
  529. sid = authdict["session"]
  530. return sid
  531. async def set_session_data(self, session_id: str, key: str, value: Any) -> None:
  532. """
  533. Store a key-value pair into the sessions data associated with this
  534. request. This data is stored server-side and cannot be modified by
  535. the client.
  536. Args:
  537. session_id: The ID of this session as returned from check_auth
  538. key: The key to store the data under. An entry from
  539. UIAuthSessionDataConstants.
  540. value: The data to store
  541. """
  542. try:
  543. await self.store.set_ui_auth_session_data(session_id, key, value)
  544. except StoreError:
  545. raise SynapseError(400, "Unknown session ID: %s" % (session_id,))
  546. async def get_session_data(
  547. self, session_id: str, key: str, default: Optional[Any] = None
  548. ) -> Any:
  549. """
  550. Retrieve data stored with set_session_data
  551. Args:
  552. session_id: The ID of this session as returned from check_auth
  553. key: The key the data was stored under. An entry from
  554. UIAuthSessionDataConstants.
  555. default: Value to return if the key has not been set
  556. """
  557. try:
  558. return await self.store.get_ui_auth_session_data(session_id, key, default)
  559. except StoreError:
  560. raise SynapseError(400, "Unknown session ID: %s" % (session_id,))
  561. async def _expire_old_sessions(self) -> None:
  562. """
  563. Invalidate any user interactive authentication sessions that have expired.
  564. """
  565. now = self._clock.time_msec()
  566. expiration_time = now - self.SESSION_EXPIRE_MS
  567. await self.store.delete_old_ui_auth_sessions(expiration_time)
  568. async def _check_auth_dict(
  569. self, authdict: Dict[str, Any], clientip: str
  570. ) -> Union[Dict[str, Any], str]:
  571. """Attempt to validate the auth dict provided by a client
  572. Args:
  573. authdict: auth dict provided by the client
  574. clientip: IP address of the client
  575. Returns:
  576. Result of the stage verification.
  577. Raises:
  578. StoreError if there was a problem accessing the database
  579. SynapseError if there was a problem with the request
  580. LoginError if there was an authentication problem.
  581. """
  582. login_type = authdict["type"]
  583. checker = self.checkers.get(login_type)
  584. if checker is not None:
  585. res = await checker.check_auth(authdict, clientip=clientip)
  586. return res
  587. # fall back to the v1 login flow
  588. canonical_id, _ = await self.validate_login(authdict, is_reauth=True)
  589. return canonical_id
  590. def _get_params_recaptcha(self) -> dict:
  591. return {"public_key": self.hs.config.captcha.recaptcha_public_key}
  592. def _get_params_terms(self) -> dict:
  593. return {
  594. "policies": {
  595. "privacy_policy": {
  596. "version": self.hs.config.consent.user_consent_version,
  597. "en": {
  598. "name": self.hs.config.consent.user_consent_policy_name,
  599. "url": "%s_matrix/consent?v=%s"
  600. % (
  601. self.hs.config.server.public_baseurl,
  602. self.hs.config.consent.user_consent_version,
  603. ),
  604. },
  605. }
  606. }
  607. }
  608. def _auth_dict_for_flows(
  609. self,
  610. flows: List[List[str]],
  611. session_id: str,
  612. ) -> Dict[str, Any]:
  613. public_flows = []
  614. for f in flows:
  615. public_flows.append(f)
  616. get_params = {
  617. LoginType.RECAPTCHA: self._get_params_recaptcha,
  618. LoginType.TERMS: self._get_params_terms,
  619. }
  620. params: Dict[str, Any] = {}
  621. for f in public_flows:
  622. for stage in f:
  623. if stage in get_params and stage not in params:
  624. params[stage] = get_params[stage]()
  625. return {
  626. "session": session_id,
  627. "flows": [{"stages": f} for f in public_flows],
  628. "params": params,
  629. }
  630. async def refresh_token(
  631. self,
  632. refresh_token: str,
  633. access_token_valid_until_ms: Optional[int],
  634. refresh_token_valid_until_ms: Optional[int],
  635. ) -> Tuple[str, str, Optional[int]]:
  636. """
  637. Consumes a refresh token and generate both a new access token and a new refresh token from it.
  638. The consumed refresh token is considered invalid after the first use of the new access token or the new refresh token.
  639. The lifetime of both the access token and refresh token will be capped so that they
  640. do not exceed the session's ultimate expiry time, if applicable.
  641. Args:
  642. refresh_token: The token to consume.
  643. access_token_valid_until_ms: The expiration timestamp of the new access token.
  644. None if the access token does not expire.
  645. refresh_token_valid_until_ms: The expiration timestamp of the new refresh token.
  646. None if the refresh token does not expire.
  647. Returns:
  648. A tuple containing:
  649. - the new access token
  650. - the new refresh token
  651. - the actual expiry time of the access token, which may be earlier than
  652. `access_token_valid_until_ms`.
  653. """
  654. # Verify the token signature first before looking up the token
  655. if not self._verify_refresh_token(refresh_token):
  656. raise SynapseError(
  657. HTTPStatus.UNAUTHORIZED, "invalid refresh token", Codes.UNKNOWN_TOKEN
  658. )
  659. existing_token = await self.store.lookup_refresh_token(refresh_token)
  660. if existing_token is None:
  661. raise SynapseError(
  662. HTTPStatus.UNAUTHORIZED,
  663. "refresh token does not exist",
  664. Codes.UNKNOWN_TOKEN,
  665. )
  666. if (
  667. existing_token.has_next_access_token_been_used
  668. or existing_token.has_next_refresh_token_been_refreshed
  669. ):
  670. raise SynapseError(
  671. HTTPStatus.FORBIDDEN,
  672. "refresh token isn't valid anymore",
  673. Codes.FORBIDDEN,
  674. )
  675. now_ms = self._clock.time_msec()
  676. if existing_token.expiry_ts is not None and existing_token.expiry_ts < now_ms:
  677. raise SynapseError(
  678. HTTPStatus.FORBIDDEN,
  679. "The supplied refresh token has expired",
  680. Codes.FORBIDDEN,
  681. )
  682. if existing_token.ultimate_session_expiry_ts is not None:
  683. # This session has a bounded lifetime, even across refreshes.
  684. if access_token_valid_until_ms is not None:
  685. access_token_valid_until_ms = min(
  686. access_token_valid_until_ms,
  687. existing_token.ultimate_session_expiry_ts,
  688. )
  689. else:
  690. access_token_valid_until_ms = existing_token.ultimate_session_expiry_ts
  691. if refresh_token_valid_until_ms is not None:
  692. refresh_token_valid_until_ms = min(
  693. refresh_token_valid_until_ms,
  694. existing_token.ultimate_session_expiry_ts,
  695. )
  696. else:
  697. refresh_token_valid_until_ms = existing_token.ultimate_session_expiry_ts
  698. if existing_token.ultimate_session_expiry_ts < now_ms:
  699. raise SynapseError(
  700. HTTPStatus.FORBIDDEN,
  701. "The session has expired and can no longer be refreshed",
  702. Codes.FORBIDDEN,
  703. )
  704. (
  705. new_refresh_token,
  706. new_refresh_token_id,
  707. ) = await self.create_refresh_token_for_user_id(
  708. user_id=existing_token.user_id,
  709. device_id=existing_token.device_id,
  710. expiry_ts=refresh_token_valid_until_ms,
  711. ultimate_session_expiry_ts=existing_token.ultimate_session_expiry_ts,
  712. )
  713. access_token = await self.create_access_token_for_user_id(
  714. user_id=existing_token.user_id,
  715. device_id=existing_token.device_id,
  716. valid_until_ms=access_token_valid_until_ms,
  717. refresh_token_id=new_refresh_token_id,
  718. )
  719. await self.store.replace_refresh_token(
  720. existing_token.token_id, new_refresh_token_id
  721. )
  722. return access_token, new_refresh_token, access_token_valid_until_ms
  723. def _verify_refresh_token(self, token: str) -> bool:
  724. """
  725. Verifies the shape of a refresh token.
  726. Args:
  727. token: The refresh token to verify
  728. Returns:
  729. Whether the token has the right shape
  730. """
  731. parts = token.split("_", maxsplit=4)
  732. if len(parts) != 4:
  733. return False
  734. type, localpart, rand, crc = parts
  735. # Refresh tokens are prefixed by "syr_", let's check that
  736. if type != "syr":
  737. return False
  738. # Check the CRC
  739. base = f"{type}_{localpart}_{rand}"
  740. expected_crc = base62_encode(crc32(base.encode("ascii")), minwidth=6)
  741. if crc != expected_crc:
  742. return False
  743. return True
  744. async def create_login_token_for_user_id(
  745. self,
  746. user_id: str,
  747. duration_ms: int = (2 * 60 * 1000),
  748. auth_provider_id: Optional[str] = None,
  749. auth_provider_session_id: Optional[str] = None,
  750. ) -> str:
  751. login_token = self.generate_login_token()
  752. now = self._clock.time_msec()
  753. expiry_ts = now + duration_ms
  754. await self.store.add_login_token_to_user(
  755. user_id=user_id,
  756. token=login_token,
  757. expiry_ts=expiry_ts,
  758. auth_provider_id=auth_provider_id,
  759. auth_provider_session_id=auth_provider_session_id,
  760. )
  761. return login_token
  762. async def create_refresh_token_for_user_id(
  763. self,
  764. user_id: str,
  765. device_id: str,
  766. expiry_ts: Optional[int],
  767. ultimate_session_expiry_ts: Optional[int],
  768. ) -> Tuple[str, int]:
  769. """
  770. Creates a new refresh token for the user with the given user ID.
  771. Args:
  772. user_id: canonical user ID
  773. device_id: the device ID to associate with the token.
  774. expiry_ts (milliseconds since the epoch): Time after which the
  775. refresh token cannot be used.
  776. If None, the refresh token never expires until it has been used.
  777. ultimate_session_expiry_ts (milliseconds since the epoch):
  778. Time at which the session will end and can not be extended any
  779. further.
  780. If None, the session can be refreshed indefinitely.
  781. Returns:
  782. The newly created refresh token and its ID in the database
  783. """
  784. refresh_token = self.generate_refresh_token(UserID.from_string(user_id))
  785. refresh_token_id = await self.store.add_refresh_token_to_user(
  786. user_id=user_id,
  787. token=refresh_token,
  788. device_id=device_id,
  789. expiry_ts=expiry_ts,
  790. ultimate_session_expiry_ts=ultimate_session_expiry_ts,
  791. )
  792. return refresh_token, refresh_token_id
  793. async def create_access_token_for_user_id(
  794. self,
  795. user_id: str,
  796. device_id: Optional[str],
  797. valid_until_ms: Optional[int],
  798. puppets_user_id: Optional[str] = None,
  799. is_appservice_ghost: bool = False,
  800. refresh_token_id: Optional[int] = None,
  801. ) -> str:
  802. """
  803. Creates a new access token for the user with the given user ID.
  804. The user is assumed to have been authenticated by some other
  805. mechanism (e.g. CAS), and the user_id converted to the canonical case.
  806. The device will be recorded in the table if it is not there already.
  807. Args:
  808. user_id: canonical User ID
  809. device_id: the device ID to associate with the tokens.
  810. None to leave the tokens unassociated with a device (deprecated:
  811. we should always have a device ID)
  812. valid_until_ms: when the token is valid until. None for
  813. no expiry.
  814. is_appservice_ghost: Whether the user is an application ghost user
  815. refresh_token_id: the refresh token ID that will be associated with
  816. this access token.
  817. Returns:
  818. The access token for the user's session.
  819. Raises:
  820. StoreError if there was a problem storing the token.
  821. """
  822. fmt_expiry = ""
  823. if valid_until_ms is not None:
  824. fmt_expiry = time.strftime(
  825. " until %Y-%m-%d %H:%M:%S", time.localtime(valid_until_ms / 1000.0)
  826. )
  827. if puppets_user_id:
  828. logger.info(
  829. "Logging in user %s as %s%s", user_id, puppets_user_id, fmt_expiry
  830. )
  831. target_user_id_obj = UserID.from_string(puppets_user_id)
  832. else:
  833. logger.info(
  834. "Logging in user %s on device %s%s", user_id, device_id, fmt_expiry
  835. )
  836. target_user_id_obj = UserID.from_string(user_id)
  837. if (
  838. not is_appservice_ghost
  839. or self.hs.config.appservice.track_appservice_user_ips
  840. ):
  841. await self.auth_blocking.check_auth_blocking(user_id)
  842. access_token = self.generate_access_token(target_user_id_obj)
  843. await self.store.add_access_token_to_user(
  844. user_id=user_id,
  845. token=access_token,
  846. device_id=device_id,
  847. valid_until_ms=valid_until_ms,
  848. puppets_user_id=puppets_user_id,
  849. refresh_token_id=refresh_token_id,
  850. )
  851. # the device *should* have been registered before we got here; however,
  852. # it's possible we raced against a DELETE operation. The thing we
  853. # really don't want is active access_tokens without a record of the
  854. # device, so we double-check it here.
  855. if device_id is not None:
  856. if await self.store.get_device(user_id, device_id) is None:
  857. await self.store.delete_access_token(access_token)
  858. raise StoreError(400, "Login raced against device deletion")
  859. return access_token
  860. async def check_user_exists(self, user_id: str) -> Optional[str]:
  861. """
  862. Checks to see if a user with the given id exists. Will check case
  863. insensitively, but return None if there are multiple inexact matches.
  864. Args:
  865. user_id: complete @user:id
  866. Returns:
  867. The canonical_user_id, or None if zero or multiple matches
  868. """
  869. res = await self._find_user_id_and_pwd_hash(user_id)
  870. if res is not None:
  871. return res[0]
  872. return None
  873. async def is_user_approved(self, user_id: str) -> bool:
  874. """Checks if a user is approved and therefore can be allowed to log in.
  875. Args:
  876. user_id: the user to check the approval status of.
  877. Returns:
  878. A boolean that is True if the user is approved, False otherwise.
  879. """
  880. return await self.store.is_user_approved(user_id)
  881. async def _find_user_id_and_pwd_hash(
  882. self, user_id: str
  883. ) -> Optional[Tuple[str, str]]:
  884. """Checks to see if a user with the given id exists. Will check case
  885. insensitively, but will return None if there are multiple inexact
  886. matches.
  887. Returns:
  888. A 2-tuple of `(canonical_user_id, password_hash)` or `None`
  889. if there is not exactly one match
  890. """
  891. user_infos = await self.store.get_users_by_id_case_insensitive(user_id)
  892. result = None
  893. if not user_infos:
  894. logger.warning("Attempted to login as %s but they do not exist", user_id)
  895. elif len(user_infos) == 1:
  896. # a single match (possibly not exact)
  897. result = user_infos.popitem()
  898. elif user_id in user_infos:
  899. # multiple matches, but one is exact
  900. result = (user_id, user_infos[user_id])
  901. else:
  902. # multiple matches, none of them exact
  903. logger.warning(
  904. "Attempted to login as %s but it matches more than one user "
  905. "inexactly: %r",
  906. user_id,
  907. user_infos.keys(),
  908. )
  909. return result
  910. def can_change_password(self) -> bool:
  911. """Get whether users on this server are allowed to change or set a password.
  912. Both `config.auth.password_enabled` and `config.auth.password_localdb_enabled` must be true.
  913. Note that any account (even SSO accounts) are allowed to add passwords if the above
  914. is true.
  915. Returns:
  916. Whether users on this server are allowed to change or set a password
  917. """
  918. return self._password_enabled_for_login and self._password_localdb_enabled
  919. def get_supported_login_types(self) -> Iterable[str]:
  920. """Get a the login types supported for the /login API
  921. By default this is just 'm.login.password' (unless password_enabled is
  922. False in the config file), but password auth providers can provide
  923. other login types.
  924. Returns:
  925. login types
  926. """
  927. # Load any login types registered by modules
  928. # This is stored in the password_auth_provider so this doesn't trigger
  929. # any callbacks
  930. types = list(self.password_auth_provider.get_supported_login_types().keys())
  931. # This list should include PASSWORD if (either _password_localdb_enabled is
  932. # true or if one of the modules registered it) AND _password_enabled is true
  933. # Also:
  934. # Some clients just pick the first type in the list. In this case, we want
  935. # them to use PASSWORD (rather than token or whatever), so we want to make sure
  936. # that comes first, where it's present.
  937. if LoginType.PASSWORD in types:
  938. types.remove(LoginType.PASSWORD)
  939. if self._password_enabled_for_login:
  940. types.insert(0, LoginType.PASSWORD)
  941. elif self._password_localdb_enabled and self._password_enabled_for_login:
  942. types.insert(0, LoginType.PASSWORD)
  943. return types
  944. async def validate_login(
  945. self,
  946. login_submission: Dict[str, Any],
  947. ratelimit: bool = False,
  948. is_reauth: bool = False,
  949. ) -> Tuple[str, Optional[Callable[["LoginResponse"], Awaitable[None]]]]:
  950. """Authenticates the user for the /login API
  951. Also used by the user-interactive auth flow to validate auth types which don't
  952. have an explicit UIA handler, including m.password.auth.
  953. Args:
  954. login_submission: the whole of the login submission
  955. (including 'type' and other relevant fields)
  956. ratelimit: whether to apply the failed_login_attempt ratelimiter
  957. is_reauth: whether this is part of a User-Interactive Authorisation
  958. flow to reauthenticate for a privileged action (rather than a
  959. new login)
  960. Returns:
  961. A tuple of the canonical user id, and optional callback
  962. to be called once the access token and device id are issued
  963. Raises:
  964. StoreError if there was a problem accessing the database
  965. SynapseError if there was a problem with the request
  966. LoginError if there was an authentication problem.
  967. """
  968. login_type = login_submission.get("type")
  969. if not isinstance(login_type, str):
  970. raise SynapseError(400, "Bad parameter: type", Codes.INVALID_PARAM)
  971. # ideally, we wouldn't be checking the identifier unless we know we have a login
  972. # method which uses it (https://github.com/matrix-org/synapse/issues/8836)
  973. #
  974. # But the auth providers' check_auth interface requires a username, so in
  975. # practice we can only support login methods which we can map to a username
  976. # anyway.
  977. # special case to check for "password" for the check_password interface
  978. # for the auth providers
  979. password = login_submission.get("password")
  980. if login_type == LoginType.PASSWORD:
  981. if is_reauth:
  982. passwords_allowed_here = self._password_enabled_for_reauth
  983. else:
  984. passwords_allowed_here = self._password_enabled_for_login
  985. if not passwords_allowed_here:
  986. raise SynapseError(400, "Password login has been disabled.")
  987. if not isinstance(password, str):
  988. raise SynapseError(400, "Bad parameter: password", Codes.INVALID_PARAM)
  989. # map old-school login fields into new-school "identifier" fields.
  990. identifier_dict = convert_client_dict_legacy_fields_to_identifier(
  991. login_submission
  992. )
  993. # convert phone type identifiers to generic threepids
  994. if identifier_dict["type"] == "m.id.phone":
  995. identifier_dict = login_id_phone_to_thirdparty(identifier_dict)
  996. # convert threepid identifiers to user IDs
  997. if identifier_dict["type"] == "m.id.thirdparty":
  998. address = identifier_dict.get("address")
  999. medium = identifier_dict.get("medium")
  1000. if medium is None or address is None:
  1001. raise SynapseError(400, "Invalid thirdparty identifier")
  1002. # For emails, canonicalise the address.
  1003. # We store all email addresses canonicalised in the DB.
  1004. # (See add_threepid in synapse/handlers/auth.py)
  1005. if medium == "email":
  1006. try:
  1007. address = canonicalise_email(address)
  1008. except ValueError as e:
  1009. raise SynapseError(400, str(e))
  1010. # We also apply account rate limiting using the 3PID as a key, as
  1011. # otherwise using 3PID bypasses the ratelimiting based on user ID.
  1012. if ratelimit:
  1013. await self._failed_login_attempts_ratelimiter.ratelimit(
  1014. None, (medium, address), update=False
  1015. )
  1016. # Check for login providers that support 3pid login types
  1017. if login_type == LoginType.PASSWORD:
  1018. # we've already checked that there is a (valid) password field
  1019. assert isinstance(password, str)
  1020. (
  1021. canonical_user_id,
  1022. callback_3pid,
  1023. ) = await self.check_password_provider_3pid(medium, address, password)
  1024. if canonical_user_id:
  1025. # Authentication through password provider and 3pid succeeded
  1026. return canonical_user_id, callback_3pid
  1027. # No password providers were able to handle this 3pid
  1028. # Check local store
  1029. user_id = await self.hs.get_datastores().main.get_user_id_by_threepid(
  1030. medium, address
  1031. )
  1032. if not user_id:
  1033. logger.warning(
  1034. "unknown 3pid identifier medium %s, address %r", medium, address
  1035. )
  1036. # We mark that we've failed to log in here, as
  1037. # `check_password_provider_3pid` might have returned `None` due
  1038. # to an incorrect password, rather than the account not
  1039. # existing.
  1040. #
  1041. # If it returned None but the 3PID was bound then we won't hit
  1042. # this code path, which is fine as then the per-user ratelimit
  1043. # will kick in below.
  1044. if ratelimit:
  1045. await self._failed_login_attempts_ratelimiter.can_do_action(
  1046. None, (medium, address)
  1047. )
  1048. raise LoginError(
  1049. 403, msg=INVALID_USERNAME_OR_PASSWORD, errcode=Codes.FORBIDDEN
  1050. )
  1051. identifier_dict = {"type": "m.id.user", "user": user_id}
  1052. # by this point, the identifier should be an m.id.user: if it's anything
  1053. # else, we haven't understood it.
  1054. if identifier_dict["type"] != "m.id.user":
  1055. raise SynapseError(400, "Unknown login identifier type")
  1056. username = identifier_dict.get("user")
  1057. if not username:
  1058. raise SynapseError(400, "User identifier is missing 'user' key")
  1059. if username.startswith("@"):
  1060. qualified_user_id = username
  1061. else:
  1062. qualified_user_id = UserID(username, self.hs.hostname).to_string()
  1063. # Check if we've hit the failed ratelimit (but don't update it)
  1064. if ratelimit:
  1065. await self._failed_login_attempts_ratelimiter.ratelimit(
  1066. None, qualified_user_id.lower(), update=False
  1067. )
  1068. try:
  1069. return await self._validate_userid_login(username, login_submission)
  1070. except LoginError:
  1071. # The user has failed to log in, so we need to update the rate
  1072. # limiter. Using `can_do_action` avoids us raising a ratelimit
  1073. # exception and masking the LoginError. The actual ratelimiting
  1074. # should have happened above.
  1075. if ratelimit:
  1076. await self._failed_login_attempts_ratelimiter.can_do_action(
  1077. None, qualified_user_id.lower()
  1078. )
  1079. raise
  1080. async def _validate_userid_login(
  1081. self,
  1082. username: str,
  1083. login_submission: Dict[str, Any],
  1084. ) -> Tuple[str, Optional[Callable[["LoginResponse"], Awaitable[None]]]]:
  1085. """Helper for validate_login
  1086. Handles login, once we've mapped 3pids onto userids
  1087. Args:
  1088. username: the username, from the identifier dict
  1089. login_submission: the whole of the login submission
  1090. (including 'type' and other relevant fields)
  1091. Returns:
  1092. A tuple of the canonical user id, and optional callback
  1093. to be called once the access token and device id are issued
  1094. Raises:
  1095. StoreError if there was a problem accessing the database
  1096. SynapseError if there was a problem with the request
  1097. LoginError if there was an authentication problem.
  1098. """
  1099. if username.startswith("@"):
  1100. qualified_user_id = username
  1101. else:
  1102. qualified_user_id = UserID(username, self.hs.hostname).to_string()
  1103. login_type = login_submission.get("type")
  1104. # we already checked that we have a valid login type
  1105. assert isinstance(login_type, str)
  1106. known_login_type = False
  1107. # Check if login_type matches a type registered by one of the modules
  1108. # We don't need to remove LoginType.PASSWORD from the list if password login is
  1109. # disabled, since if that were the case then by this point we know that the
  1110. # login_type is not LoginType.PASSWORD
  1111. supported_login_types = self.password_auth_provider.get_supported_login_types()
  1112. # check if the login type being used is supported by a module
  1113. if login_type in supported_login_types:
  1114. # Make a note that this login type is supported by the server
  1115. known_login_type = True
  1116. # Get all the fields expected for this login types
  1117. login_fields = supported_login_types[login_type]
  1118. # go through the login submission and keep track of which required fields are
  1119. # provided/not provided
  1120. missing_fields = []
  1121. login_dict = {}
  1122. for f in login_fields:
  1123. if f not in login_submission:
  1124. missing_fields.append(f)
  1125. else:
  1126. login_dict[f] = login_submission[f]
  1127. # raise an error if any of the expected fields for that login type weren't provided
  1128. if missing_fields:
  1129. raise SynapseError(
  1130. 400,
  1131. "Missing parameters for login type %s: %s"
  1132. % (login_type, missing_fields),
  1133. )
  1134. # call all of the check_auth hooks for that login_type
  1135. # it will return a result once the first success is found (or None otherwise)
  1136. result = await self.password_auth_provider.check_auth(
  1137. username, login_type, login_dict
  1138. )
  1139. if result:
  1140. return result
  1141. # if no module managed to authenticate the user, then fallback to built in password based auth
  1142. if login_type == LoginType.PASSWORD and self._password_localdb_enabled:
  1143. known_login_type = True
  1144. # we've already checked that there is a (valid) password field
  1145. password = login_submission["password"]
  1146. assert isinstance(password, str)
  1147. canonical_user_id = await self._check_local_password(
  1148. qualified_user_id, password
  1149. )
  1150. if canonical_user_id:
  1151. return canonical_user_id, None
  1152. if not known_login_type:
  1153. raise SynapseError(400, "Unknown login type %s" % login_type)
  1154. # We raise a 403 here, but note that if we're doing user-interactive
  1155. # login, it turns all LoginErrors into a 401 anyway.
  1156. raise LoginError(403, msg=INVALID_USERNAME_OR_PASSWORD, errcode=Codes.FORBIDDEN)
  1157. async def check_password_provider_3pid(
  1158. self, medium: str, address: str, password: str
  1159. ) -> Tuple[Optional[str], Optional[Callable[["LoginResponse"], Awaitable[None]]]]:
  1160. """Check if a password provider is able to validate a thirdparty login
  1161. Args:
  1162. medium: The medium of the 3pid (ex. email).
  1163. address: The address of the 3pid (ex. jdoe@example.com).
  1164. password: The password of the user.
  1165. Returns:
  1166. A tuple of `(user_id, callback)`. If authentication is successful,
  1167. `user_id`is the authenticated, canonical user ID. `callback` is
  1168. then either a function to be later run after the server has
  1169. completed login/registration, or `None`. If authentication was
  1170. unsuccessful, `user_id` and `callback` are both `None`.
  1171. """
  1172. # call all of the check_3pid_auth callbacks
  1173. # Result will be from the first callback that returns something other than None
  1174. # If all the callbacks return None, then result is also set to None
  1175. result = await self.password_auth_provider.check_3pid_auth(
  1176. medium, address, password
  1177. )
  1178. if result:
  1179. return result
  1180. # if result is None then return (None, None)
  1181. return None, None
  1182. async def _check_local_password(self, user_id: str, password: str) -> Optional[str]:
  1183. """Authenticate a user against the local password database.
  1184. user_id is checked case insensitively, but will return None if there are
  1185. multiple inexact matches.
  1186. Args:
  1187. user_id: complete @user:id
  1188. password: the provided password
  1189. Returns:
  1190. The canonical_user_id, or None if unknown user/bad password
  1191. """
  1192. lookupres = await self._find_user_id_and_pwd_hash(user_id)
  1193. if not lookupres:
  1194. return None
  1195. (user_id, password_hash) = lookupres
  1196. # If the password hash is None, the account has likely been deactivated
  1197. if not password_hash:
  1198. deactivated = await self.store.get_user_deactivated_status(user_id)
  1199. if deactivated:
  1200. raise UserDeactivatedError("This account has been deactivated")
  1201. result = await self.validate_hash(password, password_hash)
  1202. if not result:
  1203. logger.warning("Failed password login for user %s", user_id)
  1204. return None
  1205. return user_id
  1206. def generate_login_token(self) -> str:
  1207. """Generates an opaque string, for use as an short-term login token"""
  1208. # we use the following format for access tokens:
  1209. # syl_<random string>_<base62 crc check>
  1210. random_string = stringutils.random_string(20)
  1211. base = f"syl_{random_string}"
  1212. crc = base62_encode(crc32(base.encode("ascii")), minwidth=6)
  1213. return f"{base}_{crc}"
  1214. def generate_access_token(self, for_user: UserID) -> str:
  1215. """Generates an opaque string, for use as an access token"""
  1216. # we use the following format for access tokens:
  1217. # syt_<base64 local part>_<random string>_<base62 crc check>
  1218. b64local = unpaddedbase64.encode_base64(for_user.localpart.encode("utf-8"))
  1219. random_string = stringutils.random_string(20)
  1220. base = f"syt_{b64local}_{random_string}"
  1221. crc = base62_encode(crc32(base.encode("ascii")), minwidth=6)
  1222. return f"{base}_{crc}"
  1223. def generate_refresh_token(self, for_user: UserID) -> str:
  1224. """Generates an opaque string, for use as a refresh token"""
  1225. # we use the following format for refresh tokens:
  1226. # syr_<base64 local part>_<random string>_<base62 crc check>
  1227. b64local = unpaddedbase64.encode_base64(for_user.localpart.encode("utf-8"))
  1228. random_string = stringutils.random_string(20)
  1229. base = f"syr_{b64local}_{random_string}"
  1230. crc = base62_encode(crc32(base.encode("ascii")), minwidth=6)
  1231. return f"{base}_{crc}"
  1232. async def consume_login_token(self, login_token: str) -> LoginTokenLookupResult:
  1233. try:
  1234. return await self.store.consume_login_token(login_token)
  1235. except LoginTokenExpired:
  1236. invalid_login_token_counter.labels("expired").inc()
  1237. except LoginTokenReused:
  1238. invalid_login_token_counter.labels("reused").inc()
  1239. except NotFoundError:
  1240. invalid_login_token_counter.labels("not found").inc()
  1241. raise AuthError(403, "Invalid login token", errcode=Codes.FORBIDDEN)
  1242. async def delete_access_token(self, access_token: str) -> None:
  1243. """Invalidate a single access token
  1244. Args:
  1245. access_token: access token to be deleted
  1246. """
  1247. token = await self.store.get_user_by_access_token(access_token)
  1248. if not token:
  1249. # At this point, the token should already have been fetched once by
  1250. # the caller, so this should not happen, unless of a race condition
  1251. # between two delete requests
  1252. raise SynapseError(HTTPStatus.UNAUTHORIZED, "Unrecognised access token")
  1253. await self.store.delete_access_token(access_token)
  1254. # see if any modules want to know about this
  1255. await self.password_auth_provider.on_logged_out(
  1256. user_id=token.user_id,
  1257. device_id=token.device_id,
  1258. access_token=access_token,
  1259. )
  1260. # delete pushers associated with this access token
  1261. if token.token_id is not None:
  1262. await self.hs.get_pusherpool().remove_pushers_by_access_token(
  1263. token.user_id, (token.token_id,)
  1264. )
  1265. async def delete_access_tokens_for_user(
  1266. self,
  1267. user_id: str,
  1268. except_token_id: Optional[int] = None,
  1269. device_id: Optional[str] = None,
  1270. ) -> None:
  1271. """Invalidate access tokens belonging to a user
  1272. Args:
  1273. user_id: ID of user the tokens belong to
  1274. except_token_id: access_token ID which should *not* be deleted
  1275. device_id: ID of device the tokens are associated with.
  1276. If None, tokens associated with any device (or no device) will
  1277. be deleted
  1278. """
  1279. tokens_and_devices = await self.store.user_delete_access_tokens(
  1280. user_id, except_token_id=except_token_id, device_id=device_id
  1281. )
  1282. # see if any modules want to know about this
  1283. for token, _, device_id in tokens_and_devices:
  1284. await self.password_auth_provider.on_logged_out(
  1285. user_id=user_id, device_id=device_id, access_token=token
  1286. )
  1287. # delete pushers associated with the access tokens
  1288. await self.hs.get_pusherpool().remove_pushers_by_access_token(
  1289. user_id, (token_id for _, token_id, _ in tokens_and_devices)
  1290. )
  1291. async def add_threepid(
  1292. self, user_id: str, medium: str, address: str, validated_at: int
  1293. ) -> None:
  1294. # check if medium has a valid value
  1295. if medium not in ["email", "msisdn"]:
  1296. raise SynapseError(
  1297. code=400,
  1298. msg=("'%s' is not a valid value for 'medium'" % (medium,)),
  1299. errcode=Codes.INVALID_PARAM,
  1300. )
  1301. # 'Canonicalise' email addresses down to lower case.
  1302. # We've now moving towards the homeserver being the entity that
  1303. # is responsible for validating threepids used for resetting passwords
  1304. # on accounts, so in future Synapse will gain knowledge of specific
  1305. # types (mediums) of threepid. For now, we still use the existing
  1306. # infrastructure, but this is the start of synapse gaining knowledge
  1307. # of specific types of threepid (and fixes the fact that checking
  1308. # for the presence of an email address during password reset was
  1309. # case sensitive).
  1310. if medium == "email":
  1311. address = canonicalise_email(address)
  1312. await self.store.user_add_threepid(
  1313. user_id, medium, address, validated_at, self.hs.get_clock().time_msec()
  1314. )
  1315. await self._third_party_rules.on_threepid_bind(user_id, medium, address)
  1316. async def delete_threepid(
  1317. self, user_id: str, medium: str, address: str, id_server: Optional[str] = None
  1318. ) -> bool:
  1319. """Attempts to unbind the 3pid on the identity servers and deletes it
  1320. from the local database.
  1321. Args:
  1322. user_id: ID of user to remove the 3pid from.
  1323. medium: The medium of the 3pid being removed: "email" or "msisdn".
  1324. address: The 3pid address to remove.
  1325. id_server: Use the given identity server when unbinding
  1326. any threepids. If None then will attempt to unbind using the
  1327. identity server specified when binding (if known).
  1328. Returns:
  1329. Returns True if successfully unbound the 3pid on
  1330. the identity server, False if identity server doesn't support the
  1331. unbind API.
  1332. """
  1333. # 'Canonicalise' email addresses as per above
  1334. if medium == "email":
  1335. address = canonicalise_email(address)
  1336. result = await self.hs.get_identity_handler().try_unbind_threepid(
  1337. user_id, medium, address, id_server
  1338. )
  1339. await self.store.user_delete_threepid(user_id, medium, address)
  1340. if medium == "email":
  1341. await self.store.delete_pusher_by_app_id_pushkey_user_id(
  1342. app_id="m.email", pushkey=address, user_id=user_id
  1343. )
  1344. return result
  1345. async def hash(self, password: str) -> str:
  1346. """Computes a secure hash of password.
  1347. Args:
  1348. password: Password to hash.
  1349. Returns:
  1350. Hashed password.
  1351. """
  1352. def _do_hash() -> str:
  1353. # Normalise the Unicode in the password
  1354. pw = unicodedata.normalize("NFKC", password)
  1355. return bcrypt.hashpw(
  1356. pw.encode("utf8") + self.hs.config.auth.password_pepper.encode("utf8"),
  1357. bcrypt.gensalt(self.bcrypt_rounds),
  1358. ).decode("ascii")
  1359. return await defer_to_thread(self.hs.get_reactor(), _do_hash)
  1360. async def validate_hash(
  1361. self, password: str, stored_hash: Union[bytes, str]
  1362. ) -> bool:
  1363. """Validates that self.hash(password) == stored_hash.
  1364. Args:
  1365. password: Password to hash.
  1366. stored_hash: Expected hash value.
  1367. Returns:
  1368. Whether self.hash(password) == stored_hash.
  1369. """
  1370. def _do_validate_hash(checked_hash: bytes) -> bool:
  1371. # Normalise the Unicode in the password
  1372. pw = unicodedata.normalize("NFKC", password)
  1373. return bcrypt.checkpw(
  1374. pw.encode("utf8") + self.hs.config.auth.password_pepper.encode("utf8"),
  1375. checked_hash,
  1376. )
  1377. if stored_hash:
  1378. if not isinstance(stored_hash, bytes):
  1379. stored_hash = stored_hash.encode("ascii")
  1380. return await defer_to_thread(
  1381. self.hs.get_reactor(), _do_validate_hash, stored_hash
  1382. )
  1383. else:
  1384. return False
  1385. async def start_sso_ui_auth(self, request: SynapseRequest, session_id: str) -> str:
  1386. """
  1387. Get the HTML for the SSO redirect confirmation page.
  1388. Args:
  1389. request: The incoming HTTP request
  1390. session_id: The user interactive authentication session ID.
  1391. Returns:
  1392. The HTML to render.
  1393. """
  1394. try:
  1395. session = await self.store.get_ui_auth_session(session_id)
  1396. except StoreError:
  1397. raise SynapseError(400, "Unknown session ID: %s" % (session_id,))
  1398. user_id_to_verify: str = await self.get_session_data(
  1399. session_id, UIAuthSessionDataConstants.REQUEST_USER_ID
  1400. )
  1401. idps = await self.hs.get_sso_handler().get_identity_providers_for_user(
  1402. user_id_to_verify
  1403. )
  1404. if not idps:
  1405. # we checked that the user had some remote identities before offering an SSO
  1406. # flow, so either it's been deleted or the client has requested SSO despite
  1407. # it not being offered.
  1408. raise SynapseError(400, "User has no SSO identities")
  1409. # for now, just pick one
  1410. idp_id, sso_auth_provider = next(iter(idps.items()))
  1411. if len(idps) > 0:
  1412. logger.warning(
  1413. "User %r has previously logged in with multiple SSO IdPs; arbitrarily "
  1414. "picking %r",
  1415. user_id_to_verify,
  1416. idp_id,
  1417. )
  1418. redirect_url = await sso_auth_provider.handle_redirect_request(
  1419. request, None, session_id
  1420. )
  1421. return self._sso_auth_confirm_template.render(
  1422. description=session.description,
  1423. redirect_url=redirect_url,
  1424. idp=sso_auth_provider,
  1425. )
  1426. async def complete_sso_login(
  1427. self,
  1428. registered_user_id: str,
  1429. auth_provider_id: str,
  1430. request: Request,
  1431. client_redirect_url: str,
  1432. extra_attributes: Optional[JsonDict] = None,
  1433. new_user: bool = False,
  1434. auth_provider_session_id: Optional[str] = None,
  1435. ) -> None:
  1436. """Having figured out a mxid for this user, complete the HTTP request
  1437. Args:
  1438. registered_user_id: The registered user ID to complete SSO login for.
  1439. auth_provider_id: The id of the SSO Identity provider that was used for
  1440. login. This will be stored in the login token for future tracking in
  1441. prometheus metrics.
  1442. request: The request to complete.
  1443. client_redirect_url: The URL to which to redirect the user at the end of the
  1444. process.
  1445. extra_attributes: Extra attributes which will be passed to the client
  1446. during successful login. Must be JSON serializable.
  1447. new_user: True if we should use wording appropriate to a user who has just
  1448. registered.
  1449. auth_provider_session_id: The session ID from the SSO IdP received during login.
  1450. """
  1451. # If the account has been deactivated, do not proceed with the login
  1452. # flow.
  1453. deactivated = await self.store.get_user_deactivated_status(registered_user_id)
  1454. if deactivated:
  1455. respond_with_html(request, 403, self._sso_account_deactivated_template)
  1456. return
  1457. user_profile_data = await self.store.get_profileinfo(
  1458. UserID.from_string(registered_user_id).localpart
  1459. )
  1460. # Store any extra attributes which will be passed in the login response.
  1461. # Note that this is per-user so it may overwrite a previous value, this
  1462. # is considered OK since the newest SSO attributes should be most valid.
  1463. if extra_attributes:
  1464. self._extra_attributes[registered_user_id] = SsoLoginExtraAttributes(
  1465. self._clock.time_msec(),
  1466. extra_attributes,
  1467. )
  1468. # Create a login token
  1469. login_token = await self.create_login_token_for_user_id(
  1470. registered_user_id,
  1471. auth_provider_id=auth_provider_id,
  1472. auth_provider_session_id=auth_provider_session_id,
  1473. )
  1474. # Append the login token to the original redirect URL (i.e. with its query
  1475. # parameters kept intact) to build the URL to which the template needs to
  1476. # redirect the users once they have clicked on the confirmation link.
  1477. redirect_url = self.add_query_param_to_url(
  1478. client_redirect_url, "loginToken", login_token
  1479. )
  1480. # if the client is whitelisted, we can redirect straight to it
  1481. if client_redirect_url.startswith(self._whitelisted_sso_clients):
  1482. request.redirect(redirect_url)
  1483. finish_request(request)
  1484. return
  1485. # Otherwise, serve the redirect confirmation page.
  1486. # Remove the query parameters from the redirect URL to get a shorter version of
  1487. # it. This is only to display a human-readable URL in the template, but not the
  1488. # URL we redirect users to.
  1489. url_parts = urllib.parse.urlsplit(client_redirect_url)
  1490. if url_parts.scheme == "https":
  1491. # for an https uri, just show the netloc (ie, the hostname. Specifically,
  1492. # the bit between "//" and "/"; this includes any potential
  1493. # "username:password@" prefix.)
  1494. display_url = url_parts.netloc
  1495. else:
  1496. # for other uris, strip the query-params (including the login token) and
  1497. # fragment.
  1498. display_url = urllib.parse.urlunsplit(
  1499. (url_parts.scheme, url_parts.netloc, url_parts.path, "", "")
  1500. )
  1501. html = self._sso_redirect_confirm_template.render(
  1502. display_url=display_url,
  1503. redirect_url=redirect_url,
  1504. server_name=self._server_name,
  1505. new_user=new_user,
  1506. user_id=registered_user_id,
  1507. user_profile=user_profile_data,
  1508. )
  1509. respond_with_html(request, 200, html)
  1510. async def _sso_login_callback(self, login_result: "LoginResponse") -> None:
  1511. """
  1512. A login callback which might add additional attributes to the login response.
  1513. Args:
  1514. login_result: The data to be sent to the client. Includes the user
  1515. ID and access token.
  1516. """
  1517. # Expire attributes before processing. Note that there shouldn't be any
  1518. # valid logins that still have extra attributes.
  1519. self._expire_sso_extra_attributes()
  1520. extra_attributes = self._extra_attributes.get(login_result["user_id"])
  1521. if extra_attributes:
  1522. login_result_dict = cast(Dict[str, Any], login_result)
  1523. login_result_dict.update(extra_attributes.extra_attributes)
  1524. def _expire_sso_extra_attributes(self) -> None:
  1525. """
  1526. Iterate through the mapping of user IDs to extra attributes and remove any that are no longer valid.
  1527. """
  1528. # TODO This should match the amount of time the macaroon is valid for.
  1529. LOGIN_TOKEN_EXPIRATION_TIME = 2 * 60 * 1000
  1530. expire_before = self._clock.time_msec() - LOGIN_TOKEN_EXPIRATION_TIME
  1531. to_expire = set()
  1532. for user_id, data in self._extra_attributes.items():
  1533. if data.creation_time < expire_before:
  1534. to_expire.add(user_id)
  1535. for user_id in to_expire:
  1536. logger.debug("Expiring extra attributes for user %s", user_id)
  1537. del self._extra_attributes[user_id]
  1538. @staticmethod
  1539. def add_query_param_to_url(url: str, param_name: str, param: Any) -> str:
  1540. url_parts = list(urllib.parse.urlparse(url))
  1541. query = urllib.parse.parse_qsl(url_parts[4], keep_blank_values=True)
  1542. query.append((param_name, param))
  1543. url_parts[4] = urllib.parse.urlencode(query)
  1544. return urllib.parse.urlunparse(url_parts)
  1545. def load_legacy_password_auth_providers(hs: "HomeServer") -> None:
  1546. module_api = hs.get_module_api()
  1547. for module, config in hs.config.authproviders.password_providers:
  1548. load_single_legacy_password_auth_provider(
  1549. module=module, config=config, api=module_api
  1550. )
  1551. def load_single_legacy_password_auth_provider(
  1552. module: Type,
  1553. config: JsonDict,
  1554. api: "ModuleApi",
  1555. ) -> None:
  1556. try:
  1557. provider = module(config=config, account_handler=api)
  1558. except Exception as e:
  1559. logger.error("Error while initializing %r: %s", module, e)
  1560. raise
  1561. # All methods that the module provides should be async, but this wasn't enforced
  1562. # in the old module system, so we wrap them if needed
  1563. def async_wrapper(f: Optional[Callable]) -> Optional[Callable[..., Awaitable]]:
  1564. # f might be None if the callback isn't implemented by the module. In this
  1565. # case we don't want to register a callback at all so we return None.
  1566. if f is None:
  1567. return None
  1568. # We need to wrap check_password because its old form would return a boolean
  1569. # but we now want it to behave just like check_auth() and return the matrix id of
  1570. # the user if authentication succeeded or None otherwise
  1571. if f.__name__ == "check_password":
  1572. async def wrapped_check_password(
  1573. username: str, login_type: str, login_dict: JsonDict
  1574. ) -> Optional[Tuple[str, Optional[Callable]]]:
  1575. # We've already made sure f is not None above, but mypy doesn't do well
  1576. # across function boundaries so we need to tell it f is definitely not
  1577. # None.
  1578. assert f is not None
  1579. matrix_user_id = api.get_qualified_user_id(username)
  1580. password = login_dict["password"]
  1581. is_valid = await f(matrix_user_id, password)
  1582. if is_valid:
  1583. return matrix_user_id, None
  1584. return None
  1585. return wrapped_check_password
  1586. # We need to wrap check_auth as in the old form it could return
  1587. # just a str, but now it must return Optional[Tuple[str, Optional[Callable]]
  1588. if f.__name__ == "check_auth":
  1589. async def wrapped_check_auth(
  1590. username: str, login_type: str, login_dict: JsonDict
  1591. ) -> Optional[Tuple[str, Optional[Callable]]]:
  1592. # We've already made sure f is not None above, but mypy doesn't do well
  1593. # across function boundaries so we need to tell it f is definitely not
  1594. # None.
  1595. assert f is not None
  1596. result = await f(username, login_type, login_dict)
  1597. if isinstance(result, str):
  1598. return result, None
  1599. return result
  1600. return wrapped_check_auth
  1601. # We need to wrap check_3pid_auth as in the old form it could return
  1602. # just a str, but now it must return Optional[Tuple[str, Optional[Callable]]
  1603. if f.__name__ == "check_3pid_auth":
  1604. async def wrapped_check_3pid_auth(
  1605. medium: str, address: str, password: str
  1606. ) -> Optional[Tuple[str, Optional[Callable]]]:
  1607. # We've already made sure f is not None above, but mypy doesn't do well
  1608. # across function boundaries so we need to tell it f is definitely not
  1609. # None.
  1610. assert f is not None
  1611. result = await f(medium, address, password)
  1612. if isinstance(result, str):
  1613. return result, None
  1614. return result
  1615. return wrapped_check_3pid_auth
  1616. def run(*args: Tuple, **kwargs: Dict) -> Awaitable:
  1617. # mypy doesn't do well across function boundaries so we need to tell it
  1618. # f is definitely not None.
  1619. assert f is not None
  1620. return maybe_awaitable(f(*args, **kwargs))
  1621. return run
  1622. # If the module has these methods implemented, then we pull them out
  1623. # and register them as hooks.
  1624. check_3pid_auth_hook: Optional[CHECK_3PID_AUTH_CALLBACK] = async_wrapper(
  1625. getattr(provider, "check_3pid_auth", None)
  1626. )
  1627. on_logged_out_hook: Optional[ON_LOGGED_OUT_CALLBACK] = async_wrapper(
  1628. getattr(provider, "on_logged_out", None)
  1629. )
  1630. supported_login_types = {}
  1631. # call get_supported_login_types and add that to the dict
  1632. g = getattr(provider, "get_supported_login_types", None)
  1633. if g is not None:
  1634. # Note the old module style also called get_supported_login_types at loading time
  1635. # and it is synchronous
  1636. supported_login_types.update(g())
  1637. auth_checkers = {}
  1638. # Legacy modules have a check_auth method which expects to be called with one of
  1639. # the keys returned by get_supported_login_types. New style modules register a
  1640. # dictionary of login_type->check_auth_method mappings
  1641. check_auth = async_wrapper(getattr(provider, "check_auth", None))
  1642. if check_auth is not None:
  1643. for login_type, fields in supported_login_types.items():
  1644. # need tuple(fields) since fields can be any Iterable type (so may not be hashable)
  1645. auth_checkers[(login_type, tuple(fields))] = check_auth
  1646. # if it has a "check_password" method then it should handle all auth checks
  1647. # with login type of LoginType.PASSWORD
  1648. check_password = async_wrapper(getattr(provider, "check_password", None))
  1649. if check_password is not None:
  1650. # need to use a tuple here for ("password",) not a list since lists aren't hashable
  1651. auth_checkers[(LoginType.PASSWORD, ("password",))] = check_password
  1652. api.register_password_auth_provider_callbacks(
  1653. check_3pid_auth=check_3pid_auth_hook,
  1654. on_logged_out=on_logged_out_hook,
  1655. auth_checkers=auth_checkers,
  1656. )
  1657. CHECK_3PID_AUTH_CALLBACK = Callable[
  1658. [str, str, str],
  1659. Awaitable[
  1660. Optional[Tuple[str, Optional[Callable[["LoginResponse"], Awaitable[None]]]]]
  1661. ],
  1662. ]
  1663. ON_LOGGED_OUT_CALLBACK = Callable[[str, Optional[str], str], Awaitable]
  1664. CHECK_AUTH_CALLBACK = Callable[
  1665. [str, str, JsonDict],
  1666. Awaitable[
  1667. Optional[Tuple[str, Optional[Callable[["LoginResponse"], Awaitable[None]]]]]
  1668. ],
  1669. ]
  1670. GET_USERNAME_FOR_REGISTRATION_CALLBACK = Callable[
  1671. [JsonDict, JsonDict],
  1672. Awaitable[Optional[str]],
  1673. ]
  1674. GET_DISPLAYNAME_FOR_REGISTRATION_CALLBACK = Callable[
  1675. [JsonDict, JsonDict],
  1676. Awaitable[Optional[str]],
  1677. ]
  1678. IS_3PID_ALLOWED_CALLBACK = Callable[[str, str, bool], Awaitable[bool]]
  1679. class PasswordAuthProvider:
  1680. """
  1681. A class that the AuthHandler calls when authenticating users
  1682. It allows modules to provide alternative methods for authentication
  1683. """
  1684. def __init__(self) -> None:
  1685. # lists of callbacks
  1686. self.check_3pid_auth_callbacks: List[CHECK_3PID_AUTH_CALLBACK] = []
  1687. self.on_logged_out_callbacks: List[ON_LOGGED_OUT_CALLBACK] = []
  1688. self.get_username_for_registration_callbacks: List[
  1689. GET_USERNAME_FOR_REGISTRATION_CALLBACK
  1690. ] = []
  1691. self.get_displayname_for_registration_callbacks: List[
  1692. GET_DISPLAYNAME_FOR_REGISTRATION_CALLBACK
  1693. ] = []
  1694. self.is_3pid_allowed_callbacks: List[IS_3PID_ALLOWED_CALLBACK] = []
  1695. # Mapping from login type to login parameters
  1696. self._supported_login_types: Dict[str, Tuple[str, ...]] = {}
  1697. # Mapping from login type to auth checker callbacks
  1698. self.auth_checker_callbacks: Dict[str, List[CHECK_AUTH_CALLBACK]] = {}
  1699. def register_password_auth_provider_callbacks(
  1700. self,
  1701. check_3pid_auth: Optional[CHECK_3PID_AUTH_CALLBACK] = None,
  1702. on_logged_out: Optional[ON_LOGGED_OUT_CALLBACK] = None,
  1703. is_3pid_allowed: Optional[IS_3PID_ALLOWED_CALLBACK] = None,
  1704. auth_checkers: Optional[
  1705. Dict[Tuple[str, Tuple[str, ...]], CHECK_AUTH_CALLBACK]
  1706. ] = None,
  1707. get_username_for_registration: Optional[
  1708. GET_USERNAME_FOR_REGISTRATION_CALLBACK
  1709. ] = None,
  1710. get_displayname_for_registration: Optional[
  1711. GET_DISPLAYNAME_FOR_REGISTRATION_CALLBACK
  1712. ] = None,
  1713. ) -> None:
  1714. # Register check_3pid_auth callback
  1715. if check_3pid_auth is not None:
  1716. self.check_3pid_auth_callbacks.append(check_3pid_auth)
  1717. # register on_logged_out callback
  1718. if on_logged_out is not None:
  1719. self.on_logged_out_callbacks.append(on_logged_out)
  1720. if auth_checkers is not None:
  1721. # register a new supported login_type
  1722. # Iterate through all of the types being registered
  1723. for (login_type, fields), callback in auth_checkers.items():
  1724. # Note: fields may be empty here. This would allow a modules auth checker to
  1725. # be called with just 'login_type' and no password or other secrets
  1726. # Need to check that all the field names are strings or may get nasty errors later
  1727. for f in fields:
  1728. if not isinstance(f, str):
  1729. raise RuntimeError(
  1730. "A module tried to register support for login type: %s with parameters %s"
  1731. " but all parameter names must be strings"
  1732. % (login_type, fields)
  1733. )
  1734. # 2 modules supporting the same login type must expect the same fields
  1735. # e.g. 1 can't expect "pass" if the other expects "password"
  1736. # so throw an exception if that happens
  1737. if login_type not in self._supported_login_types.get(login_type, []):
  1738. self._supported_login_types[login_type] = fields
  1739. else:
  1740. fields_currently_supported = self._supported_login_types.get(
  1741. login_type
  1742. )
  1743. if fields_currently_supported != fields:
  1744. raise RuntimeError(
  1745. "A module tried to register support for login type: %s with parameters %s"
  1746. " but another module had already registered support for that type with parameters %s"
  1747. % (login_type, fields, fields_currently_supported)
  1748. )
  1749. # Add the new method to the list of auth_checker_callbacks for this login type
  1750. self.auth_checker_callbacks.setdefault(login_type, []).append(callback)
  1751. if get_username_for_registration is not None:
  1752. self.get_username_for_registration_callbacks.append(
  1753. get_username_for_registration,
  1754. )
  1755. if get_displayname_for_registration is not None:
  1756. self.get_displayname_for_registration_callbacks.append(
  1757. get_displayname_for_registration,
  1758. )
  1759. if is_3pid_allowed is not None:
  1760. self.is_3pid_allowed_callbacks.append(is_3pid_allowed)
  1761. def get_supported_login_types(self) -> Mapping[str, Iterable[str]]:
  1762. """Get the login types supported by this password provider
  1763. Returns a map from a login type identifier (such as m.login.password) to an
  1764. iterable giving the fields which must be provided by the user in the submission
  1765. to the /login API.
  1766. """
  1767. return self._supported_login_types
  1768. async def check_auth(
  1769. self, username: str, login_type: str, login_dict: JsonDict
  1770. ) -> Optional[Tuple[str, Optional[Callable[["LoginResponse"], Awaitable[None]]]]]:
  1771. """Check if the user has presented valid login credentials
  1772. Args:
  1773. username: user id presented by the client. Either an MXID or an unqualified
  1774. username.
  1775. login_type: the login type being attempted - one of the types returned by
  1776. get_supported_login_types()
  1777. login_dict: the dictionary of login secrets passed by the client.
  1778. Returns: (user_id, callback) where `user_id` is the fully-qualified mxid of the
  1779. user, and `callback` is an optional callback which will be called with the
  1780. result from the /login call (including access_token, device_id, etc.)
  1781. """
  1782. # Go through all callbacks for the login type until one returns with a value
  1783. # other than None (i.e. until a callback returns a success)
  1784. for callback in self.auth_checker_callbacks[login_type]:
  1785. try:
  1786. result = await delay_cancellation(
  1787. callback(username, login_type, login_dict)
  1788. )
  1789. except CancelledError:
  1790. raise
  1791. except Exception as e:
  1792. logger.warning("Failed to run module API callback %s: %s", callback, e)
  1793. continue
  1794. if result is not None:
  1795. # Check that the callback returned a Tuple[str, Optional[Callable]]
  1796. # "type: ignore[unreachable]" is used after some isinstance checks because mypy thinks
  1797. # result is always the right type, but as it is 3rd party code it might not be
  1798. if not isinstance(result, tuple) or len(result) != 2:
  1799. logger.warning(
  1800. "Wrong type returned by module API callback %s: %s, expected"
  1801. " Optional[Tuple[str, Optional[Callable]]]",
  1802. callback,
  1803. result,
  1804. )
  1805. continue
  1806. # pull out the two parts of the tuple so we can do type checking
  1807. str_result, callback_result = result
  1808. # the 1st item in the tuple should be a str
  1809. if not isinstance(str_result, str):
  1810. logger.warning( # type: ignore[unreachable]
  1811. "Wrong type returned by module API callback %s: %s, expected"
  1812. " Optional[Tuple[str, Optional[Callable]]]",
  1813. callback,
  1814. result,
  1815. )
  1816. continue
  1817. # the second should be Optional[Callable]
  1818. if callback_result is not None:
  1819. if not callable(callback_result):
  1820. logger.warning( # type: ignore[unreachable]
  1821. "Wrong type returned by module API callback %s: %s, expected"
  1822. " Optional[Tuple[str, Optional[Callable]]]",
  1823. callback,
  1824. result,
  1825. )
  1826. continue
  1827. # The result is a (str, Optional[callback]) tuple so return the successful result
  1828. return result
  1829. # If this point has been reached then none of the callbacks successfully authenticated
  1830. # the user so return None
  1831. return None
  1832. async def check_3pid_auth(
  1833. self, medium: str, address: str, password: str
  1834. ) -> Optional[Tuple[str, Optional[Callable[["LoginResponse"], Awaitable[None]]]]]:
  1835. # This function is able to return a deferred that either
  1836. # resolves None, meaning authentication failure, or upon
  1837. # success, to a str (which is the user_id) or a tuple of
  1838. # (user_id, callback_func), where callback_func should be run
  1839. # after we've finished everything else
  1840. for callback in self.check_3pid_auth_callbacks:
  1841. try:
  1842. result = await delay_cancellation(callback(medium, address, password))
  1843. except CancelledError:
  1844. raise
  1845. except Exception as e:
  1846. logger.warning("Failed to run module API callback %s: %s", callback, e)
  1847. continue
  1848. if result is not None:
  1849. # Check that the callback returned a Tuple[str, Optional[Callable]]
  1850. # "type: ignore[unreachable]" is used after some isinstance checks because mypy thinks
  1851. # result is always the right type, but as it is 3rd party code it might not be
  1852. if not isinstance(result, tuple) or len(result) != 2:
  1853. logger.warning(
  1854. "Wrong type returned by module API callback %s: %s, expected"
  1855. " Optional[Tuple[str, Optional[Callable]]]",
  1856. callback,
  1857. result,
  1858. )
  1859. continue
  1860. # pull out the two parts of the tuple so we can do type checking
  1861. str_result, callback_result = result
  1862. # the 1st item in the tuple should be a str
  1863. if not isinstance(str_result, str):
  1864. logger.warning( # type: ignore[unreachable]
  1865. "Wrong type returned by module API callback %s: %s, expected"
  1866. " Optional[Tuple[str, Optional[Callable]]]",
  1867. callback,
  1868. result,
  1869. )
  1870. continue
  1871. # the second should be Optional[Callable]
  1872. if callback_result is not None:
  1873. if not callable(callback_result):
  1874. logger.warning( # type: ignore[unreachable]
  1875. "Wrong type returned by module API callback %s: %s, expected"
  1876. " Optional[Tuple[str, Optional[Callable]]]",
  1877. callback,
  1878. result,
  1879. )
  1880. continue
  1881. # The result is a (str, Optional[callback]) tuple so return the successful result
  1882. return result
  1883. # If this point has been reached then none of the callbacks successfully authenticated
  1884. # the user so return None
  1885. return None
  1886. async def on_logged_out(
  1887. self, user_id: str, device_id: Optional[str], access_token: str
  1888. ) -> None:
  1889. # call all of the on_logged_out callbacks
  1890. for callback in self.on_logged_out_callbacks:
  1891. try:
  1892. await callback(user_id, device_id, access_token)
  1893. except Exception as e:
  1894. logger.warning("Failed to run module API callback %s: %s", callback, e)
  1895. continue
  1896. async def get_username_for_registration(
  1897. self,
  1898. uia_results: JsonDict,
  1899. params: JsonDict,
  1900. ) -> Optional[str]:
  1901. """Defines the username to use when registering the user, using the credentials
  1902. and parameters provided during the UIA flow.
  1903. Stops at the first callback that returns a string.
  1904. Args:
  1905. uia_results: The credentials provided during the UIA flow.
  1906. params: The parameters provided by the registration request.
  1907. Returns:
  1908. The localpart to use when registering this user, or None if no module
  1909. returned a localpart.
  1910. """
  1911. for callback in self.get_username_for_registration_callbacks:
  1912. try:
  1913. res = await delay_cancellation(callback(uia_results, params))
  1914. if isinstance(res, str):
  1915. return res
  1916. elif res is not None:
  1917. # mypy complains that this line is unreachable because it assumes the
  1918. # data returned by the module fits the expected type. We just want
  1919. # to make sure this is the case.
  1920. logger.warning( # type: ignore[unreachable]
  1921. "Ignoring non-string value returned by"
  1922. " get_username_for_registration callback %s: %s",
  1923. callback,
  1924. res,
  1925. )
  1926. except CancelledError:
  1927. raise
  1928. except Exception as e:
  1929. logger.error(
  1930. "Module raised an exception in get_username_for_registration: %s",
  1931. e,
  1932. )
  1933. raise SynapseError(code=500, msg="Internal Server Error")
  1934. return None
  1935. async def get_displayname_for_registration(
  1936. self,
  1937. uia_results: JsonDict,
  1938. params: JsonDict,
  1939. ) -> Optional[str]:
  1940. """Defines the display name to use when registering the user, using the
  1941. credentials and parameters provided during the UIA flow.
  1942. Stops at the first callback that returns a tuple containing at least one string.
  1943. Args:
  1944. uia_results: The credentials provided during the UIA flow.
  1945. params: The parameters provided by the registration request.
  1946. Returns:
  1947. A tuple which first element is the display name, and the second is an MXC URL
  1948. to the user's avatar.
  1949. """
  1950. for callback in self.get_displayname_for_registration_callbacks:
  1951. try:
  1952. res = await delay_cancellation(callback(uia_results, params))
  1953. if isinstance(res, str):
  1954. return res
  1955. elif res is not None:
  1956. # mypy complains that this line is unreachable because it assumes the
  1957. # data returned by the module fits the expected type. We just want
  1958. # to make sure this is the case.
  1959. logger.warning( # type: ignore[unreachable]
  1960. "Ignoring non-string value returned by"
  1961. " get_displayname_for_registration callback %s: %s",
  1962. callback,
  1963. res,
  1964. )
  1965. except CancelledError:
  1966. raise
  1967. except Exception as e:
  1968. logger.error(
  1969. "Module raised an exception in get_displayname_for_registration: %s",
  1970. e,
  1971. )
  1972. raise SynapseError(code=500, msg="Internal Server Error")
  1973. return None
  1974. async def is_3pid_allowed(
  1975. self,
  1976. medium: str,
  1977. address: str,
  1978. registration: bool,
  1979. ) -> bool:
  1980. """Check if the user can be allowed to bind a 3PID on this homeserver.
  1981. Args:
  1982. medium: The medium of the 3PID.
  1983. address: The address of the 3PID.
  1984. registration: Whether the 3PID is being bound when registering a new user.
  1985. Returns:
  1986. Whether the 3PID is allowed to be bound on this homeserver
  1987. """
  1988. for callback in self.is_3pid_allowed_callbacks:
  1989. try:
  1990. res = await delay_cancellation(callback(medium, address, registration))
  1991. if res is False:
  1992. return res
  1993. elif not isinstance(res, bool):
  1994. # mypy complains that this line is unreachable because it assumes the
  1995. # data returned by the module fits the expected type. We just want
  1996. # to make sure this is the case.
  1997. logger.warning( # type: ignore[unreachable]
  1998. "Ignoring non-string value returned by"
  1999. " is_3pid_allowed callback %s: %s",
  2000. callback,
  2001. res,
  2002. )
  2003. except CancelledError:
  2004. raise
  2005. except Exception as e:
  2006. logger.error("Module raised an exception in is_3pid_allowed: %s", e)
  2007. raise SynapseError(code=500, msg="Internal Server Error")
  2008. return True