event_auth.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  1. # Copyright 2014 - 2016 OpenMarket Ltd
  2. # Copyright 2020 The Matrix.org Foundation C.I.C.
  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. import logging
  16. import typing
  17. from typing import Any, Dict, Iterable, List, Optional, Set, Tuple, Union
  18. from canonicaljson import encode_canonical_json
  19. from signedjson.key import decode_verify_key_bytes
  20. from signedjson.sign import SignatureVerifyException, verify_signed_json
  21. from unpaddedbase64 import decode_base64
  22. from synapse.api.constants import (
  23. MAX_PDU_SIZE,
  24. EventContentFields,
  25. EventTypes,
  26. JoinRules,
  27. Membership,
  28. )
  29. from synapse.api.errors import AuthError, EventSizeError, SynapseError
  30. from synapse.api.room_versions import (
  31. KNOWN_ROOM_VERSIONS,
  32. EventFormatVersions,
  33. RoomVersion,
  34. )
  35. from synapse.types import StateMap, UserID, get_domain_from_id
  36. if typing.TYPE_CHECKING:
  37. # conditional imports to avoid import cycle
  38. from synapse.events import EventBase
  39. from synapse.events.builder import EventBuilder
  40. logger = logging.getLogger(__name__)
  41. def validate_event_for_room_version(
  42. room_version_obj: RoomVersion, event: "EventBase"
  43. ) -> None:
  44. """Ensure that the event complies with the limits, and has the right signatures
  45. NB: does not *validate* the signatures - it assumes that any signatures present
  46. have already been checked.
  47. NB: it does not check that the event satisfies the auth rules (that is done in
  48. check_auth_rules_for_event) - these tests are independent of the rest of the state
  49. in the room.
  50. NB: This is used to check events that have been received over federation. As such,
  51. it can only enforce the checks specified in the relevant room version, to avoid
  52. a split-brain situation where some servers accept such events, and others reject
  53. them.
  54. TODO: consider moving this into EventValidator
  55. Args:
  56. room_version_obj: the version of the room which contains this event
  57. event: the event to be checked
  58. Raises:
  59. SynapseError if there is a problem with the event
  60. """
  61. _check_size_limits(event)
  62. if not hasattr(event, "room_id"):
  63. raise AuthError(500, "Event has no room_id: %s" % event)
  64. # check that the event has the correct signatures
  65. sender_domain = get_domain_from_id(event.sender)
  66. is_invite_via_3pid = (
  67. event.type == EventTypes.Member
  68. and event.membership == Membership.INVITE
  69. and "third_party_invite" in event.content
  70. )
  71. # Check the sender's domain has signed the event
  72. if not event.signatures.get(sender_domain):
  73. # We allow invites via 3pid to have a sender from a different
  74. # HS, as the sender must match the sender of the original
  75. # 3pid invite. This is checked further down with the
  76. # other dedicated membership checks.
  77. if not is_invite_via_3pid:
  78. raise AuthError(403, "Event not signed by sender's server")
  79. if event.format_version in (EventFormatVersions.V1,):
  80. # Only older room versions have event IDs to check.
  81. event_id_domain = get_domain_from_id(event.event_id)
  82. # Check the origin domain has signed the event
  83. if not event.signatures.get(event_id_domain):
  84. raise AuthError(403, "Event not signed by sending server")
  85. is_invite_via_allow_rule = (
  86. room_version_obj.msc3083_join_rules
  87. and event.type == EventTypes.Member
  88. and event.membership == Membership.JOIN
  89. and EventContentFields.AUTHORISING_USER in event.content
  90. )
  91. if is_invite_via_allow_rule:
  92. authoriser_domain = get_domain_from_id(
  93. event.content[EventContentFields.AUTHORISING_USER]
  94. )
  95. if not event.signatures.get(authoriser_domain):
  96. raise AuthError(403, "Event not signed by authorising server")
  97. def check_auth_rules_for_event(
  98. room_version_obj: RoomVersion,
  99. event: "EventBase",
  100. auth_events: Iterable["EventBase"],
  101. ) -> None:
  102. """Check that an event complies with the auth rules
  103. Checks whether an event passes the auth rules with a given set of state events
  104. Assumes that we have already checked that the event is the right shape (it has
  105. enough signatures, has a room ID, etc). In other words:
  106. - it's fine for use in state resolution, when we have already decided whether to
  107. accept the event or not, and are now trying to decide whether it should make it
  108. into the room state
  109. - when we're doing the initial event auth, it is only suitable in combination with
  110. a bunch of other tests.
  111. Args:
  112. room_version_obj: the version of the room
  113. event: the event being checked.
  114. auth_events: the room state to check the events against.
  115. Raises:
  116. AuthError if the checks fail
  117. """
  118. # We need to ensure that the auth events are actually for the same room, to
  119. # stop people from using powers they've been granted in other rooms for
  120. # example.
  121. #
  122. # Arguably we don't need to do this when we're just doing state res, as presumably
  123. # the state res algorithm isn't silly enough to give us events from different rooms.
  124. # Still, it's easier to do it anyway.
  125. room_id = event.room_id
  126. for auth_event in auth_events:
  127. if auth_event.room_id != room_id:
  128. raise AuthError(
  129. 403,
  130. "During auth for event %s in room %s, found event %s in the state "
  131. "which is in room %s"
  132. % (event.event_id, room_id, auth_event.event_id, auth_event.room_id),
  133. )
  134. if auth_event.rejected_reason:
  135. raise AuthError(
  136. 403,
  137. "During auth for event %s: found rejected event %s in the state"
  138. % (event.event_id, auth_event.event_id),
  139. )
  140. # Implementation of https://matrix.org/docs/spec/rooms/v1#authorization-rules
  141. #
  142. # 1. If type is m.room.create:
  143. if event.type == EventTypes.Create:
  144. # 1b. If the domain of the room_id does not match the domain of the sender,
  145. # reject.
  146. sender_domain = get_domain_from_id(event.sender)
  147. room_id_domain = get_domain_from_id(event.room_id)
  148. if room_id_domain != sender_domain:
  149. raise AuthError(
  150. 403, "Creation event's room_id domain does not match sender's"
  151. )
  152. # 1c. If content.room_version is present and is not a recognised version, reject
  153. room_version_prop = event.content.get("room_version", "1")
  154. if room_version_prop not in KNOWN_ROOM_VERSIONS:
  155. raise AuthError(
  156. 403,
  157. "room appears to have unsupported version %s" % (room_version_prop,),
  158. )
  159. logger.debug("Allowing! %s", event)
  160. return
  161. auth_dict = {(e.type, e.state_key): e for e in auth_events}
  162. # 3. If event does not have a m.room.create in its auth_events, reject.
  163. creation_event = auth_dict.get((EventTypes.Create, ""), None)
  164. if not creation_event:
  165. raise AuthError(403, "No create event in auth events")
  166. # additional check for m.federate
  167. creating_domain = get_domain_from_id(event.room_id)
  168. originating_domain = get_domain_from_id(event.sender)
  169. if creating_domain != originating_domain:
  170. if not _can_federate(event, auth_dict):
  171. raise AuthError(403, "This room has been marked as unfederatable.")
  172. # 4. If type is m.room.aliases
  173. if event.type == EventTypes.Aliases and room_version_obj.special_case_aliases_auth:
  174. # 4a. If event has no state_key, reject
  175. if not event.is_state():
  176. raise AuthError(403, "Alias event must be a state event")
  177. if not event.state_key:
  178. raise AuthError(403, "Alias event must have non-empty state_key")
  179. # 4b. If sender's domain doesn't matches [sic] state_key, reject
  180. sender_domain = get_domain_from_id(event.sender)
  181. if event.state_key != sender_domain:
  182. raise AuthError(
  183. 403, "Alias event's state_key does not match sender's domain"
  184. )
  185. # 4c. Otherwise, allow.
  186. logger.debug("Allowing! %s", event)
  187. return
  188. # 5. If type is m.room.membership
  189. if event.type == EventTypes.Member:
  190. _is_membership_change_allowed(room_version_obj, event, auth_dict)
  191. logger.debug("Allowing! %s", event)
  192. return
  193. _check_event_sender_in_room(event, auth_dict)
  194. # Special case to allow m.room.third_party_invite events wherever
  195. # a user is allowed to issue invites. Fixes
  196. # https://github.com/vector-im/vector-web/issues/1208 hopefully
  197. if event.type == EventTypes.ThirdPartyInvite:
  198. user_level = get_user_power_level(event.user_id, auth_dict)
  199. invite_level = get_named_level(auth_dict, "invite", 0)
  200. if user_level < invite_level:
  201. raise AuthError(403, "You don't have permission to invite users")
  202. else:
  203. logger.debug("Allowing! %s", event)
  204. return
  205. _can_send_event(event, auth_dict)
  206. if event.type == EventTypes.PowerLevels:
  207. _check_power_levels(room_version_obj, event, auth_dict)
  208. if event.type == EventTypes.Redaction:
  209. check_redaction(room_version_obj, event, auth_dict)
  210. if (
  211. event.type == EventTypes.MSC2716_INSERTION
  212. or event.type == EventTypes.MSC2716_BATCH
  213. or event.type == EventTypes.MSC2716_MARKER
  214. ):
  215. check_historical(room_version_obj, event, auth_dict)
  216. logger.debug("Allowing! %s", event)
  217. def _check_size_limits(event: "EventBase") -> None:
  218. if len(event.user_id) > 255:
  219. raise EventSizeError("'user_id' too large")
  220. if len(event.room_id) > 255:
  221. raise EventSizeError("'room_id' too large")
  222. if event.is_state() and len(event.state_key) > 255:
  223. raise EventSizeError("'state_key' too large")
  224. if len(event.type) > 255:
  225. raise EventSizeError("'type' too large")
  226. if len(event.event_id) > 255:
  227. raise EventSizeError("'event_id' too large")
  228. if len(encode_canonical_json(event.get_pdu_json())) > MAX_PDU_SIZE:
  229. raise EventSizeError("event too large")
  230. def _can_federate(event: "EventBase", auth_events: StateMap["EventBase"]) -> bool:
  231. creation_event = auth_events.get((EventTypes.Create, ""))
  232. # There should always be a creation event, but if not don't federate.
  233. if not creation_event:
  234. return False
  235. return creation_event.content.get(EventContentFields.FEDERATE, True) is True
  236. def _is_membership_change_allowed(
  237. room_version: RoomVersion, event: "EventBase", auth_events: StateMap["EventBase"]
  238. ) -> None:
  239. """
  240. Confirms that the event which changes membership is an allowed change.
  241. Args:
  242. room_version: The version of the room.
  243. event: The event to check.
  244. auth_events: The current auth events of the room.
  245. Raises:
  246. AuthError if the event is not allowed.
  247. """
  248. membership = event.content["membership"]
  249. # Check if this is the room creator joining:
  250. if len(event.prev_event_ids()) == 1 and Membership.JOIN == membership:
  251. # Get room creation event:
  252. key = (EventTypes.Create, "")
  253. create = auth_events.get(key)
  254. if create and event.prev_event_ids()[0] == create.event_id:
  255. if create.content["creator"] == event.state_key:
  256. return
  257. target_user_id = event.state_key
  258. creating_domain = get_domain_from_id(event.room_id)
  259. target_domain = get_domain_from_id(target_user_id)
  260. if creating_domain != target_domain:
  261. if not _can_federate(event, auth_events):
  262. raise AuthError(403, "This room has been marked as unfederatable.")
  263. # get info about the caller
  264. key = (EventTypes.Member, event.user_id)
  265. caller = auth_events.get(key)
  266. caller_in_room = caller and caller.membership == Membership.JOIN
  267. caller_invited = caller and caller.membership == Membership.INVITE
  268. caller_knocked = (
  269. caller
  270. and room_version.msc2403_knocking
  271. and caller.membership == Membership.KNOCK
  272. )
  273. # get info about the target
  274. key = (EventTypes.Member, target_user_id)
  275. target = auth_events.get(key)
  276. target_in_room = target and target.membership == Membership.JOIN
  277. target_banned = target and target.membership == Membership.BAN
  278. key = (EventTypes.JoinRules, "")
  279. join_rule_event = auth_events.get(key)
  280. if join_rule_event:
  281. join_rule = join_rule_event.content.get("join_rule", JoinRules.INVITE)
  282. else:
  283. join_rule = JoinRules.INVITE
  284. user_level = get_user_power_level(event.user_id, auth_events)
  285. target_level = get_user_power_level(target_user_id, auth_events)
  286. invite_level = get_named_level(auth_events, "invite", 0)
  287. ban_level = get_named_level(auth_events, "ban", 50)
  288. logger.debug(
  289. "_is_membership_change_allowed: %s",
  290. {
  291. "caller_in_room": caller_in_room,
  292. "caller_invited": caller_invited,
  293. "caller_knocked": caller_knocked,
  294. "target_banned": target_banned,
  295. "target_in_room": target_in_room,
  296. "membership": membership,
  297. "join_rule": join_rule,
  298. "target_user_id": target_user_id,
  299. "event.user_id": event.user_id,
  300. },
  301. )
  302. if Membership.INVITE == membership and "third_party_invite" in event.content:
  303. if not _verify_third_party_invite(event, auth_events):
  304. raise AuthError(403, "You are not invited to this room.")
  305. if target_banned:
  306. raise AuthError(403, "%s is banned from the room" % (target_user_id,))
  307. return
  308. # Require the user to be in the room for membership changes other than join/knock.
  309. # Note that the room version check for knocking is done implicitly by `caller_knocked`
  310. # and the ability to set a membership of `knock` in the first place.
  311. if Membership.JOIN != membership and Membership.KNOCK != membership:
  312. # If the user has been invited or has knocked, they are allowed to change their
  313. # membership event to leave
  314. if (
  315. (caller_invited or caller_knocked)
  316. and Membership.LEAVE == membership
  317. and target_user_id == event.user_id
  318. ):
  319. return
  320. if not caller_in_room: # caller isn't joined
  321. raise AuthError(403, "%s not in room %s." % (event.user_id, event.room_id))
  322. if Membership.INVITE == membership:
  323. # TODO (erikj): We should probably handle this more intelligently
  324. # PRIVATE join rules.
  325. # Invites are valid iff caller is in the room and target isn't.
  326. if target_banned:
  327. raise AuthError(403, "%s is banned from the room" % (target_user_id,))
  328. elif target_in_room: # the target is already in the room.
  329. raise AuthError(403, "%s is already in the room." % target_user_id)
  330. else:
  331. if user_level < invite_level:
  332. raise AuthError(403, "You don't have permission to invite users")
  333. elif Membership.JOIN == membership:
  334. # Joins are valid iff caller == target and:
  335. # * They are not banned.
  336. # * They are accepting a previously sent invitation.
  337. # * They are already joined (it's a NOOP).
  338. # * The room is public.
  339. # * The room is restricted and the user meets the allows rules.
  340. if event.user_id != target_user_id:
  341. raise AuthError(403, "Cannot force another user to join.")
  342. elif target_banned:
  343. raise AuthError(403, "You are banned from this room")
  344. elif join_rule == JoinRules.PUBLIC:
  345. pass
  346. elif room_version.msc3083_join_rules and join_rule == JoinRules.RESTRICTED:
  347. # This is the same as public, but the event must contain a reference
  348. # to the server who authorised the join. If the event does not contain
  349. # the proper content it is rejected.
  350. #
  351. # Note that if the caller is in the room or invited, then they do
  352. # not need to meet the allow rules.
  353. if not caller_in_room and not caller_invited:
  354. authorising_user = event.content.get(
  355. EventContentFields.AUTHORISING_USER
  356. )
  357. if authorising_user is None:
  358. raise AuthError(403, "Join event is missing authorising user.")
  359. # The authorising user must be in the room.
  360. key = (EventTypes.Member, authorising_user)
  361. member_event = auth_events.get(key)
  362. _check_joined_room(member_event, authorising_user, event.room_id)
  363. authorising_user_level = get_user_power_level(
  364. authorising_user, auth_events
  365. )
  366. if authorising_user_level < invite_level:
  367. raise AuthError(403, "Join event authorised by invalid server.")
  368. elif join_rule == JoinRules.INVITE or (
  369. room_version.msc2403_knocking and join_rule == JoinRules.KNOCK
  370. ):
  371. if not caller_in_room and not caller_invited:
  372. raise AuthError(403, "You are not invited to this room.")
  373. else:
  374. # TODO (erikj): may_join list
  375. # TODO (erikj): private rooms
  376. raise AuthError(403, "You are not allowed to join this room")
  377. elif Membership.LEAVE == membership:
  378. # TODO (erikj): Implement kicks.
  379. if target_banned and user_level < ban_level:
  380. raise AuthError(403, "You cannot unban user %s." % (target_user_id,))
  381. elif target_user_id != event.user_id:
  382. kick_level = get_named_level(auth_events, "kick", 50)
  383. if user_level < kick_level or user_level <= target_level:
  384. raise AuthError(403, "You cannot kick user %s." % target_user_id)
  385. elif Membership.BAN == membership:
  386. if user_level < ban_level or user_level <= target_level:
  387. raise AuthError(403, "You don't have permission to ban")
  388. elif room_version.msc2403_knocking and Membership.KNOCK == membership:
  389. if join_rule != JoinRules.KNOCK:
  390. raise AuthError(403, "You don't have permission to knock")
  391. elif target_user_id != event.user_id:
  392. raise AuthError(403, "You cannot knock for other users")
  393. elif target_in_room:
  394. raise AuthError(403, "You cannot knock on a room you are already in")
  395. elif caller_invited:
  396. raise AuthError(403, "You are already invited to this room")
  397. elif target_banned:
  398. raise AuthError(403, "You are banned from this room")
  399. else:
  400. raise AuthError(500, "Unknown membership %s" % membership)
  401. def _check_event_sender_in_room(
  402. event: "EventBase", auth_events: StateMap["EventBase"]
  403. ) -> None:
  404. key = (EventTypes.Member, event.user_id)
  405. member_event = auth_events.get(key)
  406. _check_joined_room(member_event, event.user_id, event.room_id)
  407. def _check_joined_room(
  408. member: Optional["EventBase"], user_id: str, room_id: str
  409. ) -> None:
  410. if not member or member.membership != Membership.JOIN:
  411. raise AuthError(
  412. 403, "User %s not in room %s (%s)" % (user_id, room_id, repr(member))
  413. )
  414. def get_send_level(
  415. etype: str, state_key: Optional[str], power_levels_event: Optional["EventBase"]
  416. ) -> int:
  417. """Get the power level required to send an event of a given type
  418. The federation spec [1] refers to this as "Required Power Level".
  419. https://matrix.org/docs/spec/server_server/unstable.html#definitions
  420. Args:
  421. etype: type of event
  422. state_key: state_key of state event, or None if it is not
  423. a state event.
  424. power_levels_event: power levels event
  425. in force at this point in the room
  426. Returns:
  427. power level required to send this event.
  428. """
  429. if power_levels_event:
  430. power_levels_content = power_levels_event.content
  431. else:
  432. power_levels_content = {}
  433. # see if we have a custom level for this event type
  434. send_level = power_levels_content.get("events", {}).get(etype)
  435. # otherwise, fall back to the state_default/events_default.
  436. if send_level is None:
  437. if state_key is not None:
  438. send_level = power_levels_content.get("state_default", 50)
  439. else:
  440. send_level = power_levels_content.get("events_default", 0)
  441. return int(send_level)
  442. def _can_send_event(event: "EventBase", auth_events: StateMap["EventBase"]) -> bool:
  443. power_levels_event = get_power_level_event(auth_events)
  444. send_level = get_send_level(event.type, event.get("state_key"), power_levels_event)
  445. user_level = get_user_power_level(event.user_id, auth_events)
  446. if user_level < send_level:
  447. raise AuthError(
  448. 403,
  449. "You don't have permission to post that to the room. "
  450. + "user_level (%d) < send_level (%d)" % (user_level, send_level),
  451. )
  452. # Check state_key
  453. if hasattr(event, "state_key"):
  454. if event.state_key.startswith("@"):
  455. if event.state_key != event.user_id:
  456. raise AuthError(403, "You are not allowed to set others state")
  457. return True
  458. def check_redaction(
  459. room_version_obj: RoomVersion,
  460. event: "EventBase",
  461. auth_events: StateMap["EventBase"],
  462. ) -> bool:
  463. """Check whether the event sender is allowed to redact the target event.
  464. Returns:
  465. True if the the sender is allowed to redact the target event if the
  466. target event was created by them.
  467. False if the sender is allowed to redact the target event with no
  468. further checks.
  469. Raises:
  470. AuthError if the event sender is definitely not allowed to redact
  471. the target event.
  472. """
  473. user_level = get_user_power_level(event.user_id, auth_events)
  474. redact_level = get_named_level(auth_events, "redact", 50)
  475. if user_level >= redact_level:
  476. return False
  477. if room_version_obj.event_format == EventFormatVersions.V1:
  478. redacter_domain = get_domain_from_id(event.event_id)
  479. if not isinstance(event.redacts, str):
  480. return False
  481. redactee_domain = get_domain_from_id(event.redacts)
  482. if redacter_domain == redactee_domain:
  483. return True
  484. else:
  485. event.internal_metadata.recheck_redaction = True
  486. return True
  487. raise AuthError(403, "You don't have permission to redact events")
  488. def check_historical(
  489. room_version_obj: RoomVersion,
  490. event: "EventBase",
  491. auth_events: StateMap["EventBase"],
  492. ) -> None:
  493. """Check whether the event sender is allowed to send historical related
  494. events like "insertion", "batch", and "marker".
  495. Returns:
  496. None
  497. Raises:
  498. AuthError if the event sender is not allowed to send historical related events
  499. ("insertion", "batch", and "marker").
  500. """
  501. # Ignore the auth checks in room versions that do not support historical
  502. # events
  503. if not room_version_obj.msc2716_historical:
  504. return
  505. user_level = get_user_power_level(event.user_id, auth_events)
  506. historical_level = get_named_level(auth_events, "historical", 100)
  507. if user_level < historical_level:
  508. raise AuthError(
  509. 403,
  510. 'You don\'t have permission to send send historical related events ("insertion", "batch", and "marker")',
  511. )
  512. def _check_power_levels(
  513. room_version_obj: RoomVersion,
  514. event: "EventBase",
  515. auth_events: StateMap["EventBase"],
  516. ) -> None:
  517. user_list = event.content.get("users", {})
  518. # Validate users
  519. for k, v in user_list.items():
  520. try:
  521. UserID.from_string(k)
  522. except Exception:
  523. raise SynapseError(400, "Not a valid user_id: %s" % (k,))
  524. try:
  525. int(v)
  526. except Exception:
  527. raise SynapseError(400, "Not a valid power level: %s" % (v,))
  528. key = (event.type, event.state_key)
  529. current_state = auth_events.get(key)
  530. if not current_state:
  531. return
  532. user_level = get_user_power_level(event.user_id, auth_events)
  533. # Check other levels:
  534. levels_to_check: List[Tuple[str, Optional[str]]] = [
  535. ("users_default", None),
  536. ("events_default", None),
  537. ("state_default", None),
  538. ("ban", None),
  539. ("redact", None),
  540. ("kick", None),
  541. ("invite", None),
  542. ]
  543. old_list = current_state.content.get("users", {})
  544. for user in set(list(old_list) + list(user_list)):
  545. levels_to_check.append((user, "users"))
  546. old_list = current_state.content.get("events", {})
  547. new_list = event.content.get("events", {})
  548. for ev_id in set(list(old_list) + list(new_list)):
  549. levels_to_check.append((ev_id, "events"))
  550. # MSC2209 specifies these checks should also be done for the "notifications"
  551. # key.
  552. if room_version_obj.limit_notifications_power_levels:
  553. old_list = current_state.content.get("notifications", {})
  554. new_list = event.content.get("notifications", {})
  555. for ev_id in set(list(old_list) + list(new_list)):
  556. levels_to_check.append((ev_id, "notifications"))
  557. old_state = current_state.content
  558. new_state = event.content
  559. for level_to_check, dir in levels_to_check:
  560. old_loc = old_state
  561. new_loc = new_state
  562. if dir:
  563. old_loc = old_loc.get(dir, {})
  564. new_loc = new_loc.get(dir, {})
  565. if level_to_check in old_loc:
  566. old_level: Optional[int] = int(old_loc[level_to_check])
  567. else:
  568. old_level = None
  569. if level_to_check in new_loc:
  570. new_level: Optional[int] = int(new_loc[level_to_check])
  571. else:
  572. new_level = None
  573. if new_level is not None and old_level is not None:
  574. if new_level == old_level:
  575. continue
  576. if dir == "users" and level_to_check != event.user_id:
  577. if old_level == user_level:
  578. raise AuthError(
  579. 403,
  580. "You don't have permission to remove ops level equal "
  581. "to your own",
  582. )
  583. # Check if the old and new levels are greater than the user level
  584. # (if defined)
  585. old_level_too_big = old_level is not None and old_level > user_level
  586. new_level_too_big = new_level is not None and new_level > user_level
  587. if old_level_too_big or new_level_too_big:
  588. raise AuthError(
  589. 403, "You don't have permission to add ops level greater than your own"
  590. )
  591. def get_power_level_event(auth_events: StateMap["EventBase"]) -> Optional["EventBase"]:
  592. return auth_events.get((EventTypes.PowerLevels, ""))
  593. def get_user_power_level(user_id: str, auth_events: StateMap["EventBase"]) -> int:
  594. """Get a user's power level
  595. Args:
  596. user_id: user's id to look up in power_levels
  597. auth_events:
  598. state in force at this point in the room (or rather, a subset of
  599. it including at least the create event and power levels event.
  600. Returns:
  601. the user's power level in this room.
  602. """
  603. power_level_event = get_power_level_event(auth_events)
  604. if power_level_event:
  605. level = power_level_event.content.get("users", {}).get(user_id)
  606. if level is None:
  607. level = power_level_event.content.get("users_default", 0)
  608. if level is None:
  609. return 0
  610. else:
  611. return int(level)
  612. else:
  613. # if there is no power levels event, the creator gets 100 and everyone
  614. # else gets 0.
  615. # some things which call this don't pass the create event: hack around
  616. # that.
  617. key = (EventTypes.Create, "")
  618. create_event = auth_events.get(key)
  619. if create_event is not None and create_event.content["creator"] == user_id:
  620. return 100
  621. else:
  622. return 0
  623. def get_named_level(auth_events: StateMap["EventBase"], name: str, default: int) -> int:
  624. power_level_event = get_power_level_event(auth_events)
  625. if not power_level_event:
  626. return default
  627. level = power_level_event.content.get(name, None)
  628. if level is not None:
  629. return int(level)
  630. else:
  631. return default
  632. def _verify_third_party_invite(
  633. event: "EventBase", auth_events: StateMap["EventBase"]
  634. ) -> bool:
  635. """
  636. Validates that the invite event is authorized by a previous third-party invite.
  637. Checks that the public key, and keyserver, match those in the third party invite,
  638. and that the invite event has a signature issued using that public key.
  639. Args:
  640. event: The m.room.member join event being validated.
  641. auth_events: All relevant previous context events which may be used
  642. for authorization decisions.
  643. Return:
  644. True if the event fulfills the expectations of a previous third party
  645. invite event.
  646. """
  647. if "third_party_invite" not in event.content:
  648. return False
  649. if "signed" not in event.content["third_party_invite"]:
  650. return False
  651. signed = event.content["third_party_invite"]["signed"]
  652. for key in {"mxid", "token"}:
  653. if key not in signed:
  654. return False
  655. token = signed["token"]
  656. invite_event = auth_events.get((EventTypes.ThirdPartyInvite, token))
  657. if not invite_event:
  658. return False
  659. if invite_event.sender != event.sender:
  660. return False
  661. if event.user_id != invite_event.user_id:
  662. return False
  663. if signed["mxid"] != event.state_key:
  664. return False
  665. if signed["token"] != token:
  666. return False
  667. for public_key_object in get_public_keys(invite_event):
  668. public_key = public_key_object["public_key"]
  669. try:
  670. for server, signature_block in signed["signatures"].items():
  671. for key_name in signature_block.keys():
  672. if not key_name.startswith("ed25519:"):
  673. continue
  674. verify_key = decode_verify_key_bytes(
  675. key_name, decode_base64(public_key)
  676. )
  677. verify_signed_json(signed, server, verify_key)
  678. # We got the public key from the invite, so we know that the
  679. # correct server signed the signed bundle.
  680. # The caller is responsible for checking that the signing
  681. # server has not revoked that public key.
  682. return True
  683. except (KeyError, SignatureVerifyException):
  684. continue
  685. return False
  686. def get_public_keys(invite_event: "EventBase") -> List[Dict[str, Any]]:
  687. public_keys = []
  688. if "public_key" in invite_event.content:
  689. o = {"public_key": invite_event.content["public_key"]}
  690. if "key_validity_url" in invite_event.content:
  691. o["key_validity_url"] = invite_event.content["key_validity_url"]
  692. public_keys.append(o)
  693. public_keys.extend(invite_event.content.get("public_keys", []))
  694. return public_keys
  695. def auth_types_for_event(
  696. room_version: RoomVersion, event: Union["EventBase", "EventBuilder"]
  697. ) -> Set[Tuple[str, str]]:
  698. """Given an event, return a list of (EventType, StateKey) that may be
  699. needed to auth the event. The returned list may be a superset of what
  700. would actually be required depending on the full state of the room.
  701. Used to limit the number of events to fetch from the database to
  702. actually auth the event.
  703. """
  704. if event.type == EventTypes.Create:
  705. return set()
  706. auth_types = {
  707. (EventTypes.PowerLevels, ""),
  708. (EventTypes.Member, event.sender),
  709. (EventTypes.Create, ""),
  710. }
  711. if event.type == EventTypes.Member:
  712. membership = event.content["membership"]
  713. if membership in [Membership.JOIN, Membership.INVITE, Membership.KNOCK]:
  714. auth_types.add((EventTypes.JoinRules, ""))
  715. auth_types.add((EventTypes.Member, event.state_key))
  716. if membership == Membership.INVITE:
  717. if "third_party_invite" in event.content:
  718. key = (
  719. EventTypes.ThirdPartyInvite,
  720. event.content["third_party_invite"]["signed"]["token"],
  721. )
  722. auth_types.add(key)
  723. if room_version.msc3083_join_rules and membership == Membership.JOIN:
  724. if EventContentFields.AUTHORISING_USER in event.content:
  725. key = (
  726. EventTypes.Member,
  727. event.content[EventContentFields.AUTHORISING_USER],
  728. )
  729. auth_types.add(key)
  730. return auth_types