messaging.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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. from dataclasses import is_dataclass, asdict
  21. SIGNER = XMLSigner(method=methods.detached,
  22. c14n_algorithm="http://www.w3.org/2001/10/xml-exc-c14n#")
  23. VERIFIER = XMLVerifier()
  24. def parse_message(data, fingerprint=None, fingerprint_lookup=None):
  25. """
  26. Parse a message and distill its usable parts. Returns a message type and payload.
  27. """
  28. message_dict = xmltodict.parse(data, process_namespaces=True, namespaces=NAMESPACES)
  29. message_type, message_payload = message_dict['oadrPayload']['oadrSignedObject'].popitem()
  30. if 'ven_id' in message_payload:
  31. _validate_and_authenticate_message(data, message_dict, fingerprint, fingerprint_lookup)
  32. return message_type, normalize_dict(message_payload)
  33. def create_message(message_type, cert=None, key=None, passphrase=None, **message_payload):
  34. """
  35. Create and optionally sign an OpenADR message. Returns an XML string.
  36. """
  37. # If we supply the payload as dataclasses, convert them to dicts
  38. for k, v in message_payload.items():
  39. if isinstance(v, list):
  40. for i, item in enumerate(v):
  41. if is_dataclass(item):
  42. v[i] = asdict(item)
  43. elif is_dataclass(v):
  44. message_payload[k] = asdict(v)
  45. preflight_message(message_type, message_payload)
  46. signed_object = flatten_xml(TEMPLATES.get_template(f'{message_type}.xml').render(**message_payload))
  47. envelope = TEMPLATES.get_template('oadrPayload.xml')
  48. if cert and key:
  49. tree = etree.fromstring(signed_object)
  50. signature_tree = SIGNER.sign(tree,
  51. key=key,
  52. cert=cert,
  53. passphrase=ensure_bytes(passphrase),
  54. reference_uri="#oadrSignedObject",
  55. signature_properties=_create_replay_protect())
  56. signature = etree.tostring(signature_tree).decode('utf-8')
  57. else:
  58. signature = None
  59. msg = envelope.render(template=f'{message_type}',
  60. signature=signature,
  61. signed_object=signed_object)
  62. return msg
  63. def _validate_and_authenticate_message(data, message_dict, fingerprint=None, fingerprint_lookup=None):
  64. if not fingerprint and not fingerprint_lookup:
  65. return
  66. tree = etree.fromstring(ensure_bytes(data))
  67. cert = extract_pem_cert(tree)
  68. ven_id = tree.find('.//{http://docs.oasis-open.org/ns/energyinterop/201110}venID').text
  69. cert_fingerprint = certificate_fingerprint(cert)
  70. if not fingerprint:
  71. fingerprint = fingerprint_lookup(ven_id)
  72. if fingerprint != certificate_fingerprint(cert):
  73. raise ValueError("The fingerprint does not match")
  74. VERIFIER.verify(tree, x509_cert=ensure_bytes(cert), expect_references=2)
  75. _verify_replay_protect(message_dict)
  76. def _create_replay_protect():
  77. dt_element = Element("{http://openadr.org/oadr-2.0b/2012/07/xmldsig-properties}timestamp")
  78. dt_element.text = datetimeformat(datetime.now(timezone.utc))
  79. nonce_element = Element("{http://openadr.org/oadr-2.0b/2012/07/xmldsig-properties}nonce")
  80. nonce_element.text = uuid4().hex
  81. el = Element("{http://openadr.org/oadr-2.0b/2012/07/xmldsig-properties}ReplayProtect",
  82. nsmap={'dsp': 'http://openadr.org/oadr-2.0b/2012/07/xmldsig-properties'},
  83. attrib={'Id': 'myid', 'Target': '#mytarget'})
  84. el.append(dt_element)
  85. el.append(nonce_element)
  86. return el
  87. def _verify_replay_protect(message_dict):
  88. try:
  89. ts = message_dict['oadrPayload']['Signature']['Object']['SignatureProperties']['SignatureProperty']['ReplayProtect']['timestamp']
  90. nonce = message_dict['oadrPayload']['Signature']['Object']['SignatureProperties']['SignatureProperty']['ReplayProtect']['nonce']
  91. except KeyError:
  92. raise ValueError("Missing ReplayProtect")
  93. else:
  94. timestamp = datetime.strptime(ts, "%Y-%m-%dT%H:%M:%S.%f%z")
  95. if timestamp < datetime.now(timezone.utc) - REPLAY_PROTECT_MAX_TIME_DELTA:
  96. raise ValueError("Message is too old")
  97. elif (timestamp, nonce) in NONCE_CACHE:
  98. raise ValueError("This combination of timestamp and nonce was already used")
  99. _update_nonce_cache(timestamp, nonce)
  100. def _update_nonce_cache(timestamp, nonce):
  101. for timestamp, nonce in list(NONCE_CACHE):
  102. if timestamp < datetime.now(timezone.utc) - REPLAY_PROTECT_MAX_TIME_DELTA:
  103. NONCE_CACHE.remove((timestamp, nonce))
  104. NONCE_CACHE.add((timestamp, nonce))
  105. # Replay protect settings
  106. REPLAY_PROTECT_MAX_TIME_DELTA = timedelta(seconds=5)
  107. NONCE_CACHE = set()
  108. # Settings for jinja2
  109. TEMPLATES = Environment(loader=PackageLoader('openleadr', 'templates'))
  110. TEMPLATES.filters['datetimeformat'] = datetimeformat
  111. TEMPLATES.filters['timedeltaformat'] = timedeltaformat
  112. TEMPLATES.filters['booleanformat'] = booleanformat
  113. TEMPLATES.trim_blocks = True
  114. TEMPLATES.lstrip_blocks = True
  115. # Settings for xmltodict
  116. NAMESPACES = {
  117. 'http://docs.oasis-open.org/ns/energyinterop/201110': None,
  118. 'http://openadr.org/oadr-2.0b/2012/07': None,
  119. 'urn:ietf:params:xml:ns:icalendar-2.0': None,
  120. 'http://docs.oasis-open.org/ns/energyinterop/201110/payloads': None,
  121. 'http://docs.oasis-open.org/ns/emix/2011/06': None,
  122. 'urn:ietf:params:xml:ns:icalendar-2.0:stream': None,
  123. 'http://docs.oasis-open.org/ns/emix/2011/06/power': None,
  124. 'http://docs.oasis-open.org/ns/emix/2011/06/siscale': None,
  125. 'http://www.w3.org/2000/09/xmldsig#': None,
  126. 'http://openadr.org/oadr-2.0b/2012/07/xmldsig-properties': None
  127. }