auth.py 86 KB

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