4 # Copyright (C) 2007, 2008 Google Inc.
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21 """Serializer abstraction module
23 This module introduces a simple abstraction over the serialization
24 backend (currently json).
32 from ganeti import errors
35 from hashlib import sha1
42 _RE_EOLSP = re.compile('[ \t]+$', re.MULTILINE)
45 def _GetJsonDumpers():
46 """Returns two JSON functions to serialize data.
48 @rtype: (callable, callable)
49 @return: The function to generate a compact form of JSON and another one to
50 generate a more readable, indented form of JSON (if supported)
53 plain_dump = simplejson.dumps
55 # Check whether the simplejson module supports indentation
57 simplejson.dumps(1, indent=_JSON_INDENT)
59 # Indentation not supported
60 indent_dump = plain_dump
62 # Indentation supported
63 indent_dump = lambda data: simplejson.dumps(data, indent=_JSON_INDENT)
65 assert callable(plain_dump)
66 assert callable(indent_dump)
68 return (plain_dump, indent_dump)
71 (_DumpJson, _DumpJsonIndent) = _GetJsonDumpers()
74 def DumpJson(data, indent=True):
75 """Serialize a given object.
77 @param data: the data to serialize
78 @param indent: whether to indent output (depends on simplejson version)
80 @return: the string representation of data
88 txt = _RE_EOLSP.sub("", fn(data))
89 if not txt.endswith('\n'):
96 """Unserialize data from a string.
98 @param txt: the json-encoded form
100 @return: the original data
103 return simplejson.loads(txt)
106 def DumpSignedJson(data, key, salt=None):
107 """Serialize a given object and authenticate it.
109 @param data: the data to serialize
110 @param key: shared hmac key
111 @return: the string representation of data signed by the hmac key
114 txt = DumpJson(data, indent=False)
120 'hmac': hmac.new(key, salt + txt, sha1).hexdigest(),
122 return DumpJson(signed_dict, indent=False)
125 def LoadSignedJson(txt, key):
126 """Verify that a given message was signed with the given key, and load it.
128 @param txt: json-encoded hmac-signed message
129 @param key: shared hmac key
130 @rtype: tuple of original data, string
131 @return: original data, salt
132 @raises errors.SignatureError: if the message signature doesn't verify
135 signed_dict = LoadJson(txt)
136 if not isinstance(signed_dict, dict):
137 raise errors.SignatureError('Invalid external message')
139 msg = signed_dict['msg']
140 salt = signed_dict['salt']
141 hmac_sign = signed_dict['hmac']
143 raise errors.SignatureError('Invalid external message')
145 if hmac.new(key, salt + msg, sha1).hexdigest() != hmac_sign:
146 raise errors.SignatureError('Invalid Signature')
148 return LoadJson(msg), salt
153 DumpSigned = DumpSignedJson
154 LoadSigned = LoadSignedJson