auth.py 37 KB

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