blob: 35ea93c0d964c26d5ed8943af5efc6871eb4141c [file] [log] [blame]
Pengyu Lv7f6933a2023-04-04 16:05:54 +08001#!/usr/bin/env python3
2#
Pengyu Lvf8e5e052023-04-18 15:43:25 +08003# Copyright The Mbed TLS Contributors
4# SPDX-License-Identifier: Apache-2.0
Pengyu Lv7f6933a2023-04-04 16:05:54 +08005#
Pengyu Lvf8e5e052023-04-18 15:43:25 +08006# Licensed under the Apache License, Version 2.0 (the "License"); you may
7# not use this file except in compliance with the License.
8# You may obtain a copy of the License at
Pengyu Lv7f6933a2023-04-04 16:05:54 +08009#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17
Pengyu Lv57240952023-04-13 14:42:37 +080018"""Audit validity date of X509 crt/crl/csr.
Pengyu Lv7f6933a2023-04-04 16:05:54 +080019
20This script is used to audit the validity date of crt/crl/csr used for testing.
Pengyu Lv1d4cc912023-04-25 15:17:19 +080021It prints the information about X.509 objects excluding the objects that
22are valid throughout the desired validity period. The data are collected
Pengyu Lvf8e5e052023-04-18 15:43:25 +080023from tests/data_files/ and tests/suites/*.data files by default.
Pengyu Lv7f6933a2023-04-04 16:05:54 +080024"""
25
26import os
27import sys
28import re
29import typing
Pengyu Lv7f6933a2023-04-04 16:05:54 +080030import argparse
31import datetime
Pengyu Lv45e32032023-04-06 14:33:41 +080032import glob
Pengyu Lvfcda6d42023-04-21 11:04:07 +080033import logging
Pengyu Lv7f6933a2023-04-04 16:05:54 +080034from enum import Enum
35
Pengyu Lv31792322023-04-11 16:30:54 +080036# The script requires cryptography >= 35.0.0 which is only available
Pengyu Lv13815982023-04-25 14:55:38 +080037# for Python >= 3.6.
38import cryptography
39from cryptography import x509
Pengyu Lv7f6933a2023-04-04 16:05:54 +080040
Pengyu Lvad306792023-04-19 15:07:03 +080041from generate_test_code import FileWrapper
Pengyu Lv30f26832023-04-07 18:04:07 +080042
Pengyu Lv2d487212023-04-21 12:41:24 +080043import scripts_path # pylint: disable=unused-import
44from mbedtls_dev import build_tree
45
Pengyu Lv13815982023-04-25 14:55:38 +080046def check_cryptography_version():
47 match = re.match(r'^[0-9]+', cryptography.__version__)
Pengyu Lvfd72d9f2023-04-28 11:17:24 +080048 if match is None or int(match.group(0)) < 35:
Pengyu Lv13815982023-04-25 14:55:38 +080049 raise Exception("audit-validity-dates requires cryptography >= 35.0.0"
50 + "({} is too old)".format(cryptography.__version__))
51
Pengyu Lv7f6933a2023-04-04 16:05:54 +080052class DataType(Enum):
53 CRT = 1 # Certificate
54 CRL = 2 # Certificate Revocation List
55 CSR = 3 # Certificate Signing Request
56
Pengyu Lv2d487212023-04-21 12:41:24 +080057
Pengyu Lv7f6933a2023-04-04 16:05:54 +080058class DataFormat(Enum):
59 PEM = 1 # Privacy-Enhanced Mail
60 DER = 2 # Distinguished Encoding Rules
61
Pengyu Lv2d487212023-04-21 12:41:24 +080062
Pengyu Lv7f6933a2023-04-04 16:05:54 +080063class AuditData:
Pengyu Lvf8e5e052023-04-18 15:43:25 +080064 """Store data location, type and validity period of X.509 objects."""
Pengyu Lv7f6933a2023-04-04 16:05:54 +080065 #pylint: disable=too-few-public-methods
Pengyu Lvcb8fc322023-04-11 15:05:29 +080066 def __init__(self, data_type: DataType, x509_obj):
Pengyu Lv7f6933a2023-04-04 16:05:54 +080067 self.data_type = data_type
Pengyu Lvfe13bd32023-04-28 10:58:38 +080068 # the locations that the x509 object could be found
69 self.locations = [] # type: typing.List[str]
Pengyu Lvcb8fc322023-04-11 15:05:29 +080070 self.fill_validity_duration(x509_obj)
Pengyu Lvfe13bd32023-04-28 10:58:38 +080071 self._obj = x509_obj
72
73 def __eq__(self, __value) -> bool:
74 return self._obj == __value._obj
Pengyu Lv7f6933a2023-04-04 16:05:54 +080075
76 def fill_validity_duration(self, x509_obj):
Pengyu Lvf8e5e052023-04-18 15:43:25 +080077 """Read validity period from an X.509 object."""
Pengyu Lv7f6933a2023-04-04 16:05:54 +080078 # Certificate expires after "not_valid_after"
79 # Certificate is invalid before "not_valid_before"
80 if self.data_type == DataType.CRT:
81 self.not_valid_after = x509_obj.not_valid_after
82 self.not_valid_before = x509_obj.not_valid_before
83 # CertificateRevocationList expires after "next_update"
84 # CertificateRevocationList is invalid before "last_update"
85 elif self.data_type == DataType.CRL:
86 self.not_valid_after = x509_obj.next_update
87 self.not_valid_before = x509_obj.last_update
88 # CertificateSigningRequest is always valid.
89 elif self.data_type == DataType.CSR:
90 self.not_valid_after = datetime.datetime.max
91 self.not_valid_before = datetime.datetime.min
92 else:
93 raise ValueError("Unsupported file_type: {}".format(self.data_type))
94
Pengyu Lv2d487212023-04-21 12:41:24 +080095
Pengyu Lvf8e5e052023-04-18 15:43:25 +080096class X509Parser:
Pengyu Lv7f6933a2023-04-04 16:05:54 +080097 """A parser class to parse crt/crl/csr file or data in PEM/DER format."""
Pengyu Lve245c0c2023-04-28 10:46:18 +080098 PEM_REGEX = br'-{5}BEGIN (?P<type>.*?)-{5}(?P<data>.*?)-{5}END (?P=type)-{5}'
Pengyu Lv7f6933a2023-04-04 16:05:54 +080099 PEM_TAG_REGEX = br'-{5}BEGIN (?P<type>.*?)-{5}\n'
100 PEM_TAGS = {
101 DataType.CRT: 'CERTIFICATE',
102 DataType.CRL: 'X509 CRL',
103 DataType.CSR: 'CERTIFICATE REQUEST'
104 }
105
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800106 def __init__(self,
107 backends:
108 typing.Dict[DataType,
109 typing.Dict[DataFormat,
110 typing.Callable[[bytes], object]]]) \
111 -> None:
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800112 self.backends = backends
113 self.__generate_parsers()
114
115 def __generate_parser(self, data_type: DataType):
116 """Parser generator for a specific DataType"""
117 tag = self.PEM_TAGS[data_type]
118 pem_loader = self.backends[data_type][DataFormat.PEM]
119 der_loader = self.backends[data_type][DataFormat.DER]
120 def wrapper(data: bytes):
121 pem_type = X509Parser.pem_data_type(data)
122 # It is in PEM format with target tag
123 if pem_type == tag:
124 return pem_loader(data)
125 # It is in PEM format without target tag
126 if pem_type:
127 return None
128 # It might be in DER format
129 try:
130 result = der_loader(data)
131 except ValueError:
132 result = None
133 return result
134 wrapper.__name__ = "{}.parser[{}]".format(type(self).__name__, tag)
135 return wrapper
136
137 def __generate_parsers(self):
138 """Generate parsers for all support DataType"""
139 self.parsers = {}
140 for data_type, _ in self.PEM_TAGS.items():
141 self.parsers[data_type] = self.__generate_parser(data_type)
142
143 def __getitem__(self, item):
144 return self.parsers[item]
145
146 @staticmethod
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800147 def pem_data_type(data: bytes) -> typing.Optional[str]:
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800148 """Get the tag from the data in PEM format
149
150 :param data: data to be checked in binary mode.
151 :return: PEM tag or "" when no tag detected.
152 """
153 m = re.search(X509Parser.PEM_TAG_REGEX, data)
154 if m is not None:
155 return m.group('type').decode('UTF-8')
156 else:
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800157 return None
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800158
Pengyu Lv30f26832023-04-07 18:04:07 +0800159 @staticmethod
160 def check_hex_string(hex_str: str) -> bool:
161 """Check if the hex string is possibly DER data."""
162 hex_len = len(hex_str)
163 # At least 6 hex char for 3 bytes: Type + Length + Content
164 if hex_len < 6:
165 return False
166 # Check if Type (1 byte) is SEQUENCE.
167 if hex_str[0:2] != '30':
168 return False
169 # Check LENGTH (1 byte) value
170 content_len = int(hex_str[2:4], base=16)
171 consumed = 4
172 if content_len in (128, 255):
173 # Indefinite or Reserved
174 return False
175 elif content_len > 127:
176 # Definite, Long
177 length_len = (content_len - 128) * 2
178 content_len = int(hex_str[consumed:consumed+length_len], base=16)
179 consumed += length_len
180 # Check LENGTH
181 if hex_len != content_len * 2 + consumed:
182 return False
183 return True
184
Pengyu Lv2d487212023-04-21 12:41:24 +0800185
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800186class Auditor:
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800187 """
188 A base class that uses X509Parser to parse files to a list of AuditData.
189
190 A subclass must implement the following methods:
191 - collect_default_files: Return a list of file names that are defaultly
192 used for parsing (auditing). The list will be stored in
193 Auditor.default_files.
194 - parse_file: Method that parses a single file to a list of AuditData.
195
196 A subclass may override the following methods:
197 - parse_bytes: Defaultly, it parses `bytes` that contains only one valid
198 X.509 data(DER/PEM format) to an X.509 object.
199 - walk_all: Defaultly, it iterates over all the files in the provided
200 file name list, calls `parse_file` for each file and stores the results
201 by extending Auditor.audit_data.
202 """
Pengyu Lvfcda6d42023-04-21 11:04:07 +0800203 def __init__(self, logger):
204 self.logger = logger
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800205 self.default_files = self.collect_default_files()
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800206 # A list to store the parsed audit_data.
Pengyu Lva228cbc2023-04-21 11:59:25 +0800207 self.audit_data = [] # type: typing.List[AuditData]
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800208 self.parser = X509Parser({
209 DataType.CRT: {
210 DataFormat.PEM: x509.load_pem_x509_certificate,
211 DataFormat.DER: x509.load_der_x509_certificate
212 },
213 DataType.CRL: {
214 DataFormat.PEM: x509.load_pem_x509_crl,
215 DataFormat.DER: x509.load_der_x509_crl
216 },
217 DataType.CSR: {
218 DataFormat.PEM: x509.load_pem_x509_csr,
219 DataFormat.DER: x509.load_der_x509_csr
220 },
221 })
222
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800223 def collect_default_files(self) -> typing.List[str]:
224 """Collect the default files for parsing."""
225 raise NotImplementedError
226
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800227 def parse_file(self, filename: str) -> typing.List[AuditData]:
228 """
229 Parse a list of AuditData from file.
230
231 :param filename: name of the file to parse.
232 :return list of AuditData parsed from the file.
233 """
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800234 raise NotImplementedError
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800235
236 def parse_bytes(self, data: bytes):
237 """Parse AuditData from bytes."""
238 for data_type in list(DataType):
239 try:
240 result = self.parser[data_type](data)
241 except ValueError as val_error:
242 result = None
Pengyu Lvfcda6d42023-04-21 11:04:07 +0800243 self.logger.warning(val_error)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800244 if result is not None:
Pengyu Lvcb8fc322023-04-11 15:05:29 +0800245 audit_data = AuditData(data_type, result)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800246 return audit_data
247 return None
248
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800249 def walk_all(self, file_list: typing.Optional[typing.List[str]] = None):
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800250 """
251 Iterate over all the files in the list and get audit data.
252 """
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800253 if file_list is None:
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800254 file_list = self.default_files
255 for filename in file_list:
256 data_list = self.parse_file(filename)
257 self.audit_data.extend(data_list)
258
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800259 @staticmethod
260 def find_test_dir():
261 """Get the relative path for the MbedTLS test directory."""
Pengyu Lv2d487212023-04-21 12:41:24 +0800262 return os.path.relpath(build_tree.guess_mbedtls_root() + '/tests')
263
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800264
265class TestDataAuditor(Auditor):
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800266 """Class for auditing files in `tests/data_files/`"""
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800267
268 def collect_default_files(self):
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800269 """Collect all files in `tests/data_files/`"""
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800270 test_dir = self.find_test_dir()
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800271 test_data_glob = os.path.join(test_dir, 'data_files/**')
272 data_files = [f for f in glob.glob(test_data_glob, recursive=True)
273 if os.path.isfile(f)]
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800274 return data_files
275
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800276 def parse_file(self, filename: str) -> typing.List[AuditData]:
277 """
278 Parse a list of AuditData from data file.
279
280 :param filename: name of the file to parse.
281 :return list of AuditData parsed from the file.
282 """
283 with open(filename, 'rb') as f:
284 data = f.read()
Pengyu Lve245c0c2023-04-28 10:46:18 +0800285
286 results = []
287 for idx, m in enumerate(re.finditer(X509Parser.PEM_REGEX, data, flags=re.S), 1):
288 result = self.parse_bytes(data[m.start():m.end()])
289 if result is not None:
Pengyu Lvfe13bd32023-04-28 10:58:38 +0800290 result.locations.append("{}#{}".format(filename, idx))
Pengyu Lve245c0c2023-04-28 10:46:18 +0800291 results.append(result)
292
293 return results
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800294
Pengyu Lv2d487212023-04-21 12:41:24 +0800295
Pengyu Lv28fe9572023-04-23 13:56:25 +0800296def parse_suite_data(data_f):
297 """
298 Parses .data file for test arguments that possiblly have a
299 valid X.509 data. If you need a more precise parser, please
300 use generate_test_code.parse_test_data instead.
301
302 :param data_f: file object of the data file.
303 :return: Generator that yields test function argument list.
304 """
305 for line in data_f:
306 line = line.strip()
307 # Skip comments
308 if line.startswith('#'):
309 continue
310
311 # Check parameters line
312 match = re.search(r'\A\w+(.*:)?\"', line)
313 if match:
314 # Read test vectors
315 parts = re.split(r'(?<!\\):', line)
316 parts = [x for x in parts if x]
317 args = parts[1:]
318 yield args
319
320
Pengyu Lv45e32032023-04-06 14:33:41 +0800321class SuiteDataAuditor(Auditor):
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800322 """Class for auditing files in `tests/suites/*.data`"""
Pengyu Lv45e32032023-04-06 14:33:41 +0800323
324 def collect_default_files(self):
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800325 """Collect all files in `tests/suites/*.data`"""
Pengyu Lv45e32032023-04-06 14:33:41 +0800326 test_dir = self.find_test_dir()
327 suites_data_folder = os.path.join(test_dir, 'suites')
Pengyu Lv45e32032023-04-06 14:33:41 +0800328 data_files = glob.glob(os.path.join(suites_data_folder, '*.data'))
329 return data_files
330
331 def parse_file(self, filename: str):
Pengyu Lv30f26832023-04-07 18:04:07 +0800332 """
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800333 Parse a list of AuditData from test suite data file.
Pengyu Lv30f26832023-04-07 18:04:07 +0800334
335 :param filename: name of the file to parse.
336 :return list of AuditData parsed from the file.
337 """
Pengyu Lv45e32032023-04-06 14:33:41 +0800338 audit_data_list = []
Pengyu Lv30f26832023-04-07 18:04:07 +0800339 data_f = FileWrapper(filename)
Pengyu Lv28fe9572023-04-23 13:56:25 +0800340 for test_args in parse_suite_data(data_f):
Pengyu Lv7725c1d2023-04-13 15:55:30 +0800341 for idx, test_arg in enumerate(test_args):
Pengyu Lv30f26832023-04-07 18:04:07 +0800342 match = re.match(r'"(?P<data>[0-9a-fA-F]+)"', test_arg)
343 if not match:
344 continue
345 if not X509Parser.check_hex_string(match.group('data')):
346 continue
347 audit_data = self.parse_bytes(bytes.fromhex(match.group('data')))
348 if audit_data is None:
349 continue
Pengyu Lvfe13bd32023-04-28 10:58:38 +0800350 audit_data.locations.append("{}:{}:#{}".format(filename,
351 data_f.line_no,
352 idx + 1))
Pengyu Lv30f26832023-04-07 18:04:07 +0800353 audit_data_list.append(audit_data)
354
Pengyu Lv45e32032023-04-06 14:33:41 +0800355 return audit_data_list
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800356
Pengyu Lv2d487212023-04-21 12:41:24 +0800357
Pengyu Lvfe13bd32023-04-28 10:58:38 +0800358def merge_auditdata(original: typing.List[AuditData]) \
359 -> typing.List[AuditData]:
360 """
361 Multiple AuditData might be extracted from different locations for
362 an identical X.509 object. Merge them into one entry in the list.
363 """
364 results = []
365 for x in original:
366 if x not in results:
367 results.append(x)
368 else:
369 idx = results.index(x)
370 results[idx].locations.extend(x.locations)
371 return results
372
373
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800374def list_all(audit_data: AuditData):
Pengyu Lvfe13bd32023-04-28 10:58:38 +0800375 print("{:20}\t{:20}\t{:3}\t{}".format(
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800376 audit_data.not_valid_before.isoformat(timespec='seconds'),
377 audit_data.not_valid_after.isoformat(timespec='seconds'),
378 audit_data.data_type.name,
Pengyu Lvfe13bd32023-04-28 10:58:38 +0800379 audit_data.locations[0]))
380 for loc in audit_data.locations[1:]:
381 print("{:20}\t{:20}\t{:3}\t{}".format('', '', '', loc))
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800382
Pengyu Lvfcda6d42023-04-21 11:04:07 +0800383
384def configure_logger(logger: logging.Logger) -> None:
385 """
386 Configure the logging.Logger instance so that:
387 - Format is set to "[%(levelname)s]: %(message)s".
388 - loglevel >= WARNING are printed to stderr.
389 - loglevel < WARNING are printed to stdout.
390 """
391 class MaxLevelFilter(logging.Filter):
392 # pylint: disable=too-few-public-methods
393 def __init__(self, max_level, name=''):
394 super().__init__(name)
395 self.max_level = max_level
396
397 def filter(self, record: logging.LogRecord) -> bool:
398 return record.levelno <= self.max_level
399
400 log_formatter = logging.Formatter("[%(levelname)s]: %(message)s")
401
402 # set loglevel >= WARNING to be printed to stderr
403 stderr_hdlr = logging.StreamHandler(sys.stderr)
404 stderr_hdlr.setLevel(logging.WARNING)
405 stderr_hdlr.setFormatter(log_formatter)
406
407 # set loglevel <= INFO to be printed to stdout
408 stdout_hdlr = logging.StreamHandler(sys.stdout)
409 stdout_hdlr.addFilter(MaxLevelFilter(logging.INFO))
410 stdout_hdlr.setFormatter(log_formatter)
411
412 logger.addHandler(stderr_hdlr)
413 logger.addHandler(stdout_hdlr)
414
415
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800416def main():
417 """
418 Perform argument parsing.
419 """
Pengyu Lv57240952023-04-13 14:42:37 +0800420 parser = argparse.ArgumentParser(description=__doc__)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800421
422 parser.add_argument('-a', '--all',
423 action='store_true',
Pengyu Lv57240952023-04-13 14:42:37 +0800424 help='list the information of all the files')
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800425 parser.add_argument('-v', '--verbose',
426 action='store_true', dest='verbose',
Pengyu Lvfcda6d42023-04-21 11:04:07 +0800427 help='show logs')
Pengyu Lv1d4cc912023-04-25 15:17:19 +0800428 parser.add_argument('--from', dest='start_date',
429 help=('Start of desired validity period (UTC, YYYY-MM-DD). '
Pengyu Lv57240952023-04-13 14:42:37 +0800430 'Default: today'),
Pengyu Lvebf011f2023-04-11 13:39:31 +0800431 metavar='DATE')
Pengyu Lv1d4cc912023-04-25 15:17:19 +0800432 parser.add_argument('--to', dest='end_date',
433 help=('End of desired validity period (UTC, YYYY-MM-DD). '
434 'Default: --from'),
Pengyu Lvebf011f2023-04-11 13:39:31 +0800435 metavar='DATE')
Pengyu Lva228cbc2023-04-21 11:59:25 +0800436 parser.add_argument('--data-files', action='append', nargs='*',
437 help='data files to audit',
438 metavar='FILE')
439 parser.add_argument('--suite-data-files', action='append', nargs='*',
440 help='suite data files to audit',
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800441 metavar='FILE')
442
443 args = parser.parse_args()
444
445 # start main routine
Pengyu Lvfcda6d42023-04-21 11:04:07 +0800446 # setup logger
447 logger = logging.getLogger()
448 configure_logger(logger)
449 logger.setLevel(logging.DEBUG if args.verbose else logging.ERROR)
450
451 td_auditor = TestDataAuditor(logger)
452 sd_auditor = SuiteDataAuditor(logger)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800453
Pengyu Lva228cbc2023-04-21 11:59:25 +0800454 data_files = []
455 suite_data_files = []
456 if args.data_files is None and args.suite_data_files is None:
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800457 data_files = td_auditor.default_files
Pengyu Lv45e32032023-04-06 14:33:41 +0800458 suite_data_files = sd_auditor.default_files
Pengyu Lva228cbc2023-04-21 11:59:25 +0800459 else:
460 if args.data_files is not None:
461 data_files = [x for l in args.data_files for x in l]
462 if args.suite_data_files is not None:
463 suite_data_files = [x for l in args.suite_data_files for x in l]
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800464
Pengyu Lva228cbc2023-04-21 11:59:25 +0800465 # validity period start date
Pengyu Lv1d4cc912023-04-25 15:17:19 +0800466 if args.start_date:
467 start_date = datetime.datetime.fromisoformat(args.start_date)
Pengyu Lvebf011f2023-04-11 13:39:31 +0800468 else:
Pengyu Lv1d4cc912023-04-25 15:17:19 +0800469 start_date = datetime.datetime.today()
Pengyu Lva228cbc2023-04-21 11:59:25 +0800470 # validity period end date
Pengyu Lv1d4cc912023-04-25 15:17:19 +0800471 if args.end_date:
472 end_date = datetime.datetime.fromisoformat(args.end_date)
Pengyu Lvebf011f2023-04-11 13:39:31 +0800473 else:
Pengyu Lv1d4cc912023-04-25 15:17:19 +0800474 end_date = start_date
Pengyu Lvebf011f2023-04-11 13:39:31 +0800475
Pengyu Lva228cbc2023-04-21 11:59:25 +0800476 # go through all the files
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800477 td_auditor.walk_all(data_files)
Pengyu Lv45e32032023-04-06 14:33:41 +0800478 sd_auditor.walk_all(suite_data_files)
Pengyu Lvebf011f2023-04-11 13:39:31 +0800479 audit_results = td_auditor.audit_data + sd_auditor.audit_data
480
Pengyu Lvfe13bd32023-04-28 10:58:38 +0800481 audit_results = merge_auditdata(audit_results)
482
483 logger.info("Total: {} objects found!".format(len(audit_results)))
484
Pengyu Lv57240952023-04-13 14:42:37 +0800485 # we filter out the files whose validity duration covers the provided
Pengyu Lvebf011f2023-04-11 13:39:31 +0800486 # duration.
Pengyu Lv1d4cc912023-04-25 15:17:19 +0800487 filter_func = lambda d: (start_date < d.not_valid_before) or \
488 (d.not_valid_after < end_date)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800489
Pengyu Lv0b4832b2023-04-28 11:14:28 +0800490 sortby_end = lambda d: d.not_valid_after
491
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800492 if args.all:
Pengyu Lvebf011f2023-04-11 13:39:31 +0800493 filter_func = None
494
Pengyu Lva228cbc2023-04-21 11:59:25 +0800495 # filter and output the results
Pengyu Lv0b4832b2023-04-28 11:14:28 +0800496 for d in sorted(filter(filter_func, audit_results), key=sortby_end):
Pengyu Lvebf011f2023-04-11 13:39:31 +0800497 list_all(d)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800498
Pengyu Lvfcda6d42023-04-21 11:04:07 +0800499 logger.debug("Done!")
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800500
Pengyu Lv13815982023-04-25 14:55:38 +0800501check_cryptography_version()
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800502if __name__ == "__main__":
503 main()