crypto_knowledge.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  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 enum
  19. import re
  20. from typing import FrozenSet, Iterable, List, Optional, Tuple, Dict
  21. from .asymmetric_key_data import ASYMMETRIC_KEY_DATA
  22. def short_expression(original: str, level: int = 0) -> str:
  23. """Abbreviate the expression, keeping it human-readable.
  24. If `level` is 0, just remove parts that are implicit from context,
  25. such as a leading ``PSA_KEY_TYPE_``.
  26. For larger values of `level`, also abbreviate some names in an
  27. unambiguous, but ad hoc way.
  28. """
  29. short = original
  30. short = re.sub(r'\bPSA_(?:ALG|ECC_FAMILY|KEY_[A-Z]+)_', r'', short)
  31. short = re.sub(r' +', r'', short)
  32. if level >= 1:
  33. short = re.sub(r'PUBLIC_KEY\b', r'PUB', short)
  34. short = re.sub(r'KEY_PAIR\b', r'PAIR', short)
  35. short = re.sub(r'\bBRAINPOOL_P', r'BP', short)
  36. short = re.sub(r'\bMONTGOMERY\b', r'MGM', short)
  37. short = re.sub(r'AEAD_WITH_SHORTENED_TAG\b', r'AEAD_SHORT', short)
  38. short = re.sub(r'\bDETERMINISTIC_', r'DET_', short)
  39. short = re.sub(r'\bKEY_AGREEMENT\b', r'KA', short)
  40. short = re.sub(r'_PSK_TO_MS\b', r'_PSK2MS', short)
  41. return short
  42. BLOCK_CIPHERS = frozenset(['AES', 'ARIA', 'CAMELLIA', 'DES'])
  43. BLOCK_MAC_MODES = frozenset(['CBC_MAC', 'CMAC'])
  44. BLOCK_CIPHER_MODES = frozenset([
  45. 'CTR', 'CFB', 'OFB', 'XTS', 'CCM_STAR_NO_TAG',
  46. 'ECB_NO_PADDING', 'CBC_NO_PADDING', 'CBC_PKCS7',
  47. ])
  48. BLOCK_AEAD_MODES = frozenset(['CCM', 'GCM'])
  49. class EllipticCurveCategory(enum.Enum):
  50. """Categorization of elliptic curve families.
  51. The category of a curve determines what algorithms are defined over it.
  52. """
  53. SHORT_WEIERSTRASS = 0
  54. MONTGOMERY = 1
  55. TWISTED_EDWARDS = 2
  56. @staticmethod
  57. def from_family(family: str) -> 'EllipticCurveCategory':
  58. if family == 'PSA_ECC_FAMILY_MONTGOMERY':
  59. return EllipticCurveCategory.MONTGOMERY
  60. if family == 'PSA_ECC_FAMILY_TWISTED_EDWARDS':
  61. return EllipticCurveCategory.TWISTED_EDWARDS
  62. # Default to SW, which most curves belong to.
  63. return EllipticCurveCategory.SHORT_WEIERSTRASS
  64. class KeyType:
  65. """Knowledge about a PSA key type."""
  66. def __init__(self, name: str, params: Optional[Iterable[str]] = None) -> None:
  67. """Analyze a key type.
  68. The key type must be specified in PSA syntax. In its simplest form,
  69. `name` is a string 'PSA_KEY_TYPE_xxx' which is the name of a PSA key
  70. type macro. For key types that take arguments, the arguments can
  71. be passed either through the optional argument `params` or by
  72. passing an expression of the form 'PSA_KEY_TYPE_xxx(param1, ...)'
  73. in `name` as a string.
  74. """
  75. self.name = name.strip()
  76. """The key type macro name (``PSA_KEY_TYPE_xxx``).
  77. For key types constructed from a macro with arguments, this is the
  78. name of the macro, and the arguments are in `self.params`.
  79. """
  80. if params is None:
  81. if '(' in self.name:
  82. m = re.match(r'(\w+)\s*\((.*)\)\Z', self.name)
  83. assert m is not None
  84. self.name = m.group(1)
  85. params = m.group(2).split(',')
  86. self.params = (None if params is None else
  87. [param.strip() for param in params])
  88. """The parameters of the key type, if there are any.
  89. None if the key type is a macro without arguments.
  90. """
  91. assert re.match(r'PSA_KEY_TYPE_\w+\Z', self.name)
  92. self.expression = self.name
  93. """A C expression whose value is the key type encoding."""
  94. if self.params is not None:
  95. self.expression += '(' + ', '.join(self.params) + ')'
  96. m = re.match(r'PSA_KEY_TYPE_(\w+)', self.name)
  97. assert m
  98. self.head = re.sub(r'_(?:PUBLIC_KEY|KEY_PAIR)\Z', r'', m.group(1))
  99. """The key type macro name, with common prefixes and suffixes stripped."""
  100. self.private_type = re.sub(r'_PUBLIC_KEY\Z', r'_KEY_PAIR', self.name)
  101. """The key type macro name for the corresponding key pair type.
  102. For everything other than a public key type, this is the same as
  103. `self.name`.
  104. """
  105. def short_expression(self, level: int = 0) -> str:
  106. """Abbreviate the expression, keeping it human-readable.
  107. See `crypto_knowledge.short_expression`.
  108. """
  109. return short_expression(self.expression, level=level)
  110. def is_public(self) -> bool:
  111. """Whether the key type is for public keys."""
  112. return self.name.endswith('_PUBLIC_KEY')
  113. ECC_KEY_SIZES = {
  114. 'PSA_ECC_FAMILY_SECP_K1': (192, 224, 256),
  115. 'PSA_ECC_FAMILY_SECP_R1': (225, 256, 384, 521),
  116. 'PSA_ECC_FAMILY_SECP_R2': (160,),
  117. 'PSA_ECC_FAMILY_SECT_K1': (163, 233, 239, 283, 409, 571),
  118. 'PSA_ECC_FAMILY_SECT_R1': (163, 233, 283, 409, 571),
  119. 'PSA_ECC_FAMILY_SECT_R2': (163,),
  120. 'PSA_ECC_FAMILY_BRAINPOOL_P_R1': (160, 192, 224, 256, 320, 384, 512),
  121. 'PSA_ECC_FAMILY_MONTGOMERY': (255, 448),
  122. 'PSA_ECC_FAMILY_TWISTED_EDWARDS': (255, 448),
  123. } # type: Dict[str, Tuple[int, ...]]
  124. KEY_TYPE_SIZES = {
  125. 'PSA_KEY_TYPE_AES': (128, 192, 256), # exhaustive
  126. 'PSA_KEY_TYPE_ARIA': (128, 192, 256), # exhaustive
  127. 'PSA_KEY_TYPE_CAMELLIA': (128, 192, 256), # exhaustive
  128. 'PSA_KEY_TYPE_CHACHA20': (256,), # exhaustive
  129. 'PSA_KEY_TYPE_DERIVE': (120, 128), # sample
  130. 'PSA_KEY_TYPE_DES': (64, 128, 192), # exhaustive
  131. 'PSA_KEY_TYPE_HMAC': (128, 160, 224, 256, 384, 512), # standard size for each supported hash
  132. 'PSA_KEY_TYPE_PASSWORD': (48, 168, 336), # sample
  133. 'PSA_KEY_TYPE_PASSWORD_HASH': (128, 256), # sample
  134. 'PSA_KEY_TYPE_PEPPER': (128, 256), # sample
  135. 'PSA_KEY_TYPE_RAW_DATA': (8, 40, 128), # sample
  136. 'PSA_KEY_TYPE_RSA_KEY_PAIR': (1024, 1536), # small sample
  137. } # type: Dict[str, Tuple[int, ...]]
  138. def sizes_to_test(self) -> Tuple[int, ...]:
  139. """Return a tuple of key sizes to test.
  140. For key types that only allow a single size, or only a small set of
  141. sizes, these are all the possible sizes. For key types that allow a
  142. wide range of sizes, these are a representative sample of sizes,
  143. excluding large sizes for which a typical resource-constrained platform
  144. may run out of memory.
  145. """
  146. if self.private_type == 'PSA_KEY_TYPE_ECC_KEY_PAIR':
  147. assert self.params is not None
  148. return self.ECC_KEY_SIZES[self.params[0]]
  149. return self.KEY_TYPE_SIZES[self.private_type]
  150. # "48657265006973206b6579a064617461"
  151. DATA_BLOCK = b'Here\000is key\240data'
  152. def key_material(self, bits: int) -> bytes:
  153. """Return a byte string containing suitable key material with the given bit length.
  154. Use the PSA export representation. The resulting byte string is one that
  155. can be obtained with the following code:
  156. ```
  157. psa_set_key_type(&attributes, `self.expression`);
  158. psa_set_key_bits(&attributes, `bits`);
  159. psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_EXPORT);
  160. psa_generate_key(&attributes, &id);
  161. psa_export_key(id, `material`, ...);
  162. ```
  163. """
  164. if self.expression in ASYMMETRIC_KEY_DATA:
  165. if bits not in ASYMMETRIC_KEY_DATA[self.expression]:
  166. raise ValueError('No key data for {}-bit {}'
  167. .format(bits, self.expression))
  168. return ASYMMETRIC_KEY_DATA[self.expression][bits]
  169. if bits % 8 != 0:
  170. raise ValueError('Non-integer number of bytes: {} bits for {}'
  171. .format(bits, self.expression))
  172. length = bits // 8
  173. if self.name == 'PSA_KEY_TYPE_DES':
  174. # "644573206b457901644573206b457902644573206b457904"
  175. des3 = b'dEs kEy\001dEs kEy\002dEs kEy\004'
  176. return des3[:length]
  177. return b''.join([self.DATA_BLOCK] * (length // len(self.DATA_BLOCK)) +
  178. [self.DATA_BLOCK[:length % len(self.DATA_BLOCK)]])
  179. def can_do(self, alg: 'Algorithm') -> bool:
  180. """Whether this key type can be used for operations with the given algorithm.
  181. This function does not currently handle key derivation or PAKE.
  182. """
  183. #pylint: disable=too-many-branches,too-many-return-statements
  184. if not alg.is_valid_for_operation():
  185. return False
  186. if self.head == 'HMAC' and alg.head == 'HMAC':
  187. return True
  188. if self.head == 'DES':
  189. # 64-bit block ciphers only allow a reduced set of modes.
  190. return alg.head in [
  191. 'CBC_NO_PADDING', 'CBC_PKCS7',
  192. 'ECB_NO_PADDING',
  193. ]
  194. if self.head in BLOCK_CIPHERS and \
  195. alg.head in frozenset.union(BLOCK_MAC_MODES,
  196. BLOCK_CIPHER_MODES,
  197. BLOCK_AEAD_MODES):
  198. if alg.head in ['CMAC', 'OFB'] and \
  199. self.head in ['ARIA', 'CAMELLIA']:
  200. return False # not implemented in Mbed TLS
  201. return True
  202. if self.head == 'CHACHA20' and alg.head == 'CHACHA20_POLY1305':
  203. return True
  204. if self.head in {'ARC4', 'CHACHA20'} and \
  205. alg.head == 'STREAM_CIPHER':
  206. return True
  207. if self.head == 'RSA' and alg.head.startswith('RSA_'):
  208. return True
  209. if alg.category == AlgorithmCategory.KEY_AGREEMENT and \
  210. self.is_public():
  211. # The PSA API does not use public key objects in key agreement
  212. # operations: it imports the public key as a formatted byte string.
  213. # So a public key object with a key agreement algorithm is not
  214. # a valid combination.
  215. return False
  216. if alg.is_invalid_key_agreement_with_derivation():
  217. return False
  218. if self.head == 'ECC':
  219. assert self.params is not None
  220. eccc = EllipticCurveCategory.from_family(self.params[0])
  221. if alg.head == 'ECDH' and \
  222. eccc in {EllipticCurveCategory.SHORT_WEIERSTRASS,
  223. EllipticCurveCategory.MONTGOMERY}:
  224. return True
  225. if alg.head == 'ECDSA' and \
  226. eccc == EllipticCurveCategory.SHORT_WEIERSTRASS:
  227. return True
  228. if alg.head in {'PURE_EDDSA', 'EDDSA_PREHASH'} and \
  229. eccc == EllipticCurveCategory.TWISTED_EDWARDS:
  230. return True
  231. return False
  232. class AlgorithmCategory(enum.Enum):
  233. """PSA algorithm categories."""
  234. # The numbers are aligned with the category bits in numerical values of
  235. # algorithms.
  236. HASH = 2
  237. MAC = 3
  238. CIPHER = 4
  239. AEAD = 5
  240. SIGN = 6
  241. ASYMMETRIC_ENCRYPTION = 7
  242. KEY_DERIVATION = 8
  243. KEY_AGREEMENT = 9
  244. PAKE = 10
  245. def requires_key(self) -> bool:
  246. """Whether operations in this category are set up with a key."""
  247. return self not in {self.HASH, self.KEY_DERIVATION}
  248. def is_asymmetric(self) -> bool:
  249. """Whether operations in this category involve asymmetric keys."""
  250. return self in {
  251. self.SIGN,
  252. self.ASYMMETRIC_ENCRYPTION,
  253. self.KEY_AGREEMENT
  254. }
  255. class AlgorithmNotRecognized(Exception):
  256. def __init__(self, expr: str) -> None:
  257. super().__init__('Algorithm not recognized: ' + expr)
  258. self.expr = expr
  259. class Algorithm:
  260. """Knowledge about a PSA algorithm."""
  261. @staticmethod
  262. def determine_base(expr: str) -> str:
  263. """Return an expression for the "base" of the algorithm.
  264. This strips off variants of algorithms such as MAC truncation.
  265. This function does not attempt to detect invalid inputs.
  266. """
  267. m = re.match(r'PSA_ALG_(?:'
  268. r'(?:TRUNCATED|AT_LEAST_THIS_LENGTH)_MAC|'
  269. r'AEAD_WITH_(?:SHORTENED|AT_LEAST_THIS_LENGTH)_TAG'
  270. r')\((.*),[^,]+\)\Z', expr)
  271. if m:
  272. expr = m.group(1)
  273. return expr
  274. @staticmethod
  275. def determine_head(expr: str) -> str:
  276. """Return the head of an algorithm expression.
  277. The head is the first (outermost) constructor, without its PSA_ALG_
  278. prefix, and with some normalization of similar algorithms.
  279. """
  280. m = re.match(r'PSA_ALG_(?:DETERMINISTIC_)?(\w+)', expr)
  281. if not m:
  282. raise AlgorithmNotRecognized(expr)
  283. head = m.group(1)
  284. if head == 'KEY_AGREEMENT':
  285. m = re.match(r'PSA_ALG_KEY_AGREEMENT\s*\(\s*PSA_ALG_(\w+)', expr)
  286. if not m:
  287. raise AlgorithmNotRecognized(expr)
  288. head = m.group(1)
  289. head = re.sub(r'_ANY\Z', r'', head)
  290. if re.match(r'ED[0-9]+PH\Z', head):
  291. head = 'EDDSA_PREHASH'
  292. return head
  293. CATEGORY_FROM_HEAD = {
  294. 'SHA': AlgorithmCategory.HASH,
  295. 'SHAKE256_512': AlgorithmCategory.HASH,
  296. 'MD': AlgorithmCategory.HASH,
  297. 'RIPEMD': AlgorithmCategory.HASH,
  298. 'ANY_HASH': AlgorithmCategory.HASH,
  299. 'HMAC': AlgorithmCategory.MAC,
  300. 'STREAM_CIPHER': AlgorithmCategory.CIPHER,
  301. 'CHACHA20_POLY1305': AlgorithmCategory.AEAD,
  302. 'DSA': AlgorithmCategory.SIGN,
  303. 'ECDSA': AlgorithmCategory.SIGN,
  304. 'EDDSA': AlgorithmCategory.SIGN,
  305. 'PURE_EDDSA': AlgorithmCategory.SIGN,
  306. 'RSA_PSS': AlgorithmCategory.SIGN,
  307. 'RSA_PKCS1V15_SIGN': AlgorithmCategory.SIGN,
  308. 'RSA_PKCS1V15_CRYPT': AlgorithmCategory.ASYMMETRIC_ENCRYPTION,
  309. 'RSA_OAEP': AlgorithmCategory.ASYMMETRIC_ENCRYPTION,
  310. 'HKDF': AlgorithmCategory.KEY_DERIVATION,
  311. 'TLS12_PRF': AlgorithmCategory.KEY_DERIVATION,
  312. 'TLS12_PSK_TO_MS': AlgorithmCategory.KEY_DERIVATION,
  313. 'TLS12_ECJPAKE_TO_PMS': AlgorithmCategory.KEY_DERIVATION,
  314. 'PBKDF': AlgorithmCategory.KEY_DERIVATION,
  315. 'ECDH': AlgorithmCategory.KEY_AGREEMENT,
  316. 'FFDH': AlgorithmCategory.KEY_AGREEMENT,
  317. # KEY_AGREEMENT(...) is a key derivation with a key agreement component
  318. 'KEY_AGREEMENT': AlgorithmCategory.KEY_DERIVATION,
  319. 'JPAKE': AlgorithmCategory.PAKE,
  320. }
  321. for x in BLOCK_MAC_MODES:
  322. CATEGORY_FROM_HEAD[x] = AlgorithmCategory.MAC
  323. for x in BLOCK_CIPHER_MODES:
  324. CATEGORY_FROM_HEAD[x] = AlgorithmCategory.CIPHER
  325. for x in BLOCK_AEAD_MODES:
  326. CATEGORY_FROM_HEAD[x] = AlgorithmCategory.AEAD
  327. def determine_category(self, expr: str, head: str) -> AlgorithmCategory:
  328. """Return the category of the given algorithm expression.
  329. This function does not attempt to detect invalid inputs.
  330. """
  331. prefix = head
  332. while prefix:
  333. if prefix in self.CATEGORY_FROM_HEAD:
  334. return self.CATEGORY_FROM_HEAD[prefix]
  335. if re.match(r'.*[0-9]\Z', prefix):
  336. prefix = re.sub(r'_*[0-9]+\Z', r'', prefix)
  337. else:
  338. prefix = re.sub(r'_*[^_]*\Z', r'', prefix)
  339. raise AlgorithmNotRecognized(expr)
  340. @staticmethod
  341. def determine_wildcard(expr) -> bool:
  342. """Whether the given algorithm expression is a wildcard.
  343. This function does not attempt to detect invalid inputs.
  344. """
  345. if re.search(r'\bPSA_ALG_ANY_HASH\b', expr):
  346. return True
  347. if re.search(r'_AT_LEAST_', expr):
  348. return True
  349. return False
  350. def __init__(self, expr: str) -> None:
  351. """Analyze an algorithm value.
  352. The algorithm must be expressed as a C expression containing only
  353. calls to PSA algorithm constructor macros and numeric literals.
  354. This class is only programmed to handle valid expressions. Invalid
  355. expressions may result in exceptions or in nonsensical results.
  356. """
  357. self.expression = re.sub(r'\s+', r'', expr)
  358. self.base_expression = self.determine_base(self.expression)
  359. self.head = self.determine_head(self.base_expression)
  360. self.category = self.determine_category(self.base_expression, self.head)
  361. self.is_wildcard = self.determine_wildcard(self.expression)
  362. def get_key_agreement_derivation(self) -> Optional[str]:
  363. """For a combined key agreement and key derivation algorithm, get the derivation part.
  364. For anything else, return None.
  365. """
  366. if self.category != AlgorithmCategory.KEY_AGREEMENT:
  367. return None
  368. m = re.match(r'PSA_ALG_KEY_AGREEMENT\(\w+,\s*(.*)\)\Z', self.expression)
  369. if not m:
  370. return None
  371. kdf_alg = m.group(1)
  372. # Assume kdf_alg is either a valid KDF or 0.
  373. if re.match(r'(?:0[Xx])?0+\s*\Z', kdf_alg):
  374. return None
  375. return kdf_alg
  376. KEY_DERIVATIONS_INCOMPATIBLE_WITH_AGREEMENT = frozenset([
  377. 'PSA_ALG_TLS12_ECJPAKE_TO_PMS', # secret input in specific format
  378. ])
  379. def is_valid_key_agreement_with_derivation(self) -> bool:
  380. """Whether this is a valid combined key agreement and key derivation algorithm."""
  381. kdf_alg = self.get_key_agreement_derivation()
  382. if kdf_alg is None:
  383. return False
  384. return kdf_alg not in self.KEY_DERIVATIONS_INCOMPATIBLE_WITH_AGREEMENT
  385. def is_invalid_key_agreement_with_derivation(self) -> bool:
  386. """Whether this is an invalid combined key agreement and key derivation algorithm."""
  387. kdf_alg = self.get_key_agreement_derivation()
  388. if kdf_alg is None:
  389. return False
  390. return kdf_alg in self.KEY_DERIVATIONS_INCOMPATIBLE_WITH_AGREEMENT
  391. def short_expression(self, level: int = 0) -> str:
  392. """Abbreviate the expression, keeping it human-readable.
  393. See `crypto_knowledge.short_expression`.
  394. """
  395. return short_expression(self.expression, level=level)
  396. HASH_LENGTH = {
  397. 'PSA_ALG_MD5': 16,
  398. 'PSA_ALG_SHA_1': 20,
  399. }
  400. HASH_LENGTH_BITS_RE = re.compile(r'([0-9]+)\Z')
  401. @classmethod
  402. def hash_length(cls, alg: str) -> int:
  403. """The length of the given hash algorithm, in bytes."""
  404. if alg in cls.HASH_LENGTH:
  405. return cls.HASH_LENGTH[alg]
  406. m = cls.HASH_LENGTH_BITS_RE.search(alg)
  407. if m:
  408. return int(m.group(1)) // 8
  409. raise ValueError('Unknown hash length for ' + alg)
  410. PERMITTED_TAG_LENGTHS = {
  411. 'PSA_ALG_CCM': frozenset([4, 6, 8, 10, 12, 14, 16]),
  412. 'PSA_ALG_CHACHA20_POLY1305': frozenset([16]),
  413. 'PSA_ALG_GCM': frozenset([4, 8, 12, 13, 14, 15, 16]),
  414. }
  415. MAC_LENGTH = {
  416. 'PSA_ALG_CBC_MAC': 16, # actually the block cipher length
  417. 'PSA_ALG_CMAC': 16, # actually the block cipher length
  418. }
  419. HMAC_RE = re.compile(r'PSA_ALG_HMAC\((.*)\)\Z')
  420. @classmethod
  421. def permitted_truncations(cls, base: str) -> FrozenSet[int]:
  422. """Permitted output lengths for the given MAC or AEAD base algorithm.
  423. For a MAC algorithm, this is the set of truncation lengths that
  424. Mbed TLS supports.
  425. For an AEAD algorithm, this is the set of truncation lengths that
  426. are permitted by the algorithm specification.
  427. """
  428. if base in cls.PERMITTED_TAG_LENGTHS:
  429. return cls.PERMITTED_TAG_LENGTHS[base]
  430. max_length = cls.MAC_LENGTH.get(base, None)
  431. if max_length is None:
  432. m = cls.HMAC_RE.match(base)
  433. if m:
  434. max_length = cls.hash_length(m.group(1))
  435. if max_length is None:
  436. raise ValueError('Unknown permitted lengths for ' + base)
  437. return frozenset(range(4, max_length + 1))
  438. TRUNCATED_ALG_RE = re.compile(
  439. r'(?P<face>PSA_ALG_(?:AEAD_WITH_SHORTENED_TAG|TRUNCATED_MAC))'
  440. r'\((?P<base>.*),'
  441. r'(?P<length>0[Xx][0-9A-Fa-f]+|[1-9][0-9]*|0[0-7]*)[LUlu]*\)\Z')
  442. def is_invalid_truncation(self) -> bool:
  443. """False for a MAC or AEAD algorithm truncated to an invalid length.
  444. True for a MAC or AEAD algorithm truncated to a valid length or to
  445. a length that cannot be determined. True for anything other than
  446. a truncated MAC or AEAD.
  447. """
  448. m = self.TRUNCATED_ALG_RE.match(self.expression)
  449. if m:
  450. base = m.group('base')
  451. to_length = int(m.group('length'), 0)
  452. permitted_lengths = self.permitted_truncations(base)
  453. if to_length not in permitted_lengths:
  454. return True
  455. return False
  456. def is_valid_for_operation(self) -> bool:
  457. """Whether this algorithm construction is valid for an operation.
  458. This function assumes that the algorithm is constructed in a
  459. "grammatically" correct way, and only rejects semantically invalid
  460. combinations.
  461. """
  462. if self.is_wildcard:
  463. return False
  464. if self.is_invalid_truncation():
  465. return False
  466. return True
  467. def can_do(self, category: AlgorithmCategory) -> bool:
  468. """Whether this algorithm can perform operations in the given category.
  469. """
  470. if category == self.category:
  471. return True
  472. if category == AlgorithmCategory.KEY_DERIVATION and \
  473. self.is_valid_key_agreement_with_derivation():
  474. return True
  475. return False
  476. def usage_flags(self, public: bool = False) -> List[str]:
  477. """The list of usage flags describing operations that can perform this algorithm.
  478. If public is true, only return public-key operations, not private-key operations.
  479. """
  480. if self.category == AlgorithmCategory.HASH:
  481. flags = []
  482. elif self.category == AlgorithmCategory.MAC:
  483. flags = ['SIGN_HASH', 'SIGN_MESSAGE',
  484. 'VERIFY_HASH', 'VERIFY_MESSAGE']
  485. elif self.category == AlgorithmCategory.CIPHER or \
  486. self.category == AlgorithmCategory.AEAD:
  487. flags = ['DECRYPT', 'ENCRYPT']
  488. elif self.category == AlgorithmCategory.SIGN:
  489. flags = ['VERIFY_HASH', 'VERIFY_MESSAGE']
  490. if not public:
  491. flags += ['SIGN_HASH', 'SIGN_MESSAGE']
  492. elif self.category == AlgorithmCategory.ASYMMETRIC_ENCRYPTION:
  493. flags = ['ENCRYPT']
  494. if not public:
  495. flags += ['DECRYPT']
  496. elif self.category == AlgorithmCategory.KEY_DERIVATION or \
  497. self.category == AlgorithmCategory.KEY_AGREEMENT:
  498. flags = ['DERIVE']
  499. else:
  500. raise AlgorithmNotRecognized(self.expression)
  501. return ['PSA_KEY_USAGE_' + flag for flag in flags]