auth.py 23 KB

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