auth.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014 - 2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from twisted.internet import defer
  16. from ._base import BaseHandler
  17. from synapse.api.constants import LoginType
  18. from synapse.types import UserID
  19. from synapse.api.errors import AuthError, LoginError, Codes
  20. from synapse.util.async import run_on_reactor
  21. from twisted.web.client import PartialDownloadError
  22. import logging
  23. import bcrypt
  24. import pymacaroons
  25. import simplejson
  26. import synapse.util.stringutils as stringutils
  27. logger = logging.getLogger(__name__)
  28. class AuthHandler(BaseHandler):
  29. SESSION_EXPIRE_MS = 48 * 60 * 60 * 1000
  30. def __init__(self, hs):
  31. super(AuthHandler, self).__init__(hs)
  32. self.checkers = {
  33. LoginType.PASSWORD: self._check_password_auth,
  34. LoginType.RECAPTCHA: self._check_recaptcha,
  35. LoginType.EMAIL_IDENTITY: self._check_email_identity,
  36. LoginType.DUMMY: self._check_dummy_auth,
  37. }
  38. self.bcrypt_rounds = hs.config.bcrypt_rounds
  39. self.sessions = {}
  40. self.INVALID_TOKEN_HTTP_STATUS = 401
  41. self.ldap_enabled = hs.config.ldap_enabled
  42. self.ldap_server = hs.config.ldap_server
  43. self.ldap_port = hs.config.ldap_port
  44. self.ldap_tls = hs.config.ldap_tls
  45. self.ldap_search_base = hs.config.ldap_search_base
  46. self.ldap_search_property = hs.config.ldap_search_property
  47. self.ldap_email_property = hs.config.ldap_email_property
  48. self.ldap_full_name_property = hs.config.ldap_full_name_property
  49. if self.ldap_enabled is True:
  50. import ldap
  51. logger.info("Import ldap version: %s", ldap.__version__)
  52. self.hs = hs # FIXME better possibility to access registrationHandler later?
  53. @defer.inlineCallbacks
  54. def check_auth(self, flows, clientdict, clientip):
  55. """
  56. Takes a dictionary sent by the client in the login / registration
  57. protocol and handles the login flow.
  58. As a side effect, this function fills in the 'creds' key on the user's
  59. session with a map, which maps each auth-type (str) to the relevant
  60. identity authenticated by that auth-type (mostly str, but for captcha, bool).
  61. Args:
  62. flows (list): A list of login flows. Each flow is an ordered list of
  63. strings representing auth-types. At least one full
  64. flow must be completed in order for auth to be successful.
  65. clientdict: The dictionary from the client root level, not the
  66. 'auth' key: this method prompts for auth if none is sent.
  67. clientip (str): The IP address of the client.
  68. Returns:
  69. A tuple of (authed, dict, dict, session_id) where authed is true if
  70. the client has successfully completed an auth flow. If it is true
  71. the first dict contains the authenticated credentials of each stage.
  72. If authed is false, the first dictionary is the server response to
  73. the login request and should be passed back to the client.
  74. In either case, the second dict contains the parameters for this
  75. request (which may have been given only in a previous call).
  76. session_id is the ID of this session, either passed in by the client
  77. or assigned by the call to check_auth
  78. """
  79. authdict = None
  80. sid = None
  81. if clientdict and 'auth' in clientdict:
  82. authdict = clientdict['auth']
  83. del clientdict['auth']
  84. if 'session' in authdict:
  85. sid = authdict['session']
  86. session = self._get_session_info(sid)
  87. if len(clientdict) > 0:
  88. # This was designed to allow the client to omit the parameters
  89. # and just supply the session in subsequent calls so it split
  90. # auth between devices by just sharing the session, (eg. so you
  91. # could continue registration from your phone having clicked the
  92. # email auth link on there). It's probably too open to abuse
  93. # because it lets unauthenticated clients store arbitrary objects
  94. # on a home server.
  95. # Revisit: Assumimg the REST APIs do sensible validation, the data
  96. # isn't arbintrary.
  97. session['clientdict'] = clientdict
  98. self._save_session(session)
  99. elif 'clientdict' in session:
  100. clientdict = session['clientdict']
  101. if not authdict:
  102. defer.returnValue(
  103. (
  104. False, self._auth_dict_for_flows(flows, session),
  105. clientdict, session['id']
  106. )
  107. )
  108. if 'creds' not in session:
  109. session['creds'] = {}
  110. creds = session['creds']
  111. # check auth type currently being presented
  112. if 'type' in authdict:
  113. if authdict['type'] not in self.checkers:
  114. raise LoginError(400, "", Codes.UNRECOGNIZED)
  115. result = yield self.checkers[authdict['type']](authdict, clientip)
  116. if result:
  117. creds[authdict['type']] = result
  118. self._save_session(session)
  119. for f in flows:
  120. if len(set(f) - set(creds.keys())) == 0:
  121. logger.info("Auth completed with creds: %r", creds)
  122. defer.returnValue((True, creds, clientdict, session['id']))
  123. ret = self._auth_dict_for_flows(flows, session)
  124. ret['completed'] = creds.keys()
  125. defer.returnValue((False, ret, clientdict, session['id']))
  126. @defer.inlineCallbacks
  127. def add_oob_auth(self, stagetype, authdict, clientip):
  128. """
  129. Adds the result of out-of-band authentication into an existing auth
  130. session. Currently used for adding the result of fallback auth.
  131. """
  132. if stagetype not in self.checkers:
  133. raise LoginError(400, "", Codes.MISSING_PARAM)
  134. if 'session' not in authdict:
  135. raise LoginError(400, "", Codes.MISSING_PARAM)
  136. sess = self._get_session_info(
  137. authdict['session']
  138. )
  139. if 'creds' not in sess:
  140. sess['creds'] = {}
  141. creds = sess['creds']
  142. result = yield self.checkers[stagetype](authdict, clientip)
  143. if result:
  144. creds[stagetype] = result
  145. self._save_session(sess)
  146. defer.returnValue(True)
  147. defer.returnValue(False)
  148. def get_session_id(self, clientdict):
  149. """
  150. Gets the session ID for a client given the client dictionary
  151. Args:
  152. clientdict: The dictionary sent by the client in the request
  153. Returns:
  154. str|None: The string session ID the client sent. If the client did
  155. not send a session ID, returns None.
  156. """
  157. sid = None
  158. if clientdict and 'auth' in clientdict:
  159. authdict = clientdict['auth']
  160. if 'session' in authdict:
  161. sid = authdict['session']
  162. return sid
  163. def set_session_data(self, session_id, key, value):
  164. """
  165. Store a key-value pair into the sessions data associated with this
  166. request. This data is stored server-side and cannot be modified by
  167. the client.
  168. Args:
  169. session_id (string): The ID of this session as returned from check_auth
  170. key (string): The key to store the data under
  171. value (any): The data to store
  172. """
  173. sess = self._get_session_info(session_id)
  174. sess.setdefault('serverdict', {})[key] = value
  175. self._save_session(sess)
  176. def get_session_data(self, session_id, key, default=None):
  177. """
  178. Retrieve data stored with set_session_data
  179. Args:
  180. session_id (string): The ID of this session as returned from check_auth
  181. key (string): The key to store the data under
  182. default (any): Value to return if the key has not been set
  183. """
  184. sess = self._get_session_info(session_id)
  185. return sess.setdefault('serverdict', {}).get(key, default)
  186. @defer.inlineCallbacks
  187. def _check_password_auth(self, authdict, _):
  188. if "user" not in authdict or "password" not in authdict:
  189. raise LoginError(400, "", Codes.MISSING_PARAM)
  190. user_id = authdict["user"]
  191. password = authdict["password"]
  192. if not user_id.startswith('@'):
  193. user_id = UserID.create(user_id, self.hs.hostname).to_string()
  194. if not (yield self._check_password(user_id, password)):
  195. logger.warn("Failed password login for user %s", user_id)
  196. raise LoginError(403, "", errcode=Codes.FORBIDDEN)
  197. defer.returnValue(user_id)
  198. @defer.inlineCallbacks
  199. def _check_recaptcha(self, authdict, clientip):
  200. try:
  201. user_response = authdict["response"]
  202. except KeyError:
  203. # Client tried to provide captcha but didn't give the parameter:
  204. # bad request.
  205. raise LoginError(
  206. 400, "Captcha response is required",
  207. errcode=Codes.CAPTCHA_NEEDED
  208. )
  209. logger.info(
  210. "Submitting recaptcha response %s with remoteip %s",
  211. user_response, clientip
  212. )
  213. # TODO: get this from the homeserver rather than creating a new one for
  214. # each request
  215. try:
  216. client = self.hs.get_simple_http_client()
  217. resp_body = yield client.post_urlencoded_get_json(
  218. self.hs.config.recaptcha_siteverify_api,
  219. args={
  220. 'secret': self.hs.config.recaptcha_private_key,
  221. 'response': user_response,
  222. 'remoteip': clientip,
  223. }
  224. )
  225. except PartialDownloadError as pde:
  226. # Twisted is silly
  227. data = pde.response
  228. resp_body = simplejson.loads(data)
  229. if 'success' in resp_body and resp_body['success']:
  230. defer.returnValue(True)
  231. raise LoginError(401, "", errcode=Codes.UNAUTHORIZED)
  232. @defer.inlineCallbacks
  233. def _check_email_identity(self, authdict, _):
  234. yield run_on_reactor()
  235. if 'threepid_creds' not in authdict:
  236. raise LoginError(400, "Missing threepid_creds", Codes.MISSING_PARAM)
  237. threepid_creds = authdict['threepid_creds']
  238. identity_handler = self.hs.get_handlers().identity_handler
  239. logger.info("Getting validated threepid. threepidcreds: %r" % (threepid_creds,))
  240. threepid = yield identity_handler.threepid_from_creds(threepid_creds)
  241. if not threepid:
  242. raise LoginError(401, "", errcode=Codes.UNAUTHORIZED)
  243. threepid['threepid_creds'] = authdict['threepid_creds']
  244. defer.returnValue(threepid)
  245. @defer.inlineCallbacks
  246. def _check_dummy_auth(self, authdict, _):
  247. yield run_on_reactor()
  248. defer.returnValue(True)
  249. def _get_params_recaptcha(self):
  250. return {"public_key": self.hs.config.recaptcha_public_key}
  251. def _auth_dict_for_flows(self, flows, session):
  252. public_flows = []
  253. for f in flows:
  254. public_flows.append(f)
  255. get_params = {
  256. LoginType.RECAPTCHA: self._get_params_recaptcha,
  257. }
  258. params = {}
  259. for f in public_flows:
  260. for stage in f:
  261. if stage in get_params and stage not in params:
  262. params[stage] = get_params[stage]()
  263. return {
  264. "session": session['id'],
  265. "flows": [{"stages": f} for f in public_flows],
  266. "params": params
  267. }
  268. def _get_session_info(self, session_id):
  269. if session_id not in self.sessions:
  270. session_id = None
  271. if not session_id:
  272. # create a new session
  273. while session_id is None or session_id in self.sessions:
  274. session_id = stringutils.random_string(24)
  275. self.sessions[session_id] = {
  276. "id": session_id,
  277. }
  278. return self.sessions[session_id]
  279. @defer.inlineCallbacks
  280. def login_with_password(self, user_id, password):
  281. """
  282. Authenticates the user with their username and password.
  283. Used only by the v1 login API.
  284. Args:
  285. user_id (str): User ID
  286. password (str): Password
  287. Returns:
  288. A tuple of:
  289. The user's ID.
  290. The access token for the user's session.
  291. The refresh token for the user's session.
  292. Raises:
  293. StoreError if there was a problem storing the token.
  294. LoginError if there was an authentication problem.
  295. """
  296. if not (yield self._check_password(user_id, password)):
  297. logger.warn("Failed password login for user %s", user_id)
  298. raise LoginError(403, "", errcode=Codes.FORBIDDEN)
  299. logger.info("Logging in user %s", user_id)
  300. access_token = yield self.issue_access_token(user_id)
  301. refresh_token = yield self.issue_refresh_token(user_id)
  302. defer.returnValue((user_id, access_token, refresh_token))
  303. @defer.inlineCallbacks
  304. def get_login_tuple_for_user_id(self, user_id):
  305. """
  306. Gets login tuple for the user with the given user ID.
  307. The user is assumed to have been authenticated by some other
  308. machanism (e.g. CAS)
  309. Args:
  310. user_id (str): User ID
  311. Returns:
  312. A tuple of:
  313. The user's ID.
  314. The access token for the user's session.
  315. The refresh token for the user's session.
  316. Raises:
  317. StoreError if there was a problem storing the token.
  318. LoginError if there was an authentication problem.
  319. """
  320. user_id, ignored = yield self._find_user_id_and_pwd_hash(user_id)
  321. logger.info("Logging in user %s", user_id)
  322. access_token = yield self.issue_access_token(user_id)
  323. refresh_token = yield self.issue_refresh_token(user_id)
  324. defer.returnValue((user_id, access_token, refresh_token))
  325. @defer.inlineCallbacks
  326. def does_user_exist(self, user_id):
  327. try:
  328. yield self._find_user_id_and_pwd_hash(user_id)
  329. defer.returnValue(True)
  330. except LoginError:
  331. defer.returnValue(False)
  332. @defer.inlineCallbacks
  333. def _find_user_id_and_pwd_hash(self, user_id):
  334. """Checks to see if a user with the given id exists. Will check case
  335. insensitively, but will throw if there are multiple inexact matches.
  336. Returns:
  337. tuple: A 2-tuple of `(canonical_user_id, password_hash)`
  338. """
  339. user_infos = yield self.store.get_users_by_id_case_insensitive(user_id)
  340. if not user_infos:
  341. logger.warn("Attempted to login as %s but they do not exist", user_id)
  342. raise LoginError(403, "", errcode=Codes.FORBIDDEN)
  343. if len(user_infos) > 1:
  344. if user_id not in user_infos:
  345. logger.warn(
  346. "Attempted to login as %s but it matches more than one user "
  347. "inexactly: %r",
  348. user_id, user_infos.keys()
  349. )
  350. raise LoginError(403, "", errcode=Codes.FORBIDDEN)
  351. defer.returnValue((user_id, user_infos[user_id]))
  352. else:
  353. defer.returnValue(user_infos.popitem())
  354. @defer.inlineCallbacks
  355. def _check_password(self, user_id, password):
  356. defer.returnValue(
  357. not (
  358. (yield self._check_ldap_password(user_id, password))
  359. or
  360. (yield self._check_local_password(user_id, password))
  361. ))
  362. @defer.inlineCallbacks
  363. def _check_local_password(self, user_id, password):
  364. try:
  365. user_id, password_hash = yield self._find_user_id_and_pwd_hash(user_id)
  366. defer.returnValue(not self.validate_hash(password, password_hash))
  367. except LoginError:
  368. defer.returnValue(False)
  369. @defer.inlineCallbacks
  370. def _check_ldap_password(self, user_id, password):
  371. if self.ldap_enabled is not True:
  372. logger.debug("LDAP not configured")
  373. defer.returnValue(False)
  374. import ldap
  375. logger.info("Authenticating %s with LDAP" % user_id)
  376. try:
  377. ldap_url = "%s:%s" % (self.ldap_server, self.ldap_port)
  378. logger.debug("Connecting LDAP server at %s" % ldap_url)
  379. l = ldap.initialize(ldap_url)
  380. if self.ldap_tls:
  381. logger.debug("Initiating TLS")
  382. self._connection.start_tls_s()
  383. local_name = UserID.from_string(user_id).localpart
  384. dn = "%s=%s, %s" % (
  385. self.ldap_search_property,
  386. local_name,
  387. self.ldap_search_base)
  388. logger.debug("DN for LDAP authentication: %s" % dn)
  389. l.simple_bind_s(dn.encode('utf-8'), password.encode('utf-8'))
  390. if not (yield self.does_user_exist(user_id)):
  391. handler = self.hs.get_handlers().registration_handler
  392. user_id, access_token = (
  393. yield handler.register(localpart=local_name)
  394. )
  395. defer.returnValue(True)
  396. except ldap.LDAPError, e:
  397. logger.warn("LDAP error: %s", e)
  398. defer.returnValue(False)
  399. @defer.inlineCallbacks
  400. def issue_access_token(self, user_id):
  401. access_token = self.generate_access_token(user_id)
  402. yield self.store.add_access_token_to_user(user_id, access_token)
  403. defer.returnValue(access_token)
  404. @defer.inlineCallbacks
  405. def issue_refresh_token(self, user_id):
  406. refresh_token = self.generate_refresh_token(user_id)
  407. yield self.store.add_refresh_token_to_user(user_id, refresh_token)
  408. defer.returnValue(refresh_token)
  409. def generate_access_token(self, user_id, extra_caveats=None):
  410. extra_caveats = extra_caveats or []
  411. macaroon = self._generate_base_macaroon(user_id)
  412. macaroon.add_first_party_caveat("type = access")
  413. now = self.hs.get_clock().time_msec()
  414. expiry = now + (60 * 60 * 1000)
  415. macaroon.add_first_party_caveat("time < %d" % (expiry,))
  416. for caveat in extra_caveats:
  417. macaroon.add_first_party_caveat(caveat)
  418. return macaroon.serialize()
  419. def generate_refresh_token(self, user_id):
  420. m = self._generate_base_macaroon(user_id)
  421. m.add_first_party_caveat("type = refresh")
  422. # Important to add a nonce, because otherwise every refresh token for a
  423. # user will be the same.
  424. m.add_first_party_caveat("nonce = %s" % (
  425. stringutils.random_string_with_symbols(16),
  426. ))
  427. return m.serialize()
  428. def generate_short_term_login_token(self, user_id):
  429. macaroon = self._generate_base_macaroon(user_id)
  430. macaroon.add_first_party_caveat("type = login")
  431. now = self.hs.get_clock().time_msec()
  432. expiry = now + (2 * 60 * 1000)
  433. macaroon.add_first_party_caveat("time < %d" % (expiry,))
  434. return macaroon.serialize()
  435. def validate_short_term_login_token_and_get_user_id(self, login_token):
  436. try:
  437. macaroon = pymacaroons.Macaroon.deserialize(login_token)
  438. auth_api = self.hs.get_auth()
  439. auth_api.validate_macaroon(macaroon, "login", True)
  440. return self.get_user_from_macaroon(macaroon)
  441. except (pymacaroons.exceptions.MacaroonException, TypeError, ValueError):
  442. raise AuthError(401, "Invalid token", errcode=Codes.UNKNOWN_TOKEN)
  443. def _generate_base_macaroon(self, user_id):
  444. macaroon = pymacaroons.Macaroon(
  445. location=self.hs.config.server_name,
  446. identifier="key",
  447. key=self.hs.config.macaroon_secret_key)
  448. macaroon.add_first_party_caveat("gen = 1")
  449. macaroon.add_first_party_caveat("user_id = %s" % (user_id,))
  450. return macaroon
  451. def get_user_from_macaroon(self, macaroon):
  452. user_prefix = "user_id = "
  453. for caveat in macaroon.caveats:
  454. if caveat.caveat_id.startswith(user_prefix):
  455. return caveat.caveat_id[len(user_prefix):]
  456. raise AuthError(
  457. self.INVALID_TOKEN_HTTP_STATUS, "No user_id found in token",
  458. errcode=Codes.UNKNOWN_TOKEN
  459. )
  460. @defer.inlineCallbacks
  461. def set_password(self, user_id, newpassword, requester=None):
  462. password_hash = self.hash(newpassword)
  463. except_access_token_ids = [requester.access_token_id] if requester else []
  464. yield self.store.user_set_password_hash(user_id, password_hash)
  465. yield self.store.user_delete_access_tokens(
  466. user_id, except_access_token_ids
  467. )
  468. yield self.hs.get_pusherpool().remove_pushers_by_user(
  469. user_id, except_access_token_ids
  470. )
  471. @defer.inlineCallbacks
  472. def add_threepid(self, user_id, medium, address, validated_at):
  473. yield self.store.user_add_threepid(
  474. user_id, medium, address, validated_at,
  475. self.hs.get_clock().time_msec()
  476. )
  477. def _save_session(self, session):
  478. # TODO: Persistent storage
  479. logger.debug("Saving session %s", session)
  480. session["last_used"] = self.hs.get_clock().time_msec()
  481. self.sessions[session["id"]] = session
  482. self._prune_sessions()
  483. def _prune_sessions(self):
  484. for sid, sess in self.sessions.items():
  485. last_used = 0
  486. if 'last_used' in sess:
  487. last_used = sess['last_used']
  488. now = self.hs.get_clock().time_msec()
  489. if last_used < now - AuthHandler.SESSION_EXPIRE_MS:
  490. del self.sessions[sid]
  491. def hash(self, password):
  492. """Computes a secure hash of password.
  493. Args:
  494. password (str): Password to hash.
  495. Returns:
  496. Hashed password (str).
  497. """
  498. return bcrypt.hashpw(password, bcrypt.gensalt(self.bcrypt_rounds))
  499. def validate_hash(self, password, stored_hash):
  500. """Validates that self.hash(password) == stored_hash.
  501. Args:
  502. password (str): Password to hash.
  503. stored_hash (str): Expected hash value.
  504. Returns:
  505. Whether self.hash(password) == stored_hash (bool).
  506. """
  507. return bcrypt.hashpw(password, stored_hash) == stored_hash