Debian Codegraph @

updaters/oqs.py

raw
1 #!/usr/bin/env python
2 # SPDX-License-Identifier: MPL-2.0
3 # -*- coding: utf-8 -*-
4
5 import abc
6 import collections
7 import importlib
8 import itertools
9 import re
10
11 import attr
12 import yaml
13
14 import cryptodatahub.common.algorithm
15 import cryptodatahub.common.pqc
16 import cryptodatahub.tls.algorithm
17 import cryptodatahub.tls.version
18 from cryptodatahub.common.fetcher import FetcherBase
19 from cryptodatahub.common.utils import HttpFetcher, name_to_enum_item_name
20
21 from updaters.common import UpdaterBase
22 import updaters.oqs_datasheet
23 import updaters.oqs_params
24
25
26 @attr.s(frozen=True)
27 class OqsNamedGroup:
28 code = attr.ib(validator=attr.validators.instance_of(int))
29 name = attr.ib(validator=attr.validators.instance_of(str))
30 size = attr.ib(validator=attr.validators.instance_of(int))
31 oqs_name = attr.ib(validator=attr.validators.optional(attr.validators.instance_of(str)))
32 # The halves are the names of the entries a hybrid group is composed of, not the entries themselves: the
33 # updater reloads the enum modules between its phases, so an enum member kept here would be an instance of a
34 # class that no longer is the one the reloaded module defines. A group that has no classical half is not a
35 # hybrid one.
36 classical_key_parameter = attr.ib(
37 default=None, validator=attr.validators.optional(attr.validators.instance_of(str))
38 )
39 post_quantum_key_parameter = attr.ib(
40 default=None, validator=attr.validators.optional(attr.validators.instance_of(str))
41 )
42
43 @property
44 def hybrid(self):
45 return self.classical_key_parameter is not None
46
47
48 @attr.s(frozen=True)
49 class OqsAuthentication:
50 identifier = attr.ib(validator=attr.validators.instance_of(str))
51 name = attr.ib(validator=attr.validators.instance_of(str))
52 long_name = attr.ib(validator=attr.validators.optional(attr.validators.instance_of(str)))
53
54
55 @attr.s(frozen=True)
56 class OqsSignatureAlgorithm:
57 code = attr.ib(validator=attr.validators.instance_of(int))
58 name = attr.ib(validator=attr.validators.instance_of(str))
59 authentication_identifier = attr.ib(validator=attr.validators.instance_of(str))
60 authentication_name = attr.ib(validator=attr.validators.instance_of(str))
61 authentication_long_name = attr.ib(
62 validator=attr.validators.optional(attr.validators.instance_of(str))
63 )
64
65
66 class FetcherOqsBase(FetcherBase):
67 _OQS_PROVIDER_VERSION = '0.11.0-rc1'
68 _LIBOQS_VERSION = '0.15.0'
69 _OQS_PROVIDER_CONFIG_URL = (
70 'https://raw.githubusercontent.com/open-quantum-safe/oqs-provider/{version}/'
71 'oqs-template/generate.yml'
72 )
73 _LIBOQS_ALGORITHM_DATASHEET_URL = (
74 'https://raw.githubusercontent.com/open-quantum-safe/liboqs/{version}/'
75 'docs/algorithms/kem/{name}.yml'
76 )
77 _OQS_ALGORITHM_NAME_PREFIX = 'OQS_KEM_alg_'
78 _TLS_ENABLED_UP_TO_RELEASE_0_5 = True
79 _DATASHEET_NAME_BY_FAMILY = {'CRYSTALS-Kyber': 'kyber'}
80 _CLASSICAL_NAMED_CURVES = (
81 cryptodatahub.tls.algorithm.TlsNamedCurve.SECP256R1,
82 cryptodatahub.tls.algorithm.TlsNamedCurve.SECP384R1,
83 cryptodatahub.tls.algorithm.TlsNamedCurve.SECP521R1,
84 )
85 _CLASSICAL_NAMED_CURVE_BY_HYBRID_GROUP_UP_TO_RELEASE_0_8_0 = {
86 'p256': cryptodatahub.tls.algorithm.TlsNamedCurve.SECP256R1,
87 'p384': cryptodatahub.tls.algorithm.TlsNamedCurve.SECP384R1,
88 }
89 _CLASSICAL_NAMED_CURVE_BY_HYBRID_GROUP = {
90 **_CLASSICAL_NAMED_CURVE_BY_HYBRID_GROUP_UP_TO_RELEASE_0_8_0,
91 'secp256_r1': cryptodatahub.tls.algorithm.TlsNamedCurve.SECP256R1,
92 'secp384_r1': cryptodatahub.tls.algorithm.TlsNamedCurve.SECP384R1,
93 'secp521_r1': cryptodatahub.tls.algorithm.TlsNamedCurve.SECP521R1,
94 'bp256': cryptodatahub.tls.algorithm.TlsNamedCurve.BRAINPOOLP256R1,
95 'bp384': cryptodatahub.tls.algorithm.TlsNamedCurve.BRAINPOOLP384R1,
96 'bp512': cryptodatahub.tls.algorithm.TlsNamedCurve.BRAINPOOLP512R1,
97 'x25519': cryptodatahub.tls.algorithm.TlsNamedCurve.X25519,
98 'x448': cryptodatahub.tls.algorithm.TlsNamedCurve.X448,
99 }
100
101 @classmethod
102 @abc.abstractmethod
103 def _transform_data(cls, current_data):
104 raise NotImplementedError()
105
106 @classmethod
107 def get_config_url(cls, version=None):
108 return cls._OQS_PROVIDER_CONFIG_URL.format(version=version or cls._OQS_PROVIDER_VERSION)
109
110 @classmethod
111 def get_algorithm_datasheet_url(cls, name):
112 return cls._LIBOQS_ALGORITHM_DATASHEET_URL.format(version=cls._LIBOQS_VERSION, name=name)
113
114 @classmethod
115 def _fetch_yaml(cls, url):
116 return yaml.safe_load(HttpFetcher(connect_timeout=5, read_timeout=30)(url))
117
118 @classmethod
119 def _get_config(cls):
120 return cls._fetch_yaml(cls.get_config_url())
121
122 @staticmethod
123 def _get_code(nid):
124 nid = str(nid)
125
126 return int(nid, 16) if nid.startswith('0x') else int(nid, 10)
127
128 @staticmethod
129 def _get_named_curve_size(named_curve):
130 return named_curve.value.key_parameter.value.field_size
131
132 @classmethod
133 def _get_classical_named_curve(cls, bit_security):
134 return min(
135 (
136 named_curve
137 for named_curve in cls._CLASSICAL_NAMED_CURVES
138 if cls._get_named_curve_size(named_curve) >= bit_security * 2
139 ),
140 key=cls._get_named_curve_size,
141 )
142
143 @classmethod
144 def _get_hybrid_group(cls, named_curve):
145 return f'p{cls._get_named_curve_size(named_curve)}'
146
147 @classmethod
148 def _get_datasheet_name(cls, family):
149 return cls._DATASHEET_NAME_BY_FAMILY.get(family, family.lower().replace('-', '_'))
150
151 @staticmethod
152 def _get_comparable_algorithm_name(name):
153 return name.replace('FrodoKEM', 'Frodo').lower().replace('_', '').replace('-', '')
154
155 @classmethod
156 def _is_tls_enabled(cls, key_encapsulation_mechanism):
157 return key_encapsulation_mechanism.get('enable_tls', cls._TLS_ENABLED_UP_TO_RELEASE_0_5)
158
159 @classmethod
160 def _get_tls_enabled_key_encapsulation_mechanisms(cls, config):
161 return list(filter(cls._is_tls_enabled, config['kems']))
162
163 @classmethod
164 def _get_algorithm_datasheets(cls, key_encapsulation_mechanisms):
165 datasheets = collections.OrderedDict()
166 for key_encapsulation_mechanism in key_encapsulation_mechanisms:
167 datasheet_name = cls._get_datasheet_name(key_encapsulation_mechanism['family'])
168 if datasheet_name not in datasheets:
169 datasheets[datasheet_name] = cls._fetch_yaml(
170 cls.get_algorithm_datasheet_url(datasheet_name)
171 )
172
173 return datasheets
174
175 @classmethod
176 def _get_parameter_set(cls, datasheets, key_encapsulation_mechanism):
177 datasheet = datasheets[cls._get_datasheet_name(key_encapsulation_mechanism['family'])]
178 comparable_name = cls._get_comparable_algorithm_name(key_encapsulation_mechanism['name_group'])
179 for parameter_set in datasheet['parameter-sets']:
180 if cls._get_comparable_algorithm_name(parameter_set['name']) == comparable_name:
181 return parameter_set
182
183 return None
184
185 @classmethod
186 def _get_post_quantum_key_parameter(cls, key_encapsulation_mechanism, nist_round):
187 """The plain entry a hybrid one of the same round is composed with.
188
189 A round bearing entry is named after the algorithm for some families and
190 after the group for others, so the candidates are resolved against the
191 registry rather than one of the two spellings being assumed. None means
192 the half cannot be named, and the composition is left unwritten.
193 """
194 name_group = key_encapsulation_mechanism['name_group']
195 algorithm_name = key_encapsulation_mechanism['oqs_alg'][len(cls._OQS_ALGORITHM_NAME_PREFIX):]
196
197 if nist_round is None:
198 candidates = (name_group, algorithm_name)
199 else:
200 candidates = (f'{algorithm_name}_r{nist_round}', f'{name_group}_r{nist_round}')
201
202 for candidate in candidates:
203 identifier = name_to_enum_item_name(candidate)
204 if identifier in cryptodatahub.common.pqc.KeyEncapsulationMechanism.__members__:
205 return identifier
206
207 return None
208
209 @classmethod
210 def _get_named_groups(cls, key_encapsulation_mechanism, bit_security, size):
211 name_group = key_encapsulation_mechanism['name_group']
212
213 if 'nid' in key_encapsulation_mechanism:
214 yield OqsNamedGroup(
215 code=cls._get_code(key_encapsulation_mechanism['nid']),
216 name=name_group,
217 size=size,
218 oqs_name=name_group,
219 )
220
221 # Only this branch needs the strength, to choose a classical curve by it.
222 # An entry whose parameter set the pinned release no longer describes still
223 # names the classical half of every hybrid beside it outright.
224 if 'nid_hybrid' in key_encapsulation_mechanism and bit_security is not None:
225 classical_named_curve = cls._get_classical_named_curve(bit_security)
226 yield OqsNamedGroup(
227 code=cls._get_code(key_encapsulation_mechanism['nid_hybrid']),
228 name=f'{classical_named_curve.name.lower()}/{name_group}',
229 size=size,
230 oqs_name=f'{cls._get_hybrid_group(classical_named_curve)}_{name_group}',
231 classical_key_parameter=classical_named_curve.value.key_parameter.name,
232 post_quantum_key_parameter=cls._get_post_quantum_key_parameter(
233 key_encapsulation_mechanism, None
234 ),
235 )
236
237 extra_nids = key_encapsulation_mechanism.get('extra_nids', {})
238 for extra_nid in itertools.chain(extra_nids.get('current', []), extra_nids.get('old', [])):
239 yield cls._get_named_group_from_extra_nid(
240 key_encapsulation_mechanism, extra_nid, size
241 )
242
243 @classmethod
244 def _get_named_group_from_extra_nid(cls, key_encapsulation_mechanism, extra_nid, size):
245 name_group = key_encapsulation_mechanism['name_group']
246 named_group_name = key_encapsulation_mechanism['oqs_alg'][len(cls._OQS_ALGORITHM_NAME_PREFIX):]
247 nist_round = extra_nid.get('nist-round')
248 if nist_round is not None:
249 named_group_name += f'_r{nist_round}'
250
251 hybrid_group = extra_nid.get('hybrid_group')
252 classical_key_parameter = None
253 if hybrid_group is not None:
254 classical_named_curve = cls._CLASSICAL_NAMED_CURVE_BY_HYBRID_GROUP[hybrid_group]
255 classical_key_parameter = classical_named_curve.value.key_parameter.name
256 named_group_name = f'{classical_named_curve.name.lower()}/{named_group_name}'
257
258 is_earlier_nist_round = nist_round is not None
259 repeats_plain_code_point = hybrid_group is None
260 if is_earlier_nist_round or repeats_plain_code_point:
261 oqs_name = None
262 else:
263 oqs_name = extra_nid.get('standard_name', f'{hybrid_group}_{name_group}')
264
265 return OqsNamedGroup(
266 code=cls._get_code(extra_nid['nid']),
267 name=named_group_name,
268 size=size,
269 oqs_name=oqs_name,
270 classical_key_parameter=classical_key_parameter,
271 post_quantum_key_parameter=(
272 None if classical_key_parameter is None
273 else cls._get_post_quantum_key_parameter(key_encapsulation_mechanism, nist_round)
274 ),
275 )
276
277 @classmethod
278 def _get_current_data(cls):
279 config = cls._get_config()
280 key_encapsulation_mechanisms = cls._get_tls_enabled_key_encapsulation_mechanisms(config)
281 datasheets = cls._get_algorithm_datasheets(key_encapsulation_mechanisms)
282
283 oqs_named_groups = []
284 for key_encapsulation_mechanism in key_encapsulation_mechanisms:
285 parameter_set = cls._get_parameter_set(datasheets, key_encapsulation_mechanism)
286 if parameter_set is None:
287 continue
288
289 nist_security_level = cryptodatahub.common.algorithm.NistSecurityLevel.from_code(
290 parameter_set['claimed-nist-level']
291 )
292 oqs_named_groups.extend(cls._get_named_groups(
293 key_encapsulation_mechanism,
294 nist_security_level.value.bit_security,
295 parameter_set['length-public-key'] * 8,
296 ))
297
298 return oqs_named_groups
299
300
301 class FetcherOqsSignatureAlgorithmBase(FetcherOqsBase):
302 _AUTHENTICATION_BY_FAMILY = {
303 'ML-DSA': OqsAuthentication(
304 'MLDSA', 'ML-DSA', 'Module-Lattice-Based Digital Signature Algorithm'
305 ),
306 'Falcon': OqsAuthentication(
307 'FALCON', 'Falcon', 'Fast-Fourier Lattice-based Compact Signatures over NTRU'
308 ),
309 'SPHINCS-SHA2': OqsAuthentication(
310 'SLHDSA', 'SLH-DSA', 'Stateless Hash-Based Digital Signature Algorithm'
311 ),
312 'SPHINCS-SHAKE': OqsAuthentication(
313 'SLHDSA', 'SLH-DSA', 'Stateless Hash-Based Digital Signature Algorithm'
314 ),
315 'MAYO': OqsAuthentication('MAYO', 'MAYO', None),
316 'CROSS': OqsAuthentication(
317 'CROSS', 'CROSS', 'Codes and Restricted Objects Signature Scheme'
318 ),
319 'UOV': OqsAuthentication('UOV', 'UOV', 'Unbalanced Oil and Vinegar'),
320 'SNOVA': OqsAuthentication('SNOVA', 'SNOVA', None),
321 }
322 _PQCLEAN_IMPLEMENTATION_NAME = 'PQClean'
323
324 @classmethod
325 @abc.abstractmethod
326 def _transform_data(cls, current_data):
327 raise NotImplementedError()
328
329 @classmethod
330 def _is_pqclean_rebuild(cls, extra_nid):
331 return cls._PQCLEAN_IMPLEMENTATION_NAME in extra_nid.get('implementation_version', '')
332
333 @classmethod
334 def _get_name_suffix(cls, extra_nid):
335 nist_round = extra_nid.get('nist-round')
336 name_suffix = '' if nist_round is None else f'_r{nist_round}'
337
338 # Falcon carries both the round 3 submission and its PQClean rebuild under nist-round 3, and
339 # upstream tells the two apart by the free text implementation_version only
340 if cls._is_pqclean_rebuild(extra_nid):
341 name_suffix += '_pqclean'
342
343 return name_suffix
344
345 @classmethod
346 def _get_signature_algorithms(cls, family, variant):
347 oqs_authentication = cls._AUTHENTICATION_BY_FAMILY[family]
348 code_points = [('', variant['code_point'], variant.get('mix_with', []))]
349 for extra_nid in variant.get('extra_nids', {}).get('old', []):
350 code_points.append(
351 (cls._get_name_suffix(extra_nid), extra_nid['code_point'], extra_nid.get('mix_with', []))
352 )
353
354 for name_suffix, code_point, mixed_algorithms in code_points:
355 yield OqsSignatureAlgorithm(
356 code=cls._get_code(code_point),
357 name=f'{variant["name"]}{name_suffix}',
358 authentication_identifier=oqs_authentication.identifier,
359 authentication_name=oqs_authentication.name,
360 authentication_long_name=oqs_authentication.long_name,
361 )
362
363 for mixed_algorithm in mixed_algorithms:
364 composite_name = f'{mixed_algorithm["name"]}_{variant["name"]}'
365 yield OqsSignatureAlgorithm(
366 code=cls._get_code(mixed_algorithm['code_point']),
367 name=f'{composite_name}{name_suffix}',
368 authentication_identifier=name_to_enum_item_name(composite_name),
369 authentication_name=f'{mixed_algorithm["pretty_name"]} + {variant["pretty_name"]}',
370 authentication_long_name=None,
371 )
372
373 @classmethod
374 def _get_current_data(cls):
375 oqs_signature_algorithms = []
376 for family in cls._get_config()['sigs']:
377 for variant in family.get('variants', []):
378 if not variant.get('enable_tls'):
379 continue
380
381 oqs_signature_algorithms.extend(cls._get_signature_algorithms(family['family'], variant))
382
383 return oqs_signature_algorithms
384
385
386 def _get_oqs_provider_release_order(version):
387 release, _, candidate = version.partition('-rc')
388 is_final_release = 0 if candidate else 1
389
390 return tuple(map(int, release.split('.'))), is_final_release, int(candidate or 0)
391
392
393 class FetcherOqsHybridNamedGroup(FetcherOqsBase):
394 # The first release that yields a group is the one that names it, and an algorithm carries no
395 # round while it is current and gains one only once a later release retires it, so the oldest
396 # naming would register secp256r1/kyber512 where the registry has secp256r1/kyber_512_r2.
397 _OQS_PROVIDER_RETIRED_VERSIONS_NEWEST_FIRST = tuple(sorted(
398 (
399 '0.11.0', '0.10.0', '0.10.0-rc1', '0.9.0', '0.9.0-rc1', '0.8.0', '0.8.0-rc1',
400 '0.7.0', '0.7.0-rc1', '0.6.1', '0.6.1-rc1', '0.6.0', '0.6.0-rc1',
401 '0.5.3', '0.5.2', '0.5.1', '0.5.1-rc1', '0.5.0',
402 ),
403 key=_get_oqs_provider_release_order,
404 reverse=True,
405 ))
406
407 @classmethod
408 def _get_config_versions(cls):
409 return (cls._OQS_PROVIDER_VERSION,) + cls._OQS_PROVIDER_RETIRED_VERSIONS_NEWEST_FIRST
410
411 @classmethod
412 def _get_family_nist_round(cls, datasheets, key_encapsulation_mechanism):
413 datasheet = datasheets[cls._get_datasheet_name(key_encapsulation_mechanism['family'])]
414 nist_round = datasheet.get('nist-round')
415
416 return nist_round if isinstance(nist_round, int) else None
417
418 @classmethod
419 def _get_current_data(cls):
420 oqs_named_groups = []
421 for version in cls._get_config_versions():
422 config = cls._fetch_yaml(cls.get_config_url(version))
423 key_encapsulation_mechanisms = cls._get_tls_enabled_key_encapsulation_mechanisms(config)
424 datasheets = cls._get_algorithm_datasheets(key_encapsulation_mechanisms)
425
426 for key_encapsulation_mechanism in key_encapsulation_mechanisms:
427 parameter_set = cls._get_parameter_set(datasheets, key_encapsulation_mechanism)
428 bit_security = None
429 if parameter_set is not None:
430 bit_security = cryptodatahub.common.algorithm.NistSecurityLevel.from_code(
431 parameter_set['claimed-nist-level']
432 ).value.bit_security
433
434 oqs_named_groups.extend(cls._get_named_groups(
435 key_encapsulation_mechanism, bit_security, 0
436 ))
437 oqs_named_groups.extend(cls._get_named_groups_of_family_round(
438 key_encapsulation_mechanism,
439 bit_security,
440 cls._get_family_nist_round(datasheets, key_encapsulation_mechanism),
441 ))
442
443 return oqs_named_groups
444
445 @classmethod
446 def _get_named_groups_of_family_round(
447 cls, key_encapsulation_mechanism, bit_security, family_nist_round
448 ):
449 if family_nist_round is None:
450 return
451
452 for oqs_named_group in cls._get_named_groups(key_encapsulation_mechanism, bit_security, 0):
453 if not oqs_named_group.hybrid or oqs_named_group.name.endswith(f'_r{family_nist_round}'):
454 continue
455
456 yield attr.evolve(
457 oqs_named_group,
458 name=f'{oqs_named_group.name}_r{family_nist_round}',
459 post_quantum_key_parameter=cls._get_post_quantum_key_parameter(
460 key_encapsulation_mechanism, family_nist_round
461 ),
462 )
463
464 @classmethod
465 def _transform_data(cls, current_data):
466 hybrid_named_group_params = collections.OrderedDict([
467 (
468 hybrid_named_group.name,
469 updaters.oqs_params.FetchedHybridNamedGroupParams(
470 identifier=hybrid_named_group.name, **hybrid_named_group.value._asdict()
471 ),
472 )
473 for hybrid_named_group in cryptodatahub.common.pqc.HybridNamedGroup
474 ])
475 composed_halves = {
476 (params.classical_key_parameter.name, params.post_quantum_key_parameter.name)
477 for params in hybrid_named_group_params.values()
478 }
479
480 for oqs_named_group in current_data:
481 if not oqs_named_group.hybrid:
482 continue
483
484 identifier = name_to_enum_item_name(oqs_named_group.name)
485 if identifier in hybrid_named_group_params:
486 continue
487
488 if oqs_named_group.post_quantum_key_parameter is None:
489 continue
490
491 halves = (
492 oqs_named_group.classical_key_parameter, oqs_named_group.post_quantum_key_parameter
493 )
494 if halves in composed_halves:
495 continue
496 composed_halves.add(halves)
497
498 hybrid_named_group_params[identifier] = (
499 updaters.oqs_params.FetchedHybridNamedGroupParams(
500 identifier=identifier,
501 # The classical curve and the algorithm joined, which is how the provider names the
502 # group. The Open Quantum Safe name is not an alternative: it holds a standard name
503 # for a few entries and an internal one built from the two halves for the rest, so
504 # it is two kinds of thing under one field.
505 name=oqs_named_group.name,
506 long_name=None,
507 # A composition is graded by the two halves it names, so it
508 # states no vulnerability of its own.
509 vulnerabilities=[],
510 classical_key_parameter=oqs_named_group.classical_key_parameter,
511 post_quantum_key_parameter=oqs_named_group.post_quantum_key_parameter,
512 oqs_name=oqs_named_group.name,
513 )
514 )
515
516 return list(hybrid_named_group_params.values())
517
518
519 class FetcherOqsKeyEncapsulationMechanism(FetcherOqsBase):
520 # Every release that documents its parameter sets, newest first. A round is
521 # taken from the newest release still in it, because an older one may carry a
522 # mistake a later release of the same round corrects: liboqs 0.5.0 claims NIST
523 # level 1 for Kyber768-90s where 0.4.0 and 0.7.0 both claim 3.
524 _LIBOQS_DATASHEET_VERSIONS = (
525 '0.16.0', '0.15.0', '0.14.0', '0.13.0', '0.12.0', '0.11.0', '0.10.1', '0.10.0',
526 '0.9.2', '0.9.1', '0.9.0', '0.8.0', '0.7.2', '0.7.1', '0.7.0',
527 )
528 # The releases before 0.7.0 state the same numbers in a table instead.
529 _LIBOQS_MARKDOWN_DATASHEET_VERSIONS = ('0.6.0', '0.5.0', '0.4.0', '0.3.0')
530 _LIBOQS_ALGORITHM_DATASHEET_MARKDOWN_URL = (
531 'https://raw.githubusercontent.com/open-quantum-safe/liboqs/{version}/'
532 'docs/algorithms/kem/{name}.md'
533 )
534 _DATASHEET_NAMES = ('bike', 'frodokem', 'hqc', 'kyber', 'ml_kem', 'ntru')
535
536 @classmethod
537 def get_algorithm_datasheet_markdown_url(cls, version, name):
538 return cls._LIBOQS_ALGORITHM_DATASHEET_MARKDOWN_URL.format(version=version, name=name)
539
540 @staticmethod
541 def _split_nist_round(name):
542 """A registry name carries the round it belongs to, a parameter set name does not.
543
544 The separator is a hyphen in the stored records and an underscore in the
545 named group names, so both are accepted.
546 """
547 match = re.search(r'[_-]r(\d)$', name)
548 if match is None:
549 return name, None
550
551 return name[:match.start()], int(match.group(1))
552
553 @classmethod
554 def _get_datasheet_of_version(cls, version, datasheet_name, markdown):
555 if markdown:
556 content = HttpFetcher(connect_timeout=5, read_timeout=30)(
557 cls.get_algorithm_datasheet_markdown_url(version, datasheet_name)
558 )
559 if isinstance(content, bytes):
560 # The submitter names are not all spelled in ASCII.
561 content = content.decode('utf-8')
562
563 return (
564 updaters.oqs_datasheet.get_nist_round_of_markdown(content),
565 updaters.oqs_datasheet.get_parameter_sets_of_markdown(content),
566 )
567
568 datasheet = cls._fetch_yaml(
569 cls._LIBOQS_ALGORITHM_DATASHEET_URL.format(version=version, name=datasheet_name)
570 )
571
572 return (
573 updaters.oqs_datasheet.get_nist_round(datasheet),
574 updaters.oqs_datasheet.get_parameter_sets(datasheet),
575 )
576
577 @classmethod
578 def _get_datasheets_of_version(cls, version, markdown):
579 datasheets = {}
580 for datasheet_name in cls._DATASHEET_NAMES:
581 try:
582 nist_round, parameter_sets = cls._get_datasheet_of_version(
583 version, datasheet_name, markdown
584 )
585 except AttributeError:
586 # A family that release does not describe. The fetcher leaves no
587 # response behind for one, which is what reading it raises on.
588 continue
589
590 datasheets[datasheet_name] = (
591 nist_round,
592 {
593 cls._get_comparable_algorithm_name(name): parameter_set
594 for name, parameter_set in parameter_sets.items()
595 },
596 )
597
598 return datasheets
599
600 @classmethod
601 def _get_current_data(cls):
602 wanted = collections.OrderedDict(
603 (
604 key_encapsulation_mechanism.name,
605 cls._split_nist_round(key_encapsulation_mechanism.value.name),
606 )
607 for key_encapsulation_mechanism in cryptodatahub.common.pqc.KeyEncapsulationMechanism
608 )
609
610 resolved = collections.OrderedDict()
611 versions = (
612 [(version, False) for version in cls._LIBOQS_DATASHEET_VERSIONS] +
613 [(version, True) for version in cls._LIBOQS_MARKDOWN_DATASHEET_VERSIONS]
614 )
615 for version, markdown in versions:
616 if len(resolved) == len(wanted):
617 break
618
619 datasheets = cls._get_datasheets_of_version(version, markdown)
620 for identifier, (name, nist_round) in wanted.items():
621 if identifier in resolved:
622 continue
623
624 comparable_name = cls._get_comparable_algorithm_name(name)
625 for family_nist_round, parameter_sets in datasheets.values():
626 if comparable_name not in parameter_sets:
627 continue
628 # A datasheet that states its round has to agree, because a
629 # family can carry one parameter set name into two rounds with
630 # different sizes: Kyber512 encapsulates into 736 bytes in
631 # round 2 and 768 in round 3. Where a datasheet states no
632 # round the name is the only identity there is, and only the
633 # families that state one reuse a name across rounds.
634 if None not in (nist_round, family_nist_round) \
635 and family_nist_round != nist_round:
636 continue
637
638 parameter_set = parameter_sets[comparable_name]
639 # The round belongs in the name, the way the stored records
640 # spell it. Two rounds of one parameter set can hold the same
641 # sizes, and records that agree in every field are one record.
642 resolved[identifier] = attr.evolve(
643 parameter_set,
644 identifier=identifier,
645 name=(
646 parameter_set.name if nist_round is None
647 else f'{parameter_set.name}-r{nist_round}'
648 ),
649 )
650 break
651
652 return list(resolved.values())
653
654 @classmethod
655 def _transform_data(cls, current_data):
656 key_encapsulation_mechanism_params = collections.OrderedDict([
657 (
658 key_encapsulation_mechanism.name,
659 updaters.oqs_params.FetchedKeyEncapsulationMechanismParams(
660 identifier=key_encapsulation_mechanism.name,
661 **key_encapsulation_mechanism.value._asdict()
662 ),
663 )
664 for key_encapsulation_mechanism in cryptodatahub.common.pqc.KeyEncapsulationMechanism
665 ])
666
667 for parameter_set in current_data:
668 existing = key_encapsulation_mechanism_params.get(parameter_set.identifier)
669 # The sizes and the security category are what the datasheet states,
670 # so they are taken from it even where a record already holds them.
671 # The name, the aliases, the sources and the Open Quantum Safe name
672 # are not in a datasheet at all — the last one is in the provider
673 # configuration the hybrid compositions are read from — so a record
674 # that has them keeps them.
675 key_encapsulation_mechanism_params[parameter_set.identifier] = (
676 updaters.oqs_params.FetchedKeyEncapsulationMechanismParams(
677 identifier=parameter_set.identifier,
678 name=existing.name if existing else parameter_set.name,
679 long_name=existing.long_name if existing else None,
680 vulnerabilities=existing.vulnerabilities if existing else [],
681 aliases=existing.aliases if existing else [],
682 sources=existing.sources if existing else [],
683 encapsulation_key_size=parameter_set.encapsulation_key_size,
684 decapsulation_key_size=parameter_set.decapsulation_key_size,
685 ciphertext_size=parameter_set.ciphertext_size,
686 shared_secret_size=parameter_set.shared_secret_size,
687 security_category=cryptodatahub.common.algorithm.NistSecurityLevel.from_code(
688 parameter_set.security_category
689 ),
690 oqs_name=existing.oqs_name if existing else None,
691 )
692 )
693
694 return list(key_encapsulation_mechanism_params.values())
695
696
697 class FetcherOqsNamedCurve(FetcherOqsBase):
698 @classmethod
699 def _transform_data(cls, current_data):
700 named_curve_params = []
701 for named_curve in cryptodatahub.tls.algorithm.TlsNamedCurve:
702 params = named_curve.value._asdict()
703 params.pop('gradeables', None)
704 named_curve_params.append(
705 updaters.oqs_params.FetchedNamedCurveParams(identifier=named_curve.name, **params)
706 )
707
708 existing_identifier_by_code = {params.code: params.identifier for params in named_curve_params}
709 existing_identifiers = {params.identifier for params in named_curve_params}
710
711 for oqs_named_group in current_data:
712 identifier = name_to_enum_item_name(oqs_named_group.name)
713
714 existing_identifier = existing_identifier_by_code.get(oqs_named_group.code)
715 if existing_identifier is not None:
716 if existing_identifier != identifier:
717 print(
718 f'Code point already assigned; code=0x{oqs_named_group.code:04x}, '
719 f'existing={existing_identifier}, fetched={identifier}'
720 )
721
722 continue
723
724 if identifier in existing_identifiers:
725 continue
726
727 named_curve_params.append(updaters.oqs_params.FetchedNamedCurveParams(
728 identifier=identifier,
729 code=oqs_named_group.code,
730 key_parameter=identifier,
731 initial_version=cryptodatahub.tls.version.TlsVersion.TLS1_3,
732 last_version=cryptodatahub.tls.version.TlsVersion.TLS1_3,
733 ))
734 existing_identifier_by_code[oqs_named_group.code] = identifier
735 existing_identifiers.add(identifier)
736
737 return named_curve_params
738
739
740 class FetcherOqsAuthentication(FetcherOqsSignatureAlgorithmBase):
741 @classmethod
742 def _transform_data(cls, current_data):
743 authentication_params = collections.OrderedDict([
744 (
745 authentication.name,
746 updaters.oqs_params.FetchedAuthenticationParams(
747 identifier=authentication.name, **authentication.value._asdict()
748 ),
749 )
750 for authentication in cryptodatahub.common.algorithm.Authentication
751 ])
752
753 for oqs_signature_algorithm in current_data:
754 identifier = oqs_signature_algorithm.authentication_identifier
755 if identifier in authentication_params:
756 continue
757
758 authentication_params[identifier] = updaters.oqs_params.FetchedAuthenticationParams(
759 identifier=identifier,
760 name=oqs_signature_algorithm.authentication_name,
761 long_name=oqs_signature_algorithm.authentication_long_name,
762 oid=None,
763 vulnerabilities=[],
764 anonymous=False,
765 )
766
767 return list(authentication_params.values())
768
769
770 class FetcherOqsSignatureAlgorithm(FetcherOqsSignatureAlgorithmBase):
771 @classmethod
772 def _transform_data(cls, current_data):
773 signature_algorithm_params = collections.OrderedDict()
774 for signature_algorithm in cryptodatahub.tls.algorithm.TlsSignatureAndHashAlgorithm:
775 params = signature_algorithm.value._asdict()
776 params.pop('gradeables', None)
777 params.pop('last_version', None)
778 signature_algorithm_params[signature_algorithm.name] = (
779 updaters.oqs_params.FetchedHashAndSignatureAlgorithmParams(
780 identifier=signature_algorithm.name, **params
781 )
782 )
783
784 existing_identifiers_by_code = collections.OrderedDict([
785 (params.code, params.identifier) for params in signature_algorithm_params.values()
786 ])
787
788 for oqs_signature_algorithm in current_data:
789 identifier = name_to_enum_item_name(oqs_signature_algorithm.name)
790
791 existing_identifier = existing_identifiers_by_code.get(oqs_signature_algorithm.code)
792 if existing_identifier is not None:
793 if existing_identifier != identifier:
794 print(
795 f'Code point already assigned; code=0x{oqs_signature_algorithm.code:04x}, '
796 f'existing={existing_identifier}, fetched={identifier}'
797 )
798
799 continue
800
801 if identifier in signature_algorithm_params:
802 print(
803 f'Identifier already in use; code=0x{oqs_signature_algorithm.code:04x}, '
804 f'identifier={identifier}'
805 )
806
807 continue
808
809 signature_algorithm_params[identifier] = (
810 updaters.oqs_params.FetchedHashAndSignatureAlgorithmParams(
811 identifier=identifier,
812 code=oqs_signature_algorithm.code,
813 hash_algorithm=None,
814 signature_algorithm=oqs_signature_algorithm.authentication_identifier,
815 initial_version=cryptodatahub.tls.version.TlsVersion.TLS1_3,
816 )
817 )
818 existing_identifiers_by_code[oqs_signature_algorithm.code] = identifier
819
820 return list(signature_algorithm_params.values())
821
822
823 class UpdaterOqsBase(UpdaterBase):
824 @staticmethod
825 def reload_enum_modules(): # pragma: no cover
826 # The enum classes are built from the JSON data files at import time, so the named groups and
827 # the authentication algorithms an updater writes can be referred to by the named curve and
828 # the signature algorithm entries only after the modules defining those enum classes have
829 # been imported again. Reloading them in a test would replace the enum classes the other
830 # tests compare against, so this is only ever exercised by main().
831 importlib.reload(cryptodatahub.common.algorithm)
832 importlib.reload(cryptodatahub.common.pqc)
833 importlib.reload(cryptodatahub.tls.algorithm)
834 importlib.reload(updaters.oqs_params)
835
836
837 class UpdaterOqsHybridNamedGroup(UpdaterOqsBase):
838 def __init__(self):
839 super().__init__(
840 FetcherOqsHybridNamedGroup,
841 cryptodatahub.common.pqc.HybridNamedGroup,
842 cryptodatahub.common.pqc.HybridNamedGroupParams,
843 )
844
845
846 class UpdaterOqsKeyEncapsulationMechanism(UpdaterOqsBase):
847 def __init__(self):
848 super().__init__(
849 FetcherOqsKeyEncapsulationMechanism,
850 cryptodatahub.common.pqc.KeyEncapsulationMechanism,
851 cryptodatahub.common.pqc.KeyEncapsulationMechanismParams,
852 )
853
854
855 class UpdaterOqsNamedCurve(UpdaterOqsBase):
856 def __init__(self):
857 super().__init__(
858 FetcherOqsNamedCurve,
859 cryptodatahub.tls.algorithm.TlsNamedCurve,
860 cryptodatahub.tls.algorithm.NamedCurveParams,
861 )
862
863 @staticmethod
864 def sort_key(merged_item):
865 _, params = merged_item
866
867 return params['code']
868
869
870 class UpdaterOqsAuthentication(UpdaterOqsBase):
871 def __init__(self):
872 super().__init__(
873 FetcherOqsAuthentication,
874 cryptodatahub.common.algorithm.Authentication,
875 cryptodatahub.common.algorithm.AuthenticationParams,
876 )
877
878
879 class UpdaterOqsSignatureAlgorithm(UpdaterOqsBase):
880 def __init__(self):
881 super().__init__(
882 FetcherOqsSignatureAlgorithm,
883 cryptodatahub.tls.algorithm.TlsSignatureAndHashAlgorithm,
884 cryptodatahub.tls.algorithm.HashAndSignatureAlgorithmParams,
885 )
886
887 @staticmethod
888 def sort_key(merged_item):
889 _, params = merged_item
890
891 return params['code']
892
893
894 def main():
895 UpdaterOqsKeyEncapsulationMechanism()() # pragma: no cover
896 UpdaterOqsBase.reload_enum_modules() # pragma: no cover
897 UpdaterOqsHybridNamedGroup()() # pragma: no cover
898 UpdaterOqsBase.reload_enum_modules() # pragma: no cover
899 UpdaterOqsNamedCurve()() # pragma: no cover
900
901 UpdaterOqsAuthentication()() # pragma: no cover
902 UpdaterOqsBase.reload_enum_modules() # pragma: no cover
903 UpdaterOqsSignatureAlgorithm()() # pragma: no cover
904
905
906 if __name__ == '__main__':
907 main() # pragma: no cover