blob: f227a411b09322c564de62fc02c250330b890722 [file] [log] [blame]
Gilles Peskine0156a152021-01-26 21:23:56 +01001"""Knowledge about cryptographic mechanisms implemented in Mbed TLS.
2
3This module is entirely based on the PSA API.
4"""
5
6# Copyright The Mbed TLS Contributors
7# SPDX-License-Identifier: Apache-2.0
8#
9# Licensed under the Apache License, Version 2.0 (the "License"); you may
10# not use this file except in compliance with the License.
11# You may obtain a copy of the License at
12#
13# http://www.apache.org/licenses/LICENSE-2.0
14#
15# Unless required by applicable law or agreed to in writing, software
16# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
17# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18# See the License for the specific language governing permissions and
19# limitations under the License.
20
Gilles Peskine0dacd4d2021-04-29 20:38:01 +020021import enum
Gilles Peskine0156a152021-01-26 21:23:56 +010022import re
Gilles Peskineb0537ba2022-03-19 10:37:33 +010023from typing import FrozenSet, Iterable, List, Optional, Tuple
Gilles Peskine0156a152021-01-26 21:23:56 +010024
Gilles Peskine239765a2022-09-16 22:35:18 +020025from .asymmetric_key_data import ASYMMETRIC_KEY_DATA
Gilles Peskine6f6483f2021-01-27 12:43:24 +010026
Gilles Peskine0dacd4d2021-04-29 20:38:01 +020027
Gilles Peskine930ccef2022-03-18 00:02:15 +010028def short_expression(original: str, level: int = 0) -> str:
Gilles Peskined79aef52022-03-17 23:42:25 +010029 """Abbreviate the expression, keeping it human-readable.
30
31 If `level` is 0, just remove parts that are implicit from context,
32 such as a leading ``PSA_KEY_TYPE_``.
33 For larger values of `level`, also abbreviate some names in an
34 unambiguous, but ad hoc way.
35 """
36 short = original
37 short = re.sub(r'\bPSA_(?:ALG|ECC_FAMILY|KEY_[A-Z]+)_', r'', short)
38 short = re.sub(r' +', r'', short)
Gilles Peskine930ccef2022-03-18 00:02:15 +010039 if level >= 1:
40 short = re.sub(r'PUBLIC_KEY\b', r'PUB', short)
41 short = re.sub(r'KEY_PAIR\b', r'PAIR', short)
42 short = re.sub(r'\bBRAINPOOL_P', r'BP', short)
43 short = re.sub(r'\bMONTGOMERY\b', r'MGM', short)
44 short = re.sub(r'AEAD_WITH_SHORTENED_TAG\b', r'AEAD_SHORT', short)
45 short = re.sub(r'\bDETERMINISTIC_', r'DET_', short)
46 short = re.sub(r'\bKEY_AGREEMENT\b', r'KA', short)
47 short = re.sub(r'_PSK_TO_MS\b', r'_PSK2MS', short)
Gilles Peskined79aef52022-03-17 23:42:25 +010048 return short
49
50
Gilles Peskine39054332021-04-29 20:38:47 +020051BLOCK_CIPHERS = frozenset(['AES', 'ARIA', 'CAMELLIA', 'DES'])
Gilles Peskine0dacd4d2021-04-29 20:38:01 +020052BLOCK_MAC_MODES = frozenset(['CBC_MAC', 'CMAC'])
53BLOCK_CIPHER_MODES = frozenset([
54 'CTR', 'CFB', 'OFB', 'XTS', 'CCM_STAR_NO_TAG',
55 'ECB_NO_PADDING', 'CBC_NO_PADDING', 'CBC_PKCS7',
56])
57BLOCK_AEAD_MODES = frozenset(['CCM', 'GCM'])
58
Gilles Peskine39054332021-04-29 20:38:47 +020059class EllipticCurveCategory(enum.Enum):
60 """Categorization of elliptic curve families.
61
62 The category of a curve determines what algorithms are defined over it.
63 """
64
65 SHORT_WEIERSTRASS = 0
66 MONTGOMERY = 1
67 TWISTED_EDWARDS = 2
68
69 @staticmethod
70 def from_family(family: str) -> 'EllipticCurveCategory':
71 if family == 'PSA_ECC_FAMILY_MONTGOMERY':
72 return EllipticCurveCategory.MONTGOMERY
73 if family == 'PSA_ECC_FAMILY_TWISTED_EDWARDS':
74 return EllipticCurveCategory.TWISTED_EDWARDS
75 # Default to SW, which most curves belong to.
76 return EllipticCurveCategory.SHORT_WEIERSTRASS
77
Gilles Peskine0dacd4d2021-04-29 20:38:01 +020078
Gilles Peskine0156a152021-01-26 21:23:56 +010079class KeyType:
80 """Knowledge about a PSA key type."""
81
Gilles Peskine2a71b722021-04-29 20:19:57 +020082 def __init__(self, name: str, params: Optional[Iterable[str]] = None) -> None:
Gilles Peskine0156a152021-01-26 21:23:56 +010083 """Analyze a key type.
84
85 The key type must be specified in PSA syntax. In its simplest form,
Gilles Peskinefa3c69a2021-02-16 14:29:22 +010086 `name` is a string 'PSA_KEY_TYPE_xxx' which is the name of a PSA key
Gilles Peskine0156a152021-01-26 21:23:56 +010087 type macro. For key types that take arguments, the arguments can
88 be passed either through the optional argument `params` or by
Gilles Peskine0ba69a42021-04-12 13:41:52 +020089 passing an expression of the form 'PSA_KEY_TYPE_xxx(param1, ...)'
Gilles Peskinefa3c69a2021-02-16 14:29:22 +010090 in `name` as a string.
Gilles Peskine0156a152021-01-26 21:23:56 +010091 """
Gilles Peskined75adfc2021-02-17 18:04:28 +010092
Gilles Peskine0156a152021-01-26 21:23:56 +010093 self.name = name.strip()
Gilles Peskinefa3c69a2021-02-16 14:29:22 +010094 """The key type macro name (``PSA_KEY_TYPE_xxx``).
95
96 For key types constructed from a macro with arguments, this is the
97 name of the macro, and the arguments are in `self.params`.
98 """
Gilles Peskine0156a152021-01-26 21:23:56 +010099 if params is None:
100 if '(' in self.name:
101 m = re.match(r'(\w+)\s*\((.*)\)\Z', self.name)
102 assert m is not None
103 self.name = m.group(1)
Gilles Peskine0ba69a42021-04-12 13:41:52 +0200104 params = m.group(2).split(',')
Gilles Peskinefa3c69a2021-02-16 14:29:22 +0100105 self.params = (None if params is None else
106 [param.strip() for param in params])
107 """The parameters of the key type, if there are any.
108
109 None if the key type is a macro without arguments.
110 """
Gilles Peskined75adfc2021-02-17 18:04:28 +0100111 assert re.match(r'PSA_KEY_TYPE_\w+\Z', self.name)
112
Gilles Peskine0156a152021-01-26 21:23:56 +0100113 self.expression = self.name
Gilles Peskinefa3c69a2021-02-16 14:29:22 +0100114 """A C expression whose value is the key type encoding."""
Gilles Peskine0156a152021-01-26 21:23:56 +0100115 if self.params is not None:
116 self.expression += '(' + ', '.join(self.params) + ')'
Gilles Peskined75adfc2021-02-17 18:04:28 +0100117
Gilles Peskine39054332021-04-29 20:38:47 +0200118 m = re.match(r'PSA_KEY_TYPE_(\w+)', self.name)
119 assert m
120 self.head = re.sub(r'_(?:PUBLIC_KEY|KEY_PAIR)\Z', r'', m.group(1))
121 """The key type macro name, with common prefixes and suffixes stripped."""
122
Gilles Peskine0156a152021-01-26 21:23:56 +0100123 self.private_type = re.sub(r'_PUBLIC_KEY\Z', r'_KEY_PAIR', self.name)
Gilles Peskinefa3c69a2021-02-16 14:29:22 +0100124 """The key type macro name for the corresponding key pair type.
125
126 For everything other than a public key type, this is the same as
127 `self.name`.
128 """
Gilles Peskinedf639682021-01-26 21:25:34 +0100129
Gilles Peskine930ccef2022-03-18 00:02:15 +0100130 def short_expression(self, level: int = 0) -> str:
Gilles Peskined79aef52022-03-17 23:42:25 +0100131 """Abbreviate the expression, keeping it human-readable.
132
133 See `crypto_knowledge.short_expression`.
134 """
Gilles Peskine930ccef2022-03-18 00:02:15 +0100135 return short_expression(self.expression, level=level)
Gilles Peskined79aef52022-03-17 23:42:25 +0100136
Gilles Peskinec2fc2412021-04-29 21:56:59 +0200137 def is_public(self) -> bool:
138 """Whether the key type is for public keys."""
139 return self.name.endswith('_PUBLIC_KEY')
140
Gilles Peskinedf639682021-01-26 21:25:34 +0100141 ECC_KEY_SIZES = {
142 'PSA_ECC_FAMILY_SECP_K1': (192, 224, 256),
Gilles Peskine0ac258e2021-01-27 13:11:59 +0100143 'PSA_ECC_FAMILY_SECP_R1': (225, 256, 384, 521),
Gilles Peskinedf639682021-01-26 21:25:34 +0100144 'PSA_ECC_FAMILY_SECP_R2': (160,),
145 'PSA_ECC_FAMILY_SECT_K1': (163, 233, 239, 283, 409, 571),
146 'PSA_ECC_FAMILY_SECT_R1': (163, 233, 283, 409, 571),
147 'PSA_ECC_FAMILY_SECT_R2': (163,),
148 'PSA_ECC_FAMILY_BRAINPOOL_P_R1': (160, 192, 224, 256, 320, 384, 512),
149 'PSA_ECC_FAMILY_MONTGOMERY': (255, 448),
Gilles Peskinea00abc62021-03-16 18:25:14 +0100150 'PSA_ECC_FAMILY_TWISTED_EDWARDS': (255, 448),
Gilles Peskinedf639682021-01-26 21:25:34 +0100151 }
152 KEY_TYPE_SIZES = {
153 'PSA_KEY_TYPE_AES': (128, 192, 256), # exhaustive
154 'PSA_KEY_TYPE_ARC4': (8, 128, 2048), # extremes + sensible
155 'PSA_KEY_TYPE_ARIA': (128, 192, 256), # exhaustive
156 'PSA_KEY_TYPE_CAMELLIA': (128, 192, 256), # exhaustive
157 'PSA_KEY_TYPE_CHACHA20': (256,), # exhaustive
158 'PSA_KEY_TYPE_DERIVE': (120, 128), # sample
159 'PSA_KEY_TYPE_DES': (64, 128, 192), # exhaustive
160 'PSA_KEY_TYPE_HMAC': (128, 160, 224, 256, 384, 512), # standard size for each supported hash
161 'PSA_KEY_TYPE_RAW_DATA': (8, 40, 128), # sample
162 'PSA_KEY_TYPE_RSA_KEY_PAIR': (1024, 1536), # small sample
163 }
164 def sizes_to_test(self) -> Tuple[int, ...]:
165 """Return a tuple of key sizes to test.
166
167 For key types that only allow a single size, or only a small set of
168 sizes, these are all the possible sizes. For key types that allow a
169 wide range of sizes, these are a representative sample of sizes,
170 excluding large sizes for which a typical resource-constrained platform
171 may run out of memory.
172 """
173 if self.private_type == 'PSA_KEY_TYPE_ECC_KEY_PAIR':
174 assert self.params is not None
175 return self.ECC_KEY_SIZES[self.params[0]]
176 return self.KEY_TYPE_SIZES[self.private_type]
Gilles Peskine397b0282021-01-26 21:26:26 +0100177
178 # "48657265006973206b6579a064617461"
179 DATA_BLOCK = b'Here\000is key\240data'
180 def key_material(self, bits: int) -> bytes:
181 """Return a byte string containing suitable key material with the given bit length.
182
183 Use the PSA export representation. The resulting byte string is one that
184 can be obtained with the following code:
185 ```
186 psa_set_key_type(&attributes, `self.expression`);
187 psa_set_key_bits(&attributes, `bits`);
188 psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_EXPORT);
189 psa_generate_key(&attributes, &id);
190 psa_export_key(id, `material`, ...);
191 ```
192 """
Gilles Peskine6f6483f2021-01-27 12:43:24 +0100193 if self.expression in ASYMMETRIC_KEY_DATA:
194 if bits not in ASYMMETRIC_KEY_DATA[self.expression]:
195 raise ValueError('No key data for {}-bit {}'
196 .format(bits, self.expression))
197 return ASYMMETRIC_KEY_DATA[self.expression][bits]
Gilles Peskine397b0282021-01-26 21:26:26 +0100198 if bits % 8 != 0:
Gilles Peskine6f6483f2021-01-27 12:43:24 +0100199 raise ValueError('Non-integer number of bytes: {} bits for {}'
200 .format(bits, self.expression))
Gilles Peskine397b0282021-01-26 21:26:26 +0100201 length = bits // 8
202 if self.name == 'PSA_KEY_TYPE_DES':
203 # "644573206b457901644573206b457902644573206b457904"
204 des3 = b'dEs kEy\001dEs kEy\002dEs kEy\004'
205 return des3[:length]
Gilles Peskine397b0282021-01-26 21:26:26 +0100206 return b''.join([self.DATA_BLOCK] * (length // len(self.DATA_BLOCK)) +
207 [self.DATA_BLOCK[:length % len(self.DATA_BLOCK)]])
gabor-mezei-arm805c7352021-06-28 20:02:11 +0200208
Gilles Peskine39054332021-04-29 20:38:47 +0200209 def can_do(self, alg: 'Algorithm') -> bool:
210 """Whether this key type can be used for operations with the given algorithm.
211
212 This function does not currently handle key derivation or PAKE.
213 """
Gilles Peskine32611242022-03-19 12:09:13 +0100214 #pylint: disable=too-many-branches,too-many-return-statements
Gilles Peskine39054332021-04-29 20:38:47 +0200215 if alg.is_wildcard:
216 return False
Gilles Peskineb0537ba2022-03-19 10:37:33 +0100217 if alg.is_invalid_truncation():
218 return False
Gilles Peskine39054332021-04-29 20:38:47 +0200219 if self.head == 'HMAC' and alg.head == 'HMAC':
220 return True
Gilles Peskine4eb1c7e2022-03-18 10:18:58 +0100221 if self.head == 'DES':
222 # 64-bit block ciphers only allow a reduced set of modes.
223 return alg.head in [
224 'CBC_NO_PADDING', 'CBC_PKCS7',
225 'ECB_NO_PADDING',
226 ]
Gilles Peskine39054332021-04-29 20:38:47 +0200227 if self.head in BLOCK_CIPHERS and \
228 alg.head in frozenset.union(BLOCK_MAC_MODES,
229 BLOCK_CIPHER_MODES,
230 BLOCK_AEAD_MODES):
Gilles Peskineae93ee62022-03-19 10:49:43 +0100231 if alg.head in ['CMAC', 'OFB'] and \
232 self.head in ['ARIA', 'CAMELLIA']:
233 return False # not implemented in Mbed TLS
Gilles Peskine39054332021-04-29 20:38:47 +0200234 return True
235 if self.head == 'CHACHA20' and alg.head == 'CHACHA20_POLY1305':
236 return True
237 if self.head in {'ARC4', 'CHACHA20'} and \
238 alg.head == 'STREAM_CIPHER':
239 return True
240 if self.head == 'RSA' and alg.head.startswith('RSA_'):
241 return True
Gilles Peskinecb451702022-03-19 12:16:45 +0100242 if alg.category == AlgorithmCategory.KEY_AGREEMENT and \
243 self.is_public():
244 # The PSA API does not use public key objects in key agreement
245 # operations: it imports the public key as a formatted byte string.
246 # So a public key object with a key agreement algorithm is not
247 # a valid combination.
248 return False
Gilles Peskine39054332021-04-29 20:38:47 +0200249 if self.head == 'ECC':
250 assert self.params is not None
251 eccc = EllipticCurveCategory.from_family(self.params[0])
252 if alg.head == 'ECDH' and \
253 eccc in {EllipticCurveCategory.SHORT_WEIERSTRASS,
254 EllipticCurveCategory.MONTGOMERY}:
255 return True
256 if alg.head == 'ECDSA' and \
257 eccc == EllipticCurveCategory.SHORT_WEIERSTRASS:
258 return True
259 if alg.head in {'PURE_EDDSA', 'EDDSA_PREHASH'} and \
260 eccc == EllipticCurveCategory.TWISTED_EDWARDS:
261 return True
262 return False
263
Gilles Peskine0dacd4d2021-04-29 20:38:01 +0200264
265class AlgorithmCategory(enum.Enum):
266 """PSA algorithm categories."""
267 # The numbers are aligned with the category bits in numerical values of
268 # algorithms.
269 HASH = 2
270 MAC = 3
271 CIPHER = 4
272 AEAD = 5
273 SIGN = 6
274 ASYMMETRIC_ENCRYPTION = 7
275 KEY_DERIVATION = 8
276 KEY_AGREEMENT = 9
277 PAKE = 10
278
279 def requires_key(self) -> bool:
Gilles Peskinec2fc2412021-04-29 21:56:59 +0200280 """Whether operations in this category are set up with a key."""
Gilles Peskine0dacd4d2021-04-29 20:38:01 +0200281 return self not in {self.HASH, self.KEY_DERIVATION}
282
Gilles Peskinec2fc2412021-04-29 21:56:59 +0200283 def is_asymmetric(self) -> bool:
284 """Whether operations in this category involve asymmetric keys."""
285 return self in {
286 self.SIGN,
287 self.ASYMMETRIC_ENCRYPTION,
288 self.KEY_AGREEMENT
289 }
290
Gilles Peskine0dacd4d2021-04-29 20:38:01 +0200291
292class AlgorithmNotRecognized(Exception):
293 def __init__(self, expr: str) -> None:
294 super().__init__('Algorithm not recognized: ' + expr)
295 self.expr = expr
296
297
298class Algorithm:
299 """Knowledge about a PSA algorithm."""
300
301 @staticmethod
302 def determine_base(expr: str) -> str:
303 """Return an expression for the "base" of the algorithm.
304
305 This strips off variants of algorithms such as MAC truncation.
306
307 This function does not attempt to detect invalid inputs.
308 """
309 m = re.match(r'PSA_ALG_(?:'
310 r'(?:TRUNCATED|AT_LEAST_THIS_LENGTH)_MAC|'
311 r'AEAD_WITH_(?:SHORTENED|AT_LEAST_THIS_LENGTH)_TAG'
312 r')\((.*),[^,]+\)\Z', expr)
313 if m:
314 expr = m.group(1)
315 return expr
316
317 @staticmethod
318 def determine_head(expr: str) -> str:
319 """Return the head of an algorithm expression.
320
321 The head is the first (outermost) constructor, without its PSA_ALG_
322 prefix, and with some normalization of similar algorithms.
323 """
324 m = re.match(r'PSA_ALG_(?:DETERMINISTIC_)?(\w+)', expr)
325 if not m:
326 raise AlgorithmNotRecognized(expr)
327 head = m.group(1)
328 if head == 'KEY_AGREEMENT':
329 m = re.match(r'PSA_ALG_KEY_AGREEMENT\s*\(\s*PSA_ALG_(\w+)', expr)
330 if not m:
331 raise AlgorithmNotRecognized(expr)
332 head = m.group(1)
333 head = re.sub(r'_ANY\Z', r'', head)
334 if re.match(r'ED[0-9]+PH\Z', head):
335 head = 'EDDSA_PREHASH'
336 return head
337
338 CATEGORY_FROM_HEAD = {
339 'SHA': AlgorithmCategory.HASH,
340 'SHAKE256_512': AlgorithmCategory.HASH,
341 'MD': AlgorithmCategory.HASH,
342 'RIPEMD': AlgorithmCategory.HASH,
343 'ANY_HASH': AlgorithmCategory.HASH,
344 'HMAC': AlgorithmCategory.MAC,
345 'STREAM_CIPHER': AlgorithmCategory.CIPHER,
346 'CHACHA20_POLY1305': AlgorithmCategory.AEAD,
347 'DSA': AlgorithmCategory.SIGN,
348 'ECDSA': AlgorithmCategory.SIGN,
349 'EDDSA': AlgorithmCategory.SIGN,
350 'PURE_EDDSA': AlgorithmCategory.SIGN,
351 'RSA_PSS': AlgorithmCategory.SIGN,
352 'RSA_PKCS1V15_SIGN': AlgorithmCategory.SIGN,
353 'RSA_PKCS1V15_CRYPT': AlgorithmCategory.ASYMMETRIC_ENCRYPTION,
354 'RSA_OAEP': AlgorithmCategory.ASYMMETRIC_ENCRYPTION,
355 'HKDF': AlgorithmCategory.KEY_DERIVATION,
356 'TLS12_PRF': AlgorithmCategory.KEY_DERIVATION,
357 'TLS12_PSK_TO_MS': AlgorithmCategory.KEY_DERIVATION,
358 'PBKDF': AlgorithmCategory.KEY_DERIVATION,
359 'ECDH': AlgorithmCategory.KEY_AGREEMENT,
360 'FFDH': AlgorithmCategory.KEY_AGREEMENT,
361 # KEY_AGREEMENT(...) is a key derivation with a key agreement component
362 'KEY_AGREEMENT': AlgorithmCategory.KEY_DERIVATION,
363 'JPAKE': AlgorithmCategory.PAKE,
364 }
365 for x in BLOCK_MAC_MODES:
366 CATEGORY_FROM_HEAD[x] = AlgorithmCategory.MAC
367 for x in BLOCK_CIPHER_MODES:
368 CATEGORY_FROM_HEAD[x] = AlgorithmCategory.CIPHER
369 for x in BLOCK_AEAD_MODES:
370 CATEGORY_FROM_HEAD[x] = AlgorithmCategory.AEAD
371
372 def determine_category(self, expr: str, head: str) -> AlgorithmCategory:
373 """Return the category of the given algorithm expression.
374
375 This function does not attempt to detect invalid inputs.
376 """
377 prefix = head
378 while prefix:
379 if prefix in self.CATEGORY_FROM_HEAD:
380 return self.CATEGORY_FROM_HEAD[prefix]
381 if re.match(r'.*[0-9]\Z', prefix):
382 prefix = re.sub(r'_*[0-9]+\Z', r'', prefix)
383 else:
384 prefix = re.sub(r'_*[^_]*\Z', r'', prefix)
385 raise AlgorithmNotRecognized(expr)
386
387 @staticmethod
388 def determine_wildcard(expr) -> bool:
389 """Whether the given algorithm expression is a wildcard.
390
391 This function does not attempt to detect invalid inputs.
392 """
393 if re.search(r'\bPSA_ALG_ANY_HASH\b', expr):
394 return True
395 if re.search(r'_AT_LEAST_', expr):
396 return True
397 return False
398
399 def __init__(self, expr: str) -> None:
400 """Analyze an algorithm value.
401
402 The algorithm must be expressed as a C expression containing only
403 calls to PSA algorithm constructor macros and numeric literals.
404
405 This class is only programmed to handle valid expressions. Invalid
406 expressions may result in exceptions or in nonsensical results.
407 """
408 self.expression = re.sub(r'\s+', r'', expr)
409 self.base_expression = self.determine_base(self.expression)
410 self.head = self.determine_head(self.base_expression)
411 self.category = self.determine_category(self.base_expression, self.head)
412 self.is_wildcard = self.determine_wildcard(self.expression)
Gilles Peskine23cb12e2021-04-29 20:54:40 +0200413
414 def is_key_agreement_with_derivation(self) -> bool:
415 """Whether this is a combined key agreement and key derivation algorithm."""
416 if self.category != AlgorithmCategory.KEY_AGREEMENT:
417 return False
418 m = re.match(r'PSA_ALG_KEY_AGREEMENT\(\w+,\s*(.*)\)\Z', self.expression)
419 if not m:
420 return False
421 kdf_alg = m.group(1)
422 # Assume kdf_alg is either a valid KDF or 0.
423 return not re.match(r'(?:0[Xx])?0+\s*\Z', kdf_alg)
424
Gilles Peskined79aef52022-03-17 23:42:25 +0100425
Gilles Peskine930ccef2022-03-18 00:02:15 +0100426 def short_expression(self, level: int = 0) -> str:
Gilles Peskined79aef52022-03-17 23:42:25 +0100427 """Abbreviate the expression, keeping it human-readable.
428
429 See `crypto_knowledge.short_expression`.
430 """
Gilles Peskine930ccef2022-03-18 00:02:15 +0100431 return short_expression(self.expression, level=level)
Gilles Peskined79aef52022-03-17 23:42:25 +0100432
Gilles Peskine32611242022-03-19 12:09:13 +0100433 HASH_LENGTH = {
434 'PSA_ALG_MD5': 16,
435 'PSA_ALG_SHA_1': 20,
436 }
437 HASH_LENGTH_BITS_RE = re.compile(r'([0-9]+)\Z')
438 @classmethod
439 def hash_length(cls, alg: str) -> int:
440 """The length of the given hash algorithm, in bytes."""
441 if alg in cls.HASH_LENGTH:
442 return cls.HASH_LENGTH[alg]
443 m = cls.HASH_LENGTH_BITS_RE.search(alg)
444 if m:
445 return int(m.group(1)) // 8
446 raise ValueError('Unknown hash length for ' + alg)
447
Gilles Peskineb0537ba2022-03-19 10:37:33 +0100448 PERMITTED_TAG_LENGTHS = {
449 'PSA_ALG_CCM': frozenset([4, 6, 8, 10, 12, 14, 16]),
450 'PSA_ALG_CHACHA20_POLY1305': frozenset([16]),
451 'PSA_ALG_GCM': frozenset([4, 8, 12, 13, 14, 15, 16]),
452 }
453 MAC_LENGTH = {
Gilles Peskine32611242022-03-19 12:09:13 +0100454 'PSA_ALG_CBC_MAC': 16, # actually the block cipher length
455 'PSA_ALG_CMAC': 16, # actually the block cipher length
Gilles Peskineb0537ba2022-03-19 10:37:33 +0100456 }
Gilles Peskine32611242022-03-19 12:09:13 +0100457 HMAC_RE = re.compile(r'PSA_ALG_HMAC\((.*)\)\Z')
Gilles Peskineb0537ba2022-03-19 10:37:33 +0100458 @classmethod
Gilles Peskinece78c962022-04-12 18:51:01 +0200459 def permitted_truncations(cls, base: str) -> FrozenSet[int]:
460 """Permitted output lengths for the given MAC or AEAD base algorithm.
461
462 For a MAC algorithm, this is the set of truncation lengths that
463 Mbed TLS supports.
464 For an AEAD algorithm, this is the set of truncation lengths that
465 are permitted by the algorithm specification.
466 """
Gilles Peskineb0537ba2022-03-19 10:37:33 +0100467 if base in cls.PERMITTED_TAG_LENGTHS:
468 return cls.PERMITTED_TAG_LENGTHS[base]
469 max_length = cls.MAC_LENGTH.get(base, None)
470 if max_length is None:
Gilles Peskine32611242022-03-19 12:09:13 +0100471 m = cls.HMAC_RE.match(base)
Gilles Peskineb0537ba2022-03-19 10:37:33 +0100472 if m:
Gilles Peskine32611242022-03-19 12:09:13 +0100473 max_length = cls.hash_length(m.group(1))
Gilles Peskineb0537ba2022-03-19 10:37:33 +0100474 if max_length is None:
475 raise ValueError('Unknown permitted lengths for ' + base)
476 return frozenset(range(4, max_length + 1))
477
478 TRUNCATED_ALG_RE = re.compile(
479 r'(?P<face>PSA_ALG_(?:AEAD_WITH_SHORTENED_TAG|TRUNCATED_MAC))'
480 r'\((?P<base>.*),'
Gilles Peskine913c01f2022-04-05 16:31:16 +0200481 r'(?P<length>0[Xx][0-9A-Fa-f]+|[1-9][0-9]*|0[0-7]*)[LUlu]*\)\Z')
Gilles Peskineb0537ba2022-03-19 10:37:33 +0100482 def is_invalid_truncation(self) -> bool:
483 """False for a MAC or AEAD algorithm truncated to an invalid length.
484
485 True for a MAC or AEAD algorithm truncated to a valid length or to
486 a length that cannot be determined. True for anything other than
487 a truncated MAC or AEAD.
488 """
489 m = self.TRUNCATED_ALG_RE.match(self.expression)
490 if m:
491 base = m.group('base')
492 to_length = int(m.group('length'), 0)
Gilles Peskinece78c962022-04-12 18:51:01 +0200493 permitted_lengths = self.permitted_truncations(base)
Gilles Peskineb0537ba2022-03-19 10:37:33 +0100494 if to_length not in permitted_lengths:
495 return True
496 return False
497
Gilles Peskine23cb12e2021-04-29 20:54:40 +0200498 def can_do(self, category: AlgorithmCategory) -> bool:
Gilles Peskineb0537ba2022-03-19 10:37:33 +0100499 """Whether this algorithm can perform operations in the given category.
500 """
Gilles Peskine23cb12e2021-04-29 20:54:40 +0200501 if category == self.category:
502 return True
503 if category == AlgorithmCategory.KEY_DERIVATION and \
504 self.is_key_agreement_with_derivation():
505 return True
506 return False
Gilles Peskine0de11432022-03-18 09:58:09 +0100507
508 def usage_flags(self, public: bool = False) -> List[str]:
509 """The list of usage flags describing operations that can perform this algorithm.
510
511 If public is true, only return public-key operations, not private-key operations.
512 """
513 if self.category == AlgorithmCategory.HASH:
514 flags = []
515 elif self.category == AlgorithmCategory.MAC:
516 flags = ['SIGN_HASH', 'SIGN_MESSAGE',
517 'VERIFY_HASH', 'VERIFY_MESSAGE']
518 elif self.category == AlgorithmCategory.CIPHER or \
519 self.category == AlgorithmCategory.AEAD:
520 flags = ['DECRYPT', 'ENCRYPT']
521 elif self.category == AlgorithmCategory.SIGN:
522 flags = ['VERIFY_HASH', 'VERIFY_MESSAGE']
523 if not public:
524 flags += ['SIGN_HASH', 'SIGN_MESSAGE']
525 elif self.category == AlgorithmCategory.ASYMMETRIC_ENCRYPTION:
526 flags = ['ENCRYPT']
527 if not public:
528 flags += ['DECRYPT']
529 elif self.category == AlgorithmCategory.KEY_DERIVATION or \
530 self.category == AlgorithmCategory.KEY_AGREEMENT:
531 flags = ['DERIVE']
532 else:
533 raise AlgorithmNotRecognized(self.expression)
534 return ['PSA_KEY_USAGE_' + flag for flag in flags]