auth.py 97 KB

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