blob: 127c0a0fe032996c7b4d6f65331c8745d56dec96 [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 Lv13f2ef42023-05-05 16:53:37 +080034import hashlib
Pengyu Lv7f6933a2023-04-04 16:05:54 +080035from enum import Enum
36
Pengyu Lv31792322023-04-11 16:30:54 +080037# The script requires cryptography >= 35.0.0 which is only available
Pengyu Lv13815982023-04-25 14:55:38 +080038# for Python >= 3.6.
39import cryptography
40from cryptography import x509
Pengyu Lv7f6933a2023-04-04 16:05:54 +080041
Pengyu Lvad306792023-04-19 15:07:03 +080042from generate_test_code import FileWrapper
Pengyu Lv30f26832023-04-07 18:04:07 +080043
Pengyu Lv2d487212023-04-21 12:41:24 +080044import scripts_path # pylint: disable=unused-import
45from mbedtls_dev import build_tree
46
Pengyu Lv13815982023-04-25 14:55:38 +080047def check_cryptography_version():
48 match = re.match(r'^[0-9]+', cryptography.__version__)
Pengyu Lvfd72d9f2023-04-28 11:17:24 +080049 if match is None or int(match.group(0)) < 35:
Pengyu Lv13815982023-04-25 14:55:38 +080050 raise Exception("audit-validity-dates requires cryptography >= 35.0.0"
51 + "({} is too old)".format(cryptography.__version__))
52
Pengyu Lv7f6933a2023-04-04 16:05:54 +080053class DataType(Enum):
54 CRT = 1 # Certificate
55 CRL = 2 # Certificate Revocation List
56 CSR = 3 # Certificate Signing Request
57
Pengyu Lv2d487212023-04-21 12:41:24 +080058
Pengyu Lv7f6933a2023-04-04 16:05:54 +080059class DataFormat(Enum):
60 PEM = 1 # Privacy-Enhanced Mail
61 DER = 2 # Distinguished Encoding Rules
62
Pengyu Lv2d487212023-04-21 12:41:24 +080063
Pengyu Lv7f6933a2023-04-04 16:05:54 +080064class AuditData:
Pengyu Lvf8e5e052023-04-18 15:43:25 +080065 """Store data location, type and validity period of X.509 objects."""
Pengyu Lv7f6933a2023-04-04 16:05:54 +080066 #pylint: disable=too-few-public-methods
Pengyu Lvcb8fc322023-04-11 15:05:29 +080067 def __init__(self, data_type: DataType, x509_obj):
Pengyu Lv7f6933a2023-04-04 16:05:54 +080068 self.data_type = data_type
Pengyu Lvfe13bd32023-04-28 10:58:38 +080069 # the locations that the x509 object could be found
70 self.locations = [] # type: typing.List[str]
Pengyu Lvcb8fc322023-04-11 15:05:29 +080071 self.fill_validity_duration(x509_obj)
Pengyu Lvfe13bd32023-04-28 10:58:38 +080072 self._obj = x509_obj
Pengyu Lv13f2ef42023-05-05 16:53:37 +080073 encoding = cryptography.hazmat.primitives.serialization.Encoding.DER
74 self._identifier = hashlib.sha1(self._obj.public_bytes(encoding)).hexdigest()
Pengyu Lvfe13bd32023-04-28 10:58:38 +080075
76 def __eq__(self, __value) -> bool:
77 return self._obj == __value._obj
Pengyu Lv7f6933a2023-04-04 16:05:54 +080078
Pengyu Lv13f2ef42023-05-05 16:53:37 +080079 @property
80 def identifier(self):
81 """
82 Identifier of the underlying X.509 object, which is consistent across
83 different runs.
84 """
85 return self._identifier
86
Pengyu Lv7f6933a2023-04-04 16:05:54 +080087 def fill_validity_duration(self, x509_obj):
Pengyu Lvf8e5e052023-04-18 15:43:25 +080088 """Read validity period from an X.509 object."""
Pengyu Lv7f6933a2023-04-04 16:05:54 +080089 # Certificate expires after "not_valid_after"
90 # Certificate is invalid before "not_valid_before"
91 if self.data_type == DataType.CRT:
92 self.not_valid_after = x509_obj.not_valid_after
93 self.not_valid_before = x509_obj.not_valid_before
94 # CertificateRevocationList expires after "next_update"
95 # CertificateRevocationList is invalid before "last_update"
96 elif self.data_type == DataType.CRL:
97 self.not_valid_after = x509_obj.next_update
98 self.not_valid_before = x509_obj.last_update
99 # CertificateSigningRequest is always valid.
100 elif self.data_type == DataType.CSR:
101 self.not_valid_after = datetime.datetime.max
102 self.not_valid_before = datetime.datetime.min
103 else:
104 raise ValueError("Unsupported file_type: {}".format(self.data_type))
105
Pengyu Lv2d487212023-04-21 12:41:24 +0800106
Pengyu Lvf8e5e052023-04-18 15:43:25 +0800107class X509Parser:
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800108 """A parser class to parse crt/crl/csr file or data in PEM/DER format."""
Pengyu Lve245c0c2023-04-28 10:46:18 +0800109 PEM_REGEX = br'-{5}BEGIN (?P<type>.*?)-{5}(?P<data>.*?)-{5}END (?P=type)-{5}'
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800110 PEM_TAG_REGEX = br'-{5}BEGIN (?P<type>.*?)-{5}\n'
111 PEM_TAGS = {
112 DataType.CRT: 'CERTIFICATE',
113 DataType.CRL: 'X509 CRL',
114 DataType.CSR: 'CERTIFICATE REQUEST'
115 }
116
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800117 def __init__(self,
118 backends:
119 typing.Dict[DataType,
120 typing.Dict[DataFormat,
121 typing.Callable[[bytes], object]]]) \
122 -> None:
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800123 self.backends = backends
124 self.__generate_parsers()
125
126 def __generate_parser(self, data_type: DataType):
127 """Parser generator for a specific DataType"""
128 tag = self.PEM_TAGS[data_type]
129 pem_loader = self.backends[data_type][DataFormat.PEM]
130 der_loader = self.backends[data_type][DataFormat.DER]
131 def wrapper(data: bytes):
132 pem_type = X509Parser.pem_data_type(data)
133 # It is in PEM format with target tag
134 if pem_type == tag:
135 return pem_loader(data)
136 # It is in PEM format without target tag
137 if pem_type:
138 return None
139 # It might be in DER format
140 try:
141 result = der_loader(data)
142 except ValueError:
143 result = None
144 return result
145 wrapper.__name__ = "{}.parser[{}]".format(type(self).__name__, tag)
146 return wrapper
147
148 def __generate_parsers(self):
149 """Generate parsers for all support DataType"""
150 self.parsers = {}
151 for data_type, _ in self.PEM_TAGS.items():
152 self.parsers[data_type] = self.__generate_parser(data_type)
153
154 def __getitem__(self, item):
155 return self.parsers[item]
156
157 @staticmethod
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800158 def pem_data_type(data: bytes) -> typing.Optional[str]:
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800159 """Get the tag from the data in PEM format
160
161 :param data: data to be checked in binary mode.
162 :return: PEM tag or "" when no tag detected.
163 """
164 m = re.search(X509Parser.PEM_TAG_REGEX, data)
165 if m is not None:
166 return m.group('type').decode('UTF-8')
167 else:
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800168 return None
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800169
Pengyu Lv30f26832023-04-07 18:04:07 +0800170 @staticmethod
171 def check_hex_string(hex_str: str) -> bool:
172 """Check if the hex string is possibly DER data."""
173 hex_len = len(hex_str)
174 # At least 6 hex char for 3 bytes: Type + Length + Content
175 if hex_len < 6:
176 return False
177 # Check if Type (1 byte) is SEQUENCE.
178 if hex_str[0:2] != '30':
179 return False
180 # Check LENGTH (1 byte) value
181 content_len = int(hex_str[2:4], base=16)
182 consumed = 4
183 if content_len in (128, 255):
184 # Indefinite or Reserved
185 return False
186 elif content_len > 127:
187 # Definite, Long
188 length_len = (content_len - 128) * 2
189 content_len = int(hex_str[consumed:consumed+length_len], base=16)
190 consumed += length_len
191 # Check LENGTH
192 if hex_len != content_len * 2 + consumed:
193 return False
194 return True
195
Pengyu Lv2d487212023-04-21 12:41:24 +0800196
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800197class Auditor:
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800198 """
199 A base class that uses X509Parser to parse files to a list of AuditData.
200
201 A subclass must implement the following methods:
202 - collect_default_files: Return a list of file names that are defaultly
203 used for parsing (auditing). The list will be stored in
204 Auditor.default_files.
205 - parse_file: Method that parses a single file to a list of AuditData.
206
207 A subclass may override the following methods:
208 - parse_bytes: Defaultly, it parses `bytes` that contains only one valid
209 X.509 data(DER/PEM format) to an X.509 object.
210 - walk_all: Defaultly, it iterates over all the files in the provided
211 file name list, calls `parse_file` for each file and stores the results
Pengyu Lve09d27e2023-05-05 17:29:12 +0800212 by extending the `results` passed to the function.
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800213 """
Pengyu Lvfcda6d42023-04-21 11:04:07 +0800214 def __init__(self, logger):
215 self.logger = logger
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800216 self.default_files = self.collect_default_files()
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800217 self.parser = X509Parser({
218 DataType.CRT: {
219 DataFormat.PEM: x509.load_pem_x509_certificate,
220 DataFormat.DER: x509.load_der_x509_certificate
221 },
222 DataType.CRL: {
223 DataFormat.PEM: x509.load_pem_x509_crl,
224 DataFormat.DER: x509.load_der_x509_crl
225 },
226 DataType.CSR: {
227 DataFormat.PEM: x509.load_pem_x509_csr,
228 DataFormat.DER: x509.load_der_x509_csr
229 },
230 })
231
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800232 def collect_default_files(self) -> typing.List[str]:
233 """Collect the default files for parsing."""
234 raise NotImplementedError
235
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800236 def parse_file(self, filename: str) -> typing.List[AuditData]:
237 """
238 Parse a list of AuditData from file.
239
240 :param filename: name of the file to parse.
241 :return list of AuditData parsed from the file.
242 """
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800243 raise NotImplementedError
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800244
245 def parse_bytes(self, data: bytes):
246 """Parse AuditData from bytes."""
247 for data_type in list(DataType):
248 try:
249 result = self.parser[data_type](data)
250 except ValueError as val_error:
251 result = None
Pengyu Lvfcda6d42023-04-21 11:04:07 +0800252 self.logger.warning(val_error)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800253 if result is not None:
Pengyu Lvcb8fc322023-04-11 15:05:29 +0800254 audit_data = AuditData(data_type, result)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800255 return audit_data
256 return None
257
Pengyu Lve09d27e2023-05-05 17:29:12 +0800258 def walk_all(self,
259 results: typing.Dict[str, AuditData],
260 file_list: typing.Optional[typing.List[str]] = None) \
261 -> None:
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800262 """
Pengyu Lve09d27e2023-05-05 17:29:12 +0800263 Iterate over all the files in the list and get audit data. The
264 results will be written to `results` passed to this function.
265
266 :param results: The dictionary used to store the parsed
267 AuditData. The keys of this dictionary should
268 be the identifier of the AuditData.
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800269 """
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800270 if file_list is None:
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800271 file_list = self.default_files
272 for filename in file_list:
273 data_list = self.parse_file(filename)
Pengyu Lve09d27e2023-05-05 17:29:12 +0800274 for d in data_list:
275 if d.identifier in results:
276 results[d.identifier].locations.extend(d.locations)
277 else:
278 results[d.identifier] = d
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800279
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800280 @staticmethod
281 def find_test_dir():
282 """Get the relative path for the MbedTLS test directory."""
Pengyu Lv2d487212023-04-21 12:41:24 +0800283 return os.path.relpath(build_tree.guess_mbedtls_root() + '/tests')
284
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800285
286class TestDataAuditor(Auditor):
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800287 """Class for auditing files in `tests/data_files/`"""
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800288
289 def collect_default_files(self):
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800290 """Collect all files in `tests/data_files/`"""
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800291 test_dir = self.find_test_dir()
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800292 test_data_glob = os.path.join(test_dir, 'data_files/**')
293 data_files = [f for f in glob.glob(test_data_glob, recursive=True)
294 if os.path.isfile(f)]
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800295 return data_files
296
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800297 def parse_file(self, filename: str) -> typing.List[AuditData]:
298 """
299 Parse a list of AuditData from data file.
300
301 :param filename: name of the file to parse.
302 :return list of AuditData parsed from the file.
303 """
304 with open(filename, 'rb') as f:
305 data = f.read()
Pengyu Lve245c0c2023-04-28 10:46:18 +0800306
307 results = []
308 for idx, m in enumerate(re.finditer(X509Parser.PEM_REGEX, data, flags=re.S), 1):
309 result = self.parse_bytes(data[m.start():m.end()])
310 if result is not None:
Pengyu Lvfe13bd32023-04-28 10:58:38 +0800311 result.locations.append("{}#{}".format(filename, idx))
Pengyu Lve245c0c2023-04-28 10:46:18 +0800312 results.append(result)
313
314 return results
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800315
Pengyu Lv2d487212023-04-21 12:41:24 +0800316
Pengyu Lv28fe9572023-04-23 13:56:25 +0800317def parse_suite_data(data_f):
318 """
319 Parses .data file for test arguments that possiblly have a
320 valid X.509 data. If you need a more precise parser, please
321 use generate_test_code.parse_test_data instead.
322
323 :param data_f: file object of the data file.
324 :return: Generator that yields test function argument list.
325 """
326 for line in data_f:
327 line = line.strip()
328 # Skip comments
329 if line.startswith('#'):
330 continue
331
332 # Check parameters line
333 match = re.search(r'\A\w+(.*:)?\"', line)
334 if match:
335 # Read test vectors
336 parts = re.split(r'(?<!\\):', line)
337 parts = [x for x in parts if x]
338 args = parts[1:]
339 yield args
340
341
Pengyu Lv45e32032023-04-06 14:33:41 +0800342class SuiteDataAuditor(Auditor):
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800343 """Class for auditing files in `tests/suites/*.data`"""
Pengyu Lv45e32032023-04-06 14:33:41 +0800344
345 def collect_default_files(self):
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800346 """Collect all files in `tests/suites/*.data`"""
Pengyu Lv45e32032023-04-06 14:33:41 +0800347 test_dir = self.find_test_dir()
348 suites_data_folder = os.path.join(test_dir, 'suites')
Pengyu Lv45e32032023-04-06 14:33:41 +0800349 data_files = glob.glob(os.path.join(suites_data_folder, '*.data'))
350 return data_files
351
352 def parse_file(self, filename: str):
Pengyu Lv30f26832023-04-07 18:04:07 +0800353 """
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800354 Parse a list of AuditData from test suite data file.
Pengyu Lv30f26832023-04-07 18:04:07 +0800355
356 :param filename: name of the file to parse.
357 :return list of AuditData parsed from the file.
358 """
Pengyu Lv45e32032023-04-06 14:33:41 +0800359 audit_data_list = []
Pengyu Lv30f26832023-04-07 18:04:07 +0800360 data_f = FileWrapper(filename)
Pengyu Lv28fe9572023-04-23 13:56:25 +0800361 for test_args in parse_suite_data(data_f):
Pengyu Lv7725c1d2023-04-13 15:55:30 +0800362 for idx, test_arg in enumerate(test_args):
Pengyu Lv30f26832023-04-07 18:04:07 +0800363 match = re.match(r'"(?P<data>[0-9a-fA-F]+)"', test_arg)
364 if not match:
365 continue
366 if not X509Parser.check_hex_string(match.group('data')):
367 continue
368 audit_data = self.parse_bytes(bytes.fromhex(match.group('data')))
369 if audit_data is None:
370 continue
Pengyu Lvfe13bd32023-04-28 10:58:38 +0800371 audit_data.locations.append("{}:{}:#{}".format(filename,
372 data_f.line_no,
373 idx + 1))
Pengyu Lv30f26832023-04-07 18:04:07 +0800374 audit_data_list.append(audit_data)
375
Pengyu Lv45e32032023-04-06 14:33:41 +0800376 return audit_data_list
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800377
Pengyu Lv2d487212023-04-21 12:41:24 +0800378
Pengyu Lvfe13bd32023-04-28 10:58:38 +0800379def merge_auditdata(original: typing.List[AuditData]) \
380 -> typing.List[AuditData]:
381 """
382 Multiple AuditData might be extracted from different locations for
383 an identical X.509 object. Merge them into one entry in the list.
384 """
385 results = []
386 for x in original:
387 if x not in results:
388 results.append(x)
389 else:
390 idx = results.index(x)
391 results[idx].locations.extend(x.locations)
392 return results
393
394
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800395def list_all(audit_data: AuditData):
Pengyu Lv31e3d122023-05-05 17:01:49 +0800396 for loc in audit_data.locations:
397 print("{}\t{:20}\t{:20}\t{:3}\t{}".format(
398 audit_data.identifier,
399 audit_data.not_valid_before.isoformat(timespec='seconds'),
400 audit_data.not_valid_after.isoformat(timespec='seconds'),
401 audit_data.data_type.name,
402 loc))
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800403
Pengyu Lvfcda6d42023-04-21 11:04:07 +0800404
405def configure_logger(logger: logging.Logger) -> None:
406 """
407 Configure the logging.Logger instance so that:
408 - Format is set to "[%(levelname)s]: %(message)s".
409 - loglevel >= WARNING are printed to stderr.
410 - loglevel < WARNING are printed to stdout.
411 """
412 class MaxLevelFilter(logging.Filter):
413 # pylint: disable=too-few-public-methods
414 def __init__(self, max_level, name=''):
415 super().__init__(name)
416 self.max_level = max_level
417
418 def filter(self, record: logging.LogRecord) -> bool:
419 return record.levelno <= self.max_level
420
421 log_formatter = logging.Formatter("[%(levelname)s]: %(message)s")
422
423 # set loglevel >= WARNING to be printed to stderr
424 stderr_hdlr = logging.StreamHandler(sys.stderr)
425 stderr_hdlr.setLevel(logging.WARNING)
426 stderr_hdlr.setFormatter(log_formatter)
427
428 # set loglevel <= INFO to be printed to stdout
429 stdout_hdlr = logging.StreamHandler(sys.stdout)
430 stdout_hdlr.addFilter(MaxLevelFilter(logging.INFO))
431 stdout_hdlr.setFormatter(log_formatter)
432
433 logger.addHandler(stderr_hdlr)
434 logger.addHandler(stdout_hdlr)
435
436
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800437def main():
438 """
439 Perform argument parsing.
440 """
Pengyu Lv57240952023-04-13 14:42:37 +0800441 parser = argparse.ArgumentParser(description=__doc__)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800442
443 parser.add_argument('-a', '--all',
444 action='store_true',
Pengyu Lv57240952023-04-13 14:42:37 +0800445 help='list the information of all the files')
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800446 parser.add_argument('-v', '--verbose',
447 action='store_true', dest='verbose',
Pengyu Lvfcda6d42023-04-21 11:04:07 +0800448 help='show logs')
Pengyu Lv1d4cc912023-04-25 15:17:19 +0800449 parser.add_argument('--from', dest='start_date',
450 help=('Start of desired validity period (UTC, YYYY-MM-DD). '
Pengyu Lv57240952023-04-13 14:42:37 +0800451 'Default: today'),
Pengyu Lvebf011f2023-04-11 13:39:31 +0800452 metavar='DATE')
Pengyu Lv1d4cc912023-04-25 15:17:19 +0800453 parser.add_argument('--to', dest='end_date',
454 help=('End of desired validity period (UTC, YYYY-MM-DD). '
455 'Default: --from'),
Pengyu Lvebf011f2023-04-11 13:39:31 +0800456 metavar='DATE')
Pengyu Lva228cbc2023-04-21 11:59:25 +0800457 parser.add_argument('--data-files', action='append', nargs='*',
458 help='data files to audit',
459 metavar='FILE')
460 parser.add_argument('--suite-data-files', action='append', nargs='*',
461 help='suite data files to audit',
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800462 metavar='FILE')
463
464 args = parser.parse_args()
465
466 # start main routine
Pengyu Lvfcda6d42023-04-21 11:04:07 +0800467 # setup logger
468 logger = logging.getLogger()
469 configure_logger(logger)
470 logger.setLevel(logging.DEBUG if args.verbose else logging.ERROR)
471
472 td_auditor = TestDataAuditor(logger)
473 sd_auditor = SuiteDataAuditor(logger)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800474
Pengyu Lva228cbc2023-04-21 11:59:25 +0800475 data_files = []
476 suite_data_files = []
477 if args.data_files is None and args.suite_data_files is None:
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800478 data_files = td_auditor.default_files
Pengyu Lv45e32032023-04-06 14:33:41 +0800479 suite_data_files = sd_auditor.default_files
Pengyu Lva228cbc2023-04-21 11:59:25 +0800480 else:
481 if args.data_files is not None:
482 data_files = [x for l in args.data_files for x in l]
483 if args.suite_data_files is not None:
484 suite_data_files = [x for l in args.suite_data_files for x in l]
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800485
Pengyu Lva228cbc2023-04-21 11:59:25 +0800486 # validity period start date
Pengyu Lv1d4cc912023-04-25 15:17:19 +0800487 if args.start_date:
488 start_date = datetime.datetime.fromisoformat(args.start_date)
Pengyu Lvebf011f2023-04-11 13:39:31 +0800489 else:
Pengyu Lv1d4cc912023-04-25 15:17:19 +0800490 start_date = datetime.datetime.today()
Pengyu Lva228cbc2023-04-21 11:59:25 +0800491 # validity period end date
Pengyu Lv1d4cc912023-04-25 15:17:19 +0800492 if args.end_date:
493 end_date = datetime.datetime.fromisoformat(args.end_date)
Pengyu Lvebf011f2023-04-11 13:39:31 +0800494 else:
Pengyu Lv1d4cc912023-04-25 15:17:19 +0800495 end_date = start_date
Pengyu Lvebf011f2023-04-11 13:39:31 +0800496
Pengyu Lva228cbc2023-04-21 11:59:25 +0800497 # go through all the files
Pengyu Lve09d27e2023-05-05 17:29:12 +0800498 audit_results = {}
499 td_auditor.walk_all(audit_results, data_files)
500 sd_auditor.walk_all(audit_results, suite_data_files)
Pengyu Lvfe13bd32023-04-28 10:58:38 +0800501
502 logger.info("Total: {} objects found!".format(len(audit_results)))
503
Pengyu Lv57240952023-04-13 14:42:37 +0800504 # we filter out the files whose validity duration covers the provided
Pengyu Lvebf011f2023-04-11 13:39:31 +0800505 # duration.
Pengyu Lv1d4cc912023-04-25 15:17:19 +0800506 filter_func = lambda d: (start_date < d.not_valid_before) or \
507 (d.not_valid_after < end_date)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800508
Pengyu Lv0b4832b2023-04-28 11:14:28 +0800509 sortby_end = lambda d: d.not_valid_after
510
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800511 if args.all:
Pengyu Lvebf011f2023-04-11 13:39:31 +0800512 filter_func = None
513
Pengyu Lva228cbc2023-04-21 11:59:25 +0800514 # filter and output the results
Pengyu Lve09d27e2023-05-05 17:29:12 +0800515 for d in sorted(filter(filter_func, audit_results.values()), key=sortby_end):
Pengyu Lvebf011f2023-04-11 13:39:31 +0800516 list_all(d)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800517
Pengyu Lvfcda6d42023-04-21 11:04:07 +0800518 logger.debug("Done!")
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800519
Pengyu Lv13815982023-04-25 14:55:38 +0800520check_cryptography_version()
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800521if __name__ == "__main__":
522 main()