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.
 
 
 
 
 
 

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