auth.py 93 KB

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