serialization.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. # -*- coding: utf-8 -*-
  2. """Secure serializer."""
  3. from __future__ import absolute_import, unicode_literals
  4. from kombu.serialization import registry, dumps, loads
  5. from kombu.utils.encoding import bytes_to_str, str_to_bytes, ensure_bytes
  6. from celery.utils.serialization import b64encode, b64decode
  7. from .certificate import Certificate, FSCertStore
  8. from .key import PrivateKey
  9. from .utils import reraise_errors
  10. __all__ = ['SecureSerializer', 'register_auth']
  11. class SecureSerializer:
  12. def __init__(self, key=None, cert=None, cert_store=None,
  13. digest='sha1', serializer='json'):
  14. self._key = key
  15. self._cert = cert
  16. self._cert_store = cert_store
  17. self._digest = digest
  18. self._serializer = serializer
  19. def serialize(self, data):
  20. """serialize data structure into string"""
  21. assert self._key is not None
  22. assert self._cert is not None
  23. with reraise_errors('Unable to serialize: {0!r}', (Exception,)):
  24. content_type, content_encoding, body = dumps(
  25. bytes_to_str(data), serializer=self._serializer)
  26. # What we sign is the serialized body, not the body itself.
  27. # this way the receiver doesn't have to decode the contents
  28. # to verify the signature (and thus avoiding potential flaws
  29. # in the decoding step).
  30. body = ensure_bytes(body)
  31. return self._pack(body, content_type, content_encoding,
  32. signature=self._key.sign(body, self._digest),
  33. signer=self._cert.get_id())
  34. def deserialize(self, data):
  35. """deserialize data structure from string"""
  36. assert self._cert_store is not None
  37. with reraise_errors('Unable to deserialize: {0!r}', (Exception,)):
  38. payload = self._unpack(data)
  39. signature, signer, body = (payload['signature'],
  40. payload['signer'],
  41. payload['body'])
  42. self._cert_store[signer].verify(body, signature, self._digest)
  43. return loads(bytes_to_str(body), payload['content_type'],
  44. payload['content_encoding'], force=True)
  45. def _pack(self, body, content_type, content_encoding, signer, signature,
  46. sep=str_to_bytes('\x00\x01')):
  47. fields = sep.join(
  48. ensure_bytes(s) for s in [signer, signature, content_type,
  49. content_encoding, body]
  50. )
  51. return b64encode(fields)
  52. def _unpack(self, payload, sep=str_to_bytes('\x00\x01')):
  53. raw_payload = b64decode(ensure_bytes(payload))
  54. first_sep = raw_payload.find(sep)
  55. signer = raw_payload[:first_sep]
  56. signer_cert = self._cert_store[signer]
  57. sig_len = signer_cert._cert.get_pubkey().bits() >> 3
  58. signature = raw_payload[
  59. first_sep + len(sep):first_sep + len(sep) + sig_len
  60. ]
  61. end_of_sig = first_sep + len(sep) + sig_len + len(sep)
  62. v = raw_payload[end_of_sig:].split(sep)
  63. return {
  64. 'signer': signer,
  65. 'signature': signature,
  66. 'content_type': bytes_to_str(v[0]),
  67. 'content_encoding': bytes_to_str(v[1]),
  68. 'body': bytes_to_str(v[2]),
  69. }
  70. def register_auth(key=None, cert=None, store=None, digest='sha1',
  71. serializer='json'):
  72. """register security serializer"""
  73. s = SecureSerializer(key and PrivateKey(key),
  74. cert and Certificate(cert),
  75. store and FSCertStore(store),
  76. digest=digest, serializer=serializer)
  77. registry.register('auth', s.serialize, s.deserialize,
  78. content_type='application/data',
  79. content_encoding='utf-8')