root / lib / serializer.py @ fd0351ae
History | View | Annotate | Download (5.3 kB)
1 |
#
|
---|---|
2 |
#
|
3 |
|
4 |
# Copyright (C) 2007, 2008 Google Inc.
|
5 |
#
|
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.
|
10 |
#
|
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.
|
15 |
#
|
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
|
19 |
# 02110-1301, USA.
|
20 |
|
21 |
"""Serializer abstraction module
|
22 |
|
23 |
This module introduces a simple abstraction over the serialization
|
24 |
backend (currently json).
|
25 |
|
26 |
"""
|
27 |
# pylint: disable=C0103
|
28 |
|
29 |
# C0103: Invalid name, since pylint doesn't see that Dump points to a
|
30 |
# function and not a constant
|
31 |
|
32 |
_OLD_SIMPLEJSON = False
|
33 |
|
34 |
try:
|
35 |
import json |
36 |
except ImportError: |
37 |
# The "json" module was only added in Python 2.6. Earlier versions must use
|
38 |
# the separate "simplejson" module.
|
39 |
import simplejson as json |
40 |
_OLD_SIMPLEJSON = True
|
41 |
|
42 |
import re |
43 |
import logging |
44 |
|
45 |
from ganeti import errors |
46 |
from ganeti import utils |
47 |
|
48 |
|
49 |
_JSON_INDENT = 2
|
50 |
|
51 |
_RE_EOLSP = re.compile("[ \t]+$", re.MULTILINE)
|
52 |
|
53 |
|
54 |
class _CustomJsonEncoder(json.JSONEncoder): |
55 |
if __debug__ and not _OLD_SIMPLEJSON: |
56 |
try:
|
57 |
_orig_fn = json.JSONEncoder._iterencode_dict |
58 |
except AttributeError: |
59 |
raise Exception("Can't override JSONEncoder's '_iterencode_dict'") |
60 |
else:
|
61 |
def _iterencode_dict(self, data, *args, **kwargs): |
62 |
for key in data.keys(): |
63 |
if not (key is None or isinstance(key, (basestring, bool))): |
64 |
raise ValueError("Key '%s' is of disallowed type '%s'" % |
65 |
(key, type(key)))
|
66 |
|
67 |
return self._orig_fn(data, *args, **kwargs) |
68 |
|
69 |
|
70 |
def _GetJsonDumpers(_encoder_class=_CustomJsonEncoder): |
71 |
"""Returns two JSON functions to serialize data.
|
72 |
|
73 |
@rtype: (callable, callable)
|
74 |
@return: The function to generate a compact form of JSON and another one to
|
75 |
generate a more readable, indented form of JSON (if supported)
|
76 |
|
77 |
"""
|
78 |
plain_encoder = _encoder_class(sort_keys=True)
|
79 |
|
80 |
# Check whether the simplejson module supports indentation
|
81 |
try:
|
82 |
indent_encoder = _encoder_class(indent=_JSON_INDENT, sort_keys=True)
|
83 |
except TypeError: |
84 |
# Indentation not supported
|
85 |
indent_encoder = plain_encoder |
86 |
|
87 |
return (plain_encoder.encode, indent_encoder.encode)
|
88 |
|
89 |
|
90 |
(_DumpJson, _DumpJsonIndent) = _GetJsonDumpers() |
91 |
|
92 |
|
93 |
def DumpJson(data, indent=True): |
94 |
"""Serialize a given object.
|
95 |
|
96 |
@param data: the data to serialize
|
97 |
@param indent: whether to indent output (depends on simplejson version)
|
98 |
|
99 |
@return: the string representation of data
|
100 |
|
101 |
"""
|
102 |
if indent:
|
103 |
fn = _DumpJsonIndent |
104 |
else:
|
105 |
fn = _DumpJson |
106 |
|
107 |
txt = _RE_EOLSP.sub("", fn(data))
|
108 |
if not txt.endswith("\n"): |
109 |
txt += "\n"
|
110 |
|
111 |
return txt
|
112 |
|
113 |
|
114 |
def LoadJson(txt): |
115 |
"""Unserialize data from a string.
|
116 |
|
117 |
@param txt: the json-encoded form
|
118 |
|
119 |
@return: the original data
|
120 |
|
121 |
"""
|
122 |
return json.loads(txt)
|
123 |
|
124 |
|
125 |
def DumpSignedJson(data, key, salt=None, key_selector=None): |
126 |
"""Serialize a given object and authenticate it.
|
127 |
|
128 |
@param data: the data to serialize
|
129 |
@param key: shared hmac key
|
130 |
@param key_selector: name/id that identifies the key (in case there are
|
131 |
multiple keys in use, e.g. in a multi-cluster environment)
|
132 |
@return: the string representation of data signed by the hmac key
|
133 |
|
134 |
"""
|
135 |
txt = DumpJson(data, indent=False)
|
136 |
if salt is None: |
137 |
salt = ""
|
138 |
signed_dict = { |
139 |
"msg": txt,
|
140 |
"salt": salt,
|
141 |
} |
142 |
|
143 |
if key_selector:
|
144 |
signed_dict["key_selector"] = key_selector
|
145 |
else:
|
146 |
key_selector = ""
|
147 |
|
148 |
signed_dict["hmac"] = utils.Sha1Hmac(key, txt, salt=salt + key_selector)
|
149 |
|
150 |
return DumpJson(signed_dict, indent=False) |
151 |
|
152 |
|
153 |
def LoadSignedJson(txt, key): |
154 |
"""Verify that a given message was signed with the given key, and load it.
|
155 |
|
156 |
@param txt: json-encoded hmac-signed message
|
157 |
@param key: the shared hmac key or a callable taking one argument (the key
|
158 |
selector), which returns the hmac key belonging to the key selector.
|
159 |
Typical usage is to pass a reference to the get method of a dict.
|
160 |
@rtype: tuple of original data, string
|
161 |
@return: original data, salt
|
162 |
@raises errors.SignatureError: if the message signature doesn't verify
|
163 |
|
164 |
"""
|
165 |
signed_dict = LoadJson(txt) |
166 |
if not isinstance(signed_dict, dict): |
167 |
raise errors.SignatureError("Invalid external message") |
168 |
try:
|
169 |
msg = signed_dict["msg"]
|
170 |
salt = signed_dict["salt"]
|
171 |
hmac_sign = signed_dict["hmac"]
|
172 |
except KeyError: |
173 |
raise errors.SignatureError("Invalid external message") |
174 |
|
175 |
if callable(key): |
176 |
# pylint: disable=E1103
|
177 |
key_selector = signed_dict.get("key_selector", None) |
178 |
hmac_key = key(key_selector) |
179 |
if not hmac_key: |
180 |
raise errors.SignatureError("No key with key selector '%s' found" % |
181 |
key_selector) |
182 |
else:
|
183 |
key_selector = ""
|
184 |
hmac_key = key |
185 |
|
186 |
if not utils.VerifySha1Hmac(hmac_key, msg, hmac_sign, |
187 |
salt=salt + key_selector): |
188 |
raise errors.SignatureError("Invalid Signature") |
189 |
|
190 |
return LoadJson(msg), salt
|
191 |
|
192 |
|
193 |
Dump = DumpJson |
194 |
Load = LoadJson |
195 |
DumpSigned = DumpSignedJson |
196 |
LoadSigned = LoadSignedJson |