blob: cbe68b10d2df646705f26a52b21f5e691ac4d616 [file] [log] [blame]
Gilles Peskine24827022018-09-25 18:49:23 +02001#!/usr/bin/env python3
2'''Test the program psa_constant_names.
3Gather constant names from header files and test cases. Compile a C program
4to print out their numerical values, feed these numerical values to
5psa_constant_names, and check that the output is the original name.
6Return 0 if all test cases pass, 1 if the output was not always as expected,
7or 1 (with a Python backtrace) if there was an operational error.'''
8
9import argparse
10import itertools
11import os
12import platform
13import re
14import subprocess
15import sys
16import tempfile
17
Gilles Peskinea0a315c2018-10-19 11:27:10 +020018class ReadFileLineException(Exception):
19 def __init__(self, filename, line_number):
20 message = 'in {} at {}'.format(filename, line_number)
21 super(ReadFileLineException, self).__init__(message)
22 self.filename = filename
23 self.line_number = line_number
24
25class read_file_lines:
26 '''Context manager to read a text file line by line.
27with read_file_lines(filename) as lines:
28 for line in lines:
29 process(line)
30is equivalent to
31with open(filename, 'r') as input_file:
32 for line in input_file:
33 process(line)
34except that if process(line) raises an exception, then the read_file_lines
35snippet annotates the exception with the file name and line number.'''
36 def __init__(self, filename):
37 self.filename = filename
38 self.line_number = 'entry'
39 def __enter__(self):
40 self.generator = enumerate(open(self.filename, 'r'))
41 return self
42 def __iter__(self):
43 for line_number, content in self.generator:
44 self.line_number = line_number
45 yield content
46 self.line_number = 'exit'
47 def __exit__(self, type, value, traceback):
48 if type is not None:
49 raise ReadFileLineException(self.filename, self.line_number) \
50 from value
51
Gilles Peskine24827022018-09-25 18:49:23 +020052class Inputs:
53 '''Accumulate information about macros to test.
54This includes macro names as well as information about their arguments
55when applicable.'''
56 def __init__(self):
57 # Sets of names per type
58 self.statuses = set(['PSA_SUCCESS'])
59 self.algorithms = set(['0xffffffff'])
60 self.ecc_curves = set(['0xffff'])
Gilles Peskinedcaefae2019-05-16 12:55:35 +020061 self.dh_groups = set(['0xffff'])
Gilles Peskine24827022018-09-25 18:49:23 +020062 self.key_types = set(['0xffffffff'])
63 self.key_usage_flags = set(['0x80000000'])
Gilles Peskine434899f2018-10-19 11:30:26 +020064 # Hard-coded value for unknown algorithms
Darryl Green61b7f612019-02-04 16:00:21 +000065 self.hash_algorithms = set(['0x010000fe'])
Gilles Peskine434899f2018-10-19 11:30:26 +020066 self.mac_algorithms = set(['0x02ff00ff'])
Gilles Peskine882e57e2019-04-12 00:12:07 +020067 self.ka_algorithms = set(['0x30fc0000'])
68 self.kdf_algorithms = set(['0x200000ff'])
Gilles Peskine434899f2018-10-19 11:30:26 +020069 # For AEAD algorithms, the only variability is over the tag length,
70 # and this only applies to known algorithms, so don't test an
71 # unknown algorithm.
72 self.aead_algorithms = set()
Gilles Peskine24827022018-09-25 18:49:23 +020073 # Identifier prefixes
74 self.table_by_prefix = {
75 'ERROR': self.statuses,
76 'ALG': self.algorithms,
77 'CURVE': self.ecc_curves,
Gilles Peskinedcaefae2019-05-16 12:55:35 +020078 'GROUP': self.dh_groups,
Gilles Peskine24827022018-09-25 18:49:23 +020079 'KEY_TYPE': self.key_types,
80 'KEY_USAGE': self.key_usage_flags,
81 }
82 # macro name -> list of argument names
83 self.argspecs = {}
84 # argument name -> list of values
Gilles Peskine434899f2018-10-19 11:30:26 +020085 self.arguments_for = {
86 'mac_length': ['1', '63'],
87 'tag_length': ['1', '63'],
88 }
Gilles Peskine24827022018-09-25 18:49:23 +020089
90 def gather_arguments(self):
91 '''Populate the list of values for macro arguments.
92Call this after parsing all the inputs.'''
93 self.arguments_for['hash_alg'] = sorted(self.hash_algorithms)
Gilles Peskine434899f2018-10-19 11:30:26 +020094 self.arguments_for['mac_alg'] = sorted(self.mac_algorithms)
Gilles Peskine882e57e2019-04-12 00:12:07 +020095 self.arguments_for['ka_alg'] = sorted(self.ka_algorithms)
Gilles Peskine17542082019-01-04 19:46:31 +010096 self.arguments_for['kdf_alg'] = sorted(self.kdf_algorithms)
Gilles Peskine434899f2018-10-19 11:30:26 +020097 self.arguments_for['aead_alg'] = sorted(self.aead_algorithms)
Gilles Peskine24827022018-09-25 18:49:23 +020098 self.arguments_for['curve'] = sorted(self.ecc_curves)
Gilles Peskinedcaefae2019-05-16 12:55:35 +020099 self.arguments_for['group'] = sorted(self.dh_groups)
Gilles Peskine24827022018-09-25 18:49:23 +0200100
101 def format_arguments(self, name, arguments):
102 '''Format a macro call with arguments..'''
103 return name + '(' + ', '.join(arguments) + ')'
104
105 def distribute_arguments(self, name):
106 '''Generate macro calls with each tested argument set.
107If name is a macro without arguments, just yield "name".
108If name is a macro with arguments, yield a series of "name(arg1,...,argN)"
109where each argument takes each possible value at least once.'''
Gilles Peskinea0a315c2018-10-19 11:27:10 +0200110 try:
111 if name not in self.argspecs:
112 yield name
113 return
114 argspec = self.argspecs[name]
115 if argspec == []:
116 yield name + '()'
117 return
118 argument_lists = [self.arguments_for[arg] for arg in argspec]
119 arguments = [values[0] for values in argument_lists]
120 yield self.format_arguments(name, arguments)
121 for i in range(len(arguments)):
122 for value in argument_lists[i][1:]:
123 arguments[i] = value
124 yield self.format_arguments(name, arguments)
Gilles Peskinef96ed662018-10-19 11:29:56 +0200125 arguments[i] = argument_lists[0][0]
Gilles Peskinea0a315c2018-10-19 11:27:10 +0200126 except BaseException as e:
127 raise Exception('distribute_arguments({})'.format(name)) from e
Gilles Peskine24827022018-09-25 18:49:23 +0200128
129 # Regex for interesting header lines.
130 # Groups: 1=macro name, 2=type, 3=argument list (optional).
131 header_line_re = \
132 re.compile(r'#define +' +
133 r'(PSA_((?:KEY_)?[A-Z]+)_\w+)' +
134 r'(?:\(([^\n()]*)\))?')
135 # Regex of macro names to exclude.
136 excluded_name_re = re.compile('_(?:GET|IS|OF)_|_(?:BASE|FLAG|MASK)\Z')
Gilles Peskinec68ce962018-10-19 11:31:52 +0200137 # Additional excluded macros.
Darryl Greenb8fe0682019-02-06 13:21:31 +0000138 # PSA_ALG_ECDH and PSA_ALG_FFDH are excluded for now as the script
Jaeden Amero5e6d24c2019-02-21 10:41:29 +0000139 # currently doesn't support them. Deprecated errors are also excluded.
Gilles Peskinec68ce962018-10-19 11:31:52 +0200140 excluded_names = set(['PSA_ALG_AEAD_WITH_DEFAULT_TAG_LENGTH',
Darryl Greenec079502019-01-29 15:48:00 +0000141 'PSA_ALG_FULL_LENGTH_MAC',
142 'PSA_ALG_ECDH',
Jaeden Amero5e6d24c2019-02-21 10:41:29 +0000143 'PSA_ALG_FFDH',
144 'PSA_ERROR_UNKNOWN_ERROR',
145 'PSA_ERROR_OCCUPIED_SLOT',
146 'PSA_ERROR_EMPTY_SLOT',
147 'PSA_ERROR_INSUFFICIENT_CAPACITY',
148 ])
Gilles Peskine24827022018-09-25 18:49:23 +0200149 argument_split_re = re.compile(r' *, *')
150 def parse_header_line(self, line):
151 '''Parse a C header line, looking for "#define PSA_xxx".'''
152 m = re.match(self.header_line_re, line)
153 if not m:
154 return
155 name = m.group(1)
Gilles Peskinec68ce962018-10-19 11:31:52 +0200156 if re.search(self.excluded_name_re, name) or \
157 name in self.excluded_names:
Gilles Peskine24827022018-09-25 18:49:23 +0200158 return
159 dest = self.table_by_prefix.get(m.group(2))
160 if dest is None:
161 return
162 dest.add(name)
163 if m.group(3):
164 self.argspecs[name] = re.split(self.argument_split_re, m.group(3))
165
166 def parse_header(self, filename):
167 '''Parse a C header file, looking for "#define PSA_xxx".'''
Gilles Peskinea0a315c2018-10-19 11:27:10 +0200168 with read_file_lines(filename) as lines:
169 for line in lines:
Gilles Peskine24827022018-09-25 18:49:23 +0200170 self.parse_header_line(line)
171
172 def add_test_case_line(self, function, argument):
173 '''Parse a test case data line, looking for algorithm metadata tests.'''
174 if function.endswith('_algorithm'):
Darryl Greenb8fe0682019-02-06 13:21:31 +0000175 # As above, ECDH and FFDH algorithms are excluded for now.
176 # Support for them will be added in the future.
Darryl Greenec079502019-01-29 15:48:00 +0000177 if 'ECDH' in argument or 'FFDH' in argument:
178 return
Gilles Peskine24827022018-09-25 18:49:23 +0200179 self.algorithms.add(argument)
180 if function == 'hash_algorithm':
181 self.hash_algorithms.add(argument)
Gilles Peskine434899f2018-10-19 11:30:26 +0200182 elif function in ['mac_algorithm', 'hmac_algorithm']:
183 self.mac_algorithms.add(argument)
184 elif function == 'aead_algorithm':
185 self.aead_algorithms.add(argument)
Gilles Peskine24827022018-09-25 18:49:23 +0200186 elif function == 'key_type':
187 self.key_types.add(argument)
188 elif function == 'ecc_key_types':
189 self.ecc_curves.add(argument)
Gilles Peskinedcaefae2019-05-16 12:55:35 +0200190 elif function == 'dh_key_types':
191 self.dh_groups.add(argument)
Gilles Peskine24827022018-09-25 18:49:23 +0200192
193 # Regex matching a *.data line containing a test function call and
194 # its arguments. The actual definition is partly positional, but this
195 # regex is good enough in practice.
196 test_case_line_re = re.compile('(?!depends_on:)(\w+):([^\n :][^:\n]*)')
197 def parse_test_cases(self, filename):
198 '''Parse a test case file (*.data), looking for algorithm metadata tests.'''
Gilles Peskinea0a315c2018-10-19 11:27:10 +0200199 with read_file_lines(filename) as lines:
200 for line in lines:
Gilles Peskine24827022018-09-25 18:49:23 +0200201 m = re.match(self.test_case_line_re, line)
202 if m:
203 self.add_test_case_line(m.group(1), m.group(2))
204
205def gather_inputs(headers, test_suites):
206 '''Read the list of inputs to test psa_constant_names with.'''
207 inputs = Inputs()
208 for header in headers:
209 inputs.parse_header(header)
210 for test_cases in test_suites:
211 inputs.parse_test_cases(test_cases)
212 inputs.gather_arguments()
213 return inputs
214
215def remove_file_if_exists(filename):
216 '''Remove the specified file, ignoring errors.'''
217 if not filename:
218 return
219 try:
220 os.remove(filename)
221 except:
222 pass
223
Gilles Peskinecf9c18e2018-10-19 11:28:42 +0200224def run_c(options, type, names):
Gilles Peskine24827022018-09-25 18:49:23 +0200225 '''Generate and run a program to print out numerical values for names.'''
Gilles Peskinec4cd2ad2019-02-13 18:42:53 +0100226 if type == 'status':
227 cast_to = 'long'
228 printf_format = '%ld'
229 else:
230 cast_to = 'unsigned long'
231 printf_format = '0x%08lx'
Gilles Peskine24827022018-09-25 18:49:23 +0200232 c_name = None
233 exe_name = None
234 try:
Gilles Peskine95ab71a2019-01-04 19:46:59 +0100235 c_fd, c_name = tempfile.mkstemp(prefix='tmp-{}-'.format(type),
236 suffix='.c',
Gilles Peskine24827022018-09-25 18:49:23 +0200237 dir='programs/psa')
238 exe_suffix = '.exe' if platform.system() == 'Windows' else ''
239 exe_name = c_name[:-2] + exe_suffix
240 remove_file_if_exists(exe_name)
241 c_file = os.fdopen(c_fd, 'w', encoding='ascii')
Gilles Peskine95ab71a2019-01-04 19:46:59 +0100242 c_file.write('/* Generated by test_psa_constant_names.py for {} values */'
243 .format(type))
244 c_file.write('''
Gilles Peskine24827022018-09-25 18:49:23 +0200245#include <stdio.h>
246#include <psa/crypto.h>
247int main(void)
248{
249''')
250 for name in names:
Gilles Peskinec4cd2ad2019-02-13 18:42:53 +0100251 c_file.write(' printf("{}\\n", ({}) {});\n'
252 .format(printf_format, cast_to, name))
Gilles Peskine24827022018-09-25 18:49:23 +0200253 c_file.write(''' return 0;
254}
255''')
256 c_file.close()
257 cc = os.getenv('CC', 'cc')
258 subprocess.check_call([cc] +
259 ['-I' + dir for dir in options.include] +
260 ['-o', exe_name, c_name])
Gilles Peskinecf9c18e2018-10-19 11:28:42 +0200261 if options.keep_c:
262 sys.stderr.write('List of {} tests kept at {}\n'
263 .format(type, c_name))
264 else:
265 os.remove(c_name)
Gilles Peskine24827022018-09-25 18:49:23 +0200266 output = subprocess.check_output([exe_name])
267 return output.decode('ascii').strip().split('\n')
268 finally:
269 remove_file_if_exists(exe_name)
270
271normalize_strip_re = re.compile(r'\s+')
272def normalize(expr):
273 '''Normalize the C expression so as not to care about trivial differences.
274Currently "trivial differences" means whitespace.'''
275 expr = re.sub(normalize_strip_re, '', expr, len(expr))
276 return expr.strip().split('\n')
277
278def do_test(options, inputs, type, names):
279 '''Test psa_constant_names for the specified type.
280Run program on names.
281Use inputs to figure out what arguments to pass to macros that take arguments.'''
282 names = sorted(itertools.chain(*map(inputs.distribute_arguments, names)))
Gilles Peskinecf9c18e2018-10-19 11:28:42 +0200283 values = run_c(options, type, names)
Gilles Peskine24827022018-09-25 18:49:23 +0200284 output = subprocess.check_output([options.program, type] + values)
285 outputs = output.decode('ascii').strip().split('\n')
286 errors = [(type, name, value, output)
287 for (name, value, output) in zip(names, values, outputs)
288 if normalize(name) != normalize(output)]
289 return len(names), errors
290
291def report_errors(errors):
292 '''Describe each case where the output is not as expected.'''
293 for type, name, value, output in errors:
294 print('For {} "{}", got "{}" (value: {})'
295 .format(type, name, output, value))
296
297def run_tests(options, inputs):
298 '''Run psa_constant_names on all the gathered inputs.
299Return a tuple (count, errors) where count is the total number of inputs
300that were tested and errors is the list of cases where the output was
301not as expected.'''
302 count = 0
303 errors = []
304 for type, names in [('status', inputs.statuses),
305 ('algorithm', inputs.algorithms),
306 ('ecc_curve', inputs.ecc_curves),
Gilles Peskinedcaefae2019-05-16 12:55:35 +0200307 ('dh_group', inputs.dh_groups),
Gilles Peskine24827022018-09-25 18:49:23 +0200308 ('key_type', inputs.key_types),
309 ('key_usage', inputs.key_usage_flags)]:
310 c, e = do_test(options, inputs, type, names)
311 count += c
312 errors += e
313 return count, errors
314
315if __name__ == '__main__':
316 parser = argparse.ArgumentParser(description=globals()['__doc__'])
317 parser.add_argument('--include', '-I',
318 action='append', default=['include'],
319 help='Directory for header files')
320 parser.add_argument('--program',
321 default='programs/psa/psa_constant_names',
322 help='Program to test')
Gilles Peskinecf9c18e2018-10-19 11:28:42 +0200323 parser.add_argument('--keep-c',
324 action='store_true', dest='keep_c', default=False,
325 help='Keep the intermediate C file')
326 parser.add_argument('--no-keep-c',
327 action='store_false', dest='keep_c',
328 help='Don\'t keep the intermediate C file (default)')
Gilles Peskine24827022018-09-25 18:49:23 +0200329 options = parser.parse_args()
Gilles Peskine6d194bd2019-01-04 19:44:59 +0100330 headers = [os.path.join(options.include[0], 'psa', h)
331 for h in ['crypto.h', 'crypto_extra.h', 'crypto_values.h']]
Gilles Peskine24827022018-09-25 18:49:23 +0200332 test_suites = ['tests/suites/test_suite_psa_crypto_metadata.data']
333 inputs = gather_inputs(headers, test_suites)
334 count, errors = run_tests(options, inputs)
335 report_errors(errors)
336 if errors == []:
337 print('{} test cases PASS'.format(count))
338 else:
339 print('{} test cases, {} FAIL'.format(count, len(errors)))
340 exit(1)