Removing all ssh setup code from the core
[ganeti-local] / lib / serializer.py
index 2b78efd..9a5f1ce 100644 (file)
@@ -24,17 +24,16 @@ This module introduces a simple abstraction over the serialization
 backend (currently json).
 
 """
+# pylint: disable-msg=C0103
+
+# C0103: Invalid name, since pylint doesn't see that Dump points to a
+# function and not a constant
 
 import simplejson
 import re
-import hmac
 
 from ganeti import errors
-
-try:
-  from hashlib import sha1
-except ImportError:
-  import sha as sha1
+from ganeti import utils
 
 
 _JSON_INDENT = 2
@@ -42,7 +41,7 @@ _JSON_INDENT = 2
 _RE_EOLSP = re.compile('[ \t]+$', re.MULTILINE)
 
 
-def _GetJsonDumpers():
+def _GetJsonDumpers(_encoder_class=simplejson.JSONEncoder):
   """Returns two JSON functions to serialize data.
 
   @rtype: (callable, callable)
@@ -50,22 +49,16 @@ def _GetJsonDumpers():
            generate a more readable, indented form of JSON (if supported)
 
   """
-  plain_dump = simplejson.dumps
+  plain_encoder = _encoder_class(sort_keys=True)
 
   # Check whether the simplejson module supports indentation
   try:
-    simplejson.dumps(1, indent=_JSON_INDENT)
+    indent_encoder = _encoder_class(indent=_JSON_INDENT, sort_keys=True)
   except TypeError:
     # Indentation not supported
-    indent_dump = plain_dump
-  else:
-    # Indentation supported
-    indent_dump = lambda data: simplejson.dumps(data, indent=_JSON_INDENT)
+    indent_encoder = plain_encoder
 
-  assert callable(plain_dump)
-  assert callable(indent_dump)
-
-  return (plain_dump, indent_dump)
+  return (plain_encoder.encode, indent_encoder.encode)
 
 
 (_DumpJson, _DumpJsonIndent) = _GetJsonDumpers()
@@ -103,11 +96,13 @@ def LoadJson(txt):
   return simplejson.loads(txt)
 
 
-def DumpSignedJson(data, key, salt=None):
+def DumpSignedJson(data, key, salt=None, key_selector=None):
   """Serialize a given object and authenticate it.
 
   @param data: the data to serialize
   @param key: shared hmac key
+  @param key_selector: name/id that identifies the key (in case there are
+    multiple keys in use, e.g. in a multi-cluster environment)
   @return: the string representation of data signed by the hmac key
 
   """
@@ -117,8 +112,15 @@ def DumpSignedJson(data, key, salt=None):
   signed_dict = {
     'msg': txt,
     'salt': salt,
-    'hmac': hmac.new(key, salt + txt, sha1).hexdigest(),
-  }
+    }
+
+  if key_selector:
+    signed_dict["key_selector"] = key_selector
+  else:
+    key_selector = ""
+
+  signed_dict["hmac"] = utils.Sha1Hmac(key, txt, salt=salt + key_selector)
+
   return DumpJson(signed_dict, indent=False)
 
 
@@ -126,7 +128,9 @@ def LoadSignedJson(txt, key):
   """Verify that a given message was signed with the given key, and load it.
 
   @param txt: json-encoded hmac-signed message
-  @param key: shared hmac key
+  @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.
   @rtype: tuple of original data, string
   @return: original data, salt
   @raises errors.SignatureError: if the message signature doesn't verify
@@ -142,7 +146,19 @@ def LoadSignedJson(txt, key):
   except KeyError:
     raise errors.SignatureError('Invalid external message')
 
-  if hmac.new(key, salt + msg, sha1).hexdigest() != hmac_sign:
+  if callable(key):
+    # pylint: disable-msg=E1103
+    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 not utils.VerifySha1Hmac(hmac_key, msg, hmac_sign,
+                              salt=salt + key_selector):
     raise errors.SignatureError('Invalid Signature')
 
   return LoadJson(msg), salt