Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

186 рядки
6.1 KiB

  1. #
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. # Copyright 2020 The Matrix.org Foundation C.I.C.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import collections.abc
  17. import hashlib
  18. import logging
  19. from typing import Any, Callable, Dict, Tuple
  20. from canonicaljson import encode_canonical_json
  21. from signedjson.sign import sign_json
  22. from signedjson.types import SigningKey
  23. from unpaddedbase64 import decode_base64, encode_base64
  24. from synapse.api.errors import Codes, SynapseError
  25. from synapse.api.room_versions import RoomVersion
  26. from synapse.events import EventBase
  27. from synapse.events.utils import prune_event, prune_event_dict
  28. from synapse.logging.opentracing import trace
  29. from synapse.types import JsonDict
  30. logger = logging.getLogger(__name__)
  31. Hasher = Callable[[bytes], "hashlib._Hash"]
  32. @trace
  33. def check_event_content_hash(
  34. event: EventBase, hash_algorithm: Hasher = hashlib.sha256
  35. ) -> bool:
  36. """Check whether the hash for this PDU matches the contents"""
  37. name, expected_hash = compute_content_hash(event.get_pdu_json(), hash_algorithm)
  38. logger.debug(
  39. "Verifying content hash on %s (expecting: %s)",
  40. event.event_id,
  41. encode_base64(expected_hash),
  42. )
  43. # some malformed events lack a 'hashes'. Protect against it being missing
  44. # or a weird type by basically treating it the same as an unhashed event.
  45. hashes = event.get("hashes")
  46. # nb it might be a immutabledict or a dict
  47. if not isinstance(hashes, collections.abc.Mapping):
  48. raise SynapseError(
  49. 400, "Malformed 'hashes': %s" % (type(hashes),), Codes.UNAUTHORIZED
  50. )
  51. if name not in hashes:
  52. raise SynapseError(
  53. 400,
  54. "Algorithm %s not in hashes %s" % (name, list(hashes)),
  55. Codes.UNAUTHORIZED,
  56. )
  57. message_hash_base64 = hashes[name]
  58. try:
  59. message_hash_bytes = decode_base64(message_hash_base64)
  60. except Exception:
  61. raise SynapseError(
  62. 400, "Invalid base64: %s" % (message_hash_base64,), Codes.UNAUTHORIZED
  63. )
  64. return message_hash_bytes == expected_hash
  65. def compute_content_hash(
  66. event_dict: Dict[str, Any], hash_algorithm: Hasher
  67. ) -> Tuple[str, bytes]:
  68. """Compute the content hash of an event, which is the hash of the
  69. unredacted event.
  70. Args:
  71. event_dict: The unredacted event as a dict
  72. hash_algorithm: A hasher from `hashlib`, e.g. hashlib.sha256, to use
  73. to hash the event
  74. Returns:
  75. A tuple of the name of hash and the hash as raw bytes.
  76. """
  77. event_dict = dict(event_dict)
  78. event_dict.pop("age_ts", None)
  79. event_dict.pop("unsigned", None)
  80. event_dict.pop("signatures", None)
  81. event_dict.pop("hashes", None)
  82. event_dict.pop("outlier", None)
  83. event_dict.pop("destinations", None)
  84. event_json_bytes = encode_canonical_json(event_dict)
  85. hashed = hash_algorithm(event_json_bytes)
  86. return hashed.name, hashed.digest()
  87. def compute_event_reference_hash(
  88. event: EventBase, hash_algorithm: Hasher = hashlib.sha256
  89. ) -> Tuple[str, bytes]:
  90. """Computes the event reference hash. This is the hash of the redacted
  91. event.
  92. Args:
  93. event
  94. hash_algorithm: A hasher from `hashlib`, e.g. hashlib.sha256, to use
  95. to hash the event
  96. Returns:
  97. A tuple of the name of hash and the hash as raw bytes.
  98. """
  99. tmp_event = prune_event(event)
  100. event_dict = tmp_event.get_pdu_json()
  101. event_dict.pop("signatures", None)
  102. event_dict.pop("age_ts", None)
  103. event_dict.pop("unsigned", None)
  104. event_json_bytes = encode_canonical_json(event_dict)
  105. hashed = hash_algorithm(event_json_bytes)
  106. return hashed.name, hashed.digest()
  107. def compute_event_signature(
  108. room_version: RoomVersion,
  109. event_dict: JsonDict,
  110. signature_name: str,
  111. signing_key: SigningKey,
  112. ) -> Dict[str, Dict[str, str]]:
  113. """Compute the signature of the event for the given name and key.
  114. Args:
  115. room_version: the version of the room that this event is in.
  116. (the room version determines the redaction algorithm and hence the
  117. json to be signed)
  118. event_dict: The event as a dict
  119. signature_name: The name of the entity signing the event
  120. (typically the server's hostname).
  121. signing_key: The key to sign with
  122. Returns:
  123. a dictionary in the same format of an event's signatures field.
  124. """
  125. redact_json = prune_event_dict(room_version, event_dict)
  126. redact_json.pop("age_ts", None)
  127. redact_json.pop("unsigned", None)
  128. if logger.isEnabledFor(logging.DEBUG):
  129. logger.debug("Signing event: %s", encode_canonical_json(redact_json))
  130. redact_json = sign_json(redact_json, signature_name, signing_key)
  131. if logger.isEnabledFor(logging.DEBUG):
  132. logger.debug("Signed event: %s", encode_canonical_json(redact_json))
  133. return redact_json["signatures"]
  134. def add_hashes_and_signatures(
  135. room_version: RoomVersion,
  136. event_dict: JsonDict,
  137. signature_name: str,
  138. signing_key: SigningKey,
  139. ) -> None:
  140. """Add content hash and sign the event
  141. Args:
  142. room_version: the version of the room this event is in
  143. event_dict: The event to add hashes to and sign
  144. signature_name: The name of the entity signing the event
  145. (typically the server's hostname).
  146. signing_key: The key to sign with
  147. """
  148. name, digest = compute_content_hash(event_dict, hash_algorithm=hashlib.sha256)
  149. event_dict.setdefault("hashes", {})[name] = encode_base64(digest)
  150. event_dict["signatures"] = compute_event_signature(
  151. room_version, event_dict, signature_name=signature_name, signing_key=signing_key
  152. )