blob: 09559dc98ad1dbc2f52d6d5bd4a712f0936516f1 [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 Lvf8e5e052023-04-18 15:43:25 +080021It would print the information about X.509 data if the validity period of the
22X.509 data didn't cover the provided validity period. The data are collected
23from 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
37# for Python >= 3.6. Disable the pylint error here until we were
38# using modern system on our CI.
39from cryptography import x509 #pylint: disable=import-error
Pengyu Lv7f6933a2023-04-04 16:05:54 +080040
Pengyu Lv30f26832023-04-07 18:04:07 +080041# reuse the function to parse *.data file in tests/suites/
42from generate_test_code import parse_test_data as parse_suite_data
Pengyu Lvad306792023-04-19 15:07:03 +080043from generate_test_code import FileWrapper
Pengyu Lv30f26832023-04-07 18:04:07 +080044
Pengyu Lv2d487212023-04-21 12:41:24 +080045import scripts_path # pylint: disable=unused-import
46from mbedtls_dev import build_tree
47
Pengyu Lv7f6933a2023-04-04 16:05:54 +080048class DataType(Enum):
49 CRT = 1 # Certificate
50 CRL = 2 # Certificate Revocation List
51 CSR = 3 # Certificate Signing Request
52
Pengyu Lv2d487212023-04-21 12:41:24 +080053
Pengyu Lv7f6933a2023-04-04 16:05:54 +080054class DataFormat(Enum):
55 PEM = 1 # Privacy-Enhanced Mail
56 DER = 2 # Distinguished Encoding Rules
57
Pengyu Lv2d487212023-04-21 12:41:24 +080058
Pengyu Lv7f6933a2023-04-04 16:05:54 +080059class AuditData:
Pengyu Lvf8e5e052023-04-18 15:43:25 +080060 """Store data location, type and validity period of X.509 objects."""
Pengyu Lv7f6933a2023-04-04 16:05:54 +080061 #pylint: disable=too-few-public-methods
Pengyu Lvcb8fc322023-04-11 15:05:29 +080062 def __init__(self, data_type: DataType, x509_obj):
Pengyu Lv7f6933a2023-04-04 16:05:54 +080063 self.data_type = data_type
Pengyu Lvf8e5e052023-04-18 15:43:25 +080064 self.location = ""
Pengyu Lvcb8fc322023-04-11 15:05:29 +080065 self.fill_validity_duration(x509_obj)
Pengyu Lv7f6933a2023-04-04 16:05:54 +080066
67 def fill_validity_duration(self, x509_obj):
Pengyu Lvf8e5e052023-04-18 15:43:25 +080068 """Read validity period from an X.509 object."""
Pengyu Lv7f6933a2023-04-04 16:05:54 +080069 # Certificate expires after "not_valid_after"
70 # Certificate is invalid before "not_valid_before"
71 if self.data_type == DataType.CRT:
72 self.not_valid_after = x509_obj.not_valid_after
73 self.not_valid_before = x509_obj.not_valid_before
74 # CertificateRevocationList expires after "next_update"
75 # CertificateRevocationList is invalid before "last_update"
76 elif self.data_type == DataType.CRL:
77 self.not_valid_after = x509_obj.next_update
78 self.not_valid_before = x509_obj.last_update
79 # CertificateSigningRequest is always valid.
80 elif self.data_type == DataType.CSR:
81 self.not_valid_after = datetime.datetime.max
82 self.not_valid_before = datetime.datetime.min
83 else:
84 raise ValueError("Unsupported file_type: {}".format(self.data_type))
85
Pengyu Lv2d487212023-04-21 12:41:24 +080086
Pengyu Lvf8e5e052023-04-18 15:43:25 +080087class X509Parser:
Pengyu Lv7f6933a2023-04-04 16:05:54 +080088 """A parser class to parse crt/crl/csr file or data in PEM/DER format."""
89 PEM_REGEX = br'-{5}BEGIN (?P<type>.*?)-{5}\n(?P<data>.*?)-{5}END (?P=type)-{5}\n'
90 PEM_TAG_REGEX = br'-{5}BEGIN (?P<type>.*?)-{5}\n'
91 PEM_TAGS = {
92 DataType.CRT: 'CERTIFICATE',
93 DataType.CRL: 'X509 CRL',
94 DataType.CSR: 'CERTIFICATE REQUEST'
95 }
96
Pengyu Lv8e6794a2023-04-18 17:00:47 +080097 def __init__(self,
98 backends:
99 typing.Dict[DataType,
100 typing.Dict[DataFormat,
101 typing.Callable[[bytes], object]]]) \
102 -> None:
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800103 self.backends = backends
104 self.__generate_parsers()
105
106 def __generate_parser(self, data_type: DataType):
107 """Parser generator for a specific DataType"""
108 tag = self.PEM_TAGS[data_type]
109 pem_loader = self.backends[data_type][DataFormat.PEM]
110 der_loader = self.backends[data_type][DataFormat.DER]
111 def wrapper(data: bytes):
112 pem_type = X509Parser.pem_data_type(data)
113 # It is in PEM format with target tag
114 if pem_type == tag:
115 return pem_loader(data)
116 # It is in PEM format without target tag
117 if pem_type:
118 return None
119 # It might be in DER format
120 try:
121 result = der_loader(data)
122 except ValueError:
123 result = None
124 return result
125 wrapper.__name__ = "{}.parser[{}]".format(type(self).__name__, tag)
126 return wrapper
127
128 def __generate_parsers(self):
129 """Generate parsers for all support DataType"""
130 self.parsers = {}
131 for data_type, _ in self.PEM_TAGS.items():
132 self.parsers[data_type] = self.__generate_parser(data_type)
133
134 def __getitem__(self, item):
135 return self.parsers[item]
136
137 @staticmethod
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800138 def pem_data_type(data: bytes) -> typing.Optional[str]:
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800139 """Get the tag from the data in PEM format
140
141 :param data: data to be checked in binary mode.
142 :return: PEM tag or "" when no tag detected.
143 """
144 m = re.search(X509Parser.PEM_TAG_REGEX, data)
145 if m is not None:
146 return m.group('type').decode('UTF-8')
147 else:
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800148 return None
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800149
Pengyu Lv30f26832023-04-07 18:04:07 +0800150 @staticmethod
151 def check_hex_string(hex_str: str) -> bool:
152 """Check if the hex string is possibly DER data."""
153 hex_len = len(hex_str)
154 # At least 6 hex char for 3 bytes: Type + Length + Content
155 if hex_len < 6:
156 return False
157 # Check if Type (1 byte) is SEQUENCE.
158 if hex_str[0:2] != '30':
159 return False
160 # Check LENGTH (1 byte) value
161 content_len = int(hex_str[2:4], base=16)
162 consumed = 4
163 if content_len in (128, 255):
164 # Indefinite or Reserved
165 return False
166 elif content_len > 127:
167 # Definite, Long
168 length_len = (content_len - 128) * 2
169 content_len = int(hex_str[consumed:consumed+length_len], base=16)
170 consumed += length_len
171 # Check LENGTH
172 if hex_len != content_len * 2 + consumed:
173 return False
174 return True
175
Pengyu Lv2d487212023-04-21 12:41:24 +0800176
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800177class Auditor:
178 """A base class for audit."""
Pengyu Lvfcda6d42023-04-21 11:04:07 +0800179 def __init__(self, logger):
180 self.logger = logger
Pengyu Lva228cbc2023-04-21 11:59:25 +0800181 self.default_files = [] # type: typing.List[str]
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800182 # A list to store the parsed audit_data.
Pengyu Lva228cbc2023-04-21 11:59:25 +0800183 self.audit_data = [] # type: typing.List[AuditData]
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800184 self.parser = X509Parser({
185 DataType.CRT: {
186 DataFormat.PEM: x509.load_pem_x509_certificate,
187 DataFormat.DER: x509.load_der_x509_certificate
188 },
189 DataType.CRL: {
190 DataFormat.PEM: x509.load_pem_x509_crl,
191 DataFormat.DER: x509.load_der_x509_crl
192 },
193 DataType.CSR: {
194 DataFormat.PEM: x509.load_pem_x509_csr,
195 DataFormat.DER: x509.load_der_x509_csr
196 },
197 })
198
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800199 def parse_file(self, filename: str) -> typing.List[AuditData]:
200 """
201 Parse a list of AuditData from file.
202
203 :param filename: name of the file to parse.
204 :return list of AuditData parsed from the file.
205 """
206 with open(filename, 'rb') as f:
207 data = f.read()
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800208 result = self.parse_bytes(data)
209 if result is not None:
Pengyu Lvf8e5e052023-04-18 15:43:25 +0800210 result.location = filename
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800211 return [result]
212 else:
213 return []
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800214
215 def parse_bytes(self, data: bytes):
216 """Parse AuditData from bytes."""
217 for data_type in list(DataType):
218 try:
219 result = self.parser[data_type](data)
220 except ValueError as val_error:
221 result = None
Pengyu Lvfcda6d42023-04-21 11:04:07 +0800222 self.logger.warning(val_error)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800223 if result is not None:
Pengyu Lvcb8fc322023-04-11 15:05:29 +0800224 audit_data = AuditData(data_type, result)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800225 return audit_data
226 return None
227
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800228 def walk_all(self, file_list: typing.Optional[typing.List[str]] = None):
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800229 """
230 Iterate over all the files in the list and get audit data.
231 """
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800232 if file_list is None:
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800233 file_list = self.default_files
234 for filename in file_list:
235 data_list = self.parse_file(filename)
236 self.audit_data.extend(data_list)
237
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800238 @staticmethod
239 def find_test_dir():
240 """Get the relative path for the MbedTLS test directory."""
Pengyu Lv2d487212023-04-21 12:41:24 +0800241 return os.path.relpath(build_tree.guess_mbedtls_root() + '/tests')
242
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800243
244class TestDataAuditor(Auditor):
245 """Class for auditing files in tests/data_files/"""
246 def __init__(self, verbose):
247 super().__init__(verbose)
248 self.default_files = self.collect_default_files()
249
250 def collect_default_files(self):
Pengyu Lv45e32032023-04-06 14:33:41 +0800251 """Collect all files in tests/data_files/"""
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800252 test_dir = self.find_test_dir()
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800253 test_data_glob = os.path.join(test_dir, 'data_files/**')
254 data_files = [f for f in glob.glob(test_data_glob, recursive=True)
255 if os.path.isfile(f)]
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800256 return data_files
257
Pengyu Lv2d487212023-04-21 12:41:24 +0800258
Pengyu Lv45e32032023-04-06 14:33:41 +0800259class SuiteDataAuditor(Auditor):
260 """Class for auditing files in tests/suites/*.data"""
261 def __init__(self, options):
262 super().__init__(options)
263 self.default_files = self.collect_default_files()
264
265 def collect_default_files(self):
266 """Collect all files in tests/suites/*.data"""
267 test_dir = self.find_test_dir()
268 suites_data_folder = os.path.join(test_dir, 'suites')
Pengyu Lv45e32032023-04-06 14:33:41 +0800269 data_files = glob.glob(os.path.join(suites_data_folder, '*.data'))
270 return data_files
271
272 def parse_file(self, filename: str):
Pengyu Lv30f26832023-04-07 18:04:07 +0800273 """
274 Parse a list of AuditData from file.
275
276 :param filename: name of the file to parse.
277 :return list of AuditData parsed from the file.
278 """
Pengyu Lv45e32032023-04-06 14:33:41 +0800279 audit_data_list = []
Pengyu Lv30f26832023-04-07 18:04:07 +0800280 data_f = FileWrapper(filename)
281 for _, _, _, test_args in parse_suite_data(data_f):
Pengyu Lv7725c1d2023-04-13 15:55:30 +0800282 for idx, test_arg in enumerate(test_args):
Pengyu Lv30f26832023-04-07 18:04:07 +0800283 match = re.match(r'"(?P<data>[0-9a-fA-F]+)"', test_arg)
284 if not match:
285 continue
286 if not X509Parser.check_hex_string(match.group('data')):
287 continue
288 audit_data = self.parse_bytes(bytes.fromhex(match.group('data')))
289 if audit_data is None:
290 continue
Pengyu Lvf8e5e052023-04-18 15:43:25 +0800291 audit_data.location = "{}:{}:#{}".format(filename,
292 data_f.line_no,
293 idx + 1)
Pengyu Lv30f26832023-04-07 18:04:07 +0800294 audit_data_list.append(audit_data)
295
Pengyu Lv45e32032023-04-06 14:33:41 +0800296 return audit_data_list
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800297
Pengyu Lv2d487212023-04-21 12:41:24 +0800298
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800299def list_all(audit_data: AuditData):
300 print("{}\t{}\t{}\t{}".format(
301 audit_data.not_valid_before.isoformat(timespec='seconds'),
302 audit_data.not_valid_after.isoformat(timespec='seconds'),
303 audit_data.data_type.name,
Pengyu Lvf8e5e052023-04-18 15:43:25 +0800304 audit_data.location))
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800305
Pengyu Lvfcda6d42023-04-21 11:04:07 +0800306
307def configure_logger(logger: logging.Logger) -> None:
308 """
309 Configure the logging.Logger instance so that:
310 - Format is set to "[%(levelname)s]: %(message)s".
311 - loglevel >= WARNING are printed to stderr.
312 - loglevel < WARNING are printed to stdout.
313 """
314 class MaxLevelFilter(logging.Filter):
315 # pylint: disable=too-few-public-methods
316 def __init__(self, max_level, name=''):
317 super().__init__(name)
318 self.max_level = max_level
319
320 def filter(self, record: logging.LogRecord) -> bool:
321 return record.levelno <= self.max_level
322
323 log_formatter = logging.Formatter("[%(levelname)s]: %(message)s")
324
325 # set loglevel >= WARNING to be printed to stderr
326 stderr_hdlr = logging.StreamHandler(sys.stderr)
327 stderr_hdlr.setLevel(logging.WARNING)
328 stderr_hdlr.setFormatter(log_formatter)
329
330 # set loglevel <= INFO to be printed to stdout
331 stdout_hdlr = logging.StreamHandler(sys.stdout)
332 stdout_hdlr.addFilter(MaxLevelFilter(logging.INFO))
333 stdout_hdlr.setFormatter(log_formatter)
334
335 logger.addHandler(stderr_hdlr)
336 logger.addHandler(stdout_hdlr)
337
338
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800339def main():
340 """
341 Perform argument parsing.
342 """
Pengyu Lv57240952023-04-13 14:42:37 +0800343 parser = argparse.ArgumentParser(description=__doc__)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800344
345 parser.add_argument('-a', '--all',
346 action='store_true',
Pengyu Lv57240952023-04-13 14:42:37 +0800347 help='list the information of all the files')
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800348 parser.add_argument('-v', '--verbose',
349 action='store_true', dest='verbose',
Pengyu Lvfcda6d42023-04-21 11:04:07 +0800350 help='show logs')
Pengyu Lvebf011f2023-04-11 13:39:31 +0800351 parser.add_argument('--not-before', dest='not_before',
Pengyu Lv57240952023-04-13 14:42:37 +0800352 help=('not valid before this date (UTC, YYYY-MM-DD). '
353 'Default: today'),
Pengyu Lvebf011f2023-04-11 13:39:31 +0800354 metavar='DATE')
355 parser.add_argument('--not-after', dest='not_after',
Pengyu Lv57240952023-04-13 14:42:37 +0800356 help=('not valid after this date (UTC, YYYY-MM-DD). '
357 'Default: not-before'),
Pengyu Lvebf011f2023-04-11 13:39:31 +0800358 metavar='DATE')
Pengyu Lva228cbc2023-04-21 11:59:25 +0800359 parser.add_argument('--data-files', action='append', nargs='*',
360 help='data files to audit',
361 metavar='FILE')
362 parser.add_argument('--suite-data-files', action='append', nargs='*',
363 help='suite data files to audit',
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800364 metavar='FILE')
365
366 args = parser.parse_args()
367
368 # start main routine
Pengyu Lvfcda6d42023-04-21 11:04:07 +0800369 # setup logger
370 logger = logging.getLogger()
371 configure_logger(logger)
372 logger.setLevel(logging.DEBUG if args.verbose else logging.ERROR)
373
374 td_auditor = TestDataAuditor(logger)
375 sd_auditor = SuiteDataAuditor(logger)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800376
Pengyu Lva228cbc2023-04-21 11:59:25 +0800377 data_files = []
378 suite_data_files = []
379 if args.data_files is None and args.suite_data_files is None:
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800380 data_files = td_auditor.default_files
Pengyu Lv45e32032023-04-06 14:33:41 +0800381 suite_data_files = sd_auditor.default_files
Pengyu Lva228cbc2023-04-21 11:59:25 +0800382 else:
383 if args.data_files is not None:
384 data_files = [x for l in args.data_files for x in l]
385 if args.suite_data_files is not None:
386 suite_data_files = [x for l in args.suite_data_files for x in l]
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800387
Pengyu Lva228cbc2023-04-21 11:59:25 +0800388 # validity period start date
Pengyu Lvebf011f2023-04-11 13:39:31 +0800389 if args.not_before:
390 not_before_date = datetime.datetime.fromisoformat(args.not_before)
391 else:
392 not_before_date = datetime.datetime.today()
Pengyu Lva228cbc2023-04-21 11:59:25 +0800393 # validity period end date
Pengyu Lvebf011f2023-04-11 13:39:31 +0800394 if args.not_after:
395 not_after_date = datetime.datetime.fromisoformat(args.not_after)
396 else:
397 not_after_date = not_before_date
398
Pengyu Lva228cbc2023-04-21 11:59:25 +0800399 # go through all the files
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800400 td_auditor.walk_all(data_files)
Pengyu Lv45e32032023-04-06 14:33:41 +0800401 sd_auditor.walk_all(suite_data_files)
Pengyu Lvebf011f2023-04-11 13:39:31 +0800402 audit_results = td_auditor.audit_data + sd_auditor.audit_data
403
Pengyu Lv57240952023-04-13 14:42:37 +0800404 # we filter out the files whose validity duration covers the provided
Pengyu Lvebf011f2023-04-11 13:39:31 +0800405 # duration.
406 filter_func = lambda d: (not_before_date < d.not_valid_before) or \
407 (d.not_valid_after < not_after_date)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800408
409 if args.all:
Pengyu Lvebf011f2023-04-11 13:39:31 +0800410 filter_func = None
411
Pengyu Lva228cbc2023-04-21 11:59:25 +0800412 # filter and output the results
Pengyu Lvebf011f2023-04-11 13:39:31 +0800413 for d in filter(filter_func, audit_results):
414 list_all(d)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800415
Pengyu Lvfcda6d42023-04-21 11:04:07 +0800416 logger.debug("Done!")
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800417
418if __name__ == "__main__":
419 main()