token.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. #!/usr/bin/env python3
  2. # SPDX-FileCopyrightText: 2012-2023 MOD Audio UG
  3. # SPDX-License-Identifier: AGPL-3.0-or-later
  4. import json
  5. import base64
  6. from mod.communication import crypto, device
  7. def create_token_message(nonce: str):
  8. signature = crypto.sign_message_sha1(device.get_device_key(), nonce)
  9. data = json.dumps({
  10. 'nonce': nonce,
  11. 'device_tag': device.get_tag(),
  12. 'device_uid': device.get_uid(),
  13. 'image_version': device.get_image_version(),
  14. 'signature': base64.encodebytes(signature).decode(),
  15. })
  16. encrypted = crypto.encrypt(device.get_server_key(), data)
  17. encoded = base64.encodebytes(encrypted)
  18. return {'message': encoded.decode()}
  19. def decode_and_decrypt(message: str):
  20. data = json.loads(message)
  21. encrypted = base64.decodebytes(data['message'].encode())
  22. token = crypto.decrypt(device.get_device_key(), encrypted)
  23. # verify signature on newer versions
  24. jwt_payload = json.loads(base64.decodebytes((token.split('.')[1] + '===').encode()).decode())
  25. version = [int(i) for i in jwt_payload.get('version', '2.2.2').split('.')]
  26. if version >= [2, 3, 2]:
  27. signature = data.get('signature', None).strip()
  28. if not signature or not crypto.verify_signature(device.get_server_key(), data['message'], base64.decodebytes(signature.encode())):
  29. raise Exception('Server signature verification failed')
  30. return token