messaging.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. # SPDX-License-Identifier: Apache-2.0
  2. # Copyright 2020 Contributors to OpenLEADR
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS,
  9. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. # See the License for the specific language governing permissions and
  11. # limitations under the License.
  12. from lxml import etree
  13. import xmltodict
  14. from jinja2 import Environment, PackageLoader
  15. from signxml import XMLSigner, XMLVerifier, methods
  16. from uuid import uuid4
  17. from lxml.etree import Element
  18. from .utils import *
  19. from .preflight import preflight_message
  20. SIGNER = XMLSigner(method=methods.detached,
  21. c14n_algorithm="http://www.w3.org/2001/10/xml-exc-c14n#")
  22. VERIFIER = XMLVerifier()
  23. def parse_message(data, fingerprint=None, fingerprint_lookup=None):
  24. """
  25. Parse a message and distill its usable parts. Returns a message type and payload.
  26. """
  27. message_dict = xmltodict.parse(data, process_namespaces=True, namespaces=NAMESPACES)
  28. message_type, message_payload = message_dict['oadrPayload']['oadrSignedObject'].popitem()
  29. if 'ven_id' in message_payload:
  30. validate_and_authenticate_message(data, message_dict, fingerprint, fingerprint_lookup)
  31. return message_type, normalize_dict(message_payload)
  32. def create_message(message_type, cert=None, key=None, passphrase=None, **message_payload):
  33. """
  34. Create and optionally sign an OpenADR message. Returns an XML string.
  35. """
  36. preflight_message(message_type, message_payload)
  37. signed_object = flatten_xml(TEMPLATES.get_template(f'{message_type}.xml').render(**message_payload))
  38. envelope = TEMPLATES.get_template('oadrPayload.xml')
  39. if cert and key:
  40. tree = etree.fromstring(signed_object)
  41. signature_tree = SIGNER.sign(tree,
  42. key=key,
  43. cert=cert,
  44. passphrase=ensure_bytes(passphrase),
  45. reference_uri="#oadrSignedObject",
  46. signature_properties=_create_replay_protect())
  47. signature = etree.tostring(signature_tree).decode('utf-8')
  48. else:
  49. signature = None
  50. msg = envelope.render(template=f'{message_type}',
  51. signature=signature,
  52. signed_object=signed_object)
  53. return msg
  54. def validate_and_authenticate_message(data, message_dict, fingerprint=None, fingerprint_lookup=None):
  55. if not fingerprint and not fingerprint_lookup:
  56. return
  57. tree = etree.fromstring(ensure_bytes(data))
  58. cert = extract_pem_cert(tree)
  59. ven_id = tree.find('.//{http://docs.oasis-open.org/ns/energyinterop/201110}venID').text
  60. cert_fingerprint = certificate_fingerprint(cert)
  61. if not fingerprint:
  62. fingerprint = fingerprint_lookup(ven_id)
  63. if fingerprint != certificate_fingerprint(cert):
  64. raise ValueError("The fingerprint does not match")
  65. VERIFIER.verify(tree, x509_cert=ensure_bytes(cert), expect_references=2)
  66. _verify_replay_protect(message_dict)
  67. def _create_replay_protect():
  68. dt_element = Element("{http://openadr.org/oadr-2.0b/2012/07/xmldsig-properties}timestamp")
  69. dt_element.text = datetimeformat(datetime.now(timezone.utc))
  70. nonce_element = Element("{http://openadr.org/oadr-2.0b/2012/07/xmldsig-properties}nonce")
  71. nonce_element.text = uuid4().hex
  72. el = Element("{http://openadr.org/oadr-2.0b/2012/07/xmldsig-properties}ReplayProtect",
  73. nsmap={'dsp': 'http://openadr.org/oadr-2.0b/2012/07/xmldsig-properties'},
  74. attrib={'Id': 'myid', 'Target': '#mytarget'})
  75. el.append(dt_element)
  76. el.append(nonce_element)
  77. return el
  78. def _verify_replay_protect(message_dict):
  79. try:
  80. ts = message_dict['oadrPayload']['Signature']['Object']['SignatureProperties']['SignatureProperty']['ReplayProtect']['timestamp']
  81. nonce = message_dict['oadrPayload']['Signature']['Object']['SignatureProperties']['SignatureProperty']['ReplayProtect']['nonce']
  82. except KeyError:
  83. raise ValueError("Missing ReplayProtect")
  84. else:
  85. timestamp = datetime.strptime(ts, "%Y-%m-%dT%H:%M:%S.%f%z")
  86. if timestamp < datetime.now(timezone.utc) - REPLAY_PROTECT_MAX_TIME_DELTA:
  87. raise ValueError("Message is too old")
  88. elif (timestamp, nonce) in NONCE_CACHE:
  89. raise ValueError("This combination of timestamp and nonce was already used")
  90. _update_nonce_cache(timestamp, nonce)
  91. def _update_nonce_cache(timestamp, nonce):
  92. for timestamp, nonce in list(NONCE_CACHE):
  93. if timestamp < datetime.now(timezone.utc) - REPLAY_PROTECT_MAX_TIME_DELTA:
  94. NONCE_CACHE.remove((timestamp, nonce))
  95. NONCE_CACHE.add((timestamp, nonce))
  96. # Replay protect settings
  97. REPLAY_PROTECT_MAX_TIME_DELTA = timedelta(seconds=5)
  98. NONCE_CACHE = set()
  99. # Settings for jinja2
  100. TEMPLATES = Environment(loader=PackageLoader('openleadr', 'templates'))
  101. TEMPLATES.filters['datetimeformat'] = datetimeformat
  102. TEMPLATES.filters['timedeltaformat'] = timedeltaformat
  103. TEMPLATES.filters['booleanformat'] = booleanformat
  104. TEMPLATES.trim_blocks = True
  105. TEMPLATES.lstrip_blocks = True
  106. # Settings for xmltodict
  107. NAMESPACES = {
  108. 'http://docs.oasis-open.org/ns/energyinterop/201110': None,
  109. 'http://openadr.org/oadr-2.0b/2012/07': None,
  110. 'urn:ietf:params:xml:ns:icalendar-2.0': None,
  111. 'http://docs.oasis-open.org/ns/energyinterop/201110/payloads': None,
  112. 'http://docs.oasis-open.org/ns/emix/2011/06': None,
  113. 'urn:ietf:params:xml:ns:icalendar-2.0:stream': None,
  114. 'http://docs.oasis-open.org/ns/emix/2011/06/power': None,
  115. 'http://docs.oasis-open.org/ns/emix/2011/06/siscale': None,
  116. 'http://www.w3.org/2000/09/xmldsig#': None,
  117. 'http://openadr.org/oadr-2.0b/2012/07/xmldsig-properties': None
  118. }