serialization.py 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. from __future__ import absolute_import
  2. import base64
  3. from kombu.serialization import registry, encode, decode
  4. from ..exceptions import SecurityError
  5. from ..utils.encoding import bytes_to_str, str_to_bytes
  6. from .certificate import Certificate, FSCertStore
  7. from .key import PrivateKey
  8. def b64encode(s):
  9. return bytes_to_str(base64.b64encode(str_to_bytes(s)))
  10. def b64decode(s):
  11. return base64.b64decode(str_to_bytes(s))
  12. class SecureSerializer(object):
  13. def __init__(self, key=None, cert=None, cert_store=None,
  14. digest="sha1", serializer="json"):
  15. self._key = key
  16. self._cert = cert
  17. self._cert_store = cert_store
  18. self._digest = digest
  19. self._serializer = serializer
  20. def serialize(self, data):
  21. """serialize data structure into string"""
  22. assert self._key is not None
  23. assert self._cert is not None
  24. try:
  25. content_type, content_encoding, body = encode(
  26. data, serializer=self._serializer)
  27. # What we sign is the serialized body, not the body itself.
  28. # this way the receiver doesn't have to decode the contents
  29. # to verify the signature (and thus avoiding potential flaws
  30. # in the decoding step).
  31. return self._pack(body, content_type, content_encoding,
  32. signature=self._key.sign(body, self._digest),
  33. signer=self._cert.get_id())
  34. except Exception, exc:
  35. raise SecurityError("Unable to serialize: %r" % (exc, ))
  36. def deserialize(self, data):
  37. """deserialize data structure from string"""
  38. assert self._cert_store is not None
  39. try:
  40. payload = self._unpack(data)
  41. signature, signer, body = (payload["signature"],
  42. payload["signer"],
  43. payload["body"])
  44. self._cert_store[signer].verify(body,
  45. signature, self._digest)
  46. except Exception, exc:
  47. raise SecurityError("Unable to deserialize: %r" % (exc, ))
  48. return decode(body, payload["content_type"],
  49. payload["content_encoding"], force=True)
  50. def _pack(self, body, content_type, content_encoding, signer, signature,
  51. sep='\x00\x01'):
  52. return b64encode(sep.join([signer, signature,
  53. content_type, content_encoding, body]))
  54. def _unpack(self, payload, sep='\x00\x01',
  55. fields=("signer", "signature", "content_type",
  56. "content_encoding", "body")):
  57. return dict(zip(fields, b64decode(payload).split(sep)))
  58. def register_auth(key=None, cert=None, store=None, digest="sha1",
  59. serializer="json"):
  60. """register security serializer"""
  61. s = SecureSerializer(key and PrivateKey(key),
  62. cert and Certificate(cert),
  63. store and FSCertStore(store),
  64. digest=digest, serializer=serializer)
  65. registry.register("auth", s.serialize, s.deserialize,
  66. content_type="application/data",
  67. content_encoding="utf-8")