serialization.py 3.9 KB

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