auth.py 91 KB

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