psa_storage.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. """Knowledge about the PSA key store as implemented in Mbed TLS.
  2. """
  3. # Copyright The Mbed TLS Contributors
  4. # SPDX-License-Identifier: Apache-2.0
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  7. # not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  14. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. import re
  18. import struct
  19. from typing import Dict, List, Optional, Set, Union
  20. import unittest
  21. from mbedtls_dev import c_build_helper
  22. class Expr:
  23. """Representation of a C expression with a known or knowable numerical value."""
  24. def __init__(self, content: Union[int, str]):
  25. if isinstance(content, int):
  26. digits = 8 if content > 0xffff else 4
  27. self.string = '{0:#0{1}x}'.format(content, digits + 2)
  28. self.value_if_known = content #type: Optional[int]
  29. else:
  30. self.string = content
  31. self.unknown_values.add(self.normalize(content))
  32. self.value_if_known = None
  33. value_cache = {} #type: Dict[str, int]
  34. """Cache of known values of expressions."""
  35. unknown_values = set() #type: Set[str]
  36. """Expressions whose values are not present in `value_cache` yet."""
  37. def update_cache(self) -> None:
  38. """Update `value_cache` for expressions registered in `unknown_values`."""
  39. expressions = sorted(self.unknown_values)
  40. values = c_build_helper.get_c_expression_values(
  41. 'unsigned long', '%lu',
  42. expressions,
  43. header="""
  44. #include <psa/crypto.h>
  45. """,
  46. include_path=['include']) #type: List[str]
  47. for e, v in zip(expressions, values):
  48. self.value_cache[e] = int(v, 0)
  49. self.unknown_values.clear()
  50. @staticmethod
  51. def normalize(string: str) -> str:
  52. """Put the given C expression in a canonical form.
  53. This function is only intended to give correct results for the
  54. relatively simple kind of C expression typically used with this
  55. module.
  56. """
  57. return re.sub(r'\s+', r'', string)
  58. def value(self) -> int:
  59. """Return the numerical value of the expression."""
  60. if self.value_if_known is None:
  61. if re.match(r'([0-9]+|0x[0-9a-f]+)\Z', self.string, re.I):
  62. return int(self.string, 0)
  63. normalized = self.normalize(self.string)
  64. if normalized not in self.value_cache:
  65. self.update_cache()
  66. self.value_if_known = self.value_cache[normalized]
  67. return self.value_if_known
  68. Exprable = Union[str, int, Expr]
  69. """Something that can be converted to a C expression with a known numerical value."""
  70. def as_expr(thing: Exprable) -> Expr:
  71. """Return an `Expr` object for `thing`.
  72. If `thing` is already an `Expr` object, return it. Otherwise build a new
  73. `Expr` object from `thing`. `thing` can be an integer or a string that
  74. contains a C expression.
  75. """
  76. if isinstance(thing, Expr):
  77. return thing
  78. else:
  79. return Expr(thing)
  80. class Key:
  81. """Representation of a PSA crypto key object and its storage encoding.
  82. """
  83. LATEST_VERSION = 0
  84. """The latest version of the storage format."""
  85. def __init__(self, *,
  86. version: Optional[int] = None,
  87. id: Optional[int] = None, #pylint: disable=redefined-builtin
  88. lifetime: Exprable = 'PSA_KEY_LIFETIME_PERSISTENT',
  89. type: Exprable, #pylint: disable=redefined-builtin
  90. bits: int,
  91. usage: Exprable, alg: Exprable, alg2: Exprable,
  92. material: bytes #pylint: disable=used-before-assignment
  93. ) -> None:
  94. self.version = self.LATEST_VERSION if version is None else version
  95. self.id = id #pylint: disable=invalid-name #type: Optional[int]
  96. self.lifetime = as_expr(lifetime) #type: Expr
  97. self.type = as_expr(type) #type: Expr
  98. self.bits = bits #type: int
  99. self.usage = as_expr(usage) #type: Expr
  100. self.alg = as_expr(alg) #type: Expr
  101. self.alg2 = as_expr(alg2) #type: Expr
  102. self.material = material #type: bytes
  103. MAGIC = b'PSA\000KEY\000'
  104. @staticmethod
  105. def pack(
  106. fmt: str,
  107. *args: Union[int, Expr]
  108. ) -> bytes: #pylint: disable=used-before-assignment
  109. """Pack the given arguments into a byte string according to the given format.
  110. This function is similar to `struct.pack`, but with the following differences:
  111. * All integer values are encoded with standard sizes and in
  112. little-endian representation. `fmt` must not include an endianness
  113. prefix.
  114. * Arguments can be `Expr` objects instead of integers.
  115. * Only integer-valued elements are supported.
  116. """
  117. return struct.pack('<' + fmt, # little-endian, standard sizes
  118. *[arg.value() if isinstance(arg, Expr) else arg
  119. for arg in args])
  120. def bytes(self) -> bytes:
  121. """Return the representation of the key in storage as a byte array.
  122. This is the content of the PSA storage file. When PSA storage is
  123. implemented over stdio files, this does not include any wrapping made
  124. by the PSA-storage-over-stdio-file implementation.
  125. """
  126. header = self.MAGIC + self.pack('L', self.version)
  127. if self.version == 0:
  128. attributes = self.pack('LHHLLL',
  129. self.lifetime, self.type, self.bits,
  130. self.usage, self.alg, self.alg2)
  131. material = self.pack('L', len(self.material)) + self.material
  132. else:
  133. raise NotImplementedError
  134. return header + attributes + material
  135. def hex(self) -> str:
  136. """Return the representation of the key as a hexadecimal string.
  137. This is the hexadecimal representation of `self.bytes`.
  138. """
  139. return self.bytes().hex()
  140. def location_value(self) -> int:
  141. """The numerical value of the location encoded in the key's lifetime."""
  142. return self.lifetime.value() >> 8
  143. class TestKey(unittest.TestCase):
  144. # pylint: disable=line-too-long
  145. """A few smoke tests for the functionality of the `Key` class."""
  146. def test_numerical(self):
  147. key = Key(version=0,
  148. id=1, lifetime=0x00000001,
  149. type=0x2400, bits=128,
  150. usage=0x00000300, alg=0x05500200, alg2=0x04c01000,
  151. material=b'@ABCDEFGHIJKLMNO')
  152. expected_hex = '505341004b45590000000000010000000024800000030000000250050010c00410000000404142434445464748494a4b4c4d4e4f'
  153. self.assertEqual(key.bytes(), bytes.fromhex(expected_hex))
  154. self.assertEqual(key.hex(), expected_hex)
  155. def test_names(self):
  156. length = 0xfff8 // 8 # PSA_MAX_KEY_BITS in bytes
  157. key = Key(version=0,
  158. id=1, lifetime='PSA_KEY_LIFETIME_PERSISTENT',
  159. type='PSA_KEY_TYPE_RAW_DATA', bits=length*8,
  160. usage=0, alg=0, alg2=0,
  161. material=b'\x00' * length)
  162. expected_hex = '505341004b45590000000000010000000110f8ff000000000000000000000000ff1f0000' + '00' * length
  163. self.assertEqual(key.bytes(), bytes.fromhex(expected_hex))
  164. self.assertEqual(key.hex(), expected_hex)
  165. def test_defaults(self):
  166. key = Key(type=0x1001, bits=8,
  167. usage=0, alg=0, alg2=0,
  168. material=b'\x2a')
  169. expected_hex = '505341004b455900000000000100000001100800000000000000000000000000010000002a'
  170. self.assertEqual(key.bytes(), bytes.fromhex(expected_hex))
  171. self.assertEqual(key.hex(), expected_hex)