server_key_resource.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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.sign import sign_json
  18. from unpaddedbase64 import encode_base64
  19. from OpenSSL import crypto
  20. from twisted.web.resource import Resource
  21. from synapse.http.server import respond_with_json_bytes
  22. logger = logging.getLogger(__name__)
  23. class LocalKey(Resource):
  24. """HTTP resource containing encoding the TLS X.509 certificate and NACL
  25. signature verification keys for this server::
  26. GET /key HTTP/1.1
  27. HTTP/1.1 200 OK
  28. Content-Type: application/json
  29. {
  30. "server_name": "this.server.example.com"
  31. "verify_keys": {
  32. "algorithm:version": # base64 encoded NACL verification key.
  33. },
  34. "tls_certificate": # base64 ASN.1 DER encoded X.509 tls cert.
  35. "signatures": {
  36. "this.server.example.com": {
  37. "algorithm:version": # NACL signature for this server.
  38. }
  39. }
  40. }
  41. """
  42. def __init__(self, hs):
  43. self.response_body = encode_canonical_json(
  44. self.response_json_object(hs.config)
  45. )
  46. Resource.__init__(self)
  47. @staticmethod
  48. def response_json_object(server_config):
  49. verify_keys = {}
  50. for key in server_config.signing_key:
  51. verify_key_bytes = key.verify_key.encode()
  52. key_id = "%s:%s" % (key.alg, key.version)
  53. verify_keys[key_id] = encode_base64(verify_key_bytes)
  54. x509_certificate_bytes = crypto.dump_certificate(
  55. crypto.FILETYPE_ASN1,
  56. server_config.tls_certificate
  57. )
  58. json_object = {
  59. u"server_name": server_config.server_name,
  60. u"verify_keys": verify_keys,
  61. u"tls_certificate": encode_base64(x509_certificate_bytes)
  62. }
  63. for key in server_config.signing_key:
  64. json_object = sign_json(
  65. json_object,
  66. server_config.server_name,
  67. key,
  68. )
  69. return json_object
  70. def render_GET(self, request):
  71. return respond_with_json_bytes(
  72. request, 200, self.response_body,
  73. )
  74. def getChild(self, name, request):
  75. if name == b'':
  76. return self