auth.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. # Copyright 2014 - 2016 OpenMarket Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import logging
  15. from typing import TYPE_CHECKING, Optional, Tuple
  16. import pymacaroons
  17. from netaddr import IPAddress
  18. from twisted.web.server import Request
  19. from synapse import event_auth
  20. from synapse.api.constants import EventTypes, HistoryVisibility, Membership
  21. from synapse.api.errors import (
  22. AuthError,
  23. Codes,
  24. InvalidClientTokenError,
  25. MissingClientTokenError,
  26. UnstableSpecAuthError,
  27. )
  28. from synapse.appservice import ApplicationService
  29. from synapse.http import get_request_user_agent
  30. from synapse.http.site import SynapseRequest
  31. from synapse.logging.opentracing import (
  32. active_span,
  33. force_tracing,
  34. start_active_span,
  35. trace,
  36. )
  37. from synapse.types import Requester, create_requester
  38. if TYPE_CHECKING:
  39. from synapse.server import HomeServer
  40. logger = logging.getLogger(__name__)
  41. # guests always get this device id.
  42. GUEST_DEVICE_ID = "guest_device"
  43. class Auth:
  44. """
  45. This class contains functions for authenticating users of our client-server API.
  46. """
  47. def __init__(self, hs: "HomeServer"):
  48. self.hs = hs
  49. self.clock = hs.get_clock()
  50. self.store = hs.get_datastores().main
  51. self._account_validity_handler = hs.get_account_validity_handler()
  52. self._storage_controllers = hs.get_storage_controllers()
  53. self._macaroon_generator = hs.get_macaroon_generator()
  54. self._track_appservice_user_ips = hs.config.appservice.track_appservice_user_ips
  55. self._track_puppeted_user_ips = hs.config.api.track_puppeted_user_ips
  56. self._force_tracing_for_users = hs.config.tracing.force_tracing_for_users
  57. async def check_user_in_room(
  58. self,
  59. room_id: str,
  60. requester: Requester,
  61. allow_departed_users: bool = False,
  62. ) -> Tuple[str, Optional[str]]:
  63. """Check if the user is in the room, or was at some point.
  64. Args:
  65. room_id: The room to check.
  66. requester: The user making the request, according to the access token.
  67. current_state: Optional map of the current state of the room.
  68. If provided then that map is used to check whether they are a
  69. member of the room. Otherwise the current membership is
  70. loaded from the database.
  71. allow_departed_users: if True, accept users that were previously
  72. members but have now departed.
  73. Raises:
  74. AuthError if the user is/was not in the room.
  75. Returns:
  76. The current membership of the user in the room and the
  77. membership event ID of the user.
  78. """
  79. user_id = requester.user.to_string()
  80. (
  81. membership,
  82. member_event_id,
  83. ) = await self.store.get_local_current_membership_for_user_in_room(
  84. user_id=user_id,
  85. room_id=room_id,
  86. )
  87. if membership:
  88. if membership == Membership.JOIN:
  89. return membership, member_event_id
  90. # XXX this looks totally bogus. Why do we not allow users who have been banned,
  91. # or those who were members previously and have been re-invited?
  92. if allow_departed_users and membership == Membership.LEAVE:
  93. forgot = await self.store.did_forget(user_id, room_id)
  94. if not forgot:
  95. return membership, member_event_id
  96. raise UnstableSpecAuthError(
  97. 403,
  98. "User %s not in room %s" % (user_id, room_id),
  99. errcode=Codes.NOT_JOINED,
  100. )
  101. async def get_user_by_req(
  102. self,
  103. request: SynapseRequest,
  104. allow_guest: bool = False,
  105. allow_expired: bool = False,
  106. ) -> Requester:
  107. """Get a registered user's ID.
  108. Args:
  109. request: An HTTP request with an access_token query parameter.
  110. allow_guest: If False, will raise an AuthError if the user making the
  111. request is a guest.
  112. allow_expired: If True, allow the request through even if the account
  113. is expired, or session token lifetime has ended. Note that
  114. /login will deliver access tokens regardless of expiration.
  115. Returns:
  116. Resolves to the requester
  117. Raises:
  118. InvalidClientCredentialsError if no user by that token exists or the token
  119. is invalid.
  120. AuthError if access is denied for the user in the access token
  121. """
  122. parent_span = active_span()
  123. with start_active_span("get_user_by_req"):
  124. requester = await self._wrapped_get_user_by_req(
  125. request, allow_guest, allow_expired
  126. )
  127. if parent_span:
  128. if requester.authenticated_entity in self._force_tracing_for_users:
  129. # request tracing is enabled for this user, so we need to force it
  130. # tracing on for the parent span (which will be the servlet span).
  131. #
  132. # It's too late for the get_user_by_req span to inherit the setting,
  133. # so we also force it on for that.
  134. force_tracing()
  135. force_tracing(parent_span)
  136. parent_span.set_tag(
  137. "authenticated_entity", requester.authenticated_entity
  138. )
  139. parent_span.set_tag("user_id", requester.user.to_string())
  140. if requester.device_id is not None:
  141. parent_span.set_tag("device_id", requester.device_id)
  142. if requester.app_service is not None:
  143. parent_span.set_tag("appservice_id", requester.app_service.id)
  144. return requester
  145. async def _wrapped_get_user_by_req(
  146. self,
  147. request: SynapseRequest,
  148. allow_guest: bool,
  149. allow_expired: bool,
  150. ) -> Requester:
  151. """Helper for get_user_by_req
  152. Once get_user_by_req has set up the opentracing span, this does the actual work.
  153. """
  154. try:
  155. ip_addr = request.getClientAddress().host
  156. user_agent = get_request_user_agent(request)
  157. access_token = self.get_access_token_from_request(request)
  158. # First check if it could be a request from an appservice
  159. requester = await self._get_appservice_user(request)
  160. if not requester:
  161. # If not, it should be from a regular user
  162. requester = await self.get_user_by_access_token(
  163. access_token, allow_expired=allow_expired
  164. )
  165. # Deny the request if the user account has expired.
  166. # This check is only done for regular users, not appservice ones.
  167. if not allow_expired:
  168. if await self._account_validity_handler.is_user_expired(
  169. requester.user.to_string()
  170. ):
  171. # Raise the error if either an account validity module has determined
  172. # the account has expired, or the legacy account validity
  173. # implementation is enabled and determined the account has expired
  174. raise AuthError(
  175. 403,
  176. "User account has expired",
  177. errcode=Codes.EXPIRED_ACCOUNT,
  178. )
  179. if ip_addr and (
  180. not requester.app_service or self._track_appservice_user_ips
  181. ):
  182. # XXX(quenting): I'm 95% confident that we could skip setting the
  183. # device_id to "dummy-device" for appservices, and that the only impact
  184. # would be some rows which whould not deduplicate in the 'user_ips'
  185. # table during the transition
  186. recorded_device_id = (
  187. "dummy-device"
  188. if requester.device_id is None and requester.app_service is not None
  189. else requester.device_id
  190. )
  191. await self.store.insert_client_ip(
  192. user_id=requester.authenticated_entity,
  193. access_token=access_token,
  194. ip=ip_addr,
  195. user_agent=user_agent,
  196. device_id=recorded_device_id,
  197. )
  198. # Track also the puppeted user client IP if enabled and the user is puppeting
  199. if (
  200. requester.user.to_string() != requester.authenticated_entity
  201. and self._track_puppeted_user_ips
  202. ):
  203. await self.store.insert_client_ip(
  204. user_id=requester.user.to_string(),
  205. access_token=access_token,
  206. ip=ip_addr,
  207. user_agent=user_agent,
  208. device_id=requester.device_id,
  209. )
  210. if requester.is_guest and not allow_guest:
  211. raise AuthError(
  212. 403,
  213. "Guest access not allowed",
  214. errcode=Codes.GUEST_ACCESS_FORBIDDEN,
  215. )
  216. request.requester = requester
  217. return requester
  218. except KeyError:
  219. raise MissingClientTokenError()
  220. async def validate_appservice_can_control_user_id(
  221. self, app_service: ApplicationService, user_id: str
  222. ) -> None:
  223. """Validates that the app service is allowed to control
  224. the given user.
  225. Args:
  226. app_service: The app service that controls the user
  227. user_id: The author MXID that the app service is controlling
  228. Raises:
  229. AuthError: If the application service is not allowed to control the user
  230. (user namespace regex does not match, wrong homeserver, etc)
  231. or if the user has not been registered yet.
  232. """
  233. # It's ok if the app service is trying to use the sender from their registration
  234. if app_service.sender == user_id:
  235. pass
  236. # Check to make sure the app service is allowed to control the user
  237. elif not app_service.is_interested_in_user(user_id):
  238. raise AuthError(
  239. 403,
  240. "Application service cannot masquerade as this user (%s)." % user_id,
  241. )
  242. # Check to make sure the user is already registered on the homeserver
  243. elif not (await self.store.get_user_by_id(user_id)):
  244. raise AuthError(
  245. 403, "Application service has not registered this user (%s)" % user_id
  246. )
  247. async def _get_appservice_user(self, request: Request) -> Optional[Requester]:
  248. """
  249. Given a request, reads the request parameters to determine:
  250. - whether it's an application service that's making this request
  251. - what user the application service should be treated as controlling
  252. (the user_id URI parameter allows an application service to masquerade
  253. any applicable user in its namespace)
  254. - what device the application service should be treated as controlling
  255. (the device_id[^1] URI parameter allows an application service to masquerade
  256. as any device that exists for the relevant user)
  257. [^1] Unstable and provided by MSC3202.
  258. Must use `org.matrix.msc3202.device_id` in place of `device_id` for now.
  259. Returns:
  260. the application service `Requester` of that request
  261. Postconditions:
  262. - The `app_service` field in the returned `Requester` is set
  263. - The `user_id` field in the returned `Requester` is either the application
  264. service sender or the controlled user set by the `user_id` URI parameter
  265. - The returned application service is permitted to control the returned user ID.
  266. - The returned device ID, if present, has been checked to be a valid device ID
  267. for the returned user ID.
  268. """
  269. DEVICE_ID_ARG_NAME = b"org.matrix.msc3202.device_id"
  270. app_service = self.store.get_app_service_by_token(
  271. self.get_access_token_from_request(request)
  272. )
  273. if app_service is None:
  274. return None
  275. if app_service.ip_range_whitelist:
  276. ip_address = IPAddress(request.getClientAddress().host)
  277. if ip_address not in app_service.ip_range_whitelist:
  278. return None
  279. # This will always be set by the time Twisted calls us.
  280. assert request.args is not None
  281. if b"user_id" in request.args:
  282. effective_user_id = request.args[b"user_id"][0].decode("utf8")
  283. await self.validate_appservice_can_control_user_id(
  284. app_service, effective_user_id
  285. )
  286. else:
  287. effective_user_id = app_service.sender
  288. effective_device_id: Optional[str] = None
  289. if (
  290. self.hs.config.experimental.msc3202_device_masquerading_enabled
  291. and DEVICE_ID_ARG_NAME in request.args
  292. ):
  293. effective_device_id = request.args[DEVICE_ID_ARG_NAME][0].decode("utf8")
  294. # We only just set this so it can't be None!
  295. assert effective_device_id is not None
  296. device_opt = await self.store.get_device(
  297. effective_user_id, effective_device_id
  298. )
  299. if device_opt is None:
  300. # For now, use 400 M_EXCLUSIVE if the device doesn't exist.
  301. # This is an open thread of discussion on MSC3202 as of 2021-12-09.
  302. raise AuthError(
  303. 400,
  304. f"Application service trying to use a device that doesn't exist ('{effective_device_id}' for {effective_user_id})",
  305. Codes.EXCLUSIVE,
  306. )
  307. return create_requester(
  308. effective_user_id, app_service=app_service, device_id=effective_device_id
  309. )
  310. async def get_user_by_access_token(
  311. self,
  312. token: str,
  313. allow_expired: bool = False,
  314. ) -> Requester:
  315. """Validate access token and get user_id from it
  316. Args:
  317. token: The access token to get the user by
  318. allow_expired: If False, raises an InvalidClientTokenError
  319. if the token is expired
  320. Raises:
  321. InvalidClientTokenError if a user by that token exists, but the token is
  322. expired
  323. InvalidClientCredentialsError if no user by that token exists or the token
  324. is invalid
  325. """
  326. # First look in the database to see if the access token is present
  327. # as an opaque token.
  328. user_info = await self.store.get_user_by_access_token(token)
  329. if user_info:
  330. valid_until_ms = user_info.valid_until_ms
  331. if (
  332. not allow_expired
  333. and valid_until_ms is not None
  334. and valid_until_ms < self.clock.time_msec()
  335. ):
  336. # there was a valid access token, but it has expired.
  337. # soft-logout the user.
  338. raise InvalidClientTokenError(
  339. msg="Access token has expired", soft_logout=True
  340. )
  341. # Mark the token as used. This is used to invalidate old refresh
  342. # tokens after some time.
  343. await self.store.mark_access_token_as_used(user_info.token_id)
  344. requester = create_requester(
  345. user_id=user_info.user_id,
  346. access_token_id=user_info.token_id,
  347. is_guest=user_info.is_guest,
  348. shadow_banned=user_info.shadow_banned,
  349. device_id=user_info.device_id,
  350. authenticated_entity=user_info.token_owner,
  351. )
  352. return requester
  353. # If the token isn't found in the database, then it could still be a
  354. # macaroon for a guest, so we check that here.
  355. try:
  356. user_id = self._macaroon_generator.verify_guest_token(token)
  357. # Guest access tokens are not stored in the database (there can
  358. # only be one access token per guest, anyway).
  359. #
  360. # In order to prevent guest access tokens being used as regular
  361. # user access tokens (and hence getting around the invalidation
  362. # process), we look up the user id and check that it is indeed
  363. # a guest user.
  364. #
  365. # It would of course be much easier to store guest access
  366. # tokens in the database as well, but that would break existing
  367. # guest tokens.
  368. stored_user = await self.store.get_user_by_id(user_id)
  369. if not stored_user:
  370. raise InvalidClientTokenError("Unknown user_id %s" % user_id)
  371. if not stored_user["is_guest"]:
  372. raise InvalidClientTokenError(
  373. "Guest access token used for regular user"
  374. )
  375. return create_requester(
  376. user_id=user_id,
  377. is_guest=True,
  378. # all guests get the same device id
  379. device_id=GUEST_DEVICE_ID,
  380. authenticated_entity=user_id,
  381. )
  382. except (
  383. pymacaroons.exceptions.MacaroonException,
  384. TypeError,
  385. ValueError,
  386. ) as e:
  387. logger.warning(
  388. "Invalid access token in auth: %s %s.",
  389. type(e),
  390. e,
  391. )
  392. raise InvalidClientTokenError("Invalid access token passed.")
  393. def get_appservice_by_req(self, request: SynapseRequest) -> ApplicationService:
  394. token = self.get_access_token_from_request(request)
  395. service = self.store.get_app_service_by_token(token)
  396. if not service:
  397. logger.warning("Unrecognised appservice access token.")
  398. raise InvalidClientTokenError()
  399. request.requester = create_requester(service.sender, app_service=service)
  400. return service
  401. async def is_server_admin(self, requester: Requester) -> bool:
  402. """Check if the given user is a local server admin.
  403. Args:
  404. requester: The user making the request, according to the access token.
  405. Returns:
  406. True if the user is an admin
  407. """
  408. return await self.store.is_server_admin(requester.user)
  409. async def check_can_change_room_list(
  410. self, room_id: str, requester: Requester
  411. ) -> bool:
  412. """Determine whether the user is allowed to edit the room's entry in the
  413. published room list.
  414. Args:
  415. room_id: The room to check.
  416. requester: The user making the request, according to the access token.
  417. """
  418. is_admin = await self.is_server_admin(requester)
  419. if is_admin:
  420. return True
  421. await self.check_user_in_room(room_id, requester)
  422. # We currently require the user is a "moderator" in the room. We do this
  423. # by checking if they would (theoretically) be able to change the
  424. # m.room.canonical_alias events
  425. power_level_event = (
  426. await self._storage_controllers.state.get_current_state_event(
  427. room_id, EventTypes.PowerLevels, ""
  428. )
  429. )
  430. auth_events = {}
  431. if power_level_event:
  432. auth_events[(EventTypes.PowerLevels, "")] = power_level_event
  433. send_level = event_auth.get_send_level(
  434. EventTypes.CanonicalAlias, "", power_level_event
  435. )
  436. user_level = event_auth.get_user_power_level(
  437. requester.user.to_string(), auth_events
  438. )
  439. return user_level >= send_level
  440. @staticmethod
  441. def has_access_token(request: Request) -> bool:
  442. """Checks if the request has an access_token.
  443. Returns:
  444. False if no access_token was given, True otherwise.
  445. """
  446. # This will always be set by the time Twisted calls us.
  447. assert request.args is not None
  448. query_params = request.args.get(b"access_token")
  449. auth_headers = request.requestHeaders.getRawHeaders(b"Authorization")
  450. return bool(query_params) or bool(auth_headers)
  451. @staticmethod
  452. def get_access_token_from_request(request: Request) -> str:
  453. """Extracts the access_token from the request.
  454. Args:
  455. request: The http request.
  456. Returns:
  457. The access_token
  458. Raises:
  459. MissingClientTokenError: If there isn't a single access_token in the
  460. request
  461. """
  462. # This will always be set by the time Twisted calls us.
  463. assert request.args is not None
  464. auth_headers = request.requestHeaders.getRawHeaders(b"Authorization")
  465. query_params = request.args.get(b"access_token")
  466. if auth_headers:
  467. # Try the get the access_token from a "Authorization: Bearer"
  468. # header
  469. if query_params is not None:
  470. raise MissingClientTokenError(
  471. "Mixing Authorization headers and access_token query parameters."
  472. )
  473. if len(auth_headers) > 1:
  474. raise MissingClientTokenError("Too many Authorization headers.")
  475. parts = auth_headers[0].split(b" ")
  476. if parts[0] == b"Bearer" and len(parts) == 2:
  477. return parts[1].decode("ascii")
  478. else:
  479. raise MissingClientTokenError("Invalid Authorization header.")
  480. else:
  481. # Try to get the access_token from the query params.
  482. if not query_params:
  483. raise MissingClientTokenError()
  484. return query_params[0].decode("ascii")
  485. @trace
  486. async def check_user_in_room_or_world_readable(
  487. self, room_id: str, requester: Requester, allow_departed_users: bool = False
  488. ) -> Tuple[str, Optional[str]]:
  489. """Checks that the user is or was in the room or the room is world
  490. readable. If it isn't then an exception is raised.
  491. Args:
  492. room_id: The room to check.
  493. requester: The user making the request, according to the access token.
  494. allow_departed_users: If True, accept users that were previously
  495. members but have now departed.
  496. Returns:
  497. Resolves to the current membership of the user in the room and the
  498. membership event ID of the user. If the user is not in the room and
  499. never has been, then `(Membership.JOIN, None)` is returned.
  500. """
  501. try:
  502. # check_user_in_room will return the most recent membership
  503. # event for the user if:
  504. # * The user is a non-guest user, and was ever in the room
  505. # * The user is a guest user, and has joined the room
  506. # else it will throw.
  507. return await self.check_user_in_room(
  508. room_id, requester, allow_departed_users=allow_departed_users
  509. )
  510. except AuthError:
  511. visibility = await self._storage_controllers.state.get_current_state_event(
  512. room_id, EventTypes.RoomHistoryVisibility, ""
  513. )
  514. if (
  515. visibility
  516. and visibility.content.get("history_visibility")
  517. == HistoryVisibility.WORLD_READABLE
  518. ):
  519. return Membership.JOIN, None
  520. raise UnstableSpecAuthError(
  521. 403,
  522. "User %s not in room %s, and room previews are disabled"
  523. % (requester.user, room_id),
  524. errcode=Codes.NOT_JOINED,
  525. )