messaging.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  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, cert=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 cert:
  30. tree = etree.fromstring(ensure_bytes(data))
  31. VERIFIER.verify(tree, x509_cert=cert, expect_references=2)
  32. _verify_replay_protect(message_dict)
  33. return message_type, normalize_dict(message_payload)
  34. def create_message(message_type, cert=None, key=None, passphrase=None, **message_payload):
  35. """
  36. Create and optionally sign an OpenADR message. Returns an XML string.
  37. """
  38. preflight_message(message_type, message_payload)
  39. signed_object = flatten_xml(TEMPLATES.get_template(f'{message_type}.xml').render(**message_payload))
  40. envelope = TEMPLATES.get_template('oadrPayload.xml')
  41. if cert and key:
  42. tree = etree.fromstring(signed_object)
  43. signature_tree = SIGNER.sign(tree,
  44. key=key,
  45. cert=cert,
  46. passphrase=ensure_bytes(passphrase),
  47. reference_uri="#oadrSignedObject",
  48. signature_properties=_create_replay_protect())
  49. signature = etree.tostring(signature_tree).decode('utf-8')
  50. else:
  51. signature = None
  52. msg = envelope.render(template=f'{message_type}',
  53. signature=signature,
  54. signed_object=signed_object)
  55. return msg
  56. def _create_replay_protect():
  57. dt_element = Element("{http://openadr.org/oadr-2.0b/2012/07/xmldsig-properties}timestamp")
  58. dt_element.text = datetimeformat(datetime.now(timezone.utc))
  59. nonce_element = Element("{http://openadr.org/oadr-2.0b/2012/07/xmldsig-properties}nonce")
  60. nonce_element.text = uuid4().hex
  61. el = Element("{http://openadr.org/oadr-2.0b/2012/07/xmldsig-properties}ReplayProtect",
  62. nsmap={'dsp': 'http://openadr.org/oadr-2.0b/2012/07/xmldsig-properties'},
  63. attrib={'Id': 'myid', 'Target': '#mytarget'})
  64. el.append(dt_element)
  65. el.append(nonce_element)
  66. return el
  67. def _verify_replay_protect(message_dict):
  68. try:
  69. ts = message_dict['oadrPayload']['Signature']['Object']['SignatureProperties']['SignatureProperty']['ReplayProtect']['timestamp']
  70. nonce = message_dict['oadrPayload']['Signature']['Object']['SignatureProperties']['SignatureProperty']['ReplayProtect']['nonce']
  71. except KeyError:
  72. raise ValueError("Missing ReplayProtect")
  73. else:
  74. timestamp = datetime.strptime(ts, "%Y-%m-%dT%H:%M:%S.%f%z")
  75. if timestamp < datetime.now(timezone.utc) - REPLAY_PROTECT_MAX_TIME_DELTA:
  76. raise ValueError("Message is too old")
  77. elif (timestamp, nonce) in NONCE_CACHE:
  78. raise ValueError("This combination of timestamp and nonce was already used")
  79. _update_nonce_cache(timestamp, nonce)
  80. def _update_nonce_cache(timestamp, nonce):
  81. for timestamp, nonce in list(NONCE_CACHE):
  82. if timestamp < datetime.now(timezone.utc) - REPLAY_PROTECT_MAX_TIME_DELTA:
  83. NONCE_CACHE.remove((timestamp, nonce))
  84. NONCE_CACHE.add((timestamp, nonce))
  85. # Replay protect settings
  86. REPLAY_PROTECT_MAX_TIME_DELTA = timedelta(seconds=5)
  87. NONCE_CACHE = set()
  88. # Settings for jinja2
  89. TEMPLATES = Environment(loader=PackageLoader('pyopenadr', 'templates'))
  90. TEMPLATES.filters['datetimeformat'] = datetimeformat
  91. TEMPLATES.filters['timedeltaformat'] = timedeltaformat
  92. TEMPLATES.filters['booleanformat'] = booleanformat
  93. TEMPLATES.trim_blocks = True
  94. TEMPLATES.lstrip_blocks = True
  95. # Settings for xmltodict
  96. NAMESPACES = {
  97. 'http://docs.oasis-open.org/ns/energyinterop/201110': None,
  98. 'http://openadr.org/oadr-2.0b/2012/07': None,
  99. 'urn:ietf:params:xml:ns:icalendar-2.0': None,
  100. 'http://docs.oasis-open.org/ns/energyinterop/201110/payloads': None,
  101. 'http://docs.oasis-open.org/ns/emix/2011/06': None,
  102. 'urn:ietf:params:xml:ns:icalendar-2.0:stream': None,
  103. 'http://docs.oasis-open.org/ns/emix/2011/06/power': None,
  104. 'http://docs.oasis-open.org/ns/emix/2011/06/siscale': None,
  105. 'http://www.w3.org/2000/09/xmldsig#': None,
  106. 'http://openadr.org/oadr-2.0b/2012/07/xmldsig-properties': None
  107. }