serializer.py 4.61 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
#
#

# Copyright (C) 2007, 2008 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.

"""Serializer abstraction module

This module introduces a simple abstraction over the serialization
backend (currently json).

"""
Iustin Pop's avatar
Iustin Pop committed
27 28 29 30
# pylint: disable-msg=C0103

# C0103: Invalid name, since pylint doesn't see that Dump points to a
# function and not a constant
31 32 33

import simplejson
import re
34 35 36
import hmac

from ganeti import errors
37

Guido Trotter's avatar
Guido Trotter committed
38 39 40 41
try:
  from hashlib import sha1
except ImportError:
  import sha as sha1
42

Michael Hanselmann's avatar
Michael Hanselmann committed
43

44 45
_JSON_INDENT = 2

46
_RE_EOLSP = re.compile('[ \t]+$', re.MULTILINE)
47 48


49
def _GetJsonDumpers(_encoder_class=simplejson.JSONEncoder):
Michael Hanselmann's avatar
Michael Hanselmann committed
50 51 52 53 54 55 56
  """Returns two JSON functions to serialize data.

  @rtype: (callable, callable)
  @return: The function to generate a compact form of JSON and another one to
           generate a more readable, indented form of JSON (if supported)

  """
57
  plain_encoder = _encoder_class(sort_keys=True)
Michael Hanselmann's avatar
Michael Hanselmann committed
58 59 60

  # Check whether the simplejson module supports indentation
  try:
61
    indent_encoder = _encoder_class(indent=_JSON_INDENT, sort_keys=True)
Michael Hanselmann's avatar
Michael Hanselmann committed
62 63
  except TypeError:
    # Indentation not supported
64
    indent_encoder = plain_encoder
Michael Hanselmann's avatar
Michael Hanselmann committed
65

66
  return (plain_encoder.encode, indent_encoder.encode)
Michael Hanselmann's avatar
Michael Hanselmann committed
67 68 69 70 71


(_DumpJson, _DumpJsonIndent) = _GetJsonDumpers()


72
def DumpJson(data, indent=True):
73 74
  """Serialize a given object.

Iustin Pop's avatar
Iustin Pop committed
75 76 77 78
  @param data: the data to serialize
  @param indent: whether to indent output (depends on simplejson version)

  @return: the string representation of data
79

80
  """
Michael Hanselmann's avatar
Michael Hanselmann committed
81 82
  if indent:
    fn = _DumpJsonIndent
83
  else:
Michael Hanselmann's avatar
Michael Hanselmann committed
84
    fn = _DumpJson
85

Michael Hanselmann's avatar
Michael Hanselmann committed
86
  txt = _RE_EOLSP.sub("", fn(data))
87 88
  if not txt.endswith('\n'):
    txt += '\n'
Michael Hanselmann's avatar
Michael Hanselmann committed
89

90 91 92
  return txt


93
def LoadJson(txt):
94 95
  """Unserialize data from a string.

Iustin Pop's avatar
Iustin Pop committed
96 97 98 99
  @param txt: the json-encoded form

  @return: the original data

100 101
  """
  return simplejson.loads(txt)
102 103


104
def DumpSignedJson(data, key, salt=None, key_selector=None):
105 106 107 108
  """Serialize a given object and authenticate it.

  @param data: the data to serialize
  @param key: shared hmac key
109 110
  @param key_selector: name/id that identifies the key (in case there are
    multiple keys in use, e.g. in a multi-cluster environment)
111 112 113 114 115 116 117 118 119 120
  @return: the string representation of data signed by the hmac key

  """
  txt = DumpJson(data, indent=False)
  if salt is None:
    salt = ''
  signed_dict = {
    'msg': txt,
    'salt': salt,
  }
121 122 123 124 125 126 127 128
  if key_selector:
    signed_dict["key_selector"] = key_selector
    message = salt + key_selector + txt
  else:
    message = salt + txt
  signed_dict["hmac"] = hmac.new(key, message,
                                 sha1).hexdigest()

Guido Trotter's avatar
Guido Trotter committed
129
  return DumpJson(signed_dict, indent=False)
130 131


132
def LoadSignedJson(txt, key):
133 134 135
  """Verify that a given message was signed with the given key, and load it.

  @param txt: json-encoded hmac-signed message
136 137 138
  @param key: the shared hmac key or a callable taking one argument (the key
    selector), which returns the hmac key belonging to the key selector.
    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 142 143 144 145 146 147 148 149 150 151 152 153
  @raises errors.SignatureError: if the message signature doesn't verify

  """
  signed_dict = LoadJson(txt)
  if not isinstance(signed_dict, dict):
    raise errors.SignatureError('Invalid external message')
  try:
    msg = signed_dict['msg']
    salt = signed_dict['salt']
    hmac_sign = signed_dict['hmac']
  except KeyError:
    raise errors.SignatureError('Invalid external message')

154
  if callable(key):
Guido Trotter's avatar
Guido Trotter committed
155
    # pylint: disable-msg=E1103
156 157 158 159 160 161 162 163 164 165 166
    key_selector = signed_dict.get("key_selector", None)
    hmac_key = key(key_selector)
    if not hmac_key:
      raise errors.SignatureError("No key with key selector '%s' found" %
                                  key_selector)
  else:
    key_selector = ""
    hmac_key = key

  if hmac.new(hmac_key, salt + key_selector + msg,
              sha1).hexdigest() != hmac_sign:
167 168
    raise errors.SignatureError('Invalid Signature')

169
  return LoadJson(msg), salt
170 171


172 173
Dump = DumpJson
Load = LoadJson
174 175
DumpSigned = DumpSignedJson
LoadSigned = LoadSignedJson