auth.py 34 KB

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