Exemple #1
0
def check_event_content_hash(event: EventBase,
                             hash_algorithm: Hasher = hashlib.sha256) -> bool:
    """Check whether the hash for this PDU matches the contents"""
    name, expected_hash = compute_content_hash(event.get_pdu_json(),
                                               hash_algorithm)
    logger.debug(
        "Verifying content hash on %s (expecting: %s)",
        event.event_id,
        encode_base64(expected_hash),
    )

    # some malformed events lack a 'hashes'. Protect against it being missing
    # or a weird type by basically treating it the same as an unhashed event.
    hashes = event.get("hashes")
    # nb it might be a frozendict or a dict
    if not isinstance(hashes, collections.abc.Mapping):
        raise SynapseError(400, "Malformed 'hashes': %s" % (type(hashes), ),
                           Codes.UNAUTHORIZED)

    if name not in hashes:
        raise SynapseError(
            400,
            "Algorithm %s not in hashes %s" % (name, list(hashes)),
            Codes.UNAUTHORIZED,
        )
    message_hash_base64 = hashes[name]
    try:
        message_hash_bytes = decode_base64(message_hash_base64)
    except Exception:
        raise SynapseError(400, "Invalid base64: %s" % (message_hash_base64, ),
                           Codes.UNAUTHORIZED)
    return message_hash_bytes == expected_hash
Exemple #2
0
 def on_new_room_event(
     self,
     event: EventBase,
     event_pos: PersistedEventPosition,
     max_room_stream_token: RoomStreamToken,
     extra_users: Collection[UserID] = [],
 ):
     """Unwraps event and calls `on_new_room_event_args`."""
     self.on_new_room_event_args(
         event_pos=event_pos,
         room_id=event.room_id,
         event_type=event.type,
         state_key=event.get("state_key"),
         membership=event.content.get("membership"),
         max_room_stream_token=max_room_stream_token,
         extra_users=extra_users,
     )
Exemple #3
0
def _can_send_event(event: EventBase, auth_events: StateMap[EventBase]) -> bool:
    power_levels_event = get_power_level_event(auth_events)

    send_level = get_send_level(event.type, event.get("state_key"), power_levels_event)
    user_level = get_user_power_level(event.user_id, auth_events)

    if user_level < send_level:
        raise AuthError(
            403,
            "You don't have permission to post that to the room. "
            + "user_level (%d) < send_level (%d)" % (user_level, send_level),
        )

    # Check state_key
    if hasattr(event, "state_key"):
        if event.state_key.startswith("@"):
            if event.state_key != event.user_id:
                raise AuthError(403, "You are not allowed to set others state")

    return True