blob: 1ccfc2188f525c0c074e532b7266fd17a99135c8 [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__)
48 if match is None or int(match[0]) < 35:
49 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 Lvf8e5e052023-04-18 15:43:25 +080068 self.location = ""
Pengyu Lvcb8fc322023-04-11 15:05:29 +080069 self.fill_validity_duration(x509_obj)
Pengyu Lv7f6933a2023-04-04 16:05:54 +080070
71 def fill_validity_duration(self, x509_obj):
Pengyu Lvf8e5e052023-04-18 15:43:25 +080072 """Read validity period from an X.509 object."""
Pengyu Lv7f6933a2023-04-04 16:05:54 +080073 # Certificate expires after "not_valid_after"
74 # Certificate is invalid before "not_valid_before"
75 if self.data_type == DataType.CRT:
76 self.not_valid_after = x509_obj.not_valid_after
77 self.not_valid_before = x509_obj.not_valid_before
78 # CertificateRevocationList expires after "next_update"
79 # CertificateRevocationList is invalid before "last_update"
80 elif self.data_type == DataType.CRL:
81 self.not_valid_after = x509_obj.next_update
82 self.not_valid_before = x509_obj.last_update
83 # CertificateSigningRequest is always valid.
84 elif self.data_type == DataType.CSR:
85 self.not_valid_after = datetime.datetime.max
86 self.not_valid_before = datetime.datetime.min
87 else:
88 raise ValueError("Unsupported file_type: {}".format(self.data_type))
89
Pengyu Lv2d487212023-04-21 12:41:24 +080090
Pengyu Lvf8e5e052023-04-18 15:43:25 +080091class X509Parser:
Pengyu Lv7f6933a2023-04-04 16:05:54 +080092 """A parser class to parse crt/crl/csr file or data in PEM/DER format."""
93 PEM_REGEX = br'-{5}BEGIN (?P<type>.*?)-{5}\n(?P<data>.*?)-{5}END (?P=type)-{5}\n'
94 PEM_TAG_REGEX = br'-{5}BEGIN (?P<type>.*?)-{5}\n'
95 PEM_TAGS = {
96 DataType.CRT: 'CERTIFICATE',
97 DataType.CRL: 'X509 CRL',
98 DataType.CSR: 'CERTIFICATE REQUEST'
99 }
100
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800101 def __init__(self,
102 backends:
103 typing.Dict[DataType,
104 typing.Dict[DataFormat,
105 typing.Callable[[bytes], object]]]) \
106 -> None:
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800107 self.backends = backends
108 self.__generate_parsers()
109
110 def __generate_parser(self, data_type: DataType):
111 """Parser generator for a specific DataType"""
112 tag = self.PEM_TAGS[data_type]
113 pem_loader = self.backends[data_type][DataFormat.PEM]
114 der_loader = self.backends[data_type][DataFormat.DER]
115 def wrapper(data: bytes):
116 pem_type = X509Parser.pem_data_type(data)
117 # It is in PEM format with target tag
118 if pem_type == tag:
119 return pem_loader(data)
120 # It is in PEM format without target tag
121 if pem_type:
122 return None
123 # It might be in DER format
124 try:
125 result = der_loader(data)
126 except ValueError:
127 result = None
128 return result
129 wrapper.__name__ = "{}.parser[{}]".format(type(self).__name__, tag)
130 return wrapper
131
132 def __generate_parsers(self):
133 """Generate parsers for all support DataType"""
134 self.parsers = {}
135 for data_type, _ in self.PEM_TAGS.items():
136 self.parsers[data_type] = self.__generate_parser(data_type)
137
138 def __getitem__(self, item):
139 return self.parsers[item]
140
141 @staticmethod
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800142 def pem_data_type(data: bytes) -> typing.Optional[str]:
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800143 """Get the tag from the data in PEM format
144
145 :param data: data to be checked in binary mode.
146 :return: PEM tag or "" when no tag detected.
147 """
148 m = re.search(X509Parser.PEM_TAG_REGEX, data)
149 if m is not None:
150 return m.group('type').decode('UTF-8')
151 else:
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800152 return None
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800153
Pengyu Lv30f26832023-04-07 18:04:07 +0800154 @staticmethod
155 def check_hex_string(hex_str: str) -> bool:
156 """Check if the hex string is possibly DER data."""
157 hex_len = len(hex_str)
158 # At least 6 hex char for 3 bytes: Type + Length + Content
159 if hex_len < 6:
160 return False
161 # Check if Type (1 byte) is SEQUENCE.
162 if hex_str[0:2] != '30':
163 return False
164 # Check LENGTH (1 byte) value
165 content_len = int(hex_str[2:4], base=16)
166 consumed = 4
167 if content_len in (128, 255):
168 # Indefinite or Reserved
169 return False
170 elif content_len > 127:
171 # Definite, Long
172 length_len = (content_len - 128) * 2
173 content_len = int(hex_str[consumed:consumed+length_len], base=16)
174 consumed += length_len
175 # Check LENGTH
176 if hex_len != content_len * 2 + consumed:
177 return False
178 return True
179
Pengyu Lv2d487212023-04-21 12:41:24 +0800180
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800181class Auditor:
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800182 """
183 A base class that uses X509Parser to parse files to a list of AuditData.
184
185 A subclass must implement the following methods:
186 - collect_default_files: Return a list of file names that are defaultly
187 used for parsing (auditing). The list will be stored in
188 Auditor.default_files.
189 - parse_file: Method that parses a single file to a list of AuditData.
190
191 A subclass may override the following methods:
192 - parse_bytes: Defaultly, it parses `bytes` that contains only one valid
193 X.509 data(DER/PEM format) to an X.509 object.
194 - walk_all: Defaultly, it iterates over all the files in the provided
195 file name list, calls `parse_file` for each file and stores the results
196 by extending Auditor.audit_data.
197 """
Pengyu Lvfcda6d42023-04-21 11:04:07 +0800198 def __init__(self, logger):
199 self.logger = logger
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800200 self.default_files = self.collect_default_files()
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800201 # A list to store the parsed audit_data.
Pengyu Lva228cbc2023-04-21 11:59:25 +0800202 self.audit_data = [] # type: typing.List[AuditData]
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800203 self.parser = X509Parser({
204 DataType.CRT: {
205 DataFormat.PEM: x509.load_pem_x509_certificate,
206 DataFormat.DER: x509.load_der_x509_certificate
207 },
208 DataType.CRL: {
209 DataFormat.PEM: x509.load_pem_x509_crl,
210 DataFormat.DER: x509.load_der_x509_crl
211 },
212 DataType.CSR: {
213 DataFormat.PEM: x509.load_pem_x509_csr,
214 DataFormat.DER: x509.load_der_x509_csr
215 },
216 })
217
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800218 def collect_default_files(self) -> typing.List[str]:
219 """Collect the default files for parsing."""
220 raise NotImplementedError
221
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800222 def parse_file(self, filename: str) -> typing.List[AuditData]:
223 """
224 Parse a list of AuditData from file.
225
226 :param filename: name of the file to parse.
227 :return list of AuditData parsed from the file.
228 """
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800229 raise NotImplementedError
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800230
231 def parse_bytes(self, data: bytes):
232 """Parse AuditData from bytes."""
233 for data_type in list(DataType):
234 try:
235 result = self.parser[data_type](data)
236 except ValueError as val_error:
237 result = None
Pengyu Lvfcda6d42023-04-21 11:04:07 +0800238 self.logger.warning(val_error)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800239 if result is not None:
Pengyu Lvcb8fc322023-04-11 15:05:29 +0800240 audit_data = AuditData(data_type, result)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800241 return audit_data
242 return None
243
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800244 def walk_all(self, file_list: typing.Optional[typing.List[str]] = None):
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800245 """
246 Iterate over all the files in the list and get audit data.
247 """
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800248 if file_list is None:
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800249 file_list = self.default_files
250 for filename in file_list:
251 data_list = self.parse_file(filename)
252 self.audit_data.extend(data_list)
253
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800254 @staticmethod
255 def find_test_dir():
256 """Get the relative path for the MbedTLS test directory."""
Pengyu Lv2d487212023-04-21 12:41:24 +0800257 return os.path.relpath(build_tree.guess_mbedtls_root() + '/tests')
258
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800259
260class TestDataAuditor(Auditor):
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800261 """Class for auditing files in `tests/data_files/`"""
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800262
263 def collect_default_files(self):
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800264 """Collect all files in `tests/data_files/`"""
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800265 test_dir = self.find_test_dir()
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800266 test_data_glob = os.path.join(test_dir, 'data_files/**')
267 data_files = [f for f in glob.glob(test_data_glob, recursive=True)
268 if os.path.isfile(f)]
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800269 return data_files
270
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800271 def parse_file(self, filename: str) -> typing.List[AuditData]:
272 """
273 Parse a list of AuditData from data file.
274
275 :param filename: name of the file to parse.
276 :return list of AuditData parsed from the file.
277 """
278 with open(filename, 'rb') as f:
279 data = f.read()
280 result = self.parse_bytes(data)
281 if result is not None:
282 result.location = filename
283 return [result]
284 else:
285 return []
286
Pengyu Lv2d487212023-04-21 12:41:24 +0800287
Pengyu Lv28fe9572023-04-23 13:56:25 +0800288def parse_suite_data(data_f):
289 """
290 Parses .data file for test arguments that possiblly have a
291 valid X.509 data. If you need a more precise parser, please
292 use generate_test_code.parse_test_data instead.
293
294 :param data_f: file object of the data file.
295 :return: Generator that yields test function argument list.
296 """
297 for line in data_f:
298 line = line.strip()
299 # Skip comments
300 if line.startswith('#'):
301 continue
302
303 # Check parameters line
304 match = re.search(r'\A\w+(.*:)?\"', line)
305 if match:
306 # Read test vectors
307 parts = re.split(r'(?<!\\):', line)
308 parts = [x for x in parts if x]
309 args = parts[1:]
310 yield args
311
312
Pengyu Lv45e32032023-04-06 14:33:41 +0800313class SuiteDataAuditor(Auditor):
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800314 """Class for auditing files in `tests/suites/*.data`"""
Pengyu Lv45e32032023-04-06 14:33:41 +0800315
316 def collect_default_files(self):
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800317 """Collect all files in `tests/suites/*.data`"""
Pengyu Lv45e32032023-04-06 14:33:41 +0800318 test_dir = self.find_test_dir()
319 suites_data_folder = os.path.join(test_dir, 'suites')
Pengyu Lv45e32032023-04-06 14:33:41 +0800320 data_files = glob.glob(os.path.join(suites_data_folder, '*.data'))
321 return data_files
322
323 def parse_file(self, filename: str):
Pengyu Lv30f26832023-04-07 18:04:07 +0800324 """
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800325 Parse a list of AuditData from test suite data file.
Pengyu Lv30f26832023-04-07 18:04:07 +0800326
327 :param filename: name of the file to parse.
328 :return list of AuditData parsed from the file.
329 """
Pengyu Lv45e32032023-04-06 14:33:41 +0800330 audit_data_list = []
Pengyu Lv30f26832023-04-07 18:04:07 +0800331 data_f = FileWrapper(filename)
Pengyu Lv28fe9572023-04-23 13:56:25 +0800332 for test_args in parse_suite_data(data_f):
Pengyu Lv7725c1d2023-04-13 15:55:30 +0800333 for idx, test_arg in enumerate(test_args):
Pengyu Lv30f26832023-04-07 18:04:07 +0800334 match = re.match(r'"(?P<data>[0-9a-fA-F]+)"', test_arg)
335 if not match:
336 continue
337 if not X509Parser.check_hex_string(match.group('data')):
338 continue
339 audit_data = self.parse_bytes(bytes.fromhex(match.group('data')))
340 if audit_data is None:
341 continue
Pengyu Lvf8e5e052023-04-18 15:43:25 +0800342 audit_data.location = "{}:{}:#{}".format(filename,
343 data_f.line_no,
344 idx + 1)
Pengyu Lv30f26832023-04-07 18:04:07 +0800345 audit_data_list.append(audit_data)
346
Pengyu Lv45e32032023-04-06 14:33:41 +0800347 return audit_data_list
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800348
Pengyu Lv2d487212023-04-21 12:41:24 +0800349
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800350def list_all(audit_data: AuditData):
351 print("{}\t{}\t{}\t{}".format(
352 audit_data.not_valid_before.isoformat(timespec='seconds'),
353 audit_data.not_valid_after.isoformat(timespec='seconds'),
354 audit_data.data_type.name,
Pengyu Lvf8e5e052023-04-18 15:43:25 +0800355 audit_data.location))
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800356
Pengyu Lvfcda6d42023-04-21 11:04:07 +0800357
358def configure_logger(logger: logging.Logger) -> None:
359 """
360 Configure the logging.Logger instance so that:
361 - Format is set to "[%(levelname)s]: %(message)s".
362 - loglevel >= WARNING are printed to stderr.
363 - loglevel < WARNING are printed to stdout.
364 """
365 class MaxLevelFilter(logging.Filter):
366 # pylint: disable=too-few-public-methods
367 def __init__(self, max_level, name=''):
368 super().__init__(name)
369 self.max_level = max_level
370
371 def filter(self, record: logging.LogRecord) -> bool:
372 return record.levelno <= self.max_level
373
374 log_formatter = logging.Formatter("[%(levelname)s]: %(message)s")
375
376 # set loglevel >= WARNING to be printed to stderr
377 stderr_hdlr = logging.StreamHandler(sys.stderr)
378 stderr_hdlr.setLevel(logging.WARNING)
379 stderr_hdlr.setFormatter(log_formatter)
380
381 # set loglevel <= INFO to be printed to stdout
382 stdout_hdlr = logging.StreamHandler(sys.stdout)
383 stdout_hdlr.addFilter(MaxLevelFilter(logging.INFO))
384 stdout_hdlr.setFormatter(log_formatter)
385
386 logger.addHandler(stderr_hdlr)
387 logger.addHandler(stdout_hdlr)
388
389
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800390def main():
391 """
392 Perform argument parsing.
393 """
Pengyu Lv57240952023-04-13 14:42:37 +0800394 parser = argparse.ArgumentParser(description=__doc__)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800395
396 parser.add_argument('-a', '--all',
397 action='store_true',
Pengyu Lv57240952023-04-13 14:42:37 +0800398 help='list the information of all the files')
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800399 parser.add_argument('-v', '--verbose',
400 action='store_true', dest='verbose',
Pengyu Lvfcda6d42023-04-21 11:04:07 +0800401 help='show logs')
Pengyu Lv1d4cc912023-04-25 15:17:19 +0800402 parser.add_argument('--from', dest='start_date',
403 help=('Start of desired validity period (UTC, YYYY-MM-DD). '
Pengyu Lv57240952023-04-13 14:42:37 +0800404 'Default: today'),
Pengyu Lvebf011f2023-04-11 13:39:31 +0800405 metavar='DATE')
Pengyu Lv1d4cc912023-04-25 15:17:19 +0800406 parser.add_argument('--to', dest='end_date',
407 help=('End of desired validity period (UTC, YYYY-MM-DD). '
408 'Default: --from'),
Pengyu Lvebf011f2023-04-11 13:39:31 +0800409 metavar='DATE')
Pengyu Lva228cbc2023-04-21 11:59:25 +0800410 parser.add_argument('--data-files', action='append', nargs='*',
411 help='data files to audit',
412 metavar='FILE')
413 parser.add_argument('--suite-data-files', action='append', nargs='*',
414 help='suite data files to audit',
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800415 metavar='FILE')
416
417 args = parser.parse_args()
418
419 # start main routine
Pengyu Lvfcda6d42023-04-21 11:04:07 +0800420 # setup logger
421 logger = logging.getLogger()
422 configure_logger(logger)
423 logger.setLevel(logging.DEBUG if args.verbose else logging.ERROR)
424
425 td_auditor = TestDataAuditor(logger)
426 sd_auditor = SuiteDataAuditor(logger)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800427
Pengyu Lva228cbc2023-04-21 11:59:25 +0800428 data_files = []
429 suite_data_files = []
430 if args.data_files is None and args.suite_data_files is None:
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800431 data_files = td_auditor.default_files
Pengyu Lv45e32032023-04-06 14:33:41 +0800432 suite_data_files = sd_auditor.default_files
Pengyu Lva228cbc2023-04-21 11:59:25 +0800433 else:
434 if args.data_files is not None:
435 data_files = [x for l in args.data_files for x in l]
436 if args.suite_data_files is not None:
437 suite_data_files = [x for l in args.suite_data_files for x in l]
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800438
Pengyu Lva228cbc2023-04-21 11:59:25 +0800439 # validity period start date
Pengyu Lv1d4cc912023-04-25 15:17:19 +0800440 if args.start_date:
441 start_date = datetime.datetime.fromisoformat(args.start_date)
Pengyu Lvebf011f2023-04-11 13:39:31 +0800442 else:
Pengyu Lv1d4cc912023-04-25 15:17:19 +0800443 start_date = datetime.datetime.today()
Pengyu Lva228cbc2023-04-21 11:59:25 +0800444 # validity period end date
Pengyu Lv1d4cc912023-04-25 15:17:19 +0800445 if args.end_date:
446 end_date = datetime.datetime.fromisoformat(args.end_date)
Pengyu Lvebf011f2023-04-11 13:39:31 +0800447 else:
Pengyu Lv1d4cc912023-04-25 15:17:19 +0800448 end_date = start_date
Pengyu Lvebf011f2023-04-11 13:39:31 +0800449
Pengyu Lva228cbc2023-04-21 11:59:25 +0800450 # go through all the files
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800451 td_auditor.walk_all(data_files)
Pengyu Lv45e32032023-04-06 14:33:41 +0800452 sd_auditor.walk_all(suite_data_files)
Pengyu Lvebf011f2023-04-11 13:39:31 +0800453 audit_results = td_auditor.audit_data + sd_auditor.audit_data
454
Pengyu Lv57240952023-04-13 14:42:37 +0800455 # we filter out the files whose validity duration covers the provided
Pengyu Lvebf011f2023-04-11 13:39:31 +0800456 # duration.
Pengyu Lv1d4cc912023-04-25 15:17:19 +0800457 filter_func = lambda d: (start_date < d.not_valid_before) or \
458 (d.not_valid_after < end_date)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800459
460 if args.all:
Pengyu Lvebf011f2023-04-11 13:39:31 +0800461 filter_func = None
462
Pengyu Lva228cbc2023-04-21 11:59:25 +0800463 # filter and output the results
Pengyu Lvebf011f2023-04-11 13:39:31 +0800464 for d in filter(filter_func, audit_results):
465 list_all(d)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800466
Pengyu Lvfcda6d42023-04-21 11:04:07 +0800467 logger.debug("Done!")
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800468
Pengyu Lv13815982023-04-25 14:55:38 +0800469check_cryptography_version()
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800470if __name__ == "__main__":
471 main()