Statistics
| Branch: | Tag: | Revision:

root / lib / serializer.py @ 196ec587

History | View | Annotate | Download (4.6 kB)

1 8d14b30d Iustin Pop
#
2 8d14b30d Iustin Pop
#
3 8d14b30d Iustin Pop
4 8d14b30d Iustin Pop
# Copyright (C) 2007, 2008 Google Inc.
5 8d14b30d Iustin Pop
#
6 8d14b30d Iustin Pop
# This program is free software; you can redistribute it and/or modify
7 8d14b30d Iustin Pop
# it under the terms of the GNU General Public License as published by
8 8d14b30d Iustin Pop
# the Free Software Foundation; either version 2 of the License, or
9 8d14b30d Iustin Pop
# (at your option) any later version.
10 8d14b30d Iustin Pop
#
11 8d14b30d Iustin Pop
# This program is distributed in the hope that it will be useful, but
12 8d14b30d Iustin Pop
# WITHOUT ANY WARRANTY; without even the implied warranty of
13 8d14b30d Iustin Pop
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 8d14b30d Iustin Pop
# General Public License for more details.
15 8d14b30d Iustin Pop
#
16 8d14b30d Iustin Pop
# You should have received a copy of the GNU General Public License
17 8d14b30d Iustin Pop
# along with this program; if not, write to the Free Software
18 8d14b30d Iustin Pop
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 8d14b30d Iustin Pop
# 02110-1301, USA.
20 8d14b30d Iustin Pop
21 8d14b30d Iustin Pop
"""Serializer abstraction module
22 8d14b30d Iustin Pop

23 8d14b30d Iustin Pop
This module introduces a simple abstraction over the serialization
24 8d14b30d Iustin Pop
backend (currently json).
25 8d14b30d Iustin Pop

26 8d14b30d Iustin Pop
"""
27 fe267188 Iustin Pop
# pylint: disable-msg=C0103
28 fe267188 Iustin Pop
29 fe267188 Iustin Pop
# C0103: Invalid name, since pylint doesn't see that Dump points to a
30 fe267188 Iustin Pop
# function and not a constant
31 8d14b30d Iustin Pop
32 8d14b30d Iustin Pop
import simplejson
33 8d14b30d Iustin Pop
import re
34 f4a2f532 Guido Trotter
import hmac
35 f4a2f532 Guido Trotter
36 f4a2f532 Guido Trotter
from ganeti import errors
37 8d14b30d Iustin Pop
38 541822e0 Guido Trotter
try:
39 541822e0 Guido Trotter
  from hashlib import sha1
40 541822e0 Guido Trotter
except ImportError:
41 541822e0 Guido Trotter
  import sha as sha1
42 071448fb Michael Hanselmann
43 d357f531 Michael Hanselmann
44 8d14b30d Iustin Pop
_JSON_INDENT = 2
45 8d14b30d Iustin Pop
46 e91ffe49 Michael Hanselmann
_RE_EOLSP = re.compile('[ \t]+$', re.MULTILINE)
47 8d14b30d Iustin Pop
48 8d14b30d Iustin Pop
49 02141fb1 Michael Hanselmann
def _GetJsonDumpers(_encoder_class=simplejson.JSONEncoder):
50 d357f531 Michael Hanselmann
  """Returns two JSON functions to serialize data.
51 d357f531 Michael Hanselmann

52 d357f531 Michael Hanselmann
  @rtype: (callable, callable)
53 d357f531 Michael Hanselmann
  @return: The function to generate a compact form of JSON and another one to
54 d357f531 Michael Hanselmann
           generate a more readable, indented form of JSON (if supported)
55 d357f531 Michael Hanselmann

56 d357f531 Michael Hanselmann
  """
57 02141fb1 Michael Hanselmann
  plain_encoder = _encoder_class(sort_keys=True)
58 d357f531 Michael Hanselmann
59 d357f531 Michael Hanselmann
  # Check whether the simplejson module supports indentation
60 d357f531 Michael Hanselmann
  try:
61 02141fb1 Michael Hanselmann
    indent_encoder = _encoder_class(indent=_JSON_INDENT, sort_keys=True)
62 d357f531 Michael Hanselmann
  except TypeError:
63 d357f531 Michael Hanselmann
    # Indentation not supported
64 02141fb1 Michael Hanselmann
    indent_encoder = plain_encoder
65 d357f531 Michael Hanselmann
66 02141fb1 Michael Hanselmann
  return (plain_encoder.encode, indent_encoder.encode)
67 d357f531 Michael Hanselmann
68 d357f531 Michael Hanselmann
69 d357f531 Michael Hanselmann
(_DumpJson, _DumpJsonIndent) = _GetJsonDumpers()
70 d357f531 Michael Hanselmann
71 d357f531 Michael Hanselmann
72 071448fb Michael Hanselmann
def DumpJson(data, indent=True):
73 8d14b30d Iustin Pop
  """Serialize a given object.
74 8d14b30d Iustin Pop

75 c41eea6e Iustin Pop
  @param data: the data to serialize
76 c41eea6e Iustin Pop
  @param indent: whether to indent output (depends on simplejson version)
77 c41eea6e Iustin Pop

78 c41eea6e Iustin Pop
  @return: the string representation of data
79 071448fb Michael Hanselmann

80 8d14b30d Iustin Pop
  """
81 d357f531 Michael Hanselmann
  if indent:
82 d357f531 Michael Hanselmann
    fn = _DumpJsonIndent
83 8d14b30d Iustin Pop
  else:
84 d357f531 Michael Hanselmann
    fn = _DumpJson
85 071448fb Michael Hanselmann
86 d357f531 Michael Hanselmann
  txt = _RE_EOLSP.sub("", fn(data))
87 8d14b30d Iustin Pop
  if not txt.endswith('\n'):
88 8d14b30d Iustin Pop
    txt += '\n'
89 d357f531 Michael Hanselmann
90 8d14b30d Iustin Pop
  return txt
91 8d14b30d Iustin Pop
92 8d14b30d Iustin Pop
93 228538cf Michael Hanselmann
def LoadJson(txt):
94 8d14b30d Iustin Pop
  """Unserialize data from a string.
95 8d14b30d Iustin Pop

96 c41eea6e Iustin Pop
  @param txt: the json-encoded form
97 c41eea6e Iustin Pop

98 c41eea6e Iustin Pop
  @return: the original data
99 c41eea6e Iustin Pop

100 8d14b30d Iustin Pop
  """
101 8d14b30d Iustin Pop
  return simplejson.loads(txt)
102 228538cf Michael Hanselmann
103 228538cf Michael Hanselmann
104 72ca1dcb Balazs Lecz
def DumpSignedJson(data, key, salt=None, key_selector=None):
105 f4a2f532 Guido Trotter
  """Serialize a given object and authenticate it.
106 f4a2f532 Guido Trotter

107 f4a2f532 Guido Trotter
  @param data: the data to serialize
108 f4a2f532 Guido Trotter
  @param key: shared hmac key
109 72ca1dcb Balazs Lecz
  @param key_selector: name/id that identifies the key (in case there are
110 72ca1dcb Balazs Lecz
    multiple keys in use, e.g. in a multi-cluster environment)
111 f4a2f532 Guido Trotter
  @return: the string representation of data signed by the hmac key
112 f4a2f532 Guido Trotter

113 f4a2f532 Guido Trotter
  """
114 f4a2f532 Guido Trotter
  txt = DumpJson(data, indent=False)
115 f4a2f532 Guido Trotter
  if salt is None:
116 f4a2f532 Guido Trotter
    salt = ''
117 f4a2f532 Guido Trotter
  signed_dict = {
118 f4a2f532 Guido Trotter
    'msg': txt,
119 f4a2f532 Guido Trotter
    'salt': salt,
120 f4a2f532 Guido Trotter
  }
121 72ca1dcb Balazs Lecz
  if key_selector:
122 72ca1dcb Balazs Lecz
    signed_dict["key_selector"] = key_selector
123 72ca1dcb Balazs Lecz
    message = salt + key_selector + txt
124 72ca1dcb Balazs Lecz
  else:
125 72ca1dcb Balazs Lecz
    message = salt + txt
126 72ca1dcb Balazs Lecz
  signed_dict["hmac"] = hmac.new(key, message,
127 72ca1dcb Balazs Lecz
                                 sha1).hexdigest()
128 72ca1dcb Balazs Lecz
129 40765aa0 Guido Trotter
  return DumpJson(signed_dict, indent=False)
130 f4a2f532 Guido Trotter
131 f4a2f532 Guido Trotter
132 4e9dac14 Guido Trotter
def LoadSignedJson(txt, key):
133 f4a2f532 Guido Trotter
  """Verify that a given message was signed with the given key, and load it.
134 f4a2f532 Guido Trotter

135 f4a2f532 Guido Trotter
  @param txt: json-encoded hmac-signed message
136 72ca1dcb Balazs Lecz
  @param key: the shared hmac key or a callable taking one argument (the key
137 72ca1dcb Balazs Lecz
    selector), which returns the hmac key belonging to the key selector.
138 72ca1dcb Balazs Lecz
    Typical usage is to pass a reference to the get method of a dict.
139 f4a2f532 Guido Trotter
  @rtype: tuple of original data, string
140 4e9dac14 Guido Trotter
  @return: original data, salt
141 f4a2f532 Guido Trotter
  @raises errors.SignatureError: if the message signature doesn't verify
142 f4a2f532 Guido Trotter

143 f4a2f532 Guido Trotter
  """
144 f4a2f532 Guido Trotter
  signed_dict = LoadJson(txt)
145 f4a2f532 Guido Trotter
  if not isinstance(signed_dict, dict):
146 f4a2f532 Guido Trotter
    raise errors.SignatureError('Invalid external message')
147 f4a2f532 Guido Trotter
  try:
148 f4a2f532 Guido Trotter
    msg = signed_dict['msg']
149 f4a2f532 Guido Trotter
    salt = signed_dict['salt']
150 f4a2f532 Guido Trotter
    hmac_sign = signed_dict['hmac']
151 f4a2f532 Guido Trotter
  except KeyError:
152 f4a2f532 Guido Trotter
    raise errors.SignatureError('Invalid external message')
153 f4a2f532 Guido Trotter
154 72ca1dcb Balazs Lecz
  if callable(key):
155 fe7c59d5 Guido Trotter
    # pylint: disable-msg=E1103
156 72ca1dcb Balazs Lecz
    key_selector = signed_dict.get("key_selector", None)
157 72ca1dcb Balazs Lecz
    hmac_key = key(key_selector)
158 72ca1dcb Balazs Lecz
    if not hmac_key:
159 72ca1dcb Balazs Lecz
      raise errors.SignatureError("No key with key selector '%s' found" %
160 72ca1dcb Balazs Lecz
                                  key_selector)
161 72ca1dcb Balazs Lecz
  else:
162 72ca1dcb Balazs Lecz
    key_selector = ""
163 72ca1dcb Balazs Lecz
    hmac_key = key
164 72ca1dcb Balazs Lecz
165 72ca1dcb Balazs Lecz
  if hmac.new(hmac_key, salt + key_selector + msg,
166 72ca1dcb Balazs Lecz
              sha1).hexdigest() != hmac_sign:
167 f4a2f532 Guido Trotter
    raise errors.SignatureError('Invalid Signature')
168 f4a2f532 Guido Trotter
169 4e9dac14 Guido Trotter
  return LoadJson(msg), salt
170 f4a2f532 Guido Trotter
171 f4a2f532 Guido Trotter
172 228538cf Michael Hanselmann
Dump = DumpJson
173 228538cf Michael Hanselmann
Load = LoadJson
174 f4a2f532 Guido Trotter
DumpSigned = DumpSignedJson
175 f4a2f532 Guido Trotter
LoadSigned = LoadSignedJson