blob: 89a6dd4f574d5a826dc1cb11abe7846cdf73032e [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 Lv7f6933a2023-04-04 16:05:54 +080033from enum import Enum
34
Pengyu Lv31792322023-04-11 16:30:54 +080035# The script requires cryptography >= 35.0.0 which is only available
36# for Python >= 3.6. Disable the pylint error here until we were
37# using modern system on our CI.
38from cryptography import x509 #pylint: disable=import-error
Pengyu Lv7f6933a2023-04-04 16:05:54 +080039
Pengyu Lv30f26832023-04-07 18:04:07 +080040# reuse the function to parse *.data file in tests/suites/
41from generate_test_code import parse_test_data as parse_suite_data
Pengyu Lvad306792023-04-19 15:07:03 +080042from generate_test_code import FileWrapper
Pengyu Lv30f26832023-04-07 18:04:07 +080043
Pengyu Lv7f6933a2023-04-04 16:05:54 +080044class DataType(Enum):
45 CRT = 1 # Certificate
46 CRL = 2 # Certificate Revocation List
47 CSR = 3 # Certificate Signing Request
48
49class DataFormat(Enum):
50 PEM = 1 # Privacy-Enhanced Mail
51 DER = 2 # Distinguished Encoding Rules
52
53class AuditData:
Pengyu Lvf8e5e052023-04-18 15:43:25 +080054 """Store data location, type and validity period of X.509 objects."""
Pengyu Lv7f6933a2023-04-04 16:05:54 +080055 #pylint: disable=too-few-public-methods
Pengyu Lvcb8fc322023-04-11 15:05:29 +080056 def __init__(self, data_type: DataType, x509_obj):
Pengyu Lv7f6933a2023-04-04 16:05:54 +080057 self.data_type = data_type
Pengyu Lvf8e5e052023-04-18 15:43:25 +080058 self.location = ""
Pengyu Lvcb8fc322023-04-11 15:05:29 +080059 self.fill_validity_duration(x509_obj)
Pengyu Lv7f6933a2023-04-04 16:05:54 +080060
61 def fill_validity_duration(self, x509_obj):
Pengyu Lvf8e5e052023-04-18 15:43:25 +080062 """Read validity period from an X.509 object."""
Pengyu Lv7f6933a2023-04-04 16:05:54 +080063 # Certificate expires after "not_valid_after"
64 # Certificate is invalid before "not_valid_before"
65 if self.data_type == DataType.CRT:
66 self.not_valid_after = x509_obj.not_valid_after
67 self.not_valid_before = x509_obj.not_valid_before
68 # CertificateRevocationList expires after "next_update"
69 # CertificateRevocationList is invalid before "last_update"
70 elif self.data_type == DataType.CRL:
71 self.not_valid_after = x509_obj.next_update
72 self.not_valid_before = x509_obj.last_update
73 # CertificateSigningRequest is always valid.
74 elif self.data_type == DataType.CSR:
75 self.not_valid_after = datetime.datetime.max
76 self.not_valid_before = datetime.datetime.min
77 else:
78 raise ValueError("Unsupported file_type: {}".format(self.data_type))
79
Pengyu Lvf8e5e052023-04-18 15:43:25 +080080class X509Parser:
Pengyu Lv7f6933a2023-04-04 16:05:54 +080081 """A parser class to parse crt/crl/csr file or data in PEM/DER format."""
82 PEM_REGEX = br'-{5}BEGIN (?P<type>.*?)-{5}\n(?P<data>.*?)-{5}END (?P=type)-{5}\n'
83 PEM_TAG_REGEX = br'-{5}BEGIN (?P<type>.*?)-{5}\n'
84 PEM_TAGS = {
85 DataType.CRT: 'CERTIFICATE',
86 DataType.CRL: 'X509 CRL',
87 DataType.CSR: 'CERTIFICATE REQUEST'
88 }
89
Pengyu Lv8e6794a2023-04-18 17:00:47 +080090 def __init__(self,
91 backends:
92 typing.Dict[DataType,
93 typing.Dict[DataFormat,
94 typing.Callable[[bytes], object]]]) \
95 -> None:
Pengyu Lv7f6933a2023-04-04 16:05:54 +080096 self.backends = backends
97 self.__generate_parsers()
98
99 def __generate_parser(self, data_type: DataType):
100 """Parser generator for a specific DataType"""
101 tag = self.PEM_TAGS[data_type]
102 pem_loader = self.backends[data_type][DataFormat.PEM]
103 der_loader = self.backends[data_type][DataFormat.DER]
104 def wrapper(data: bytes):
105 pem_type = X509Parser.pem_data_type(data)
106 # It is in PEM format with target tag
107 if pem_type == tag:
108 return pem_loader(data)
109 # It is in PEM format without target tag
110 if pem_type:
111 return None
112 # It might be in DER format
113 try:
114 result = der_loader(data)
115 except ValueError:
116 result = None
117 return result
118 wrapper.__name__ = "{}.parser[{}]".format(type(self).__name__, tag)
119 return wrapper
120
121 def __generate_parsers(self):
122 """Generate parsers for all support DataType"""
123 self.parsers = {}
124 for data_type, _ in self.PEM_TAGS.items():
125 self.parsers[data_type] = self.__generate_parser(data_type)
126
127 def __getitem__(self, item):
128 return self.parsers[item]
129
130 @staticmethod
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800131 def pem_data_type(data: bytes) -> typing.Optional[str]:
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800132 """Get the tag from the data in PEM format
133
134 :param data: data to be checked in binary mode.
135 :return: PEM tag or "" when no tag detected.
136 """
137 m = re.search(X509Parser.PEM_TAG_REGEX, data)
138 if m is not None:
139 return m.group('type').decode('UTF-8')
140 else:
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800141 return None
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800142
Pengyu Lv30f26832023-04-07 18:04:07 +0800143 @staticmethod
144 def check_hex_string(hex_str: str) -> bool:
145 """Check if the hex string is possibly DER data."""
146 hex_len = len(hex_str)
147 # At least 6 hex char for 3 bytes: Type + Length + Content
148 if hex_len < 6:
149 return False
150 # Check if Type (1 byte) is SEQUENCE.
151 if hex_str[0:2] != '30':
152 return False
153 # Check LENGTH (1 byte) value
154 content_len = int(hex_str[2:4], base=16)
155 consumed = 4
156 if content_len in (128, 255):
157 # Indefinite or Reserved
158 return False
159 elif content_len > 127:
160 # Definite, Long
161 length_len = (content_len - 128) * 2
162 content_len = int(hex_str[consumed:consumed+length_len], base=16)
163 consumed += length_len
164 # Check LENGTH
165 if hex_len != content_len * 2 + consumed:
166 return False
167 return True
168
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800169class Auditor:
170 """A base class for audit."""
171 def __init__(self, verbose):
172 self.verbose = verbose
173 self.default_files = []
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800174 # A list to store the parsed audit_data.
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800175 self.audit_data = []
176 self.parser = X509Parser({
177 DataType.CRT: {
178 DataFormat.PEM: x509.load_pem_x509_certificate,
179 DataFormat.DER: x509.load_der_x509_certificate
180 },
181 DataType.CRL: {
182 DataFormat.PEM: x509.load_pem_x509_crl,
183 DataFormat.DER: x509.load_der_x509_crl
184 },
185 DataType.CSR: {
186 DataFormat.PEM: x509.load_pem_x509_csr,
187 DataFormat.DER: x509.load_der_x509_csr
188 },
189 })
190
191 def error(self, *args):
192 #pylint: disable=no-self-use
193 print("Error: ", *args, file=sys.stderr)
194
195 def warn(self, *args):
196 if self.verbose:
197 print("Warn: ", *args, file=sys.stderr)
198
199 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
222 self.warn(val_error)
223 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."""
241 if os.path.isdir('tests'):
242 tests_dir = 'tests'
243 elif os.path.isdir('suites'):
244 tests_dir = '.'
245 elif os.path.isdir('../suites'):
246 tests_dir = '..'
247 else:
248 raise Exception("Mbed TLS source tree not found")
249 return tests_dir
250
251class TestDataAuditor(Auditor):
252 """Class for auditing files in tests/data_files/"""
253 def __init__(self, verbose):
254 super().__init__(verbose)
255 self.default_files = self.collect_default_files()
256
257 def collect_default_files(self):
Pengyu Lv45e32032023-04-06 14:33:41 +0800258 """Collect all files in tests/data_files/"""
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800259 test_dir = self.find_test_dir()
Pengyu Lv8e6794a2023-04-18 17:00:47 +0800260 test_data_glob = os.path.join(test_dir, 'data_files/**')
261 data_files = [f for f in glob.glob(test_data_glob, recursive=True)
262 if os.path.isfile(f)]
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800263 return data_files
264
Pengyu Lv45e32032023-04-06 14:33:41 +0800265class SuiteDataAuditor(Auditor):
266 """Class for auditing files in tests/suites/*.data"""
267 def __init__(self, options):
268 super().__init__(options)
269 self.default_files = self.collect_default_files()
270
271 def collect_default_files(self):
272 """Collect all files in tests/suites/*.data"""
273 test_dir = self.find_test_dir()
274 suites_data_folder = os.path.join(test_dir, 'suites')
Pengyu Lv45e32032023-04-06 14:33:41 +0800275 data_files = glob.glob(os.path.join(suites_data_folder, '*.data'))
276 return data_files
277
278 def parse_file(self, filename: str):
Pengyu Lv30f26832023-04-07 18:04:07 +0800279 """
280 Parse a list of AuditData from file.
281
282 :param filename: name of the file to parse.
283 :return list of AuditData parsed from the file.
284 """
Pengyu Lv45e32032023-04-06 14:33:41 +0800285 audit_data_list = []
Pengyu Lv30f26832023-04-07 18:04:07 +0800286 data_f = FileWrapper(filename)
287 for _, _, _, test_args in parse_suite_data(data_f):
Pengyu Lv7725c1d2023-04-13 15:55:30 +0800288 for idx, test_arg in enumerate(test_args):
Pengyu Lv30f26832023-04-07 18:04:07 +0800289 match = re.match(r'"(?P<data>[0-9a-fA-F]+)"', test_arg)
290 if not match:
291 continue
292 if not X509Parser.check_hex_string(match.group('data')):
293 continue
294 audit_data = self.parse_bytes(bytes.fromhex(match.group('data')))
295 if audit_data is None:
296 continue
Pengyu Lvf8e5e052023-04-18 15:43:25 +0800297 audit_data.location = "{}:{}:#{}".format(filename,
298 data_f.line_no,
299 idx + 1)
Pengyu Lv30f26832023-04-07 18:04:07 +0800300 audit_data_list.append(audit_data)
301
Pengyu Lv45e32032023-04-06 14:33:41 +0800302 return audit_data_list
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800303
304def list_all(audit_data: AuditData):
305 print("{}\t{}\t{}\t{}".format(
306 audit_data.not_valid_before.isoformat(timespec='seconds'),
307 audit_data.not_valid_after.isoformat(timespec='seconds'),
308 audit_data.data_type.name,
Pengyu Lvf8e5e052023-04-18 15:43:25 +0800309 audit_data.location))
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800310
311def main():
312 """
313 Perform argument parsing.
314 """
Pengyu Lv57240952023-04-13 14:42:37 +0800315 parser = argparse.ArgumentParser(description=__doc__)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800316
317 parser.add_argument('-a', '--all',
318 action='store_true',
Pengyu Lv57240952023-04-13 14:42:37 +0800319 help='list the information of all the files')
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800320 parser.add_argument('-v', '--verbose',
321 action='store_true', dest='verbose',
Pengyu Lv57240952023-04-13 14:42:37 +0800322 help='show warnings')
Pengyu Lvebf011f2023-04-11 13:39:31 +0800323 parser.add_argument('--not-before', dest='not_before',
Pengyu Lv57240952023-04-13 14:42:37 +0800324 help=('not valid before this date (UTC, YYYY-MM-DD). '
325 'Default: today'),
Pengyu Lvebf011f2023-04-11 13:39:31 +0800326 metavar='DATE')
327 parser.add_argument('--not-after', dest='not_after',
Pengyu Lv57240952023-04-13 14:42:37 +0800328 help=('not valid after this date (UTC, YYYY-MM-DD). '
329 'Default: not-before'),
Pengyu Lvebf011f2023-04-11 13:39:31 +0800330 metavar='DATE')
Pengyu Lv57240952023-04-13 14:42:37 +0800331 parser.add_argument('files', nargs='*', help='files to audit',
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800332 metavar='FILE')
333
334 args = parser.parse_args()
335
336 # start main routine
337 td_auditor = TestDataAuditor(args.verbose)
Pengyu Lv45e32032023-04-06 14:33:41 +0800338 sd_auditor = SuiteDataAuditor(args.verbose)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800339
Pengyu Lv57240952023-04-13 14:42:37 +0800340 if args.files:
341 data_files = args.files
342 suite_data_files = args.files
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800343 else:
344 data_files = td_auditor.default_files
Pengyu Lv45e32032023-04-06 14:33:41 +0800345 suite_data_files = sd_auditor.default_files
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800346
Pengyu Lvebf011f2023-04-11 13:39:31 +0800347 if args.not_before:
348 not_before_date = datetime.datetime.fromisoformat(args.not_before)
349 else:
350 not_before_date = datetime.datetime.today()
351 if args.not_after:
352 not_after_date = datetime.datetime.fromisoformat(args.not_after)
353 else:
354 not_after_date = not_before_date
355
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800356 td_auditor.walk_all(data_files)
Pengyu Lv45e32032023-04-06 14:33:41 +0800357 sd_auditor.walk_all(suite_data_files)
Pengyu Lvebf011f2023-04-11 13:39:31 +0800358 audit_results = td_auditor.audit_data + sd_auditor.audit_data
359
Pengyu Lv57240952023-04-13 14:42:37 +0800360 # we filter out the files whose validity duration covers the provided
Pengyu Lvebf011f2023-04-11 13:39:31 +0800361 # duration.
362 filter_func = lambda d: (not_before_date < d.not_valid_before) or \
363 (d.not_valid_after < not_after_date)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800364
365 if args.all:
Pengyu Lvebf011f2023-04-11 13:39:31 +0800366 filter_func = None
367
368 for d in filter(filter_func, audit_results):
369 list_all(d)
Pengyu Lv7f6933a2023-04-04 16:05:54 +0800370
371 print("\nDone!\n")
372
373if __name__ == "__main__":
374 main()