You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

184 lines
6.0 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.types import JsonDict
  29. logger = logging.getLogger(__name__)
  30. Hasher = Callable[[bytes], "hashlib._Hash"]
  31. def check_event_content_hash(
  32. event: EventBase, hash_algorithm: Hasher = hashlib.sha256
  33. ) -> bool:
  34. """Check whether the hash for this PDU matches the contents"""
  35. name, expected_hash = compute_content_hash(event.get_pdu_json(), hash_algorithm)
  36. logger.debug(
  37. "Verifying content hash on %s (expecting: %s)",
  38. event.event_id,
  39. encode_base64(expected_hash),
  40. )
  41. # some malformed events lack a 'hashes'. Protect against it being missing
  42. # or a weird type by basically treating it the same as an unhashed event.
  43. hashes = event.get("hashes")
  44. # nb it might be a frozendict or a dict
  45. if not isinstance(hashes, collections.abc.Mapping):
  46. raise SynapseError(
  47. 400, "Malformed 'hashes': %s" % (type(hashes),), Codes.UNAUTHORIZED
  48. )
  49. if name not in hashes:
  50. raise SynapseError(
  51. 400,
  52. "Algorithm %s not in hashes %s" % (name, list(hashes)),
  53. Codes.UNAUTHORIZED,
  54. )
  55. message_hash_base64 = hashes[name]
  56. try:
  57. message_hash_bytes = decode_base64(message_hash_base64)
  58. except Exception:
  59. raise SynapseError(
  60. 400, "Invalid base64: %s" % (message_hash_base64,), Codes.UNAUTHORIZED
  61. )
  62. return message_hash_bytes == expected_hash
  63. def compute_content_hash(
  64. event_dict: Dict[str, Any], hash_algorithm: Hasher
  65. ) -> Tuple[str, bytes]:
  66. """Compute the content hash of an event, which is the hash of the
  67. unredacted event.
  68. Args:
  69. event_dict: The unredacted event as a dict
  70. hash_algorithm: A hasher from `hashlib`, e.g. hashlib.sha256, to use
  71. to hash the event
  72. Returns:
  73. A tuple of the name of hash and the hash as raw bytes.
  74. """
  75. event_dict = dict(event_dict)
  76. event_dict.pop("age_ts", None)
  77. event_dict.pop("unsigned", None)
  78. event_dict.pop("signatures", None)
  79. event_dict.pop("hashes", None)
  80. event_dict.pop("outlier", None)
  81. event_dict.pop("destinations", None)
  82. event_json_bytes = encode_canonical_json(event_dict)
  83. hashed = hash_algorithm(event_json_bytes)
  84. return hashed.name, hashed.digest()
  85. def compute_event_reference_hash(
  86. event, hash_algorithm: Hasher = hashlib.sha256
  87. ) -> Tuple[str, bytes]:
  88. """Computes the event reference hash. This is the hash of the redacted
  89. event.
  90. Args:
  91. event
  92. hash_algorithm: A hasher from `hashlib`, e.g. hashlib.sha256, to use
  93. to hash the event
  94. Returns:
  95. A tuple of the name of hash and the hash as raw bytes.
  96. """
  97. tmp_event = prune_event(event)
  98. event_dict = tmp_event.get_pdu_json()
  99. event_dict.pop("signatures", None)
  100. event_dict.pop("age_ts", None)
  101. event_dict.pop("unsigned", None)
  102. event_json_bytes = encode_canonical_json(event_dict)
  103. hashed = hash_algorithm(event_json_bytes)
  104. return hashed.name, hashed.digest()
  105. def compute_event_signature(
  106. room_version: RoomVersion,
  107. event_dict: JsonDict,
  108. signature_name: str,
  109. signing_key: SigningKey,
  110. ) -> Dict[str, Dict[str, str]]:
  111. """Compute the signature of the event for the given name and key.
  112. Args:
  113. room_version: the version of the room that this event is in.
  114. (the room version determines the redaction algorithm and hence the
  115. json to be signed)
  116. event_dict: The event as a dict
  117. signature_name: The name of the entity signing the event
  118. (typically the server's hostname).
  119. signing_key: The key to sign with
  120. Returns:
  121. a dictionary in the same format of an event's signatures field.
  122. """
  123. redact_json = prune_event_dict(room_version, event_dict)
  124. redact_json.pop("age_ts", None)
  125. redact_json.pop("unsigned", None)
  126. if logger.isEnabledFor(logging.DEBUG):
  127. logger.debug("Signing event: %s", encode_canonical_json(redact_json))
  128. redact_json = sign_json(redact_json, signature_name, signing_key)
  129. if logger.isEnabledFor(logging.DEBUG):
  130. logger.debug("Signed event: %s", encode_canonical_json(redact_json))
  131. return redact_json["signatures"]
  132. def add_hashes_and_signatures(
  133. room_version: RoomVersion,
  134. event_dict: JsonDict,
  135. signature_name: str,
  136. signing_key: SigningKey,
  137. ) -> None:
  138. """Add content hash and sign the event
  139. Args:
  140. room_version: the version of the room this event is in
  141. event_dict: The event to add hashes to and sign
  142. signature_name: The name of the entity signing the event
  143. (typically the server's hostname).
  144. signing_key: The key to sign with
  145. """
  146. name, digest = compute_content_hash(event_dict, hash_algorithm=hashlib.sha256)
  147. event_dict.setdefault("hashes", {})[name] = encode_base64(digest)
  148. event_dict["signatures"] = compute_event_signature(
  149. room_version, event_dict, signature_name=signature_name, signing_key=signing_key
  150. )