crypto_knowledge.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. """Knowledge about cryptographic mechanisms implemented in Mbed TLS.
  2. This module is entirely based on the PSA API.
  3. """
  4. # Copyright The Mbed TLS Contributors
  5. # SPDX-License-Identifier: Apache-2.0
  6. #
  7. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  8. # not use this file except in compliance with the License.
  9. # You may obtain a copy of the License at
  10. #
  11. # http://www.apache.org/licenses/LICENSE-2.0
  12. #
  13. # Unless required by applicable law or agreed to in writing, software
  14. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  15. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. # See the License for the specific language governing permissions and
  17. # limitations under the License.
  18. import re
  19. from typing import Dict, Iterable, Optional, Pattern, Tuple
  20. from mbedtls_dev.asymmetric_key_data import ASYMMETRIC_KEY_DATA
  21. class KeyType:
  22. """Knowledge about a PSA key type."""
  23. def __init__(self, name: str, params: Optional[Iterable[str]] = None):
  24. """Analyze a key type.
  25. The key type must be specified in PSA syntax. In its simplest form,
  26. `name` is a string 'PSA_KEY_TYPE_xxx' which is the name of a PSA key
  27. type macro. For key types that take arguments, the arguments can
  28. be passed either through the optional argument `params` or by
  29. passing an expression of the form 'PSA_KEY_TYPE_xxx(param1, ...)'
  30. in `name` as a string.
  31. """
  32. self.name = name.strip()
  33. """The key type macro name (``PSA_KEY_TYPE_xxx``).
  34. For key types constructed from a macro with arguments, this is the
  35. name of the macro, and the arguments are in `self.params`.
  36. """
  37. if params is None:
  38. if '(' in self.name:
  39. m = re.match(r'(\w+)\s*\((.*)\)\Z', self.name)
  40. assert m is not None
  41. self.name = m.group(1)
  42. params = m.group(2).split(',')
  43. self.params = (None if params is None else
  44. [param.strip() for param in params])
  45. """The parameters of the key type, if there are any.
  46. None if the key type is a macro without arguments.
  47. """
  48. assert re.match(r'PSA_KEY_TYPE_\w+\Z', self.name)
  49. self.expression = self.name
  50. """A C expression whose value is the key type encoding."""
  51. if self.params is not None:
  52. self.expression += '(' + ', '.join(self.params) + ')'
  53. self.private_type = re.sub(r'_PUBLIC_KEY\Z', r'_KEY_PAIR', self.name)
  54. """The key type macro name for the corresponding key pair type.
  55. For everything other than a public key type, this is the same as
  56. `self.name`.
  57. """
  58. ECC_KEY_SIZES = {
  59. 'PSA_ECC_FAMILY_SECP_K1': (192, 224, 256),
  60. 'PSA_ECC_FAMILY_SECP_R1': (225, 256, 384, 521),
  61. 'PSA_ECC_FAMILY_SECP_R2': (160,),
  62. 'PSA_ECC_FAMILY_SECT_K1': (163, 233, 239, 283, 409, 571),
  63. 'PSA_ECC_FAMILY_SECT_R1': (163, 233, 283, 409, 571),
  64. 'PSA_ECC_FAMILY_SECT_R2': (163,),
  65. 'PSA_ECC_FAMILY_BRAINPOOL_P_R1': (160, 192, 224, 256, 320, 384, 512),
  66. 'PSA_ECC_FAMILY_MONTGOMERY': (255, 448),
  67. 'PSA_ECC_FAMILY_TWISTED_EDWARDS': (255, 448),
  68. }
  69. KEY_TYPE_SIZES = {
  70. 'PSA_KEY_TYPE_AES': (128, 192, 256), # exhaustive
  71. 'PSA_KEY_TYPE_ARC4': (8, 128, 2048), # extremes + sensible
  72. 'PSA_KEY_TYPE_ARIA': (128, 192, 256), # exhaustive
  73. 'PSA_KEY_TYPE_CAMELLIA': (128, 192, 256), # exhaustive
  74. 'PSA_KEY_TYPE_CHACHA20': (256,), # exhaustive
  75. 'PSA_KEY_TYPE_DERIVE': (120, 128), # sample
  76. 'PSA_KEY_TYPE_DES': (64, 128, 192), # exhaustive
  77. 'PSA_KEY_TYPE_HMAC': (128, 160, 224, 256, 384, 512), # standard size for each supported hash
  78. 'PSA_KEY_TYPE_RAW_DATA': (8, 40, 128), # sample
  79. 'PSA_KEY_TYPE_RSA_KEY_PAIR': (1024, 1536), # small sample
  80. }
  81. def sizes_to_test(self) -> Tuple[int, ...]:
  82. """Return a tuple of key sizes to test.
  83. For key types that only allow a single size, or only a small set of
  84. sizes, these are all the possible sizes. For key types that allow a
  85. wide range of sizes, these are a representative sample of sizes,
  86. excluding large sizes for which a typical resource-constrained platform
  87. may run out of memory.
  88. """
  89. if self.private_type == 'PSA_KEY_TYPE_ECC_KEY_PAIR':
  90. assert self.params is not None
  91. return self.ECC_KEY_SIZES[self.params[0]]
  92. return self.KEY_TYPE_SIZES[self.private_type]
  93. # "48657265006973206b6579a064617461"
  94. DATA_BLOCK = b'Here\000is key\240data'
  95. def key_material(self, bits: int) -> bytes:
  96. """Return a byte string containing suitable key material with the given bit length.
  97. Use the PSA export representation. The resulting byte string is one that
  98. can be obtained with the following code:
  99. ```
  100. psa_set_key_type(&attributes, `self.expression`);
  101. psa_set_key_bits(&attributes, `bits`);
  102. psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_EXPORT);
  103. psa_generate_key(&attributes, &id);
  104. psa_export_key(id, `material`, ...);
  105. ```
  106. """
  107. if self.expression in ASYMMETRIC_KEY_DATA:
  108. if bits not in ASYMMETRIC_KEY_DATA[self.expression]:
  109. raise ValueError('No key data for {}-bit {}'
  110. .format(bits, self.expression))
  111. return ASYMMETRIC_KEY_DATA[self.expression][bits]
  112. if bits % 8 != 0:
  113. raise ValueError('Non-integer number of bytes: {} bits for {}'
  114. .format(bits, self.expression))
  115. length = bits // 8
  116. if self.name == 'PSA_KEY_TYPE_DES':
  117. # "644573206b457901644573206b457902644573206b457904"
  118. des3 = b'dEs kEy\001dEs kEy\002dEs kEy\004'
  119. return des3[:length]
  120. return b''.join([self.DATA_BLOCK] * (length // len(self.DATA_BLOCK)) +
  121. [self.DATA_BLOCK[:length % len(self.DATA_BLOCK)]])
  122. KEY_TYPE_FOR_SIGNATURE = {
  123. 'PSA_KEY_USAGE_SIGN_HASH': re.compile('.*KEY_PAIR'),
  124. 'PSA_KEY_USAGE_VERIFY_HASH': re.compile('.*KEY.*')
  125. } #type: Dict[str, Pattern]
  126. """Use a regexp to determine key types for which signature is possible
  127. when using the actual usage flag.
  128. """
  129. def is_valid_for_signature(self, usage: str) -> bool:
  130. """Determine if the key type is compatible with the specified
  131. signitute type.
  132. """
  133. # This is just temporaly solution for the implicit usage flags.
  134. return re.match(self.KEY_TYPE_FOR_SIGNATURE[usage], self.name) is not None