Signed-off-by: Balazs Lecz <[email protected]>
---
lib/serializer.py | 22 ++++++++++++++++++++--
test/ganeti.serializer_unittest.py | 6 ++++++
2 files changed, 26 insertions(+), 2 deletions(-)
diff --git a/lib/serializer.py b/lib/serializer.py
index b568497..5423f97 100644
--- a/lib/serializer.py
+++ b/lib/serializer.py
@@ -101,11 +101,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,19 +119,24 @@ def DumpSignedJson(data, key, salt=None):
'salt': salt,
'hmac': hmac.new(key, salt + txt, sha1).hexdigest(),
}
+ if key_selector:
+ signed_dict["key_selector"] = key_selector
return DumpJson(signed_dict, indent=False)
-def LoadSignedJson(txt, key):
+def LoadSignedJson(txt, key=None, keydict=None):
"""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 keydict: a dictionary that maps key_selector values to keys
@rtype: tuple of original data, string
@return: original data, salt
@raises errors.SignatureError: if the message signature doesn't verify
"""
+ if not key and not keydict:
+ raise errors.ProgrammerError("A key or keydict must be supplied")
signed_dict = LoadJson(txt)
if not isinstance(signed_dict, dict):
raise errors.SignatureError('Invalid external message')
@@ -140,6 +147,17 @@ def LoadSignedJson(txt, key):
except KeyError:
raise errors.SignatureError('Invalid external message')
+ if keydict:
+ try:
+ key_selector = signed_dict["key_selector"]
+ except KeyError:
+ raise errors.SignatureError("No key_selector found in external message")
+ try:
+ key = keydict[key_selector]
+ except KeyError:
+ raise errors.SignatureError("No key with key selector '%s' found" %
+ key_selector)
+
if hmac.new(key, salt + msg, sha1).hexdigest() != hmac_sign:
raise errors.SignatureError('Invalid Signature')
diff --git a/test/ganeti.serializer_unittest.py
b/test/ganeti.serializer_unittest.py
index 11a60e6..32b3744 100755
--- a/test/ganeti.serializer_unittest.py
+++ b/test/ganeti.serializer_unittest.py
@@ -75,6 +75,12 @@ class TestSerializer(testutils.GanetiTestCase):
"myprivatekey"),
(data, "mysalt"))
+ self.assertEqualValues(
+ LoadSigned(DumpSigned(data, "myprivatekey",
+ "mysalt", "mykey_id"),
+ keydict={"mykey_id": "myprivatekey"}),
+ (data, "mysalt"))
+
self.assertRaises(errors.SignatureError, serializer.LoadSigned,
serializer.DumpSigned("test", "myprivatekey"),
"myotherkey")
--
1.6.6.2