Debian Codegraph @

tests/test_core.py

raw
1 # Copyright 2016-2018 Yubico AB
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 """
16 Tests of the core.py module. Currently just includes test of functions that
17 don't require mocking.
18 """
19
20 import struct
21 import unittest
22
23 from yubihsm.core import (
24 DeviceInfo,
25 _derive,
26 _unpad_resp,
27 LogEntry,
28 YubiHsm,
29 AuthSession,
30 )
31 from yubihsm.defs import COMMAND, CAPABILITY, ALGORITHM
32 from yubihsm.backends import YhsmBackend
33 from unittest.mock import patch, MagicMock, call
34 from yubihsm.exceptions import YubiHsmDeviceError, YubiHsmInvalidResponseError
35
36 _DEVICE_INFO = b"\x02\x00\x00\x00s5m>>\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./" # noqa
37 _TRANSCEIVE_DEVICE_INFO = b"\x86\x008\x02\x00\x00\x00s4\xbc>\x04\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./" # noqa
38
39
40 def get_backend():
41 return MagicMock(YhsmBackend)
42
43
44 def simple_urandom(length):
45 """See https://xkcd.com/221/"""
46 return b"\x00" * length
47
48
49 @patch("os.urandom", side_effect=simple_urandom)
50 def get_mocked_session(patch):
51 """
52 Create a fake session by mocking
53 the backend.transceive function
54 """
55 mocked_backend = get_backend()
56 mocked_backend.transceive.side_effect = [
57 _TRANSCEIVE_DEVICE_INFO, # get_device_info is called during initialization
58 b"\x83\x00\x11\x00\x05MV1\xc9\x18o\x802%\xed\x8a2$\xf2\xcf",
59 b"\x84\x00\x00",
60 ]
61 hsm = YubiHsm(backend=mocked_backend)
62
63 auth_key_id = 1
64 key_enc = b"\t\x0bG\xdb\xedYVT\x90\x1d\xee\x1c\xc6U\xe4 "
65 key_mac = b"Y/\xd4\x83\xf7Y\xe2\x99\t\xa0LE\x05\xd2\xce\n"
66 return hsm.create_session(auth_key_id, key_enc, key_mac)
67
68
69 class TestDeviceInfo(unittest.TestCase):
70 """Test the functionality of the DeviceInfo class"""
71
72 def test_class(self):
73 """
74 Full testing of the Device Info class
75 """
76 info = DeviceInfo.parse(_DEVICE_INFO)
77 self.assertEqual(info.version, (2, 0, 0))
78 self.assertEqual(info.serial, 7550317)
79 self.assertEqual(info.log_size, 62)
80 self.assertEqual(info.log_used, 62)
81 self.assertEqual(len(info.supported_algorithms), 47)
82
83
84 class TestDeriveFct(unittest.TestCase):
85 """
86 Test the functionality of the private method _derive. If we decide not to
87 test private functions, this can be removed.
88 """
89
90 def test_success(self):
91 """
92 Make sure the function works on a test case that should succeed
93 """
94 context = b"\x0c\xf4\xf5L\xb9\xdfY["
95 t = 0x04
96 key = b"0xff0xff0x120xff0xff0xff0xff0xaf"
97 rval = _derive(key, t, context)
98 self.assertEqual(rval, b"W\xa0\x7f1\xb9\x13\xbc\xe5\xff\x066J\x0e9Fz")
99
100 def test_value_error(self):
101 """
102 Make sure the test fails when an unsupported value
103 """
104 context = b"\x0c\xf4\xf5L\xb9\xdfY["
105 t = 0x04
106 key = b"0xff0xff0x120xff0xff0xff0xff0xaf"
107 self.assertRaises(ValueError, _derive, key, t, context, 0x60)
108
109
110 class TestUnpad(unittest.TestCase):
111 """
112 Test the functionality of the private method _unpad. If we decide not to
113 test private functions, this can be removed.
114 """
115
116 def test_invalid_len(self):
117 """Check if the response length is invalid"""
118 resp = b"\x02\x7f"
119 cmd = COMMAND.SIGN_ECDSA
120 self.assertRaises(YubiHsmInvalidResponseError, _unpad_resp, resp, cmd)
121 resp = b"\x14\x00\x06\x00|\x00\xff"
122 self.assertRaises(YubiHsmInvalidResponseError, _unpad_resp, resp, cmd)
123
124 def test_device_error(self):
125 """Check if the length of the response doesn't match promised length"""
126 cmd = COMMAND.ERROR
127 resp = b"\x7f\x00\x01\x00\x01\x00>"
128 self.assertRaises(YubiHsmDeviceError, _unpad_resp, resp, cmd)
129
130 def test_invalid_rcommand(self):
131 """Throw error if the response command doesn't match the
132 command sent | 0x80"""
133 cmd = COMMAND.AUTHENTICATE_SESSION
134 resp = struct.pack("!BHHH", cmd - 1, 1, 1, 62)
135 self.assertRaises(YubiHsmInvalidResponseError, _unpad_resp, resp, cmd)
136
137 def test_success(self):
138 """Otherwise, succeed"""
139 cmd = COMMAND.AUTHENTICATE_SESSION
140 resp = b"\x84\x00\x02\x00\x01\x00\x1d\x00\x04"
141 rval = _unpad_resp(resp, cmd)
142 self.assertEqual(rval, b"\x00\x01")
143
144
145 class TestLogEntry(unittest.TestCase):
146 """
147 Full testing of the LogEntry class
148 """
149
150 def test_construction(self):
151 """Use classmethod `parse` to construct log entry from data"""
152
153 # Decide on values
154 vals = 513, 250, 1020, 56, 800, 900, 20, 1023, b"abcdefghiklmnop0"
155 keys = (
156 "number",
157 "command",
158 "length",
159 "session_key",
160 "target_key",
161 "second_key",
162 "result",
163 "tick",
164 "digest",
165 )
166
167 # Pack it up for parsing
168 data = struct.pack("!HBHHHHBL16s", *vals)
169
170 # Use the `parse` alternate constructor
171 log = LogEntry.parse(data)
172 for key, val in zip(keys, vals):
173 self.assertEqual(getattr(log, key), val)
174
175 # Make sure __init__ and parse give you the same result
176 self.assertEqual(LogEntry(**dict(zip(keys, vals))), log)
177
178
179 class TestLogCorrect(unittest.TestCase):
180 """
181 Full coverage tests of the log class. Includes construction, checks
182 for errors, and validation
183 """
184
185 FORMAT = "!HBHHHHBL16s"
186
187 # The first 2 entries in the log are provided below, along with a
188 # version of log 2 with a tampered hash
189 log1_vals = (
190 2,
191 0,
192 0,
193 65535,
194 0,
195 0,
196 0,
197 0,
198 b"\xf6\x96\x90n[9)\xc6<\xa6\xf1\n\x83\xd2\xa0\xcc",
199 )
200
201 log2_vals = (
202 3,
203 3,
204 10,
205 65535,
206 1,
207 65535,
208 131,
209 35,
210 b'"d\xd4Q\xb5\xef\xf5\xdf\xa9LTO3\xb7\x87\xa9',
211 )
212
213 # Log 2 is valid, aside from its hash, which doesn't match
214 log2_badvals = (
215 3,
216 3,
217 10,
218 65535,
219 1,
220 65535,
221 131,
222 35,
223 b'"d\xd4Q\xb5\xef\xf5\xdf\xa9LTO3\xb7\x87\xa8',
224 )
225
226 log1 = struct.pack(FORMAT, *log1_vals)
227 log2 = struct.pack(FORMAT, *log2_vals)
228 log2_bad = struct.pack(FORMAT, *log2_badvals)
229
230 e1 = LogEntry.parse(log1)
231 e2 = LogEntry.parse(log2)
232 e2_bad = LogEntry.parse(log2_bad)
233
234 def test_logvalidation(self):
235 """Make sure we can validate correct, sequential entries"""
236 self.assertTrue(self.e2.validate(self.e1))
237
238 def test_unorderedloginvalid(self):
239 """Entries can't validate if out of order"""
240 self.assertRaises(ValueError, self.e1.validate, self.e2)
241
242 def test_tamperedhash(self):
243 """Bad hashes can be detected"""
244 self.assertFalse(self.e2_bad.validate(self.e1))
245
246 def test_data(self):
247 """Check that the data property works"""
248 self.assertTrue(self.e1.data == self.log1[:-16])
249
250 def test_initializer(self):
251 """
252 Check that using the default initializer gives the same
253 result as using the pack constructor
254 """
255 self.assertTrue(self.e1 == LogEntry(*self.log1_vals))
256
257
258 class TestYubiHsm(unittest.TestCase):
259 @patch("yubihsm.core.YubiHsm.create_session")
260 def test_create_session_derived(self, item):
261 """
262 Test if create_session_derived calls create_session correctly
263 """
264
265 auth_key_id = 1
266 password = "password"
267 expect_enc = b"\t\x0bG\xdb\xedYVT\x90\x1d\xee\x1c\xc6U\xe4 "
268 expect_mac = b"Y/\xd4\x83\xf7Y\xe2\x99\t\xa0LE\x05\xd2\xce\n"
269
270 # Note: get_device_info gets called during initialization
271 # which is why we mock the transceive function.
272 backend = get_backend()
273 backend.transceive.return_value = _TRANSCEIVE_DEVICE_INFO
274
275 hsm = YubiHsm(backend)
276 hsm.create_session_derived(auth_key_id, password)
277
278 hsm.create_session.assert_called_once_with(auth_key_id, expect_enc, expect_mac)
279
280 def test_get_device_info_mock_transceive(self):
281 """
282 Test get_device_info function by mocking the transceive function
283 """
284
285 backend = get_backend()
286 backend.transceive.return_value = _TRANSCEIVE_DEVICE_INFO
287
288 hsm = YubiHsm(backend)
289
290 info = hsm.get_device_info()
291 hsm._backend.transceive.assert_has_calls(
292 [
293 call(b"\x06\x00\x00"), # first call during YubiHSM::__init__
294 call(b"\x06\x00\x00"),
295 ]
296 )
297
298 self.assertEqual(info.version, (2, 0, 0))
299 self.assertEqual(info.serial, 7550140)
300 self.assertEqual(info.log_size, 62)
301 self.assertEqual(info.log_used, 4)
302 self.assertEqual(len(info.supported_algorithms), 47)
303
304
305 class TestAuthsession(unittest.TestCase):
306 def test_list_objects1(self):
307 """
308 Test the first half of the list_objects function:
309 We process the input and make our query to the send_cmd
310 """
311 # Create fake session, and mock the return from a call to side_effect
312 session = MagicMock(AuthSession)
313 session.send_secure_cmd.side_effect = [b"\x00\x01\x02\x00V7\x03\x00"]
314
315 # Run the function, and make sure the correct call is made to secure_cmd
316 AuthSession.list_objects(
317 session,
318 object_id=2,
319 object_type=1,
320 domains=65535,
321 capabilities=CAPABILITY.ALL,
322 algorithm=ALGORITHM.HMAC_SHA384,
323 )
324
325 # We care only about the value sent; we aren't checking the return value
326 # from send_secure_cmd
327 session.send_secure_cmd.assert_called_with(
328 72,
329 b"\x01\x00\x02\x02\x01\x03\xff\xff\x04\x00\xff\xff\xff\xff\xff\xff\xff\x05\x15", # noqa E501
330 )
331
332 def test_list_objects2(self):
333 """
334 Test the second half of list_objects(): process the response from the
335 send_cmd function and return the list of objects
336 """
337 list_objects = AuthSession.list_objects
338 session = MagicMock(AuthSession)
339 session.send_secure_cmd.return_value = b"\x00\x01\x02\x00d\x8f\x03\x00\x00\x01\x03\x00\x00\x04\x05\x00\x00\x05\x05\x00\x00\x05\x03\x00" # noqa
340
341 # The input to the below function doesn't matter;
342 # it's overwritten by the return value listed above
343 objlist = list_objects(session)
344
345 # Finally, make sure we decode the results correctly
346 # Not the best way to check, but it is succinct
347 self.assertEqual(
348 objlist.__repr__(),
349 "[AuthenticationKey(id=1), AsymmetricKey(id=25743), AsymmetricKey(id=1), HmacKey(id=4), HmacKey(id=5), AsymmetricKey(id=5)]", # noqa E501
350 )
351
352 def test__create_session_patch_transceive(self):
353 """
354 Tests the entire authsession generation codebase, by mocking just
355 os.urandom and the transceive method.
356 This test should probably be broken up later.
357 """
358 authsession = get_mocked_session()
359 # Create session should make two calls to transceive.
360 # First call was to create session. Second was to authenticate session.
361 calls = [
362 call(b"\x03\x00\n\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00"),
363 call(b"\x04\x00\x11\x00\x1c\xe7U.\x0fyv\xdb\xcc!\x98\xfd\x15\\3Z"),
364 ]
365
366 authsession._hsm._backend.transceive.assert_has_calls(calls)
367
368 def test_close_session(self):
369 """
370 Test the close session command; only tests output to send_secure_cmd
371 not to transceive
372 """
373
374 session = get_mocked_session()
375 session.send_secure_cmd = MagicMock(session.send_secure_cmd)
376
377 session.close()
378 session.send_secure_cmd.assert_called_once_with(COMMAND.CLOSE_SESSION)
379
380 def test_reset(self):
381 """
382 Tests the reset command; only tests output to send_secure_cmd
383 not to transceive
384 """
385 session = get_mocked_session()
386 session.send_secure_cmd = MagicMock(session.send_secure_cmd)
387 session.send_secure_cmd.return_value = b""
388
389 session.reset_device()
390
391 session.send_secure_cmd.assert_called_with(COMMAND.RESET_DEVICE)
392
393 def test_reset_error(self):
394 """
395 Make sure reset command throws error if nonempty response is returned
396 """
397
398 session = get_mocked_session()
399 session.send_secure_cmd = MagicMock(session.send_secure_cmd)
400 session.send_secure_cmd.return_value = b"\00"
401
402 self.assertRaises(YubiHsmInvalidResponseError, session.reset_device)