Gilles Peskine | 0156a15 | 2021-01-26 21:23:56 +0100 | [diff] [blame] | 1 | """Knowledge about cryptographic mechanisms implemented in Mbed TLS. |
| 2 | |
| 3 | This 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 Peskine | ee7554e | 2021-04-29 20:38:01 +0200 | [diff] [blame] | 21 | import enum |
Gilles Peskine | 0156a15 | 2021-01-26 21:23:56 +0100 | [diff] [blame] | 22 | import re |
Gilles Peskine | e6b85b4 | 2022-03-18 09:58:09 +0100 | [diff] [blame] | 23 | from typing import Iterable, List, Optional, Tuple |
Gilles Peskine | 0156a15 | 2021-01-26 21:23:56 +0100 | [diff] [blame] | 24 | |
Gilles Peskine | 6f6483f | 2021-01-27 12:43:24 +0100 | [diff] [blame] | 25 | from mbedtls_dev.asymmetric_key_data import ASYMMETRIC_KEY_DATA |
| 26 | |
Gilles Peskine | ee7554e | 2021-04-29 20:38:01 +0200 | [diff] [blame] | 27 | |
Gilles Peskine | 16b2506 | 2022-03-18 00:02:15 +0100 | [diff] [blame] | 28 | def short_expression(original: str, level: int = 0) -> str: |
Gilles Peskine | e8e058c | 2022-03-17 23:42:25 +0100 | [diff] [blame] | 29 | """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 Peskine | 16b2506 | 2022-03-18 00:02:15 +0100 | [diff] [blame] | 39 | 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 Peskine | e8e058c | 2022-03-17 23:42:25 +0100 | [diff] [blame] | 48 | return short |
| 49 | |
| 50 | |
Gilles Peskine | 8345d63 | 2021-04-29 20:38:47 +0200 | [diff] [blame] | 51 | BLOCK_CIPHERS = frozenset(['AES', 'ARIA', 'CAMELLIA', 'DES']) |
Gilles Peskine | ee7554e | 2021-04-29 20:38:01 +0200 | [diff] [blame] | 52 | BLOCK_MAC_MODES = frozenset(['CBC_MAC', 'CMAC']) |
| 53 | BLOCK_CIPHER_MODES = frozenset([ |
| 54 | 'CTR', 'CFB', 'OFB', 'XTS', 'CCM_STAR_NO_TAG', |
| 55 | 'ECB_NO_PADDING', 'CBC_NO_PADDING', 'CBC_PKCS7', |
| 56 | ]) |
| 57 | BLOCK_AEAD_MODES = frozenset(['CCM', 'GCM']) |
| 58 | |
Gilles Peskine | 8345d63 | 2021-04-29 20:38:47 +0200 | [diff] [blame] | 59 | class 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 Peskine | ee7554e | 2021-04-29 20:38:01 +0200 | [diff] [blame] | 78 | |
Gilles Peskine | 0156a15 | 2021-01-26 21:23:56 +0100 | [diff] [blame] | 79 | class KeyType: |
| 80 | """Knowledge about a PSA key type.""" |
| 81 | |
Gilles Peskine | b9dbb7f | 2021-04-29 20:19:57 +0200 | [diff] [blame] | 82 | def __init__(self, name: str, params: Optional[Iterable[str]] = None) -> None: |
Gilles Peskine | 0156a15 | 2021-01-26 21:23:56 +0100 | [diff] [blame] | 83 | """Analyze a key type. |
| 84 | |
| 85 | The key type must be specified in PSA syntax. In its simplest form, |
Gilles Peskine | fa3c69a | 2021-02-16 14:29:22 +0100 | [diff] [blame] | 86 | `name` is a string 'PSA_KEY_TYPE_xxx' which is the name of a PSA key |
Gilles Peskine | 0156a15 | 2021-01-26 21:23:56 +0100 | [diff] [blame] | 87 | type macro. For key types that take arguments, the arguments can |
| 88 | be passed either through the optional argument `params` or by |
Gilles Peskine | 4d0b089 | 2021-04-12 13:41:52 +0200 | [diff] [blame] | 89 | passing an expression of the form 'PSA_KEY_TYPE_xxx(param1, ...)' |
Gilles Peskine | fa3c69a | 2021-02-16 14:29:22 +0100 | [diff] [blame] | 90 | in `name` as a string. |
Gilles Peskine | 0156a15 | 2021-01-26 21:23:56 +0100 | [diff] [blame] | 91 | """ |
Gilles Peskine | d75adfc | 2021-02-17 18:04:28 +0100 | [diff] [blame] | 92 | |
Gilles Peskine | 0156a15 | 2021-01-26 21:23:56 +0100 | [diff] [blame] | 93 | self.name = name.strip() |
Gilles Peskine | fa3c69a | 2021-02-16 14:29:22 +0100 | [diff] [blame] | 94 | """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 Peskine | 0156a15 | 2021-01-26 21:23:56 +0100 | [diff] [blame] | 99 | 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 Peskine | 4d0b089 | 2021-04-12 13:41:52 +0200 | [diff] [blame] | 104 | params = m.group(2).split(',') |
Gilles Peskine | fa3c69a | 2021-02-16 14:29:22 +0100 | [diff] [blame] | 105 | 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 Peskine | d75adfc | 2021-02-17 18:04:28 +0100 | [diff] [blame] | 111 | assert re.match(r'PSA_KEY_TYPE_\w+\Z', self.name) |
| 112 | |
Gilles Peskine | 0156a15 | 2021-01-26 21:23:56 +0100 | [diff] [blame] | 113 | self.expression = self.name |
Gilles Peskine | fa3c69a | 2021-02-16 14:29:22 +0100 | [diff] [blame] | 114 | """A C expression whose value is the key type encoding.""" |
Gilles Peskine | 0156a15 | 2021-01-26 21:23:56 +0100 | [diff] [blame] | 115 | if self.params is not None: |
| 116 | self.expression += '(' + ', '.join(self.params) + ')' |
Gilles Peskine | d75adfc | 2021-02-17 18:04:28 +0100 | [diff] [blame] | 117 | |
Gilles Peskine | 8345d63 | 2021-04-29 20:38:47 +0200 | [diff] [blame] | 118 | 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 Peskine | 0156a15 | 2021-01-26 21:23:56 +0100 | [diff] [blame] | 123 | self.private_type = re.sub(r'_PUBLIC_KEY\Z', r'_KEY_PAIR', self.name) |
Gilles Peskine | fa3c69a | 2021-02-16 14:29:22 +0100 | [diff] [blame] | 124 | """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 Peskine | df63968 | 2021-01-26 21:25:34 +0100 | [diff] [blame] | 129 | |
Gilles Peskine | 16b2506 | 2022-03-18 00:02:15 +0100 | [diff] [blame] | 130 | def short_expression(self, level: int = 0) -> str: |
Gilles Peskine | e8e058c | 2022-03-17 23:42:25 +0100 | [diff] [blame] | 131 | """Abbreviate the expression, keeping it human-readable. |
| 132 | |
| 133 | See `crypto_knowledge.short_expression`. |
| 134 | """ |
Gilles Peskine | 16b2506 | 2022-03-18 00:02:15 +0100 | [diff] [blame] | 135 | return short_expression(self.expression, level=level) |
Gilles Peskine | e8e058c | 2022-03-17 23:42:25 +0100 | [diff] [blame] | 136 | |
Gilles Peskine | e630095 | 2021-04-29 21:56:59 +0200 | [diff] [blame] | 137 | def is_public(self) -> bool: |
| 138 | """Whether the key type is for public keys.""" |
| 139 | return self.name.endswith('_PUBLIC_KEY') |
| 140 | |
Gilles Peskine | df63968 | 2021-01-26 21:25:34 +0100 | [diff] [blame] | 141 | ECC_KEY_SIZES = { |
| 142 | 'PSA_ECC_FAMILY_SECP_K1': (192, 224, 256), |
Gilles Peskine | 0ac258e | 2021-01-27 13:11:59 +0100 | [diff] [blame] | 143 | 'PSA_ECC_FAMILY_SECP_R1': (225, 256, 384, 521), |
Gilles Peskine | df63968 | 2021-01-26 21:25:34 +0100 | [diff] [blame] | 144 | '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 Peskine | a00abc6 | 2021-03-16 18:25:14 +0100 | [diff] [blame] | 150 | 'PSA_ECC_FAMILY_TWISTED_EDWARDS': (255, 448), |
Gilles Peskine | df63968 | 2021-01-26 21:25:34 +0100 | [diff] [blame] | 151 | } |
| 152 | KEY_TYPE_SIZES = { |
| 153 | 'PSA_KEY_TYPE_AES': (128, 192, 256), # exhaustive |
Gilles Peskine | df63968 | 2021-01-26 21:25:34 +0100 | [diff] [blame] | 154 | 'PSA_KEY_TYPE_ARIA': (128, 192, 256), # exhaustive |
| 155 | 'PSA_KEY_TYPE_CAMELLIA': (128, 192, 256), # exhaustive |
| 156 | 'PSA_KEY_TYPE_CHACHA20': (256,), # exhaustive |
| 157 | 'PSA_KEY_TYPE_DERIVE': (120, 128), # sample |
| 158 | 'PSA_KEY_TYPE_DES': (64, 128, 192), # exhaustive |
| 159 | 'PSA_KEY_TYPE_HMAC': (128, 160, 224, 256, 384, 512), # standard size for each supported hash |
Manuel Pégourié-Gonnard | b12de9f | 2021-05-03 11:02:56 +0200 | [diff] [blame] | 160 | 'PSA_KEY_TYPE_PASSWORD': (48, 168, 336), # sample |
| 161 | 'PSA_KEY_TYPE_PASSWORD_HASH': (128, 256), # sample |
| 162 | 'PSA_KEY_TYPE_PEPPER': (128, 256), # sample |
Gilles Peskine | df63968 | 2021-01-26 21:25:34 +0100 | [diff] [blame] | 163 | 'PSA_KEY_TYPE_RAW_DATA': (8, 40, 128), # sample |
| 164 | 'PSA_KEY_TYPE_RSA_KEY_PAIR': (1024, 1536), # small sample |
| 165 | } |
| 166 | def sizes_to_test(self) -> Tuple[int, ...]: |
| 167 | """Return a tuple of key sizes to test. |
| 168 | |
| 169 | For key types that only allow a single size, or only a small set of |
| 170 | sizes, these are all the possible sizes. For key types that allow a |
| 171 | wide range of sizes, these are a representative sample of sizes, |
| 172 | excluding large sizes for which a typical resource-constrained platform |
| 173 | may run out of memory. |
| 174 | """ |
| 175 | if self.private_type == 'PSA_KEY_TYPE_ECC_KEY_PAIR': |
| 176 | assert self.params is not None |
| 177 | return self.ECC_KEY_SIZES[self.params[0]] |
| 178 | return self.KEY_TYPE_SIZES[self.private_type] |
Gilles Peskine | 397b028 | 2021-01-26 21:26:26 +0100 | [diff] [blame] | 179 | |
| 180 | # "48657265006973206b6579a064617461" |
| 181 | DATA_BLOCK = b'Here\000is key\240data' |
| 182 | def key_material(self, bits: int) -> bytes: |
| 183 | """Return a byte string containing suitable key material with the given bit length. |
| 184 | |
| 185 | Use the PSA export representation. The resulting byte string is one that |
| 186 | can be obtained with the following code: |
| 187 | ``` |
| 188 | psa_set_key_type(&attributes, `self.expression`); |
| 189 | psa_set_key_bits(&attributes, `bits`); |
| 190 | psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_EXPORT); |
| 191 | psa_generate_key(&attributes, &id); |
| 192 | psa_export_key(id, `material`, ...); |
| 193 | ``` |
| 194 | """ |
Gilles Peskine | 6f6483f | 2021-01-27 12:43:24 +0100 | [diff] [blame] | 195 | if self.expression in ASYMMETRIC_KEY_DATA: |
| 196 | if bits not in ASYMMETRIC_KEY_DATA[self.expression]: |
| 197 | raise ValueError('No key data for {}-bit {}' |
| 198 | .format(bits, self.expression)) |
| 199 | return ASYMMETRIC_KEY_DATA[self.expression][bits] |
Gilles Peskine | 397b028 | 2021-01-26 21:26:26 +0100 | [diff] [blame] | 200 | if bits % 8 != 0: |
Gilles Peskine | 6f6483f | 2021-01-27 12:43:24 +0100 | [diff] [blame] | 201 | raise ValueError('Non-integer number of bytes: {} bits for {}' |
| 202 | .format(bits, self.expression)) |
Gilles Peskine | 397b028 | 2021-01-26 21:26:26 +0100 | [diff] [blame] | 203 | length = bits // 8 |
| 204 | if self.name == 'PSA_KEY_TYPE_DES': |
| 205 | # "644573206b457901644573206b457902644573206b457904" |
| 206 | des3 = b'dEs kEy\001dEs kEy\002dEs kEy\004' |
| 207 | return des3[:length] |
Gilles Peskine | 397b028 | 2021-01-26 21:26:26 +0100 | [diff] [blame] | 208 | return b''.join([self.DATA_BLOCK] * (length // len(self.DATA_BLOCK)) + |
| 209 | [self.DATA_BLOCK[:length % len(self.DATA_BLOCK)]]) |
gabor-mezei-arm | 2784bfe | 2021-06-28 20:02:11 +0200 | [diff] [blame] | 210 | |
Gilles Peskine | 8345d63 | 2021-04-29 20:38:47 +0200 | [diff] [blame] | 211 | def can_do(self, alg: 'Algorithm') -> bool: |
| 212 | """Whether this key type can be used for operations with the given algorithm. |
| 213 | |
| 214 | This function does not currently handle key derivation or PAKE. |
| 215 | """ |
| 216 | #pylint: disable=too-many-return-statements |
| 217 | if alg.is_wildcard: |
| 218 | return False |
| 219 | if self.head == 'HMAC' and alg.head == 'HMAC': |
| 220 | return True |
Gilles Peskine | c47d3a4 | 2022-03-18 10:18:58 +0100 | [diff] [blame^] | 221 | 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 Peskine | 8345d63 | 2021-04-29 20:38:47 +0200 | [diff] [blame] | 227 | if self.head in BLOCK_CIPHERS and \ |
| 228 | alg.head in frozenset.union(BLOCK_MAC_MODES, |
| 229 | BLOCK_CIPHER_MODES, |
| 230 | BLOCK_AEAD_MODES): |
| 231 | return True |
| 232 | if self.head == 'CHACHA20' and alg.head == 'CHACHA20_POLY1305': |
| 233 | return True |
| 234 | if self.head in {'ARC4', 'CHACHA20'} and \ |
| 235 | alg.head == 'STREAM_CIPHER': |
| 236 | return True |
| 237 | if self.head == 'RSA' and alg.head.startswith('RSA_'): |
| 238 | return True |
| 239 | if self.head == 'ECC': |
| 240 | assert self.params is not None |
| 241 | eccc = EllipticCurveCategory.from_family(self.params[0]) |
| 242 | if alg.head == 'ECDH' and \ |
| 243 | eccc in {EllipticCurveCategory.SHORT_WEIERSTRASS, |
| 244 | EllipticCurveCategory.MONTGOMERY}: |
| 245 | return True |
| 246 | if alg.head == 'ECDSA' and \ |
| 247 | eccc == EllipticCurveCategory.SHORT_WEIERSTRASS: |
| 248 | return True |
| 249 | if alg.head in {'PURE_EDDSA', 'EDDSA_PREHASH'} and \ |
| 250 | eccc == EllipticCurveCategory.TWISTED_EDWARDS: |
| 251 | return True |
| 252 | return False |
| 253 | |
Gilles Peskine | ee7554e | 2021-04-29 20:38:01 +0200 | [diff] [blame] | 254 | |
| 255 | class AlgorithmCategory(enum.Enum): |
| 256 | """PSA algorithm categories.""" |
| 257 | # The numbers are aligned with the category bits in numerical values of |
| 258 | # algorithms. |
| 259 | HASH = 2 |
| 260 | MAC = 3 |
| 261 | CIPHER = 4 |
| 262 | AEAD = 5 |
| 263 | SIGN = 6 |
| 264 | ASYMMETRIC_ENCRYPTION = 7 |
| 265 | KEY_DERIVATION = 8 |
| 266 | KEY_AGREEMENT = 9 |
| 267 | PAKE = 10 |
| 268 | |
| 269 | def requires_key(self) -> bool: |
Gilles Peskine | e630095 | 2021-04-29 21:56:59 +0200 | [diff] [blame] | 270 | """Whether operations in this category are set up with a key.""" |
Gilles Peskine | ee7554e | 2021-04-29 20:38:01 +0200 | [diff] [blame] | 271 | return self not in {self.HASH, self.KEY_DERIVATION} |
| 272 | |
Gilles Peskine | e630095 | 2021-04-29 21:56:59 +0200 | [diff] [blame] | 273 | def is_asymmetric(self) -> bool: |
| 274 | """Whether operations in this category involve asymmetric keys.""" |
| 275 | return self in { |
| 276 | self.SIGN, |
| 277 | self.ASYMMETRIC_ENCRYPTION, |
| 278 | self.KEY_AGREEMENT |
| 279 | } |
| 280 | |
Gilles Peskine | ee7554e | 2021-04-29 20:38:01 +0200 | [diff] [blame] | 281 | |
| 282 | class AlgorithmNotRecognized(Exception): |
| 283 | def __init__(self, expr: str) -> None: |
| 284 | super().__init__('Algorithm not recognized: ' + expr) |
| 285 | self.expr = expr |
| 286 | |
| 287 | |
| 288 | class Algorithm: |
| 289 | """Knowledge about a PSA algorithm.""" |
| 290 | |
| 291 | @staticmethod |
| 292 | def determine_base(expr: str) -> str: |
| 293 | """Return an expression for the "base" of the algorithm. |
| 294 | |
| 295 | This strips off variants of algorithms such as MAC truncation. |
| 296 | |
| 297 | This function does not attempt to detect invalid inputs. |
| 298 | """ |
| 299 | m = re.match(r'PSA_ALG_(?:' |
| 300 | r'(?:TRUNCATED|AT_LEAST_THIS_LENGTH)_MAC|' |
| 301 | r'AEAD_WITH_(?:SHORTENED|AT_LEAST_THIS_LENGTH)_TAG' |
| 302 | r')\((.*),[^,]+\)\Z', expr) |
| 303 | if m: |
| 304 | expr = m.group(1) |
| 305 | return expr |
| 306 | |
| 307 | @staticmethod |
| 308 | def determine_head(expr: str) -> str: |
| 309 | """Return the head of an algorithm expression. |
| 310 | |
| 311 | The head is the first (outermost) constructor, without its PSA_ALG_ |
| 312 | prefix, and with some normalization of similar algorithms. |
| 313 | """ |
| 314 | m = re.match(r'PSA_ALG_(?:DETERMINISTIC_)?(\w+)', expr) |
| 315 | if not m: |
| 316 | raise AlgorithmNotRecognized(expr) |
| 317 | head = m.group(1) |
| 318 | if head == 'KEY_AGREEMENT': |
| 319 | m = re.match(r'PSA_ALG_KEY_AGREEMENT\s*\(\s*PSA_ALG_(\w+)', expr) |
| 320 | if not m: |
| 321 | raise AlgorithmNotRecognized(expr) |
| 322 | head = m.group(1) |
| 323 | head = re.sub(r'_ANY\Z', r'', head) |
| 324 | if re.match(r'ED[0-9]+PH\Z', head): |
| 325 | head = 'EDDSA_PREHASH' |
| 326 | return head |
| 327 | |
| 328 | CATEGORY_FROM_HEAD = { |
| 329 | 'SHA': AlgorithmCategory.HASH, |
| 330 | 'SHAKE256_512': AlgorithmCategory.HASH, |
| 331 | 'MD': AlgorithmCategory.HASH, |
| 332 | 'RIPEMD': AlgorithmCategory.HASH, |
| 333 | 'ANY_HASH': AlgorithmCategory.HASH, |
| 334 | 'HMAC': AlgorithmCategory.MAC, |
| 335 | 'STREAM_CIPHER': AlgorithmCategory.CIPHER, |
| 336 | 'CHACHA20_POLY1305': AlgorithmCategory.AEAD, |
| 337 | 'DSA': AlgorithmCategory.SIGN, |
| 338 | 'ECDSA': AlgorithmCategory.SIGN, |
| 339 | 'EDDSA': AlgorithmCategory.SIGN, |
| 340 | 'PURE_EDDSA': AlgorithmCategory.SIGN, |
| 341 | 'RSA_PSS': AlgorithmCategory.SIGN, |
| 342 | 'RSA_PKCS1V15_SIGN': AlgorithmCategory.SIGN, |
| 343 | 'RSA_PKCS1V15_CRYPT': AlgorithmCategory.ASYMMETRIC_ENCRYPTION, |
| 344 | 'RSA_OAEP': AlgorithmCategory.ASYMMETRIC_ENCRYPTION, |
| 345 | 'HKDF': AlgorithmCategory.KEY_DERIVATION, |
| 346 | 'TLS12_PRF': AlgorithmCategory.KEY_DERIVATION, |
| 347 | 'TLS12_PSK_TO_MS': AlgorithmCategory.KEY_DERIVATION, |
| 348 | 'PBKDF': AlgorithmCategory.KEY_DERIVATION, |
| 349 | 'ECDH': AlgorithmCategory.KEY_AGREEMENT, |
| 350 | 'FFDH': AlgorithmCategory.KEY_AGREEMENT, |
| 351 | # KEY_AGREEMENT(...) is a key derivation with a key agreement component |
| 352 | 'KEY_AGREEMENT': AlgorithmCategory.KEY_DERIVATION, |
| 353 | 'JPAKE': AlgorithmCategory.PAKE, |
| 354 | } |
| 355 | for x in BLOCK_MAC_MODES: |
| 356 | CATEGORY_FROM_HEAD[x] = AlgorithmCategory.MAC |
| 357 | for x in BLOCK_CIPHER_MODES: |
| 358 | CATEGORY_FROM_HEAD[x] = AlgorithmCategory.CIPHER |
| 359 | for x in BLOCK_AEAD_MODES: |
| 360 | CATEGORY_FROM_HEAD[x] = AlgorithmCategory.AEAD |
| 361 | |
| 362 | def determine_category(self, expr: str, head: str) -> AlgorithmCategory: |
| 363 | """Return the category of the given algorithm expression. |
| 364 | |
| 365 | This function does not attempt to detect invalid inputs. |
| 366 | """ |
| 367 | prefix = head |
| 368 | while prefix: |
| 369 | if prefix in self.CATEGORY_FROM_HEAD: |
| 370 | return self.CATEGORY_FROM_HEAD[prefix] |
| 371 | if re.match(r'.*[0-9]\Z', prefix): |
| 372 | prefix = re.sub(r'_*[0-9]+\Z', r'', prefix) |
| 373 | else: |
| 374 | prefix = re.sub(r'_*[^_]*\Z', r'', prefix) |
| 375 | raise AlgorithmNotRecognized(expr) |
| 376 | |
| 377 | @staticmethod |
| 378 | def determine_wildcard(expr) -> bool: |
| 379 | """Whether the given algorithm expression is a wildcard. |
| 380 | |
| 381 | This function does not attempt to detect invalid inputs. |
| 382 | """ |
| 383 | if re.search(r'\bPSA_ALG_ANY_HASH\b', expr): |
| 384 | return True |
| 385 | if re.search(r'_AT_LEAST_', expr): |
| 386 | return True |
| 387 | return False |
| 388 | |
| 389 | def __init__(self, expr: str) -> None: |
| 390 | """Analyze an algorithm value. |
| 391 | |
| 392 | The algorithm must be expressed as a C expression containing only |
| 393 | calls to PSA algorithm constructor macros and numeric literals. |
| 394 | |
| 395 | This class is only programmed to handle valid expressions. Invalid |
| 396 | expressions may result in exceptions or in nonsensical results. |
| 397 | """ |
| 398 | self.expression = re.sub(r'\s+', r'', expr) |
| 399 | self.base_expression = self.determine_base(self.expression) |
| 400 | self.head = self.determine_head(self.base_expression) |
| 401 | self.category = self.determine_category(self.base_expression, self.head) |
| 402 | self.is_wildcard = self.determine_wildcard(self.expression) |
Gilles Peskine | a401386 | 2021-04-29 20:54:40 +0200 | [diff] [blame] | 403 | |
| 404 | def is_key_agreement_with_derivation(self) -> bool: |
| 405 | """Whether this is a combined key agreement and key derivation algorithm.""" |
| 406 | if self.category != AlgorithmCategory.KEY_AGREEMENT: |
| 407 | return False |
| 408 | m = re.match(r'PSA_ALG_KEY_AGREEMENT\(\w+,\s*(.*)\)\Z', self.expression) |
| 409 | if not m: |
| 410 | return False |
| 411 | kdf_alg = m.group(1) |
| 412 | # Assume kdf_alg is either a valid KDF or 0. |
| 413 | return not re.match(r'(?:0[Xx])?0+\s*\Z', kdf_alg) |
| 414 | |
Gilles Peskine | e8e058c | 2022-03-17 23:42:25 +0100 | [diff] [blame] | 415 | |
Gilles Peskine | 16b2506 | 2022-03-18 00:02:15 +0100 | [diff] [blame] | 416 | def short_expression(self, level: int = 0) -> str: |
Gilles Peskine | e8e058c | 2022-03-17 23:42:25 +0100 | [diff] [blame] | 417 | """Abbreviate the expression, keeping it human-readable. |
| 418 | |
| 419 | See `crypto_knowledge.short_expression`. |
| 420 | """ |
Gilles Peskine | 16b2506 | 2022-03-18 00:02:15 +0100 | [diff] [blame] | 421 | return short_expression(self.expression, level=level) |
Gilles Peskine | e8e058c | 2022-03-17 23:42:25 +0100 | [diff] [blame] | 422 | |
Gilles Peskine | a401386 | 2021-04-29 20:54:40 +0200 | [diff] [blame] | 423 | def can_do(self, category: AlgorithmCategory) -> bool: |
| 424 | """Whether this algorithm fits the specified operation category.""" |
| 425 | if category == self.category: |
| 426 | return True |
| 427 | if category == AlgorithmCategory.KEY_DERIVATION and \ |
| 428 | self.is_key_agreement_with_derivation(): |
| 429 | return True |
| 430 | return False |
Gilles Peskine | e6b85b4 | 2022-03-18 09:58:09 +0100 | [diff] [blame] | 431 | |
| 432 | def usage_flags(self, public: bool = False) -> List[str]: |
| 433 | """The list of usage flags describing operations that can perform this algorithm. |
| 434 | |
| 435 | If public is true, only return public-key operations, not private-key operations. |
| 436 | """ |
| 437 | if self.category == AlgorithmCategory.HASH: |
| 438 | flags = [] |
| 439 | elif self.category == AlgorithmCategory.MAC: |
| 440 | flags = ['SIGN_HASH', 'SIGN_MESSAGE', |
| 441 | 'VERIFY_HASH', 'VERIFY_MESSAGE'] |
| 442 | elif self.category == AlgorithmCategory.CIPHER or \ |
| 443 | self.category == AlgorithmCategory.AEAD: |
| 444 | flags = ['DECRYPT', 'ENCRYPT'] |
| 445 | elif self.category == AlgorithmCategory.SIGN: |
| 446 | flags = ['VERIFY_HASH', 'VERIFY_MESSAGE'] |
| 447 | if not public: |
| 448 | flags += ['SIGN_HASH', 'SIGN_MESSAGE'] |
| 449 | elif self.category == AlgorithmCategory.ASYMMETRIC_ENCRYPTION: |
| 450 | flags = ['ENCRYPT'] |
| 451 | if not public: |
| 452 | flags += ['DECRYPT'] |
| 453 | elif self.category == AlgorithmCategory.KEY_DERIVATION or \ |
| 454 | self.category == AlgorithmCategory.KEY_AGREEMENT: |
| 455 | flags = ['DERIVE'] |
| 456 | else: |
| 457 | raise AlgorithmNotRecognized(self.expression) |
| 458 | return ['PSA_KEY_USAGE_' + flag for flag in flags] |