blob: 623fd23523a4ad0109ec218cdd7e3a541d422834 [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
Pengyu Lv7f6933a2023-04-04 16:05:54 +080027import re
28import typing
Pengyu Lv7f6933a2023-04-04 16:05:54 +080029import argparse
30import datetime
Pengyu Lv45e32032023-04-06 14:33:41 +080031import glob
Pengyu Lvfcda6d42023-04-21 11:04:07 +080032import logging
Pengyu Lv13f2ef42023-05-05 16:53:37 +080033import hashlib
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
Yanray Wang21127f72023-07-19 12:09:45 +080045from mbedtls_dev import logging_util
Pengyu Lv2d487212023-04-21 12:41:24 +080046
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
Pengyu Lv13f2ef42023-05-05 16:53:37 +080076 @property
77 def identifier(self):
78 """
79 Identifier of the underlying X.509 object, which is consistent across
80 different runs.
81 """
82 return self._identifier
83
Pengyu Lv7f6933a2023-04-04 16:05:54 +080084 def fill_validity_duration(self, x509_obj):
Pengyu Lvf8e5e052023-04-18 15:43:25 +080085 """Read validity period from an X.509 object."""
Pengyu Lv7f6933a2023-04-04 16:05:54 +080086 # Certificate expires after "not_valid_after"
87 # Certificate is invalid before "not_valid_before"
88 if self.data_type == DataType.CRT:
89 self.not_valid_after = x509_obj.not_valid_after
90 self.not_valid_before = x509_obj.not_valid_before
91 # CertificateRevocationList expires after "next_update"
92 # CertificateRevocationList is invalid before "last_update"
93 elif self.data_type == DataType.CRL:
94 self.not_valid_after = x509_obj.next_update
95 self.not_valid_before = x509_obj.last_update
96 # CertificateSigningRequest is always valid.
97 elif self.data_type == DataType.CSR:
98 self.not_valid_after = datetime.datetime.max
99 self.not_valid_before = datetime.datetime.min
100 else:
101 raise ValueError("Unsupported file_type: {}".format(self.data_type))
102
Pengyu Lv2d487212023-04-21 12:41:24 +0800103
Pengyu Lvf8e5e052023-04-18 15:43:25 +0800104class X509Parser:
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800105 """A parser class to parse crt/crl/csr file or data in PEM/DER format."""
Pengyu Lve245c0c2023-04-28 10:46:18 +0800106 PEM_REGEX = br'-{5}BEGIN (?P<type>.*?)-{5}(?P<data>.*?)-{5}END (?P=type)-{5}'
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800107 PEM_TAG_REGEX = br'-{5}BEGIN (?P<type>.*?)-{5}\n'
108 PEM_TAGS = {
109 DataType.CRT: 'CERTIFICATE',
110 DataType.CRL: 'X509 CRL',
111 DataType.CSR: 'CERTIFICATE REQUEST'
112 }
113
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800114 def __init__(self,
115 backends:
116 typing.Dict[DataType,
117 typing.Dict[DataFormat,
118 typing.Callable[[bytes], object]]]) \
119 -> None:
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800120 self.backends = backends
121 self.__generate_parsers()
122
123 def __generate_parser(self, data_type: DataType):
124 """Parser generator for a specific DataType"""
125 tag = self.PEM_TAGS[data_type]
126 pem_loader = self.backends[data_type][DataFormat.PEM]
127 der_loader = self.backends[data_type][DataFormat.DER]
128 def wrapper(data: bytes):
129 pem_type = X509Parser.pem_data_type(data)
130 # It is in PEM format with target tag
131 if pem_type == tag:
132 return pem_loader(data)
133 # It is in PEM format without target tag
134 if pem_type:
135 return None
136 # It might be in DER format
137 try:
138 result = der_loader(data)
139 except ValueError:
140 result = None
141 return result
142 wrapper.__name__ = "{}.parser[{}]".format(type(self).__name__, tag)
143 return wrapper
144
145 def __generate_parsers(self):
146 """Generate parsers for all support DataType"""
147 self.parsers = {}
148 for data_type, _ in self.PEM_TAGS.items():
149 self.parsers[data_type] = self.__generate_parser(data_type)
150
151 def __getitem__(self, item):
152 return self.parsers[item]
153
154 @staticmethod
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800155 def pem_data_type(data: bytes) -> typing.Optional[str]:
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800156 """Get the tag from the data in PEM format
157
158 :param data: data to be checked in binary mode.
159 :return: PEM tag or "" when no tag detected.
160 """
161 m = re.search(X509Parser.PEM_TAG_REGEX, data)
162 if m is not None:
163 return m.group('type').decode('UTF-8')
164 else:
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800165 return None
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800166
Pengyu Lv30f26832023-04-07 18:04:07 +0800167 @staticmethod
168 def check_hex_string(hex_str: str) -> bool:
169 """Check if the hex string is possibly DER data."""
170 hex_len = len(hex_str)
171 # At least 6 hex char for 3 bytes: Type + Length + Content
172 if hex_len < 6:
173 return False
174 # Check if Type (1 byte) is SEQUENCE.
175 if hex_str[0:2] != '30':
176 return False
177 # Check LENGTH (1 byte) value
178 content_len = int(hex_str[2:4], base=16)
179 consumed = 4
180 if content_len in (128, 255):
181 # Indefinite or Reserved
182 return False
183 elif content_len > 127:
184 # Definite, Long
185 length_len = (content_len - 128) * 2
186 content_len = int(hex_str[consumed:consumed+length_len], base=16)
187 consumed += length_len
188 # Check LENGTH
189 if hex_len != content_len * 2 + consumed:
190 return False
191 return True
192
Pengyu Lv2d487212023-04-21 12:41:24 +0800193
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800194class Auditor:
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800195 """
196 A base class that uses X509Parser to parse files to a list of AuditData.
197
198 A subclass must implement the following methods:
199 - collect_default_files: Return a list of file names that are defaultly
200 used for parsing (auditing). The list will be stored in
201 Auditor.default_files.
202 - parse_file: Method that parses a single file to a list of AuditData.
203
204 A subclass may override the following methods:
205 - parse_bytes: Defaultly, it parses `bytes` that contains only one valid
206 X.509 data(DER/PEM format) to an X.509 object.
207 - walk_all: Defaultly, it iterates over all the files in the provided
208 file name list, calls `parse_file` for each file and stores the results
Pengyu Lve09d27e2023-05-05 17:29:12 +0800209 by extending the `results` passed to the function.
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800210 """
Pengyu Lvfcda6d42023-04-21 11:04:07 +0800211 def __init__(self, logger):
212 self.logger = logger
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800213 self.default_files = self.collect_default_files()
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800214 self.parser = X509Parser({
215 DataType.CRT: {
216 DataFormat.PEM: x509.load_pem_x509_certificate,
217 DataFormat.DER: x509.load_der_x509_certificate
218 },
219 DataType.CRL: {
220 DataFormat.PEM: x509.load_pem_x509_crl,
221 DataFormat.DER: x509.load_der_x509_crl
222 },
223 DataType.CSR: {
224 DataFormat.PEM: x509.load_pem_x509_csr,
225 DataFormat.DER: x509.load_der_x509_csr
226 },
227 })
228
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800229 def collect_default_files(self) -> typing.List[str]:
230 """Collect the default files for parsing."""
231 raise NotImplementedError
232
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800233 def parse_file(self, filename: str) -> typing.List[AuditData]:
234 """
235 Parse a list of AuditData from file.
236
237 :param filename: name of the file to parse.
238 :return list of AuditData parsed from the file.
239 """
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800240 raise NotImplementedError
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800241
242 def parse_bytes(self, data: bytes):
243 """Parse AuditData from bytes."""
244 for data_type in list(DataType):
245 try:
246 result = self.parser[data_type](data)
247 except ValueError as val_error:
248 result = None
Pengyu Lvfcda6d42023-04-21 11:04:07 +0800249 self.logger.warning(val_error)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800250 if result is not None:
Pengyu Lvcb8fc322023-04-11 15:05:29 +0800251 audit_data = AuditData(data_type, result)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800252 return audit_data
253 return None
254
Pengyu Lve09d27e2023-05-05 17:29:12 +0800255 def walk_all(self,
256 results: typing.Dict[str, AuditData],
257 file_list: typing.Optional[typing.List[str]] = None) \
258 -> None:
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800259 """
Pengyu Lve09d27e2023-05-05 17:29:12 +0800260 Iterate over all the files in the list and get audit data. The
261 results will be written to `results` passed to this function.
262
Pengyu Lvee870a62023-05-06 10:06:19 +0800263 :param results: The dictionary used to store the parsed
Pengyu Lve09d27e2023-05-05 17:29:12 +0800264 AuditData. The keys of this dictionary should
265 be the identifier of the AuditData.
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800266 """
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800267 if file_list is None:
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800268 file_list = self.default_files
269 for filename in file_list:
270 data_list = self.parse_file(filename)
Pengyu Lve09d27e2023-05-05 17:29:12 +0800271 for d in data_list:
272 if d.identifier in results:
273 results[d.identifier].locations.extend(d.locations)
274 else:
275 results[d.identifier] = d
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800276
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800277 @staticmethod
278 def find_test_dir():
279 """Get the relative path for the MbedTLS test directory."""
Pengyu Lv2d487212023-04-21 12:41:24 +0800280 return os.path.relpath(build_tree.guess_mbedtls_root() + '/tests')
281
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800282
283class TestDataAuditor(Auditor):
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800284 """Class for auditing files in `tests/data_files/`"""
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800285
286 def collect_default_files(self):
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800287 """Collect all files in `tests/data_files/`"""
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800288 test_dir = self.find_test_dir()
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800289 test_data_glob = os.path.join(test_dir, 'data_files/**')
290 data_files = [f for f in glob.glob(test_data_glob, recursive=True)
291 if os.path.isfile(f)]
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800292 return data_files
293
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800294 def parse_file(self, filename: str) -> typing.List[AuditData]:
295 """
296 Parse a list of AuditData from data file.
297
298 :param filename: name of the file to parse.
299 :return list of AuditData parsed from the file.
300 """
301 with open(filename, 'rb') as f:
302 data = f.read()
Pengyu Lve245c0c2023-04-28 10:46:18 +0800303
304 results = []
Pengyu Lva57f6772023-05-08 18:07:28 +0800305 # Try to parse all PEM blocks.
306 is_pem = False
Pengyu Lve245c0c2023-04-28 10:46:18 +0800307 for idx, m in enumerate(re.finditer(X509Parser.PEM_REGEX, data, flags=re.S), 1):
Pengyu Lva57f6772023-05-08 18:07:28 +0800308 is_pem = True
Pengyu Lve245c0c2023-04-28 10:46:18 +0800309 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
Pengyu Lva57f6772023-05-08 18:07:28 +0800314 # Might be DER format.
315 if not is_pem:
316 result = self.parse_bytes(data)
317 if result is not None:
318 result.locations.append("{}".format(filename))
319 results.append(result)
320
Pengyu Lve245c0c2023-04-28 10:46:18 +0800321 return results
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800322
Pengyu Lv2d487212023-04-21 12:41:24 +0800323
Pengyu Lv28fe9572023-04-23 13:56:25 +0800324def parse_suite_data(data_f):
325 """
326 Parses .data file for test arguments that possiblly have a
327 valid X.509 data. If you need a more precise parser, please
328 use generate_test_code.parse_test_data instead.
329
330 :param data_f: file object of the data file.
331 :return: Generator that yields test function argument list.
332 """
333 for line in data_f:
334 line = line.strip()
335 # Skip comments
336 if line.startswith('#'):
337 continue
338
339 # Check parameters line
340 match = re.search(r'\A\w+(.*:)?\"', line)
341 if match:
342 # Read test vectors
343 parts = re.split(r'(?<!\\):', line)
344 parts = [x for x in parts if x]
345 args = parts[1:]
346 yield args
347
348
Pengyu Lv45e32032023-04-06 14:33:41 +0800349class SuiteDataAuditor(Auditor):
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800350 """Class for auditing files in `tests/suites/*.data`"""
Pengyu Lv45e32032023-04-06 14:33:41 +0800351
352 def collect_default_files(self):
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800353 """Collect all files in `tests/suites/*.data`"""
Pengyu Lv45e32032023-04-06 14:33:41 +0800354 test_dir = self.find_test_dir()
355 suites_data_folder = os.path.join(test_dir, 'suites')
Pengyu Lv45e32032023-04-06 14:33:41 +0800356 data_files = glob.glob(os.path.join(suites_data_folder, '*.data'))
357 return data_files
358
359 def parse_file(self, filename: str):
Pengyu Lv30f26832023-04-07 18:04:07 +0800360 """
Pengyu Lvc34b9ac2023-04-23 14:51:18 +0800361 Parse a list of AuditData from test suite data file.
Pengyu Lv30f26832023-04-07 18:04:07 +0800362
363 :param filename: name of the file to parse.
364 :return list of AuditData parsed from the file.
365 """
Pengyu Lv45e32032023-04-06 14:33:41 +0800366 audit_data_list = []
Pengyu Lv30f26832023-04-07 18:04:07 +0800367 data_f = FileWrapper(filename)
Pengyu Lv28fe9572023-04-23 13:56:25 +0800368 for test_args in parse_suite_data(data_f):
Pengyu Lv7725c1d2023-04-13 15:55:30 +0800369 for idx, test_arg in enumerate(test_args):
Pengyu Lv30f26832023-04-07 18:04:07 +0800370 match = re.match(r'"(?P<data>[0-9a-fA-F]+)"', test_arg)
371 if not match:
372 continue
373 if not X509Parser.check_hex_string(match.group('data')):
374 continue
375 audit_data = self.parse_bytes(bytes.fromhex(match.group('data')))
376 if audit_data is None:
377 continue
Pengyu Lvfe13bd32023-04-28 10:58:38 +0800378 audit_data.locations.append("{}:{}:#{}".format(filename,
379 data_f.line_no,
380 idx + 1))
Pengyu Lv30f26832023-04-07 18:04:07 +0800381 audit_data_list.append(audit_data)
382
Pengyu Lv45e32032023-04-06 14:33:41 +0800383 return audit_data_list
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800384
Pengyu Lv2d487212023-04-21 12:41:24 +0800385
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800386def list_all(audit_data: AuditData):
Pengyu Lv31e3d122023-05-05 17:01:49 +0800387 for loc in audit_data.locations:
388 print("{}\t{:20}\t{:20}\t{:3}\t{}".format(
389 audit_data.identifier,
390 audit_data.not_valid_before.isoformat(timespec='seconds'),
391 audit_data.not_valid_after.isoformat(timespec='seconds'),
392 audit_data.data_type.name,
393 loc))
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800394
Pengyu Lvfcda6d42023-04-21 11:04:07 +0800395
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800396def main():
397 """
398 Perform argument parsing.
399 """
Pengyu Lv57240952023-04-13 14:42:37 +0800400 parser = argparse.ArgumentParser(description=__doc__)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800401
402 parser.add_argument('-a', '--all',
403 action='store_true',
Pengyu Lv57240952023-04-13 14:42:37 +0800404 help='list the information of all the files')
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800405 parser.add_argument('-v', '--verbose',
406 action='store_true', dest='verbose',
Pengyu Lvfcda6d42023-04-21 11:04:07 +0800407 help='show logs')
Pengyu Lv1d4cc912023-04-25 15:17:19 +0800408 parser.add_argument('--from', dest='start_date',
409 help=('Start of desired validity period (UTC, YYYY-MM-DD). '
Pengyu Lv57240952023-04-13 14:42:37 +0800410 'Default: today'),
Pengyu Lvebf011f2023-04-11 13:39:31 +0800411 metavar='DATE')
Pengyu Lv1d4cc912023-04-25 15:17:19 +0800412 parser.add_argument('--to', dest='end_date',
413 help=('End of desired validity period (UTC, YYYY-MM-DD). '
414 'Default: --from'),
Pengyu Lvebf011f2023-04-11 13:39:31 +0800415 metavar='DATE')
Pengyu Lva228cbc2023-04-21 11:59:25 +0800416 parser.add_argument('--data-files', action='append', nargs='*',
417 help='data files to audit',
418 metavar='FILE')
419 parser.add_argument('--suite-data-files', action='append', nargs='*',
420 help='suite data files to audit',
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800421 metavar='FILE')
422
423 args = parser.parse_args()
424
425 # start main routine
Pengyu Lvfcda6d42023-04-21 11:04:07 +0800426 # setup logger
427 logger = logging.getLogger()
Yanray Wang21127f72023-07-19 12:09:45 +0800428 logging_util.configure_logger(logger)
Pengyu Lvfcda6d42023-04-21 11:04:07 +0800429 logger.setLevel(logging.DEBUG if args.verbose else logging.ERROR)
430
431 td_auditor = TestDataAuditor(logger)
432 sd_auditor = SuiteDataAuditor(logger)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800433
Pengyu Lva228cbc2023-04-21 11:59:25 +0800434 data_files = []
435 suite_data_files = []
436 if args.data_files is None and args.suite_data_files is None:
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800437 data_files = td_auditor.default_files
Pengyu Lv45e32032023-04-06 14:33:41 +0800438 suite_data_files = sd_auditor.default_files
Pengyu Lva228cbc2023-04-21 11:59:25 +0800439 else:
440 if args.data_files is not None:
441 data_files = [x for l in args.data_files for x in l]
442 if args.suite_data_files is not None:
443 suite_data_files = [x for l in args.suite_data_files for x in l]
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800444
Pengyu Lva228cbc2023-04-21 11:59:25 +0800445 # validity period start date
Pengyu Lv1d4cc912023-04-25 15:17:19 +0800446 if args.start_date:
447 start_date = datetime.datetime.fromisoformat(args.start_date)
Pengyu Lvebf011f2023-04-11 13:39:31 +0800448 else:
Pengyu Lv1d4cc912023-04-25 15:17:19 +0800449 start_date = datetime.datetime.today()
Pengyu Lva228cbc2023-04-21 11:59:25 +0800450 # validity period end date
Pengyu Lv1d4cc912023-04-25 15:17:19 +0800451 if args.end_date:
452 end_date = datetime.datetime.fromisoformat(args.end_date)
Pengyu Lvebf011f2023-04-11 13:39:31 +0800453 else:
Pengyu Lv1d4cc912023-04-25 15:17:19 +0800454 end_date = start_date
Pengyu Lvebf011f2023-04-11 13:39:31 +0800455
Pengyu Lva228cbc2023-04-21 11:59:25 +0800456 # go through all the files
Pengyu Lve09d27e2023-05-05 17:29:12 +0800457 audit_results = {}
458 td_auditor.walk_all(audit_results, data_files)
459 sd_auditor.walk_all(audit_results, suite_data_files)
Pengyu Lvfe13bd32023-04-28 10:58:38 +0800460
461 logger.info("Total: {} objects found!".format(len(audit_results)))
462
Pengyu Lv57240952023-04-13 14:42:37 +0800463 # we filter out the files whose validity duration covers the provided
Pengyu Lvebf011f2023-04-11 13:39:31 +0800464 # duration.
Pengyu Lv1d4cc912023-04-25 15:17:19 +0800465 filter_func = lambda d: (start_date < d.not_valid_before) or \
466 (d.not_valid_after < end_date)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800467
Pengyu Lv0b4832b2023-04-28 11:14:28 +0800468 sortby_end = lambda d: d.not_valid_after
469
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800470 if args.all:
Pengyu Lvebf011f2023-04-11 13:39:31 +0800471 filter_func = None
472
Pengyu Lva228cbc2023-04-21 11:59:25 +0800473 # filter and output the results
Pengyu Lve09d27e2023-05-05 17:29:12 +0800474 for d in sorted(filter(filter_func, audit_results.values()), key=sortby_end):
Pengyu Lvebf011f2023-04-11 13:39:31 +0800475 list_all(d)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800476
Pengyu Lvfcda6d42023-04-21 11:04:07 +0800477 logger.debug("Done!")
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800478
Pengyu Lv13815982023-04-25 14:55:38 +0800479check_cryptography_version()
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800480if __name__ == "__main__":
481 main()