From f1d332a01d00cc08b9a7728d7c8727b5f5a067bb Mon Sep 17 00:00:00 2001 From: Rahul Nair Date: Wed, 15 Feb 2017 14:33:48 -0600 Subject: [PATCH] Adding a check of string type for hmacs - To ensure comparison is done on binary data The method would first check if the 2 hmacs are a python `six.stringtype`. If they are, they would be encoded using 'utf-8' as the encoding scheme to binary data. Change-Id: Idf59f669087a39c30eee4e533899b95ede66e198 --- oslo_utils/secretutils.py | 6 ++++++ oslo_utils/tests/test_secretutils.py | 2 ++ 2 files changed, 8 insertions(+) diff --git a/oslo_utils/secretutils.py b/oslo_utils/secretutils.py index fd5c3171..55abb798 100644 --- a/oslo_utils/secretutils.py +++ b/oslo_utils/secretutils.py @@ -14,6 +14,8 @@ import hmac +import six + try: constant_time_compare = hmac.compare_digest @@ -27,6 +29,10 @@ except AttributeError: content-based short circuiting behaviour, making it appropriate for cryptography. """ + if isinstance(first, six.string_types): + first = first.encode('utf-8') + if isinstance(second, six.string_types): + second = second.encode('utf-8') if len(first) != len(second): return False result = 0 diff --git a/oslo_utils/tests/test_secretutils.py b/oslo_utils/tests/test_secretutils.py index 916610be..1c4b366b 100644 --- a/oslo_utils/tests/test_secretutils.py +++ b/oslo_utils/tests/test_secretutils.py @@ -34,6 +34,7 @@ class SecretUtilsTest(testscenarios.TestWithScenarios, self.converter(u'abcd'))) self.assertTrue(ctc(self.converter(u''), self.converter(u''))) + self.assertTrue(ctc('abcd', 'abcd')) self.assertFalse(ctc(self.converter(u'abcd'), self.converter(u'efgh'))) self.assertFalse(ctc(self.converter(u'abc'), @@ -50,3 +51,4 @@ class SecretUtilsTest(testscenarios.TestWithScenarios, self.converter(u'a'))) self.assertFalse(ctc(self.converter(u'abcd1234'), self.converter(u'1234abcd'))) + self.assertFalse(ctc('abcd1234', '1234abcd'))