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).
27 # pylint: disable-msg=C0103
29 # C0103: Invalid name, since pylint doesn't see that Dump points to a
30 # function and not a constant
36 from ganeti import errors
39 from hashlib import sha1
46 _RE_EOLSP = re.compile('[ \t]+$', re.MULTILINE)
49 def _GetJsonDumpers(_encoder_class=simplejson.JSONEncoder):
50 """Returns two JSON functions to serialize data.
52 @rtype: (callable, callable)
53 @return: The function to generate a compact form of JSON and another one to
54 generate a more readable, indented form of JSON (if supported)
57 plain_encoder = _encoder_class(sort_keys=True)
59 # Check whether the simplejson module supports indentation
61 indent_encoder = _encoder_class(indent=_JSON_INDENT, sort_keys=True)
63 # Indentation not supported
64 indent_encoder = plain_encoder
66 return (plain_encoder.encode, indent_encoder.encode)
69 (_DumpJson, _DumpJsonIndent) = _GetJsonDumpers()
72 def DumpJson(data, indent=True):
73 """Serialize a given object.
75 @param data: the data to serialize
76 @param indent: whether to indent output (depends on simplejson version)
78 @return: the string representation of data
86 txt = _RE_EOLSP.sub("", fn(data))
87 if not txt.endswith('\n'):
94 """Unserialize data from a string.
96 @param txt: the json-encoded form
98 @return: the original data
101 return simplejson.loads(txt)
104 def DumpSignedJson(data, key, salt=None, key_selector=None):
105 """Serialize a given object and authenticate it.
107 @param data: the data to serialize
108 @param key: shared hmac key
109 @param key_selector: name/id that identifies the key (in case there are
110 multiple keys in use, e.g. in a multi-cluster environment)
111 @return: the string representation of data signed by the hmac key
114 txt = DumpJson(data, indent=False)
122 signed_dict["key_selector"] = key_selector
123 message = salt + key_selector + txt
126 signed_dict["hmac"] = hmac.new(key, message,
129 return DumpJson(signed_dict, indent=False)
132 def LoadSignedJson(txt, key):
133 """Verify that a given message was signed with the given key, and load it.
135 @param txt: json-encoded hmac-signed message
136 @param key: the shared hmac key or a callable taking one argument (the key
137 selector), which returns the hmac key belonging to the key selector.
138 Typical usage is to pass a reference to the get method of a dict.
139 @rtype: tuple of original data, string
140 @return: original data, salt
141 @raises errors.SignatureError: if the message signature doesn't verify
144 signed_dict = LoadJson(txt)
145 if not isinstance(signed_dict, dict):
146 raise errors.SignatureError('Invalid external message')
148 msg = signed_dict['msg']
149 salt = signed_dict['salt']
150 hmac_sign = signed_dict['hmac']
152 raise errors.SignatureError('Invalid external message')
155 key_selector = signed_dict.get("key_selector", None)
156 hmac_key = key(key_selector)
158 raise errors.SignatureError("No key with key selector '%s' found" %
164 if hmac.new(hmac_key, salt + key_selector + msg,
165 sha1).hexdigest() != hmac_sign:
166 raise errors.SignatureError('Invalid Signature')
168 return LoadJson(msg), salt
173 DumpSigned = DumpSignedJson
174 LoadSigned = LoadSignedJson