auth.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014 - 2016 OpenMarket Ltd
  3. # Copyright 2017 Vector Creations Ltd
  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 unicodedata
  18. import attr
  19. import bcrypt
  20. import pymacaroons
  21. from canonicaljson import json
  22. from twisted.internet import defer
  23. from twisted.web.client import PartialDownloadError
  24. import synapse.util.stringutils as stringutils
  25. from synapse.api.constants import LoginType
  26. from synapse.api.errors import (
  27. AuthError,
  28. Codes,
  29. InteractiveAuthIncompleteError,
  30. LoginError,
  31. StoreError,
  32. SynapseError,
  33. )
  34. from synapse.module_api import ModuleApi
  35. from synapse.types import UserID
  36. from synapse.util import logcontext
  37. from synapse.util.caches.expiringcache import ExpiringCache
  38. from ._base import BaseHandler
  39. logger = logging.getLogger(__name__)
  40. class AuthHandler(BaseHandler):
  41. SESSION_EXPIRE_MS = 48 * 60 * 60 * 1000
  42. def __init__(self, hs):
  43. """
  44. Args:
  45. hs (synapse.server.HomeServer):
  46. """
  47. super(AuthHandler, self).__init__(hs)
  48. self.checkers = {
  49. LoginType.RECAPTCHA: self._check_recaptcha,
  50. LoginType.EMAIL_IDENTITY: self._check_email_identity,
  51. LoginType.MSISDN: self._check_msisdn,
  52. LoginType.DUMMY: self._check_dummy_auth,
  53. LoginType.TERMS: self._check_terms_auth,
  54. }
  55. self.bcrypt_rounds = hs.config.bcrypt_rounds
  56. # This is not a cache per se, but a store of all current sessions that
  57. # expire after N hours
  58. self.sessions = ExpiringCache(
  59. cache_name="register_sessions",
  60. clock=hs.get_clock(),
  61. expiry_ms=self.SESSION_EXPIRE_MS,
  62. reset_expiry_on_get=True,
  63. )
  64. account_handler = ModuleApi(hs, self)
  65. self.password_providers = [
  66. module(config=config, account_handler=account_handler)
  67. for module, config in hs.config.password_providers
  68. ]
  69. logger.info("Extra password_providers: %r", self.password_providers)
  70. self.hs = hs # FIXME better possibility to access registrationHandler later?
  71. self.macaroon_gen = hs.get_macaroon_generator()
  72. self._password_enabled = hs.config.password_enabled
  73. # we keep this as a list despite the O(N^2) implication so that we can
  74. # keep PASSWORD first and avoid confusing clients which pick the first
  75. # type in the list. (NB that the spec doesn't require us to do so and
  76. # clients which favour types that they don't understand over those that
  77. # they do are technically broken)
  78. login_types = []
  79. if self._password_enabled:
  80. login_types.append(LoginType.PASSWORD)
  81. for provider in self.password_providers:
  82. if hasattr(provider, "get_supported_login_types"):
  83. for t in provider.get_supported_login_types().keys():
  84. if t not in login_types:
  85. login_types.append(t)
  86. self._supported_login_types = login_types
  87. @defer.inlineCallbacks
  88. def validate_user_via_ui_auth(self, requester, request_body, clientip):
  89. """
  90. Checks that the user is who they claim to be, via a UI auth.
  91. This is used for things like device deletion and password reset where
  92. the user already has a valid access token, but we want to double-check
  93. that it isn't stolen by re-authenticating them.
  94. Args:
  95. requester (Requester): The user, as given by the access token
  96. request_body (dict): The body of the request sent by the client
  97. clientip (str): The IP address of the client.
  98. Returns:
  99. defer.Deferred[dict]: the parameters for this request (which may
  100. have been given only in a previous call).
  101. Raises:
  102. InteractiveAuthIncompleteError if the client has not yet completed
  103. any of the permitted login flows
  104. AuthError if the client has completed a login flow, and it gives
  105. a different user to `requester`
  106. """
  107. # build a list of supported flows
  108. flows = [
  109. [login_type] for login_type in self._supported_login_types
  110. ]
  111. result, params, _ = yield self.check_auth(
  112. flows, request_body, clientip,
  113. )
  114. # find the completed login type
  115. for login_type in self._supported_login_types:
  116. if login_type not in result:
  117. continue
  118. user_id = result[login_type]
  119. break
  120. else:
  121. # this can't happen
  122. raise Exception(
  123. "check_auth returned True but no successful login type",
  124. )
  125. # check that the UI auth matched the access token
  126. if user_id != requester.user.to_string():
  127. raise AuthError(403, "Invalid auth")
  128. defer.returnValue(params)
  129. @defer.inlineCallbacks
  130. def check_auth(self, flows, clientdict, clientip):
  131. """
  132. Takes a dictionary sent by the client in the login / registration
  133. protocol and handles the User-Interactive Auth flow.
  134. As a side effect, this function fills in the 'creds' key on the user's
  135. session with a map, which maps each auth-type (str) to the relevant
  136. identity authenticated by that auth-type (mostly str, but for captcha, bool).
  137. If no auth flows have been completed successfully, raises an
  138. InteractiveAuthIncompleteError. To handle this, you can use
  139. synapse.rest.client.v2_alpha._base.interactive_auth_handler as a
  140. decorator.
  141. Args:
  142. flows (list): A list of login flows. Each flow is an ordered list of
  143. strings representing auth-types. At least one full
  144. flow must be completed in order for auth to be successful.
  145. clientdict: The dictionary from the client root level, not the
  146. 'auth' key: this method prompts for auth if none is sent.
  147. clientip (str): The IP address of the client.
  148. Returns:
  149. defer.Deferred[dict, dict, str]: a deferred tuple of
  150. (creds, params, session_id).
  151. 'creds' contains the authenticated credentials of each stage.
  152. 'params' contains the parameters for this request (which may
  153. have been given only in a previous call).
  154. 'session_id' is the ID of this session, either passed in by the
  155. client or assigned by this call
  156. Raises:
  157. InteractiveAuthIncompleteError if the client has not yet completed
  158. all the stages in any of the permitted flows.
  159. """
  160. authdict = None
  161. sid = None
  162. if clientdict and 'auth' in clientdict:
  163. authdict = clientdict['auth']
  164. del clientdict['auth']
  165. if 'session' in authdict:
  166. sid = authdict['session']
  167. session = self._get_session_info(sid)
  168. if len(clientdict) > 0:
  169. # This was designed to allow the client to omit the parameters
  170. # and just supply the session in subsequent calls so it split
  171. # auth between devices by just sharing the session, (eg. so you
  172. # could continue registration from your phone having clicked the
  173. # email auth link on there). It's probably too open to abuse
  174. # because it lets unauthenticated clients store arbitrary objects
  175. # on a home server.
  176. # Revisit: Assumimg the REST APIs do sensible validation, the data
  177. # isn't arbintrary.
  178. session['clientdict'] = clientdict
  179. self._save_session(session)
  180. elif 'clientdict' in session:
  181. clientdict = session['clientdict']
  182. if not authdict:
  183. raise InteractiveAuthIncompleteError(
  184. self._auth_dict_for_flows(flows, session),
  185. )
  186. if 'creds' not in session:
  187. session['creds'] = {}
  188. creds = session['creds']
  189. # check auth type currently being presented
  190. errordict = {}
  191. if 'type' in authdict:
  192. login_type = authdict['type']
  193. try:
  194. result = yield self._check_auth_dict(authdict, clientip)
  195. if result:
  196. creds[login_type] = result
  197. self._save_session(session)
  198. except LoginError as e:
  199. if login_type == LoginType.EMAIL_IDENTITY:
  200. # riot used to have a bug where it would request a new
  201. # validation token (thus sending a new email) each time it
  202. # got a 401 with a 'flows' field.
  203. # (https://github.com/vector-im/vector-web/issues/2447).
  204. #
  205. # Grandfather in the old behaviour for now to avoid
  206. # breaking old riot deployments.
  207. raise
  208. # this step failed. Merge the error dict into the response
  209. # so that the client can have another go.
  210. errordict = e.error_dict()
  211. for f in flows:
  212. if len(set(f) - set(creds)) == 0:
  213. # it's very useful to know what args are stored, but this can
  214. # include the password in the case of registering, so only log
  215. # the keys (confusingly, clientdict may contain a password
  216. # param, creds is just what the user authed as for UI auth
  217. # and is not sensitive).
  218. logger.info(
  219. "Auth completed with creds: %r. Client dict has keys: %r",
  220. creds, list(clientdict)
  221. )
  222. defer.returnValue((creds, clientdict, session['id']))
  223. ret = self._auth_dict_for_flows(flows, session)
  224. ret['completed'] = list(creds)
  225. ret.update(errordict)
  226. raise InteractiveAuthIncompleteError(
  227. ret,
  228. )
  229. @defer.inlineCallbacks
  230. def add_oob_auth(self, stagetype, authdict, clientip):
  231. """
  232. Adds the result of out-of-band authentication into an existing auth
  233. session. Currently used for adding the result of fallback auth.
  234. """
  235. if stagetype not in self.checkers:
  236. raise LoginError(400, "", Codes.MISSING_PARAM)
  237. if 'session' not in authdict:
  238. raise LoginError(400, "", Codes.MISSING_PARAM)
  239. sess = self._get_session_info(
  240. authdict['session']
  241. )
  242. if 'creds' not in sess:
  243. sess['creds'] = {}
  244. creds = sess['creds']
  245. result = yield self.checkers[stagetype](authdict, clientip)
  246. if result:
  247. creds[stagetype] = result
  248. self._save_session(sess)
  249. defer.returnValue(True)
  250. defer.returnValue(False)
  251. def get_session_id(self, clientdict):
  252. """
  253. Gets the session ID for a client given the client dictionary
  254. Args:
  255. clientdict: The dictionary sent by the client in the request
  256. Returns:
  257. str|None: The string session ID the client sent. If the client did
  258. not send a session ID, returns None.
  259. """
  260. sid = None
  261. if clientdict and 'auth' in clientdict:
  262. authdict = clientdict['auth']
  263. if 'session' in authdict:
  264. sid = authdict['session']
  265. return sid
  266. def set_session_data(self, session_id, key, value):
  267. """
  268. Store a key-value pair into the sessions data associated with this
  269. request. This data is stored server-side and cannot be modified by
  270. the client.
  271. Args:
  272. session_id (string): The ID of this session as returned from check_auth
  273. key (string): The key to store the data under
  274. value (any): The data to store
  275. """
  276. sess = self._get_session_info(session_id)
  277. sess.setdefault('serverdict', {})[key] = value
  278. self._save_session(sess)
  279. def get_session_data(self, session_id, key, default=None):
  280. """
  281. Retrieve data stored with set_session_data
  282. Args:
  283. session_id (string): The ID of this session as returned from check_auth
  284. key (string): The key to store the data under
  285. default (any): Value to return if the key has not been set
  286. """
  287. sess = self._get_session_info(session_id)
  288. return sess.setdefault('serverdict', {}).get(key, default)
  289. @defer.inlineCallbacks
  290. def _check_auth_dict(self, authdict, clientip):
  291. """Attempt to validate the auth dict provided by a client
  292. Args:
  293. authdict (object): auth dict provided by the client
  294. clientip (str): IP address of the client
  295. Returns:
  296. Deferred: result of the stage verification.
  297. Raises:
  298. StoreError if there was a problem accessing the database
  299. SynapseError if there was a problem with the request
  300. LoginError if there was an authentication problem.
  301. """
  302. login_type = authdict['type']
  303. checker = self.checkers.get(login_type)
  304. if checker is not None:
  305. res = yield checker(authdict, clientip)
  306. defer.returnValue(res)
  307. # build a v1-login-style dict out of the authdict and fall back to the
  308. # v1 code
  309. user_id = authdict.get("user")
  310. if user_id is None:
  311. raise SynapseError(400, "", Codes.MISSING_PARAM)
  312. (canonical_id, callback) = yield self.validate_login(user_id, authdict)
  313. defer.returnValue(canonical_id)
  314. @defer.inlineCallbacks
  315. def _check_recaptcha(self, authdict, clientip):
  316. try:
  317. user_response = authdict["response"]
  318. except KeyError:
  319. # Client tried to provide captcha but didn't give the parameter:
  320. # bad request.
  321. raise LoginError(
  322. 400, "Captcha response is required",
  323. errcode=Codes.CAPTCHA_NEEDED
  324. )
  325. logger.info(
  326. "Submitting recaptcha response %s with remoteip %s",
  327. user_response, clientip
  328. )
  329. # TODO: get this from the homeserver rather than creating a new one for
  330. # each request
  331. try:
  332. client = self.hs.get_simple_http_client()
  333. resp_body = yield client.post_urlencoded_get_json(
  334. self.hs.config.recaptcha_siteverify_api,
  335. args={
  336. 'secret': self.hs.config.recaptcha_private_key,
  337. 'response': user_response,
  338. 'remoteip': clientip,
  339. }
  340. )
  341. except PartialDownloadError as pde:
  342. # Twisted is silly
  343. data = pde.response
  344. resp_body = json.loads(data)
  345. if 'success' in resp_body:
  346. # Note that we do NOT check the hostname here: we explicitly
  347. # intend the CAPTCHA to be presented by whatever client the
  348. # user is using, we just care that they have completed a CAPTCHA.
  349. logger.info(
  350. "%s reCAPTCHA from hostname %s",
  351. "Successful" if resp_body['success'] else "Failed",
  352. resp_body.get('hostname')
  353. )
  354. if resp_body['success']:
  355. defer.returnValue(True)
  356. raise LoginError(401, "", errcode=Codes.UNAUTHORIZED)
  357. def _check_email_identity(self, authdict, _):
  358. return self._check_threepid('email', authdict)
  359. def _check_msisdn(self, authdict, _):
  360. return self._check_threepid('msisdn', authdict)
  361. def _check_dummy_auth(self, authdict, _):
  362. return defer.succeed(True)
  363. def _check_terms_auth(self, authdict, _):
  364. return defer.succeed(True)
  365. @defer.inlineCallbacks
  366. def _check_threepid(self, medium, authdict):
  367. if 'threepid_creds' not in authdict:
  368. raise LoginError(400, "Missing threepid_creds", Codes.MISSING_PARAM)
  369. threepid_creds = authdict['threepid_creds']
  370. identity_handler = self.hs.get_handlers().identity_handler
  371. logger.info("Getting validated threepid. threepidcreds: %r", (threepid_creds,))
  372. threepid = yield identity_handler.threepid_from_creds(threepid_creds)
  373. if not threepid:
  374. raise LoginError(401, "", errcode=Codes.UNAUTHORIZED)
  375. if threepid['medium'] != medium:
  376. raise LoginError(
  377. 401,
  378. "Expecting threepid of type '%s', got '%s'" % (
  379. medium, threepid['medium'],
  380. ),
  381. errcode=Codes.UNAUTHORIZED
  382. )
  383. threepid['threepid_creds'] = authdict['threepid_creds']
  384. defer.returnValue(threepid)
  385. def _get_params_recaptcha(self):
  386. return {"public_key": self.hs.config.recaptcha_public_key}
  387. def _get_params_terms(self):
  388. return {
  389. "policies": {
  390. "privacy_policy": {
  391. "version": self.hs.config.user_consent_version,
  392. "en": {
  393. "name": self.hs.config.user_consent_policy_name,
  394. "url": "%s_matrix/consent?v=%s" % (
  395. self.hs.config.public_baseurl,
  396. self.hs.config.user_consent_version,
  397. ),
  398. },
  399. },
  400. },
  401. }
  402. def _auth_dict_for_flows(self, flows, session):
  403. public_flows = []
  404. for f in flows:
  405. public_flows.append(f)
  406. get_params = {
  407. LoginType.RECAPTCHA: self._get_params_recaptcha,
  408. LoginType.TERMS: self._get_params_terms,
  409. }
  410. params = {}
  411. for f in public_flows:
  412. for stage in f:
  413. if stage in get_params and stage not in params:
  414. params[stage] = get_params[stage]()
  415. return {
  416. "session": session['id'],
  417. "flows": [{"stages": f} for f in public_flows],
  418. "params": params
  419. }
  420. def _get_session_info(self, session_id):
  421. if session_id not in self.sessions:
  422. session_id = None
  423. if not session_id:
  424. # create a new session
  425. while session_id is None or session_id in self.sessions:
  426. session_id = stringutils.random_string(24)
  427. self.sessions[session_id] = {
  428. "id": session_id,
  429. }
  430. return self.sessions[session_id]
  431. @defer.inlineCallbacks
  432. def get_access_token_for_user_id(self, user_id, device_id=None):
  433. """
  434. Creates a new access token for the user with the given user ID.
  435. The user is assumed to have been authenticated by some other
  436. machanism (e.g. CAS), and the user_id converted to the canonical case.
  437. The device will be recorded in the table if it is not there already.
  438. Args:
  439. user_id (str): canonical User ID
  440. device_id (str|None): the device ID to associate with the tokens.
  441. None to leave the tokens unassociated with a device (deprecated:
  442. we should always have a device ID)
  443. Returns:
  444. The access token for the user's session.
  445. Raises:
  446. StoreError if there was a problem storing the token.
  447. """
  448. logger.info("Logging in user %s on device %s", user_id, device_id)
  449. access_token = yield self.issue_access_token(user_id, device_id)
  450. yield self.auth.check_auth_blocking(user_id)
  451. # the device *should* have been registered before we got here; however,
  452. # it's possible we raced against a DELETE operation. The thing we
  453. # really don't want is active access_tokens without a record of the
  454. # device, so we double-check it here.
  455. if device_id is not None:
  456. try:
  457. yield self.store.get_device(user_id, device_id)
  458. except StoreError:
  459. yield self.store.delete_access_token(access_token)
  460. raise StoreError(400, "Login raced against device deletion")
  461. defer.returnValue(access_token)
  462. @defer.inlineCallbacks
  463. def check_user_exists(self, user_id):
  464. """
  465. Checks to see if a user with the given id exists. Will check case
  466. insensitively, but return None if there are multiple inexact matches.
  467. Args:
  468. (unicode|bytes) user_id: complete @user:id
  469. Returns:
  470. defer.Deferred: (unicode) canonical_user_id, or None if zero or
  471. multiple matches
  472. """
  473. res = yield self._find_user_id_and_pwd_hash(user_id)
  474. if res is not None:
  475. defer.returnValue(res[0])
  476. defer.returnValue(None)
  477. @defer.inlineCallbacks
  478. def _find_user_id_and_pwd_hash(self, user_id):
  479. """Checks to see if a user with the given id exists. Will check case
  480. insensitively, but will return None if there are multiple inexact
  481. matches.
  482. Returns:
  483. tuple: A 2-tuple of `(canonical_user_id, password_hash)`
  484. None: if there is not exactly one match
  485. """
  486. user_infos = yield self.store.get_users_by_id_case_insensitive(user_id)
  487. result = None
  488. if not user_infos:
  489. logger.warn("Attempted to login as %s but they do not exist", user_id)
  490. elif len(user_infos) == 1:
  491. # a single match (possibly not exact)
  492. result = user_infos.popitem()
  493. elif user_id in user_infos:
  494. # multiple matches, but one is exact
  495. result = (user_id, user_infos[user_id])
  496. else:
  497. # multiple matches, none of them exact
  498. logger.warn(
  499. "Attempted to login as %s but it matches more than one user "
  500. "inexactly: %r",
  501. user_id, user_infos.keys()
  502. )
  503. defer.returnValue(result)
  504. def get_supported_login_types(self):
  505. """Get a the login types supported for the /login API
  506. By default this is just 'm.login.password' (unless password_enabled is
  507. False in the config file), but password auth providers can provide
  508. other login types.
  509. Returns:
  510. Iterable[str]: login types
  511. """
  512. return self._supported_login_types
  513. @defer.inlineCallbacks
  514. def validate_login(self, username, login_submission):
  515. """Authenticates the user for the /login API
  516. Also used by the user-interactive auth flow to validate
  517. m.login.password auth types.
  518. Args:
  519. username (str): username supplied by the user
  520. login_submission (dict): the whole of the login submission
  521. (including 'type' and other relevant fields)
  522. Returns:
  523. Deferred[str, func]: canonical user id, and optional callback
  524. to be called once the access token and device id are issued
  525. Raises:
  526. StoreError if there was a problem accessing the database
  527. SynapseError if there was a problem with the request
  528. LoginError if there was an authentication problem.
  529. """
  530. if username.startswith('@'):
  531. qualified_user_id = username
  532. else:
  533. qualified_user_id = UserID(
  534. username, self.hs.hostname
  535. ).to_string()
  536. login_type = login_submission.get("type")
  537. known_login_type = False
  538. # special case to check for "password" for the check_password interface
  539. # for the auth providers
  540. password = login_submission.get("password")
  541. if login_type == LoginType.PASSWORD:
  542. if not self._password_enabled:
  543. raise SynapseError(400, "Password login has been disabled.")
  544. if not password:
  545. raise SynapseError(400, "Missing parameter: password")
  546. for provider in self.password_providers:
  547. if (hasattr(provider, "check_password")
  548. and login_type == LoginType.PASSWORD):
  549. known_login_type = True
  550. is_valid = yield provider.check_password(
  551. qualified_user_id, password,
  552. )
  553. if is_valid:
  554. defer.returnValue((qualified_user_id, None))
  555. if (not hasattr(provider, "get_supported_login_types")
  556. or not hasattr(provider, "check_auth")):
  557. # this password provider doesn't understand custom login types
  558. continue
  559. supported_login_types = provider.get_supported_login_types()
  560. if login_type not in supported_login_types:
  561. # this password provider doesn't understand this login type
  562. continue
  563. known_login_type = True
  564. login_fields = supported_login_types[login_type]
  565. missing_fields = []
  566. login_dict = {}
  567. for f in login_fields:
  568. if f not in login_submission:
  569. missing_fields.append(f)
  570. else:
  571. login_dict[f] = login_submission[f]
  572. if missing_fields:
  573. raise SynapseError(
  574. 400, "Missing parameters for login type %s: %s" % (
  575. login_type,
  576. missing_fields,
  577. ),
  578. )
  579. result = yield provider.check_auth(
  580. username, login_type, login_dict,
  581. )
  582. if result:
  583. if isinstance(result, str):
  584. result = (result, None)
  585. defer.returnValue(result)
  586. if login_type == LoginType.PASSWORD:
  587. known_login_type = True
  588. canonical_user_id = yield self._check_local_password(
  589. qualified_user_id, password,
  590. )
  591. if canonical_user_id:
  592. defer.returnValue((canonical_user_id, None))
  593. if not known_login_type:
  594. raise SynapseError(400, "Unknown login type %s" % login_type)
  595. # unknown username or invalid password. We raise a 403 here, but note
  596. # that if we're doing user-interactive login, it turns all LoginErrors
  597. # into a 401 anyway.
  598. raise LoginError(
  599. 403, "Invalid password",
  600. errcode=Codes.FORBIDDEN
  601. )
  602. @defer.inlineCallbacks
  603. def _check_local_password(self, user_id, password):
  604. """Authenticate a user against the local password database.
  605. user_id is checked case insensitively, but will return None if there are
  606. multiple inexact matches.
  607. Args:
  608. user_id (unicode): complete @user:id
  609. password (unicode): the provided password
  610. Returns:
  611. (unicode) the canonical_user_id, or None if unknown user / bad password
  612. """
  613. lookupres = yield self._find_user_id_and_pwd_hash(user_id)
  614. if not lookupres:
  615. defer.returnValue(None)
  616. (user_id, password_hash) = lookupres
  617. result = yield self.validate_hash(password, password_hash)
  618. if not result:
  619. logger.warn("Failed password login for user %s", user_id)
  620. defer.returnValue(None)
  621. defer.returnValue(user_id)
  622. @defer.inlineCallbacks
  623. def issue_access_token(self, user_id, device_id=None):
  624. access_token = self.macaroon_gen.generate_access_token(user_id)
  625. yield self.store.add_access_token_to_user(user_id, access_token,
  626. device_id)
  627. defer.returnValue(access_token)
  628. @defer.inlineCallbacks
  629. def validate_short_term_login_token_and_get_user_id(self, login_token):
  630. auth_api = self.hs.get_auth()
  631. user_id = None
  632. try:
  633. macaroon = pymacaroons.Macaroon.deserialize(login_token)
  634. user_id = auth_api.get_user_id_from_macaroon(macaroon)
  635. auth_api.validate_macaroon(macaroon, "login", True, user_id)
  636. except Exception:
  637. raise AuthError(403, "Invalid token", errcode=Codes.FORBIDDEN)
  638. yield self.auth.check_auth_blocking(user_id)
  639. defer.returnValue(user_id)
  640. @defer.inlineCallbacks
  641. def delete_access_token(self, access_token):
  642. """Invalidate a single access token
  643. Args:
  644. access_token (str): access token to be deleted
  645. Returns:
  646. Deferred
  647. """
  648. user_info = yield self.auth.get_user_by_access_token(access_token)
  649. yield self.store.delete_access_token(access_token)
  650. # see if any of our auth providers want to know about this
  651. for provider in self.password_providers:
  652. if hasattr(provider, "on_logged_out"):
  653. yield provider.on_logged_out(
  654. user_id=str(user_info["user"]),
  655. device_id=user_info["device_id"],
  656. access_token=access_token,
  657. )
  658. # delete pushers associated with this access token
  659. if user_info["token_id"] is not None:
  660. yield self.hs.get_pusherpool().remove_pushers_by_access_token(
  661. str(user_info["user"]), (user_info["token_id"], )
  662. )
  663. @defer.inlineCallbacks
  664. def delete_access_tokens_for_user(self, user_id, except_token_id=None,
  665. device_id=None):
  666. """Invalidate access tokens belonging to a user
  667. Args:
  668. user_id (str): ID of user the tokens belong to
  669. except_token_id (str|None): access_token ID which should *not* be
  670. deleted
  671. device_id (str|None): ID of device the tokens are associated with.
  672. If None, tokens associated with any device (or no device) will
  673. be deleted
  674. Returns:
  675. Deferred
  676. """
  677. tokens_and_devices = yield self.store.user_delete_access_tokens(
  678. user_id, except_token_id=except_token_id, device_id=device_id,
  679. )
  680. # see if any of our auth providers want to know about this
  681. for provider in self.password_providers:
  682. if hasattr(provider, "on_logged_out"):
  683. for token, token_id, device_id in tokens_and_devices:
  684. yield provider.on_logged_out(
  685. user_id=user_id,
  686. device_id=device_id,
  687. access_token=token,
  688. )
  689. # delete pushers associated with the access tokens
  690. yield self.hs.get_pusherpool().remove_pushers_by_access_token(
  691. user_id, (token_id for _, token_id, _ in tokens_and_devices),
  692. )
  693. @defer.inlineCallbacks
  694. def add_threepid(self, user_id, medium, address, validated_at):
  695. # 'Canonicalise' email addresses down to lower case.
  696. # We've now moving towards the Home Server being the entity that
  697. # is responsible for validating threepids used for resetting passwords
  698. # on accounts, so in future Synapse will gain knowledge of specific
  699. # types (mediums) of threepid. For now, we still use the existing
  700. # infrastructure, but this is the start of synapse gaining knowledge
  701. # of specific types of threepid (and fixes the fact that checking
  702. # for the presence of an email address during password reset was
  703. # case sensitive).
  704. if medium == 'email':
  705. address = address.lower()
  706. yield self.store.user_add_threepid(
  707. user_id, medium, address, validated_at,
  708. self.hs.get_clock().time_msec()
  709. )
  710. @defer.inlineCallbacks
  711. def delete_threepid(self, user_id, medium, address):
  712. """Attempts to unbind the 3pid on the identity servers and deletes it
  713. from the local database.
  714. Args:
  715. user_id (str)
  716. medium (str)
  717. address (str)
  718. Returns:
  719. Deferred[bool]: Returns True if successfully unbound the 3pid on
  720. the identity server, False if identity server doesn't support the
  721. unbind API.
  722. """
  723. # 'Canonicalise' email addresses as per above
  724. if medium == 'email':
  725. address = address.lower()
  726. identity_handler = self.hs.get_handlers().identity_handler
  727. result = yield identity_handler.try_unbind_threepid(
  728. user_id,
  729. {
  730. 'medium': medium,
  731. 'address': address,
  732. },
  733. )
  734. yield self.store.user_delete_threepid(
  735. user_id, medium, address,
  736. )
  737. defer.returnValue(result)
  738. def _save_session(self, session):
  739. # TODO: Persistent storage
  740. logger.debug("Saving session %s", session)
  741. session["last_used"] = self.hs.get_clock().time_msec()
  742. self.sessions[session["id"]] = session
  743. def hash(self, password):
  744. """Computes a secure hash of password.
  745. Args:
  746. password (unicode): Password to hash.
  747. Returns:
  748. Deferred(unicode): Hashed password.
  749. """
  750. def _do_hash():
  751. # Normalise the Unicode in the password
  752. pw = unicodedata.normalize("NFKC", password)
  753. return bcrypt.hashpw(
  754. pw.encode('utf8') + self.hs.config.password_pepper.encode("utf8"),
  755. bcrypt.gensalt(self.bcrypt_rounds),
  756. ).decode('ascii')
  757. return logcontext.defer_to_thread(self.hs.get_reactor(), _do_hash)
  758. def validate_hash(self, password, stored_hash):
  759. """Validates that self.hash(password) == stored_hash.
  760. Args:
  761. password (unicode): Password to hash.
  762. stored_hash (bytes): Expected hash value.
  763. Returns:
  764. Deferred(bool): Whether self.hash(password) == stored_hash.
  765. """
  766. def _do_validate_hash():
  767. # Normalise the Unicode in the password
  768. pw = unicodedata.normalize("NFKC", password)
  769. return bcrypt.checkpw(
  770. pw.encode('utf8') + self.hs.config.password_pepper.encode("utf8"),
  771. stored_hash
  772. )
  773. if stored_hash:
  774. if not isinstance(stored_hash, bytes):
  775. stored_hash = stored_hash.encode('ascii')
  776. return logcontext.defer_to_thread(self.hs.get_reactor(), _do_validate_hash)
  777. else:
  778. return defer.succeed(False)
  779. @attr.s
  780. class MacaroonGenerator(object):
  781. hs = attr.ib()
  782. def generate_access_token(self, user_id, extra_caveats=None):
  783. extra_caveats = extra_caveats or []
  784. macaroon = self._generate_base_macaroon(user_id)
  785. macaroon.add_first_party_caveat("type = access")
  786. # Include a nonce, to make sure that each login gets a different
  787. # access token.
  788. macaroon.add_first_party_caveat("nonce = %s" % (
  789. stringutils.random_string_with_symbols(16),
  790. ))
  791. for caveat in extra_caveats:
  792. macaroon.add_first_party_caveat(caveat)
  793. return macaroon.serialize()
  794. def generate_short_term_login_token(self, user_id, duration_in_ms=(2 * 60 * 1000)):
  795. """
  796. Args:
  797. user_id (unicode):
  798. duration_in_ms (int):
  799. Returns:
  800. unicode
  801. """
  802. macaroon = self._generate_base_macaroon(user_id)
  803. macaroon.add_first_party_caveat("type = login")
  804. now = self.hs.get_clock().time_msec()
  805. expiry = now + duration_in_ms
  806. macaroon.add_first_party_caveat("time < %d" % (expiry,))
  807. return macaroon.serialize()
  808. def generate_delete_pusher_token(self, user_id):
  809. macaroon = self._generate_base_macaroon(user_id)
  810. macaroon.add_first_party_caveat("type = delete_pusher")
  811. return macaroon.serialize()
  812. def _generate_base_macaroon(self, user_id):
  813. macaroon = pymacaroons.Macaroon(
  814. location=self.hs.config.server_name,
  815. identifier="key",
  816. key=self.hs.config.macaroon_secret_key)
  817. macaroon.add_first_party_caveat("gen = 1")
  818. macaroon.add_first_party_caveat("user_id = %s" % (user_id,))
  819. return macaroon