event_auth.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  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. import logging
  16. from canonicaljson import encode_canonical_json
  17. from signedjson.key import decode_verify_key_bytes
  18. from signedjson.sign import SignatureVerifyException, verify_signed_json
  19. from unpaddedbase64 import decode_base64
  20. from synapse.api.constants import EventTypes, JoinRules, Membership
  21. from synapse.api.errors import AuthError, EventSizeError, SynapseError
  22. from synapse.api.room_versions import KNOWN_ROOM_VERSIONS, EventFormatVersions
  23. from synapse.types import UserID, get_domain_from_id
  24. logger = logging.getLogger(__name__)
  25. def check(room_version, event, auth_events, do_sig_check=True, do_size_check=True):
  26. """ Checks if this event is correctly authed.
  27. Args:
  28. room_version (str): the version of the room
  29. event: the event being checked.
  30. auth_events (dict: event-key -> event): the existing room state.
  31. Raises:
  32. AuthError if the checks fail
  33. Returns:
  34. if the auth checks pass.
  35. """
  36. if do_size_check:
  37. _check_size_limits(event)
  38. if not hasattr(event, "room_id"):
  39. raise AuthError(500, "Event has no room_id: %s" % event)
  40. if do_sig_check:
  41. sender_domain = get_domain_from_id(event.sender)
  42. is_invite_via_3pid = (
  43. event.type == EventTypes.Member
  44. and event.membership == Membership.INVITE
  45. and "third_party_invite" in event.content
  46. )
  47. # Check the sender's domain has signed the event
  48. if not event.signatures.get(sender_domain):
  49. # We allow invites via 3pid to have a sender from a different
  50. # HS, as the sender must match the sender of the original
  51. # 3pid invite. This is checked further down with the
  52. # other dedicated membership checks.
  53. if not is_invite_via_3pid:
  54. raise AuthError(403, "Event not signed by sender's server")
  55. if event.format_version in (EventFormatVersions.V1,):
  56. # Only older room versions have event IDs to check.
  57. event_id_domain = get_domain_from_id(event.event_id)
  58. # Check the origin domain has signed the event
  59. if not event.signatures.get(event_id_domain):
  60. raise AuthError(403, "Event not signed by sending server")
  61. if auth_events is None:
  62. # Oh, we don't know what the state of the room was, so we
  63. # are trusting that this is allowed (at least for now)
  64. logger.warn("Trusting event: %s", event.event_id)
  65. return
  66. if event.type == EventTypes.Create:
  67. sender_domain = get_domain_from_id(event.sender)
  68. room_id_domain = get_domain_from_id(event.room_id)
  69. if room_id_domain != sender_domain:
  70. raise AuthError(
  71. 403, "Creation event's room_id domain does not match sender's"
  72. )
  73. room_version = event.content.get("room_version", "1")
  74. if room_version not in KNOWN_ROOM_VERSIONS:
  75. raise AuthError(
  76. 403, "room appears to have unsupported version %s" % (room_version,)
  77. )
  78. # FIXME
  79. logger.debug("Allowing! %s", event)
  80. return
  81. creation_event = auth_events.get((EventTypes.Create, ""), None)
  82. if not creation_event:
  83. raise AuthError(403, "No create event in auth events")
  84. creating_domain = get_domain_from_id(event.room_id)
  85. originating_domain = get_domain_from_id(event.sender)
  86. if creating_domain != originating_domain:
  87. if not _can_federate(event, auth_events):
  88. raise AuthError(403, "This room has been marked as unfederatable.")
  89. # FIXME: Temp hack
  90. if event.type == EventTypes.Aliases:
  91. if not event.is_state():
  92. raise AuthError(403, "Alias event must be a state event")
  93. if not event.state_key:
  94. raise AuthError(403, "Alias event must have non-empty state_key")
  95. sender_domain = get_domain_from_id(event.sender)
  96. if event.state_key != sender_domain:
  97. raise AuthError(
  98. 403, "Alias event's state_key does not match sender's domain"
  99. )
  100. logger.debug("Allowing! %s", event)
  101. return
  102. if logger.isEnabledFor(logging.DEBUG):
  103. logger.debug("Auth events: %s", [a.event_id for a in auth_events.values()])
  104. if event.type == EventTypes.Member:
  105. _is_membership_change_allowed(event, auth_events)
  106. logger.debug("Allowing! %s", event)
  107. return
  108. _check_event_sender_in_room(event, auth_events)
  109. # Special case to allow m.room.third_party_invite events wherever
  110. # a user is allowed to issue invites. Fixes
  111. # https://github.com/vector-im/vector-web/issues/1208 hopefully
  112. if event.type == EventTypes.ThirdPartyInvite:
  113. user_level = get_user_power_level(event.user_id, auth_events)
  114. invite_level = _get_named_level(auth_events, "invite", 0)
  115. if user_level < invite_level:
  116. raise AuthError(403, "You don't have permission to invite users")
  117. else:
  118. logger.debug("Allowing! %s", event)
  119. return
  120. _can_send_event(event, auth_events)
  121. if event.type == EventTypes.PowerLevels:
  122. _check_power_levels(event, auth_events)
  123. if event.type == EventTypes.Redaction:
  124. check_redaction(room_version, event, auth_events)
  125. logger.debug("Allowing! %s", event)
  126. def _check_size_limits(event):
  127. def too_big(field):
  128. raise EventSizeError("%s too large" % (field,))
  129. if len(event.user_id) > 255:
  130. too_big("user_id")
  131. if len(event.room_id) > 255:
  132. too_big("room_id")
  133. if event.is_state() and len(event.state_key) > 255:
  134. too_big("state_key")
  135. if len(event.type) > 255:
  136. too_big("type")
  137. if len(event.event_id) > 255:
  138. too_big("event_id")
  139. if len(encode_canonical_json(event.get_pdu_json())) > 65536:
  140. too_big("event")
  141. def _can_federate(event, auth_events):
  142. creation_event = auth_events.get((EventTypes.Create, ""))
  143. return creation_event.content.get("m.federate", True) is True
  144. def _is_membership_change_allowed(event, auth_events):
  145. membership = event.content["membership"]
  146. # Check if this is the room creator joining:
  147. if len(event.prev_event_ids()) == 1 and Membership.JOIN == membership:
  148. # Get room creation event:
  149. key = (EventTypes.Create, "")
  150. create = auth_events.get(key)
  151. if create and event.prev_event_ids()[0] == create.event_id:
  152. if create.content["creator"] == event.state_key:
  153. return
  154. target_user_id = event.state_key
  155. creating_domain = get_domain_from_id(event.room_id)
  156. target_domain = get_domain_from_id(target_user_id)
  157. if creating_domain != target_domain:
  158. if not _can_federate(event, auth_events):
  159. raise AuthError(403, "This room has been marked as unfederatable.")
  160. # get info about the caller
  161. key = (EventTypes.Member, event.user_id)
  162. caller = auth_events.get(key)
  163. caller_in_room = caller and caller.membership == Membership.JOIN
  164. caller_invited = caller and caller.membership == Membership.INVITE
  165. # get info about the target
  166. key = (EventTypes.Member, target_user_id)
  167. target = auth_events.get(key)
  168. target_in_room = target and target.membership == Membership.JOIN
  169. target_banned = target and target.membership == Membership.BAN
  170. key = (EventTypes.JoinRules, "")
  171. join_rule_event = auth_events.get(key)
  172. if join_rule_event:
  173. join_rule = join_rule_event.content.get("join_rule", JoinRules.INVITE)
  174. else:
  175. join_rule = JoinRules.INVITE
  176. user_level = get_user_power_level(event.user_id, auth_events)
  177. target_level = get_user_power_level(target_user_id, auth_events)
  178. # FIXME (erikj): What should we do here as the default?
  179. ban_level = _get_named_level(auth_events, "ban", 50)
  180. logger.debug(
  181. "_is_membership_change_allowed: %s",
  182. {
  183. "caller_in_room": caller_in_room,
  184. "caller_invited": caller_invited,
  185. "target_banned": target_banned,
  186. "target_in_room": target_in_room,
  187. "membership": membership,
  188. "join_rule": join_rule,
  189. "target_user_id": target_user_id,
  190. "event.user_id": event.user_id,
  191. },
  192. )
  193. if Membership.INVITE == membership and "third_party_invite" in event.content:
  194. if not _verify_third_party_invite(event, auth_events):
  195. raise AuthError(403, "You are not invited to this room.")
  196. if target_banned:
  197. raise AuthError(403, "%s is banned from the room" % (target_user_id,))
  198. return
  199. if Membership.JOIN != membership:
  200. if (
  201. caller_invited
  202. and Membership.LEAVE == membership
  203. and target_user_id == event.user_id
  204. ):
  205. return
  206. if not caller_in_room: # caller isn't joined
  207. raise AuthError(403, "%s not in room %s." % (event.user_id, event.room_id))
  208. if Membership.INVITE == membership:
  209. # TODO (erikj): We should probably handle this more intelligently
  210. # PRIVATE join rules.
  211. # Invites are valid iff caller is in the room and target isn't.
  212. if target_banned:
  213. raise AuthError(403, "%s is banned from the room" % (target_user_id,))
  214. elif target_in_room: # the target is already in the room.
  215. raise AuthError(403, "%s is already in the room." % target_user_id)
  216. else:
  217. invite_level = _get_named_level(auth_events, "invite", 0)
  218. if user_level < invite_level:
  219. raise AuthError(403, "You don't have permission to invite users")
  220. elif Membership.JOIN == membership:
  221. # Joins are valid iff caller == target and they were:
  222. # invited: They are accepting the invitation
  223. # joined: It's a NOOP
  224. if event.user_id != target_user_id:
  225. raise AuthError(403, "Cannot force another user to join.")
  226. elif target_banned:
  227. raise AuthError(403, "You are banned from this room")
  228. elif join_rule == JoinRules.PUBLIC:
  229. pass
  230. elif join_rule == JoinRules.INVITE:
  231. if not caller_in_room and not caller_invited:
  232. raise AuthError(403, "You are not invited to this room.")
  233. else:
  234. # TODO (erikj): may_join list
  235. # TODO (erikj): private rooms
  236. raise AuthError(403, "You are not allowed to join this room")
  237. elif Membership.LEAVE == membership:
  238. # TODO (erikj): Implement kicks.
  239. if target_banned and user_level < ban_level:
  240. raise AuthError(403, "You cannot unban user %s." % (target_user_id,))
  241. elif target_user_id != event.user_id:
  242. kick_level = _get_named_level(auth_events, "kick", 50)
  243. if user_level < kick_level or user_level <= target_level:
  244. raise AuthError(403, "You cannot kick user %s." % target_user_id)
  245. elif Membership.BAN == membership:
  246. if user_level < ban_level or user_level <= target_level:
  247. raise AuthError(403, "You don't have permission to ban")
  248. else:
  249. raise AuthError(500, "Unknown membership %s" % membership)
  250. def _check_event_sender_in_room(event, auth_events):
  251. key = (EventTypes.Member, event.user_id)
  252. member_event = auth_events.get(key)
  253. return _check_joined_room(member_event, event.user_id, event.room_id)
  254. def _check_joined_room(member, user_id, room_id):
  255. if not member or member.membership != Membership.JOIN:
  256. raise AuthError(
  257. 403, "User %s not in room %s (%s)" % (user_id, room_id, repr(member))
  258. )
  259. def get_send_level(etype, state_key, power_levels_event):
  260. """Get the power level required to send an event of a given type
  261. The federation spec [1] refers to this as "Required Power Level".
  262. https://matrix.org/docs/spec/server_server/unstable.html#definitions
  263. Args:
  264. etype (str): type of event
  265. state_key (str|None): state_key of state event, or None if it is not
  266. a state event.
  267. power_levels_event (synapse.events.EventBase|None): power levels event
  268. in force at this point in the room
  269. Returns:
  270. int: power level required to send this event.
  271. """
  272. if power_levels_event:
  273. power_levels_content = power_levels_event.content
  274. else:
  275. power_levels_content = {}
  276. # see if we have a custom level for this event type
  277. send_level = power_levels_content.get("events", {}).get(etype)
  278. # otherwise, fall back to the state_default/events_default.
  279. if send_level is None:
  280. if state_key is not None:
  281. send_level = power_levels_content.get("state_default", 50)
  282. else:
  283. send_level = power_levels_content.get("events_default", 0)
  284. return int(send_level)
  285. def _can_send_event(event, auth_events):
  286. power_levels_event = _get_power_level_event(auth_events)
  287. send_level = get_send_level(event.type, event.get("state_key"), power_levels_event)
  288. user_level = get_user_power_level(event.user_id, auth_events)
  289. if user_level < send_level:
  290. raise AuthError(
  291. 403,
  292. "You don't have permission to post that to the room. "
  293. + "user_level (%d) < send_level (%d)" % (user_level, send_level),
  294. )
  295. # Check state_key
  296. if hasattr(event, "state_key"):
  297. if event.state_key.startswith("@"):
  298. if event.state_key != event.user_id:
  299. raise AuthError(403, "You are not allowed to set others state")
  300. return True
  301. def check_redaction(room_version, event, auth_events):
  302. """Check whether the event sender is allowed to redact the target event.
  303. Returns:
  304. True if the the sender is allowed to redact the target event if the
  305. target event was created by them.
  306. False if the sender is allowed to redact the target event with no
  307. further checks.
  308. Raises:
  309. AuthError if the event sender is definitely not allowed to redact
  310. the target event.
  311. """
  312. user_level = get_user_power_level(event.user_id, auth_events)
  313. redact_level = _get_named_level(auth_events, "redact", 50)
  314. if user_level >= redact_level:
  315. return False
  316. v = KNOWN_ROOM_VERSIONS.get(room_version)
  317. if not v:
  318. raise RuntimeError("Unrecognized room version %r" % (room_version,))
  319. if v.event_format == EventFormatVersions.V1:
  320. redacter_domain = get_domain_from_id(event.event_id)
  321. redactee_domain = get_domain_from_id(event.redacts)
  322. if redacter_domain == redactee_domain:
  323. return True
  324. else:
  325. event.internal_metadata.recheck_redaction = True
  326. return True
  327. raise AuthError(403, "You don't have permission to redact events")
  328. def _check_power_levels(event, auth_events):
  329. user_list = event.content.get("users", {})
  330. # Validate users
  331. for k, v in user_list.items():
  332. try:
  333. UserID.from_string(k)
  334. except Exception:
  335. raise SynapseError(400, "Not a valid user_id: %s" % (k,))
  336. try:
  337. int(v)
  338. except Exception:
  339. raise SynapseError(400, "Not a valid power level: %s" % (v,))
  340. key = (event.type, event.state_key)
  341. current_state = auth_events.get(key)
  342. if not current_state:
  343. return
  344. user_level = get_user_power_level(event.user_id, auth_events)
  345. # Check other levels:
  346. levels_to_check = [
  347. ("users_default", None),
  348. ("events_default", None),
  349. ("state_default", None),
  350. ("ban", None),
  351. ("redact", None),
  352. ("kick", None),
  353. ("invite", None),
  354. ]
  355. old_list = current_state.content.get("users", {})
  356. for user in set(list(old_list) + list(user_list)):
  357. levels_to_check.append((user, "users"))
  358. old_list = current_state.content.get("events", {})
  359. new_list = event.content.get("events", {})
  360. for ev_id in set(list(old_list) + list(new_list)):
  361. levels_to_check.append((ev_id, "events"))
  362. old_state = current_state.content
  363. new_state = event.content
  364. for level_to_check, dir in levels_to_check:
  365. old_loc = old_state
  366. new_loc = new_state
  367. if dir:
  368. old_loc = old_loc.get(dir, {})
  369. new_loc = new_loc.get(dir, {})
  370. if level_to_check in old_loc:
  371. old_level = int(old_loc[level_to_check])
  372. else:
  373. old_level = None
  374. if level_to_check in new_loc:
  375. new_level = int(new_loc[level_to_check])
  376. else:
  377. new_level = None
  378. if new_level is not None and old_level is not None:
  379. if new_level == old_level:
  380. continue
  381. if dir == "users" and level_to_check != event.user_id:
  382. if old_level == user_level:
  383. raise AuthError(
  384. 403,
  385. "You don't have permission to remove ops level equal "
  386. "to your own",
  387. )
  388. # Check if the old and new levels are greater than the user level
  389. # (if defined)
  390. old_level_too_big = old_level is not None and old_level > user_level
  391. new_level_too_big = new_level is not None and new_level > user_level
  392. if old_level_too_big or new_level_too_big:
  393. raise AuthError(
  394. 403,
  395. "You don't have permission to add ops level greater " "than your own",
  396. )
  397. def _get_power_level_event(auth_events):
  398. return auth_events.get((EventTypes.PowerLevels, ""))
  399. def get_user_power_level(user_id, auth_events):
  400. """Get a user's power level
  401. Args:
  402. user_id (str): user's id to look up in power_levels
  403. auth_events (dict[(str, str), synapse.events.EventBase]):
  404. state in force at this point in the room (or rather, a subset of
  405. it including at least the create event and power levels event.
  406. Returns:
  407. int: the user's power level in this room.
  408. """
  409. power_level_event = _get_power_level_event(auth_events)
  410. if power_level_event:
  411. level = power_level_event.content.get("users", {}).get(user_id)
  412. if not level:
  413. level = power_level_event.content.get("users_default", 0)
  414. if level is None:
  415. return 0
  416. else:
  417. return int(level)
  418. else:
  419. # if there is no power levels event, the creator gets 100 and everyone
  420. # else gets 0.
  421. # some things which call this don't pass the create event: hack around
  422. # that.
  423. key = (EventTypes.Create, "")
  424. create_event = auth_events.get(key)
  425. if create_event is not None and create_event.content["creator"] == user_id:
  426. return 100
  427. else:
  428. return 0
  429. def _get_named_level(auth_events, name, default):
  430. power_level_event = _get_power_level_event(auth_events)
  431. if not power_level_event:
  432. return default
  433. level = power_level_event.content.get(name, None)
  434. if level is not None:
  435. return int(level)
  436. else:
  437. return default
  438. def _verify_third_party_invite(event, auth_events):
  439. """
  440. Validates that the invite event is authorized by a previous third-party invite.
  441. Checks that the public key, and keyserver, match those in the third party invite,
  442. and that the invite event has a signature issued using that public key.
  443. Args:
  444. event: The m.room.member join event being validated.
  445. auth_events: All relevant previous context events which may be used
  446. for authorization decisions.
  447. Return:
  448. True if the event fulfills the expectations of a previous third party
  449. invite event.
  450. """
  451. if "third_party_invite" not in event.content:
  452. return False
  453. if "signed" not in event.content["third_party_invite"]:
  454. return False
  455. signed = event.content["third_party_invite"]["signed"]
  456. for key in {"mxid", "token"}:
  457. if key not in signed:
  458. return False
  459. token = signed["token"]
  460. invite_event = auth_events.get((EventTypes.ThirdPartyInvite, token))
  461. if not invite_event:
  462. return False
  463. if invite_event.sender != event.sender:
  464. return False
  465. if event.user_id != invite_event.user_id:
  466. return False
  467. if signed["mxid"] != event.state_key:
  468. return False
  469. if signed["token"] != token:
  470. return False
  471. for public_key_object in get_public_keys(invite_event):
  472. public_key = public_key_object["public_key"]
  473. try:
  474. for server, signature_block in signed["signatures"].items():
  475. for key_name, encoded_signature in signature_block.items():
  476. if not key_name.startswith("ed25519:"):
  477. continue
  478. verify_key = decode_verify_key_bytes(
  479. key_name, decode_base64(public_key)
  480. )
  481. verify_signed_json(signed, server, verify_key)
  482. # We got the public key from the invite, so we know that the
  483. # correct server signed the signed bundle.
  484. # The caller is responsible for checking that the signing
  485. # server has not revoked that public key.
  486. return True
  487. except (KeyError, SignatureVerifyException):
  488. continue
  489. return False
  490. def get_public_keys(invite_event):
  491. public_keys = []
  492. if "public_key" in invite_event.content:
  493. o = {"public_key": invite_event.content["public_key"]}
  494. if "key_validity_url" in invite_event.content:
  495. o["key_validity_url"] = invite_event.content["key_validity_url"]
  496. public_keys.append(o)
  497. public_keys.extend(invite_event.content.get("public_keys", []))
  498. return public_keys
  499. def auth_types_for_event(event):
  500. """Given an event, return a list of (EventType, StateKey) that may be
  501. needed to auth the event. The returned list may be a superset of what
  502. would actually be required depending on the full state of the room.
  503. Used to limit the number of events to fetch from the database to
  504. actually auth the event.
  505. """
  506. if event.type == EventTypes.Create:
  507. return []
  508. auth_types = [
  509. (EventTypes.PowerLevels, ""),
  510. (EventTypes.Member, event.sender),
  511. (EventTypes.Create, ""),
  512. ]
  513. if event.type == EventTypes.Member:
  514. membership = event.content["membership"]
  515. if membership in [Membership.JOIN, Membership.INVITE]:
  516. auth_types.append((EventTypes.JoinRules, ""))
  517. auth_types.append((EventTypes.Member, event.state_key))
  518. if membership == Membership.INVITE:
  519. if "third_party_invite" in event.content:
  520. key = (
  521. EventTypes.ThirdPartyInvite,
  522. event.content["third_party_invite"]["signed"]["token"],
  523. )
  524. auth_types.append(key)
  525. return auth_types