register.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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. """Contains functions for registering clients."""
  16. import logging
  17. from twisted.internet import defer
  18. from synapse import types
  19. from synapse.api.errors import (
  20. AuthError,
  21. Codes,
  22. InvalidCaptchaError,
  23. RegistrationError,
  24. SynapseError,
  25. )
  26. from synapse.http.client import CaptchaServerHttpClient
  27. from synapse.types import RoomAlias, RoomID, UserID, create_requester
  28. from synapse.util.async import Linearizer
  29. from synapse.util.threepids import check_3pid_allowed
  30. from ._base import BaseHandler
  31. logger = logging.getLogger(__name__)
  32. class RegistrationHandler(BaseHandler):
  33. def __init__(self, hs):
  34. """
  35. Args:
  36. hs (synapse.server.HomeServer):
  37. """
  38. super(RegistrationHandler, self).__init__(hs)
  39. self.auth = hs.get_auth()
  40. self._auth_handler = hs.get_auth_handler()
  41. self.profile_handler = hs.get_profile_handler()
  42. self.user_directory_handler = hs.get_user_directory_handler()
  43. self.captcha_client = CaptchaServerHttpClient(hs)
  44. self._next_generated_user_id = None
  45. self.macaroon_gen = hs.get_macaroon_generator()
  46. self._generate_user_id_linearizer = Linearizer(
  47. name="_generate_user_id_linearizer",
  48. )
  49. self._server_notices_mxid = hs.config.server_notices_mxid
  50. @defer.inlineCallbacks
  51. def check_username(self, localpart, guest_access_token=None,
  52. assigned_user_id=None):
  53. if types.contains_invalid_mxid_characters(localpart):
  54. raise SynapseError(
  55. 400,
  56. "User ID can only contain characters a-z, 0-9, or '=_-./'",
  57. Codes.INVALID_USERNAME
  58. )
  59. if not localpart:
  60. raise SynapseError(
  61. 400,
  62. "User ID cannot be empty",
  63. Codes.INVALID_USERNAME
  64. )
  65. if localpart[0] == '_':
  66. raise SynapseError(
  67. 400,
  68. "User ID may not begin with _",
  69. Codes.INVALID_USERNAME
  70. )
  71. user = UserID(localpart, self.hs.hostname)
  72. user_id = user.to_string()
  73. if assigned_user_id:
  74. if user_id == assigned_user_id:
  75. return
  76. else:
  77. raise SynapseError(
  78. 400,
  79. "A different user ID has already been registered for this session",
  80. )
  81. self.check_user_id_not_appservice_exclusive(user_id)
  82. users = yield self.store.get_users_by_id_case_insensitive(user_id)
  83. if users:
  84. if not guest_access_token:
  85. raise SynapseError(
  86. 400,
  87. "User ID already taken.",
  88. errcode=Codes.USER_IN_USE,
  89. )
  90. user_data = yield self.auth.get_user_by_access_token(guest_access_token)
  91. if not user_data["is_guest"] or user_data["user"].localpart != localpart:
  92. raise AuthError(
  93. 403,
  94. "Cannot register taken user ID without valid guest "
  95. "credentials for that user.",
  96. errcode=Codes.FORBIDDEN,
  97. )
  98. @defer.inlineCallbacks
  99. def register(
  100. self,
  101. localpart=None,
  102. password=None,
  103. generate_token=True,
  104. guest_access_token=None,
  105. make_guest=False,
  106. admin=False,
  107. ):
  108. """Registers a new client on the server.
  109. Args:
  110. localpart : The local part of the user ID to register. If None,
  111. one will be generated.
  112. password (str) : The password to assign to this user so they can
  113. login again. This can be None which means they cannot login again
  114. via a password (e.g. the user is an application service user).
  115. generate_token (bool): Whether a new access token should be
  116. generated. Having this be True should be considered deprecated,
  117. since it offers no means of associating a device_id with the
  118. access_token. Instead you should call auth_handler.issue_access_token
  119. after registration.
  120. Returns:
  121. A tuple of (user_id, access_token).
  122. Raises:
  123. RegistrationError if there was a problem registering.
  124. """
  125. password_hash = None
  126. if password:
  127. password_hash = yield self.auth_handler().hash(password)
  128. if localpart:
  129. yield self.check_username(localpart, guest_access_token=guest_access_token)
  130. was_guest = guest_access_token is not None
  131. if not was_guest:
  132. try:
  133. int(localpart)
  134. raise RegistrationError(
  135. 400,
  136. "Numeric user IDs are reserved for guest users."
  137. )
  138. except ValueError:
  139. pass
  140. user = UserID(localpart, self.hs.hostname)
  141. user_id = user.to_string()
  142. token = None
  143. if generate_token:
  144. token = self.macaroon_gen.generate_access_token(user_id)
  145. yield self.store.register(
  146. user_id=user_id,
  147. token=token,
  148. password_hash=password_hash,
  149. was_guest=was_guest,
  150. make_guest=make_guest,
  151. create_profile_with_localpart=(
  152. # If the user was a guest then they already have a profile
  153. None if was_guest else user.localpart
  154. ),
  155. admin=admin,
  156. )
  157. if self.hs.config.user_directory_search_all_users:
  158. profile = yield self.store.get_profileinfo(localpart)
  159. yield self.user_directory_handler.handle_local_profile_change(
  160. user_id, profile
  161. )
  162. else:
  163. # autogen a sequential user ID
  164. attempts = 0
  165. token = None
  166. user = None
  167. while not user:
  168. localpart = yield self._generate_user_id(attempts > 0)
  169. user = UserID(localpart, self.hs.hostname)
  170. user_id = user.to_string()
  171. yield self.check_user_id_not_appservice_exclusive(user_id)
  172. if generate_token:
  173. token = self.macaroon_gen.generate_access_token(user_id)
  174. try:
  175. yield self.store.register(
  176. user_id=user_id,
  177. token=token,
  178. password_hash=password_hash,
  179. make_guest=make_guest,
  180. create_profile_with_localpart=user.localpart,
  181. )
  182. except SynapseError:
  183. # if user id is taken, just generate another
  184. user = None
  185. user_id = None
  186. token = None
  187. attempts += 1
  188. # auto-join the user to any rooms we're supposed to dump them into
  189. fake_requester = create_requester(user_id)
  190. for r in self.hs.config.auto_join_rooms:
  191. try:
  192. yield self._join_user_to_room(fake_requester, r)
  193. except Exception as e:
  194. logger.error("Failed to join new user to %r: %r", r, e)
  195. # We used to generate default identicons here, but nowadays
  196. # we want clients to generate their own as part of their branding
  197. # rather than there being consistent matrix-wide ones, so we don't.
  198. defer.returnValue((user_id, token))
  199. @defer.inlineCallbacks
  200. def appservice_register(self, user_localpart, as_token):
  201. user = UserID(user_localpart, self.hs.hostname)
  202. user_id = user.to_string()
  203. service = self.store.get_app_service_by_token(as_token)
  204. if not service:
  205. raise AuthError(403, "Invalid application service token.")
  206. if not service.is_interested_in_user(user_id):
  207. raise SynapseError(
  208. 400, "Invalid user localpart for this application service.",
  209. errcode=Codes.EXCLUSIVE
  210. )
  211. service_id = service.id if service.is_exclusive_user(user_id) else None
  212. yield self.check_user_id_not_appservice_exclusive(
  213. user_id, allowed_appservice=service
  214. )
  215. yield self.store.register(
  216. user_id=user_id,
  217. password_hash="",
  218. appservice_id=service_id,
  219. create_profile_with_localpart=user.localpart,
  220. )
  221. defer.returnValue(user_id)
  222. @defer.inlineCallbacks
  223. def check_recaptcha(self, ip, private_key, challenge, response):
  224. """
  225. Checks a recaptcha is correct.
  226. Used only by c/s api v1
  227. """
  228. captcha_response = yield self._validate_captcha(
  229. ip,
  230. private_key,
  231. challenge,
  232. response
  233. )
  234. if not captcha_response["valid"]:
  235. logger.info("Invalid captcha entered from %s. Error: %s",
  236. ip, captcha_response["error_url"])
  237. raise InvalidCaptchaError(
  238. error_url=captcha_response["error_url"]
  239. )
  240. else:
  241. logger.info("Valid captcha entered from %s", ip)
  242. @defer.inlineCallbacks
  243. def register_saml2(self, localpart):
  244. """
  245. Registers email_id as SAML2 Based Auth.
  246. """
  247. if types.contains_invalid_mxid_characters(localpart):
  248. raise SynapseError(
  249. 400,
  250. "User ID can only contain characters a-z, 0-9, or '=_-./'",
  251. )
  252. user = UserID(localpart, self.hs.hostname)
  253. user_id = user.to_string()
  254. yield self.check_user_id_not_appservice_exclusive(user_id)
  255. token = self.macaroon_gen.generate_access_token(user_id)
  256. try:
  257. yield self.store.register(
  258. user_id=user_id,
  259. token=token,
  260. password_hash=None,
  261. create_profile_with_localpart=user.localpart,
  262. )
  263. except Exception as e:
  264. yield self.store.add_access_token_to_user(user_id, token)
  265. # Ignore Registration errors
  266. logger.exception(e)
  267. defer.returnValue((user_id, token))
  268. @defer.inlineCallbacks
  269. def register_email(self, threepidCreds):
  270. """
  271. Registers emails with an identity server.
  272. Used only by c/s api v1
  273. """
  274. for c in threepidCreds:
  275. logger.info("validating threepidcred sid %s on id server %s",
  276. c['sid'], c['idServer'])
  277. try:
  278. identity_handler = self.hs.get_handlers().identity_handler
  279. threepid = yield identity_handler.threepid_from_creds(c)
  280. except Exception:
  281. logger.exception("Couldn't validate 3pid")
  282. raise RegistrationError(400, "Couldn't validate 3pid")
  283. if not threepid:
  284. raise RegistrationError(400, "Couldn't validate 3pid")
  285. logger.info("got threepid with medium '%s' and address '%s'",
  286. threepid['medium'], threepid['address'])
  287. if not check_3pid_allowed(self.hs, threepid['medium'], threepid['address']):
  288. raise RegistrationError(
  289. 403, "Third party identifier is not allowed"
  290. )
  291. @defer.inlineCallbacks
  292. def bind_emails(self, user_id, threepidCreds):
  293. """Links emails with a user ID and informs an identity server.
  294. Used only by c/s api v1
  295. """
  296. # Now we have a matrix ID, bind it to the threepids we were given
  297. for c in threepidCreds:
  298. identity_handler = self.hs.get_handlers().identity_handler
  299. # XXX: This should be a deferred list, shouldn't it?
  300. yield identity_handler.bind_threepid(c, user_id)
  301. def check_user_id_not_appservice_exclusive(self, user_id, allowed_appservice=None):
  302. # don't allow people to register the server notices mxid
  303. if self._server_notices_mxid is not None:
  304. if user_id == self._server_notices_mxid:
  305. raise SynapseError(
  306. 400, "This user ID is reserved.",
  307. errcode=Codes.EXCLUSIVE
  308. )
  309. # valid user IDs must not clash with any user ID namespaces claimed by
  310. # application services.
  311. services = self.store.get_app_services()
  312. interested_services = [
  313. s for s in services
  314. if s.is_interested_in_user(user_id)
  315. and s != allowed_appservice
  316. ]
  317. for service in interested_services:
  318. if service.is_exclusive_user(user_id):
  319. raise SynapseError(
  320. 400, "This user ID is reserved by an application service.",
  321. errcode=Codes.EXCLUSIVE
  322. )
  323. @defer.inlineCallbacks
  324. def _generate_user_id(self, reseed=False):
  325. if reseed or self._next_generated_user_id is None:
  326. with (yield self._generate_user_id_linearizer.queue(())):
  327. if reseed or self._next_generated_user_id is None:
  328. self._next_generated_user_id = (
  329. yield self.store.find_next_generated_user_id_localpart()
  330. )
  331. id = self._next_generated_user_id
  332. self._next_generated_user_id += 1
  333. defer.returnValue(str(id))
  334. @defer.inlineCallbacks
  335. def _validate_captcha(self, ip_addr, private_key, challenge, response):
  336. """Validates the captcha provided.
  337. Used only by c/s api v1
  338. Returns:
  339. dict: Containing 'valid'(bool) and 'error_url'(str) if invalid.
  340. """
  341. response = yield self._submit_captcha(ip_addr, private_key, challenge,
  342. response)
  343. # parse Google's response. Lovely format..
  344. lines = response.split('\n')
  345. json = {
  346. "valid": lines[0] == 'true',
  347. "error_url": "http://www.google.com/recaptcha/api/challenge?" +
  348. "error=%s" % lines[1]
  349. }
  350. defer.returnValue(json)
  351. @defer.inlineCallbacks
  352. def _submit_captcha(self, ip_addr, private_key, challenge, response):
  353. """
  354. Used only by c/s api v1
  355. """
  356. data = yield self.captcha_client.post_urlencoded_get_raw(
  357. "http://www.google.com:80/recaptcha/api/verify",
  358. args={
  359. 'privatekey': private_key,
  360. 'remoteip': ip_addr,
  361. 'challenge': challenge,
  362. 'response': response
  363. }
  364. )
  365. defer.returnValue(data)
  366. @defer.inlineCallbacks
  367. def get_or_create_user(self, requester, localpart, displayname,
  368. password_hash=None):
  369. """Creates a new user if the user does not exist,
  370. else revokes all previous access tokens and generates a new one.
  371. Args:
  372. localpart : The local part of the user ID to register. If None,
  373. one will be randomly generated.
  374. Returns:
  375. A tuple of (user_id, access_token).
  376. Raises:
  377. RegistrationError if there was a problem registering.
  378. """
  379. if localpart is None:
  380. raise SynapseError(400, "Request must include user id")
  381. need_register = True
  382. try:
  383. yield self.check_username(localpart)
  384. except SynapseError as e:
  385. if e.errcode == Codes.USER_IN_USE:
  386. need_register = False
  387. else:
  388. raise
  389. user = UserID(localpart, self.hs.hostname)
  390. user_id = user.to_string()
  391. token = self.macaroon_gen.generate_access_token(user_id)
  392. if need_register:
  393. yield self.store.register(
  394. user_id=user_id,
  395. token=token,
  396. password_hash=password_hash,
  397. create_profile_with_localpart=user.localpart,
  398. )
  399. else:
  400. yield self._auth_handler.delete_access_tokens_for_user(user_id)
  401. yield self.store.add_access_token_to_user(user_id=user_id, token=token)
  402. if displayname is not None:
  403. logger.info("setting user display name: %s -> %s", user_id, displayname)
  404. yield self.profile_handler.set_displayname(
  405. user, requester, displayname, by_admin=True,
  406. )
  407. defer.returnValue((user_id, token))
  408. def auth_handler(self):
  409. return self.hs.get_auth_handler()
  410. @defer.inlineCallbacks
  411. def get_or_register_3pid_guest(self, medium, address, inviter_user_id):
  412. """Get a guest access token for a 3PID, creating a guest account if
  413. one doesn't already exist.
  414. Args:
  415. medium (str)
  416. address (str)
  417. inviter_user_id (str): The user ID who is trying to invite the
  418. 3PID
  419. Returns:
  420. Deferred[(str, str)]: A 2-tuple of `(user_id, access_token)` of the
  421. 3PID guest account.
  422. """
  423. access_token = yield self.store.get_3pid_guest_access_token(medium, address)
  424. if access_token:
  425. user_info = yield self.auth.get_user_by_access_token(
  426. access_token
  427. )
  428. defer.returnValue((user_info["user"].to_string(), access_token))
  429. user_id, access_token = yield self.register(
  430. generate_token=True,
  431. make_guest=True
  432. )
  433. access_token = yield self.store.save_or_get_3pid_guest_access_token(
  434. medium, address, access_token, inviter_user_id
  435. )
  436. defer.returnValue((user_id, access_token))
  437. @defer.inlineCallbacks
  438. def _join_user_to_room(self, requester, room_identifier):
  439. room_id = None
  440. room_member_handler = self.hs.get_room_member_handler()
  441. if RoomID.is_valid(room_identifier):
  442. room_id = room_identifier
  443. elif RoomAlias.is_valid(room_identifier):
  444. room_alias = RoomAlias.from_string(room_identifier)
  445. room_id, remote_room_hosts = (
  446. yield room_member_handler.lookup_room_alias(room_alias)
  447. )
  448. room_id = room_id.to_string()
  449. else:
  450. raise SynapseError(400, "%s was not legal room ID or room alias" % (
  451. room_identifier,
  452. ))
  453. yield room_member_handler.update_membership(
  454. requester=requester,
  455. target=requester.user,
  456. room_id=room_id,
  457. remote_room_hosts=remote_room_hosts,
  458. action="join",
  459. )