event_signing.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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 hashlib
  16. import logging
  17. from canonicaljson import encode_canonical_json
  18. from signedjson.sign import sign_json
  19. from unpaddedbase64 import decode_base64, encode_base64
  20. from synapse.api.errors import Codes, SynapseError
  21. from synapse.events.utils import prune_event
  22. logger = logging.getLogger(__name__)
  23. def check_event_content_hash(event, hash_algorithm=hashlib.sha256):
  24. """Check whether the hash for this PDU matches the contents"""
  25. name, expected_hash = compute_content_hash(event, hash_algorithm)
  26. logger.debug("Expecting hash: %s", encode_base64(expected_hash))
  27. # some malformed events lack a 'hashes'. Protect against it being missing
  28. # or a weird type by basically treating it the same as an unhashed event.
  29. hashes = event.get("hashes")
  30. if not isinstance(hashes, dict):
  31. raise SynapseError(400, "Malformed 'hashes'", Codes.UNAUTHORIZED)
  32. if name not in hashes:
  33. raise SynapseError(
  34. 400,
  35. "Algorithm %s not in hashes %s" % (
  36. name, list(hashes),
  37. ),
  38. Codes.UNAUTHORIZED,
  39. )
  40. message_hash_base64 = hashes[name]
  41. try:
  42. message_hash_bytes = decode_base64(message_hash_base64)
  43. except Exception:
  44. raise SynapseError(
  45. 400,
  46. "Invalid base64: %s" % (message_hash_base64,),
  47. Codes.UNAUTHORIZED,
  48. )
  49. return message_hash_bytes == expected_hash
  50. def compute_content_hash(event, hash_algorithm):
  51. event_json = event.get_pdu_json()
  52. event_json.pop("age_ts", None)
  53. event_json.pop("unsigned", None)
  54. event_json.pop("signatures", None)
  55. event_json.pop("hashes", None)
  56. event_json.pop("outlier", None)
  57. event_json.pop("destinations", None)
  58. event_json_bytes = encode_canonical_json(event_json)
  59. hashed = hash_algorithm(event_json_bytes)
  60. return (hashed.name, hashed.digest())
  61. def compute_event_reference_hash(event, hash_algorithm=hashlib.sha256):
  62. tmp_event = prune_event(event)
  63. event_json = tmp_event.get_pdu_json()
  64. event_json.pop("signatures", None)
  65. event_json.pop("age_ts", None)
  66. event_json.pop("unsigned", None)
  67. event_json_bytes = encode_canonical_json(event_json)
  68. hashed = hash_algorithm(event_json_bytes)
  69. return (hashed.name, hashed.digest())
  70. def compute_event_signature(event, signature_name, signing_key):
  71. tmp_event = prune_event(event)
  72. redact_json = tmp_event.get_pdu_json()
  73. redact_json.pop("age_ts", None)
  74. redact_json.pop("unsigned", None)
  75. logger.debug("Signing event: %s", encode_canonical_json(redact_json))
  76. redact_json = sign_json(redact_json, signature_name, signing_key)
  77. logger.debug("Signed event: %s", encode_canonical_json(redact_json))
  78. return redact_json["signatures"]
  79. def add_hashes_and_signatures(event, signature_name, signing_key,
  80. hash_algorithm=hashlib.sha256):
  81. # if hasattr(event, "old_state_events"):
  82. # state_json_bytes = encode_canonical_json(
  83. # [e.event_id for e in event.old_state_events.values()]
  84. # )
  85. # hashed = hash_algorithm(state_json_bytes)
  86. # event.state_hash = {
  87. # hashed.name: encode_base64(hashed.digest())
  88. # }
  89. name, digest = compute_content_hash(event, hash_algorithm=hash_algorithm)
  90. if not hasattr(event, "hashes"):
  91. event.hashes = {}
  92. event.hashes[name] = encode_base64(digest)
  93. event.signatures = compute_event_signature(
  94. event,
  95. signature_name=signature_name,
  96. signing_key=signing_key,
  97. )