blob: 1bd011fe21803bcbe2fa2ae4b97479c478aada14 [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 Peskineee7554e2021-04-29 20:38:01 +020021import enum
Gilles Peskine0156a152021-01-26 21:23:56 +010022import re
gabor-mezei-armf73f8962021-06-29 11:17:54 +020023from typing import Dict, Iterable, Optional, Pattern, Tuple
Gilles Peskine0156a152021-01-26 21:23:56 +010024
Gilles Peskine6f6483f2021-01-27 12:43:24 +010025from mbedtls_dev.asymmetric_key_data import ASYMMETRIC_KEY_DATA
26
Gilles Peskineee7554e2021-04-29 20:38:01 +020027
Gilles Peskine8345d632021-04-29 20:38:47 +020028BLOCK_CIPHERS = frozenset(['AES', 'ARIA', 'CAMELLIA', 'DES'])
Gilles Peskineee7554e2021-04-29 20:38:01 +020029BLOCK_MAC_MODES = frozenset(['CBC_MAC', 'CMAC'])
30BLOCK_CIPHER_MODES = frozenset([
31 'CTR', 'CFB', 'OFB', 'XTS', 'CCM_STAR_NO_TAG',
32 'ECB_NO_PADDING', 'CBC_NO_PADDING', 'CBC_PKCS7',
33])
34BLOCK_AEAD_MODES = frozenset(['CCM', 'GCM'])
35
Gilles Peskine8345d632021-04-29 20:38:47 +020036class EllipticCurveCategory(enum.Enum):
37 """Categorization of elliptic curve families.
38
39 The category of a curve determines what algorithms are defined over it.
40 """
41
42 SHORT_WEIERSTRASS = 0
43 MONTGOMERY = 1
44 TWISTED_EDWARDS = 2
45
46 @staticmethod
47 def from_family(family: str) -> 'EllipticCurveCategory':
48 if family == 'PSA_ECC_FAMILY_MONTGOMERY':
49 return EllipticCurveCategory.MONTGOMERY
50 if family == 'PSA_ECC_FAMILY_TWISTED_EDWARDS':
51 return EllipticCurveCategory.TWISTED_EDWARDS
52 # Default to SW, which most curves belong to.
53 return EllipticCurveCategory.SHORT_WEIERSTRASS
54
Gilles Peskineee7554e2021-04-29 20:38:01 +020055
Gilles Peskine0156a152021-01-26 21:23:56 +010056class KeyType:
57 """Knowledge about a PSA key type."""
58
Gilles Peskineb9dbb7f2021-04-29 20:19:57 +020059 def __init__(self, name: str, params: Optional[Iterable[str]] = None) -> None:
Gilles Peskine0156a152021-01-26 21:23:56 +010060 """Analyze a key type.
61
62 The key type must be specified in PSA syntax. In its simplest form,
Gilles Peskinefa3c69a2021-02-16 14:29:22 +010063 `name` is a string 'PSA_KEY_TYPE_xxx' which is the name of a PSA key
Gilles Peskine0156a152021-01-26 21:23:56 +010064 type macro. For key types that take arguments, the arguments can
65 be passed either through the optional argument `params` or by
Gilles Peskine4d0b0892021-04-12 13:41:52 +020066 passing an expression of the form 'PSA_KEY_TYPE_xxx(param1, ...)'
Gilles Peskinefa3c69a2021-02-16 14:29:22 +010067 in `name` as a string.
Gilles Peskine0156a152021-01-26 21:23:56 +010068 """
Gilles Peskined75adfc2021-02-17 18:04:28 +010069
Gilles Peskine0156a152021-01-26 21:23:56 +010070 self.name = name.strip()
Gilles Peskinefa3c69a2021-02-16 14:29:22 +010071 """The key type macro name (``PSA_KEY_TYPE_xxx``).
72
73 For key types constructed from a macro with arguments, this is the
74 name of the macro, and the arguments are in `self.params`.
75 """
Gilles Peskine0156a152021-01-26 21:23:56 +010076 if params is None:
77 if '(' in self.name:
78 m = re.match(r'(\w+)\s*\((.*)\)\Z', self.name)
79 assert m is not None
80 self.name = m.group(1)
Gilles Peskine4d0b0892021-04-12 13:41:52 +020081 params = m.group(2).split(',')
Gilles Peskinefa3c69a2021-02-16 14:29:22 +010082 self.params = (None if params is None else
83 [param.strip() for param in params])
84 """The parameters of the key type, if there are any.
85
86 None if the key type is a macro without arguments.
87 """
Gilles Peskined75adfc2021-02-17 18:04:28 +010088 assert re.match(r'PSA_KEY_TYPE_\w+\Z', self.name)
89
Gilles Peskine0156a152021-01-26 21:23:56 +010090 self.expression = self.name
Gilles Peskinefa3c69a2021-02-16 14:29:22 +010091 """A C expression whose value is the key type encoding."""
Gilles Peskine0156a152021-01-26 21:23:56 +010092 if self.params is not None:
93 self.expression += '(' + ', '.join(self.params) + ')'
Gilles Peskined75adfc2021-02-17 18:04:28 +010094
Gilles Peskine8345d632021-04-29 20:38:47 +020095 m = re.match(r'PSA_KEY_TYPE_(\w+)', self.name)
96 assert m
97 self.head = re.sub(r'_(?:PUBLIC_KEY|KEY_PAIR)\Z', r'', m.group(1))
98 """The key type macro name, with common prefixes and suffixes stripped."""
99
Gilles Peskine0156a152021-01-26 21:23:56 +0100100 self.private_type = re.sub(r'_PUBLIC_KEY\Z', r'_KEY_PAIR', self.name)
Gilles Peskinefa3c69a2021-02-16 14:29:22 +0100101 """The key type macro name for the corresponding key pair type.
102
103 For everything other than a public key type, this is the same as
104 `self.name`.
105 """
Gilles Peskinedf639682021-01-26 21:25:34 +0100106
Gilles Peskinee6300952021-04-29 21:56:59 +0200107 def is_public(self) -> bool:
108 """Whether the key type is for public keys."""
109 return self.name.endswith('_PUBLIC_KEY')
110
Gilles Peskinedf639682021-01-26 21:25:34 +0100111 ECC_KEY_SIZES = {
112 'PSA_ECC_FAMILY_SECP_K1': (192, 224, 256),
Gilles Peskine0ac258e2021-01-27 13:11:59 +0100113 'PSA_ECC_FAMILY_SECP_R1': (225, 256, 384, 521),
Gilles Peskinedf639682021-01-26 21:25:34 +0100114 'PSA_ECC_FAMILY_SECP_R2': (160,),
115 'PSA_ECC_FAMILY_SECT_K1': (163, 233, 239, 283, 409, 571),
116 'PSA_ECC_FAMILY_SECT_R1': (163, 233, 283, 409, 571),
117 'PSA_ECC_FAMILY_SECT_R2': (163,),
118 'PSA_ECC_FAMILY_BRAINPOOL_P_R1': (160, 192, 224, 256, 320, 384, 512),
119 'PSA_ECC_FAMILY_MONTGOMERY': (255, 448),
Gilles Peskinea00abc62021-03-16 18:25:14 +0100120 'PSA_ECC_FAMILY_TWISTED_EDWARDS': (255, 448),
Gilles Peskinedf639682021-01-26 21:25:34 +0100121 }
122 KEY_TYPE_SIZES = {
123 'PSA_KEY_TYPE_AES': (128, 192, 256), # exhaustive
Gilles Peskinedf639682021-01-26 21:25:34 +0100124 'PSA_KEY_TYPE_ARIA': (128, 192, 256), # exhaustive
125 'PSA_KEY_TYPE_CAMELLIA': (128, 192, 256), # exhaustive
126 'PSA_KEY_TYPE_CHACHA20': (256,), # exhaustive
127 'PSA_KEY_TYPE_DERIVE': (120, 128), # sample
128 'PSA_KEY_TYPE_DES': (64, 128, 192), # exhaustive
129 'PSA_KEY_TYPE_HMAC': (128, 160, 224, 256, 384, 512), # standard size for each supported hash
Manuel Pégourié-Gonnardb12de9f2021-05-03 11:02:56 +0200130 'PSA_KEY_TYPE_PASSWORD': (48, 168, 336), # sample
131 'PSA_KEY_TYPE_PASSWORD_HASH': (128, 256), # sample
132 'PSA_KEY_TYPE_PEPPER': (128, 256), # sample
Gilles Peskinedf639682021-01-26 21:25:34 +0100133 'PSA_KEY_TYPE_RAW_DATA': (8, 40, 128), # sample
134 'PSA_KEY_TYPE_RSA_KEY_PAIR': (1024, 1536), # small sample
135 }
136 def sizes_to_test(self) -> Tuple[int, ...]:
137 """Return a tuple of key sizes to test.
138
139 For key types that only allow a single size, or only a small set of
140 sizes, these are all the possible sizes. For key types that allow a
141 wide range of sizes, these are a representative sample of sizes,
142 excluding large sizes for which a typical resource-constrained platform
143 may run out of memory.
144 """
145 if self.private_type == 'PSA_KEY_TYPE_ECC_KEY_PAIR':
146 assert self.params is not None
147 return self.ECC_KEY_SIZES[self.params[0]]
148 return self.KEY_TYPE_SIZES[self.private_type]
Gilles Peskine397b0282021-01-26 21:26:26 +0100149
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
155 Use the PSA export representation. The resulting byte string is one that
156 can be obtained with the following code:
157 ```
158 psa_set_key_type(&attributes, `self.expression`);
159 psa_set_key_bits(&attributes, `bits`);
160 psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_EXPORT);
161 psa_generate_key(&attributes, &id);
162 psa_export_key(id, `material`, ...);
163 ```
164 """
Gilles Peskine6f6483f2021-01-27 12:43:24 +0100165 if self.expression in ASYMMETRIC_KEY_DATA:
166 if bits not in ASYMMETRIC_KEY_DATA[self.expression]:
167 raise ValueError('No key data for {}-bit {}'
168 .format(bits, self.expression))
169 return ASYMMETRIC_KEY_DATA[self.expression][bits]
Gilles Peskine397b0282021-01-26 21:26:26 +0100170 if bits % 8 != 0:
Gilles Peskine6f6483f2021-01-27 12:43:24 +0100171 raise ValueError('Non-integer number of bytes: {} bits for {}'
172 .format(bits, self.expression))
Gilles Peskine397b0282021-01-26 21:26:26 +0100173 length = bits // 8
174 if self.name == 'PSA_KEY_TYPE_DES':
175 # "644573206b457901644573206b457902644573206b457904"
176 des3 = b'dEs kEy\001dEs kEy\002dEs kEy\004'
177 return des3[:length]
Gilles Peskine397b0282021-01-26 21:26:26 +0100178 return b''.join([self.DATA_BLOCK] * (length // len(self.DATA_BLOCK)) +
179 [self.DATA_BLOCK[:length % len(self.DATA_BLOCK)]])
gabor-mezei-arm2784bfe2021-06-28 20:02:11 +0200180
181 KEY_TYPE_FOR_SIGNATURE = {
gabor-mezei-armf73f8962021-06-29 11:17:54 +0200182 'PSA_KEY_USAGE_SIGN_HASH': re.compile('.*KEY_PAIR'),
183 'PSA_KEY_USAGE_VERIFY_HASH': re.compile('.*KEY.*')
184 } #type: Dict[str, Pattern]
gabor-mezei-arm2784bfe2021-06-28 20:02:11 +0200185 """Use a regexp to determine key types for which signature is possible
186 when using the actual usage flag.
187 """
188 def is_valid_for_signature(self, usage: str) -> bool:
189 """Determine if the key type is compatible with the specified
190 signitute type.
191
192 """
193 # This is just temporaly solution for the implicit usage flags.
194 return re.match(self.KEY_TYPE_FOR_SIGNATURE[usage], self.name) is not None
Gilles Peskineee7554e2021-04-29 20:38:01 +0200195
Gilles Peskine8345d632021-04-29 20:38:47 +0200196 def can_do(self, alg: 'Algorithm') -> bool:
197 """Whether this key type can be used for operations with the given algorithm.
198
199 This function does not currently handle key derivation or PAKE.
200 """
201 #pylint: disable=too-many-return-statements
202 if alg.is_wildcard:
203 return False
204 if self.head == 'HMAC' and alg.head == 'HMAC':
205 return True
206 if self.head in BLOCK_CIPHERS and \
207 alg.head in frozenset.union(BLOCK_MAC_MODES,
208 BLOCK_CIPHER_MODES,
209 BLOCK_AEAD_MODES):
210 return True
211 if self.head == 'CHACHA20' and alg.head == 'CHACHA20_POLY1305':
212 return True
213 if self.head in {'ARC4', 'CHACHA20'} and \
214 alg.head == 'STREAM_CIPHER':
215 return True
216 if self.head == 'RSA' and alg.head.startswith('RSA_'):
217 return True
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
Gilles Peskineee7554e2021-04-29 20:38:01 +0200233
234class AlgorithmCategory(enum.Enum):
235 """PSA algorithm categories."""
236 # The numbers are aligned with the category bits in numerical values of
237 # algorithms.
238 HASH = 2
239 MAC = 3
240 CIPHER = 4
241 AEAD = 5
242 SIGN = 6
243 ASYMMETRIC_ENCRYPTION = 7
244 KEY_DERIVATION = 8
245 KEY_AGREEMENT = 9
246 PAKE = 10
247
248 def requires_key(self) -> bool:
Gilles Peskinee6300952021-04-29 21:56:59 +0200249 """Whether operations in this category are set up with a key."""
Gilles Peskineee7554e2021-04-29 20:38:01 +0200250 return self not in {self.HASH, self.KEY_DERIVATION}
251
Gilles Peskinee6300952021-04-29 21:56:59 +0200252 def is_asymmetric(self) -> bool:
253 """Whether operations in this category involve asymmetric keys."""
254 return self in {
255 self.SIGN,
256 self.ASYMMETRIC_ENCRYPTION,
257 self.KEY_AGREEMENT
258 }
259
Gilles Peskineee7554e2021-04-29 20:38:01 +0200260
261class AlgorithmNotRecognized(Exception):
262 def __init__(self, expr: str) -> None:
263 super().__init__('Algorithm not recognized: ' + expr)
264 self.expr = expr
265
266
267class Algorithm:
268 """Knowledge about a PSA algorithm."""
269
270 @staticmethod
271 def determine_base(expr: str) -> str:
272 """Return an expression for the "base" of the algorithm.
273
274 This strips off variants of algorithms such as MAC truncation.
275
276 This function does not attempt to detect invalid inputs.
277 """
278 m = re.match(r'PSA_ALG_(?:'
279 r'(?:TRUNCATED|AT_LEAST_THIS_LENGTH)_MAC|'
280 r'AEAD_WITH_(?:SHORTENED|AT_LEAST_THIS_LENGTH)_TAG'
281 r')\((.*),[^,]+\)\Z', expr)
282 if m:
283 expr = m.group(1)
284 return expr
285
286 @staticmethod
287 def determine_head(expr: str) -> str:
288 """Return the head of an algorithm expression.
289
290 The head is the first (outermost) constructor, without its PSA_ALG_
291 prefix, and with some normalization of similar algorithms.
292 """
293 m = re.match(r'PSA_ALG_(?:DETERMINISTIC_)?(\w+)', expr)
294 if not m:
295 raise AlgorithmNotRecognized(expr)
296 head = m.group(1)
297 if head == 'KEY_AGREEMENT':
298 m = re.match(r'PSA_ALG_KEY_AGREEMENT\s*\(\s*PSA_ALG_(\w+)', expr)
299 if not m:
300 raise AlgorithmNotRecognized(expr)
301 head = m.group(1)
302 head = re.sub(r'_ANY\Z', r'', head)
303 if re.match(r'ED[0-9]+PH\Z', head):
304 head = 'EDDSA_PREHASH'
305 return head
306
307 CATEGORY_FROM_HEAD = {
308 'SHA': AlgorithmCategory.HASH,
309 'SHAKE256_512': AlgorithmCategory.HASH,
310 'MD': AlgorithmCategory.HASH,
311 'RIPEMD': AlgorithmCategory.HASH,
312 'ANY_HASH': AlgorithmCategory.HASH,
313 'HMAC': AlgorithmCategory.MAC,
314 'STREAM_CIPHER': AlgorithmCategory.CIPHER,
315 'CHACHA20_POLY1305': AlgorithmCategory.AEAD,
316 'DSA': AlgorithmCategory.SIGN,
317 'ECDSA': AlgorithmCategory.SIGN,
318 'EDDSA': AlgorithmCategory.SIGN,
319 'PURE_EDDSA': AlgorithmCategory.SIGN,
320 'RSA_PSS': AlgorithmCategory.SIGN,
321 'RSA_PKCS1V15_SIGN': AlgorithmCategory.SIGN,
322 'RSA_PKCS1V15_CRYPT': AlgorithmCategory.ASYMMETRIC_ENCRYPTION,
323 'RSA_OAEP': AlgorithmCategory.ASYMMETRIC_ENCRYPTION,
324 'HKDF': AlgorithmCategory.KEY_DERIVATION,
325 'TLS12_PRF': AlgorithmCategory.KEY_DERIVATION,
326 'TLS12_PSK_TO_MS': AlgorithmCategory.KEY_DERIVATION,
327 'PBKDF': AlgorithmCategory.KEY_DERIVATION,
328 'ECDH': AlgorithmCategory.KEY_AGREEMENT,
329 'FFDH': AlgorithmCategory.KEY_AGREEMENT,
330 # KEY_AGREEMENT(...) is a key derivation with a key agreement component
331 'KEY_AGREEMENT': AlgorithmCategory.KEY_DERIVATION,
332 'JPAKE': AlgorithmCategory.PAKE,
333 }
334 for x in BLOCK_MAC_MODES:
335 CATEGORY_FROM_HEAD[x] = AlgorithmCategory.MAC
336 for x in BLOCK_CIPHER_MODES:
337 CATEGORY_FROM_HEAD[x] = AlgorithmCategory.CIPHER
338 for x in BLOCK_AEAD_MODES:
339 CATEGORY_FROM_HEAD[x] = AlgorithmCategory.AEAD
340
341 def determine_category(self, expr: str, head: str) -> AlgorithmCategory:
342 """Return the category of the given algorithm expression.
343
344 This function does not attempt to detect invalid inputs.
345 """
346 prefix = head
347 while prefix:
348 if prefix in self.CATEGORY_FROM_HEAD:
349 return self.CATEGORY_FROM_HEAD[prefix]
350 if re.match(r'.*[0-9]\Z', prefix):
351 prefix = re.sub(r'_*[0-9]+\Z', r'', prefix)
352 else:
353 prefix = re.sub(r'_*[^_]*\Z', r'', prefix)
354 raise AlgorithmNotRecognized(expr)
355
356 @staticmethod
357 def determine_wildcard(expr) -> bool:
358 """Whether the given algorithm expression is a wildcard.
359
360 This function does not attempt to detect invalid inputs.
361 """
362 if re.search(r'\bPSA_ALG_ANY_HASH\b', expr):
363 return True
364 if re.search(r'_AT_LEAST_', expr):
365 return True
366 return False
367
368 def __init__(self, expr: str) -> None:
369 """Analyze an algorithm value.
370
371 The algorithm must be expressed as a C expression containing only
372 calls to PSA algorithm constructor macros and numeric literals.
373
374 This class is only programmed to handle valid expressions. Invalid
375 expressions may result in exceptions or in nonsensical results.
376 """
377 self.expression = re.sub(r'\s+', r'', expr)
378 self.base_expression = self.determine_base(self.expression)
379 self.head = self.determine_head(self.base_expression)
380 self.category = self.determine_category(self.base_expression, self.head)
381 self.is_wildcard = self.determine_wildcard(self.expression)
Gilles Peskinea4013862021-04-29 20:54:40 +0200382
383 def is_key_agreement_with_derivation(self) -> bool:
384 """Whether this is a combined key agreement and key derivation algorithm."""
385 if self.category != AlgorithmCategory.KEY_AGREEMENT:
386 return False
387 m = re.match(r'PSA_ALG_KEY_AGREEMENT\(\w+,\s*(.*)\)\Z', self.expression)
388 if not m:
389 return False
390 kdf_alg = m.group(1)
391 # Assume kdf_alg is either a valid KDF or 0.
392 return not re.match(r'(?:0[Xx])?0+\s*\Z', kdf_alg)
393
394 def can_do(self, category: AlgorithmCategory) -> bool:
395 """Whether this algorithm fits the specified operation category."""
396 if category == self.category:
397 return True
398 if category == AlgorithmCategory.KEY_DERIVATION and \
399 self.is_key_agreement_with_derivation():
400 return True
401 return False