blob: 2d2e213ff6b462a0aade51477f535dd152bafd94 [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'])
61 self.key_types = set(['0xffffffff'])
62 self.key_usage_flags = set(['0x80000000'])
Gilles Peskine434899f2018-10-19 11:30:26 +020063 # Hard-coded value for unknown algorithms
Darryl Green61b7f612019-02-04 16:00:21 +000064 self.hash_algorithms = set(['0x010000fe'])
Gilles Peskine434899f2018-10-19 11:30:26 +020065 self.mac_algorithms = set(['0x02ff00ff'])
Gilles Peskine17542082019-01-04 19:46:31 +010066 self.kdf_algorithms = set(['0x300000ff', '0x310000ff'])
Gilles Peskine434899f2018-10-19 11:30:26 +020067 # For AEAD algorithms, the only variability is over the tag length,
68 # and this only applies to known algorithms, so don't test an
69 # unknown algorithm.
70 self.aead_algorithms = set()
Gilles Peskine24827022018-09-25 18:49:23 +020071 # Identifier prefixes
72 self.table_by_prefix = {
73 'ERROR': self.statuses,
74 'ALG': self.algorithms,
75 'CURVE': self.ecc_curves,
76 'KEY_TYPE': self.key_types,
77 'KEY_USAGE': self.key_usage_flags,
78 }
79 # macro name -> list of argument names
80 self.argspecs = {}
81 # argument name -> list of values
Gilles Peskine434899f2018-10-19 11:30:26 +020082 self.arguments_for = {
83 'mac_length': ['1', '63'],
84 'tag_length': ['1', '63'],
85 }
Gilles Peskine24827022018-09-25 18:49:23 +020086
87 def gather_arguments(self):
88 '''Populate the list of values for macro arguments.
89Call this after parsing all the inputs.'''
90 self.arguments_for['hash_alg'] = sorted(self.hash_algorithms)
Gilles Peskine434899f2018-10-19 11:30:26 +020091 self.arguments_for['mac_alg'] = sorted(self.mac_algorithms)
Gilles Peskine17542082019-01-04 19:46:31 +010092 self.arguments_for['kdf_alg'] = sorted(self.kdf_algorithms)
Gilles Peskine434899f2018-10-19 11:30:26 +020093 self.arguments_for['aead_alg'] = sorted(self.aead_algorithms)
Gilles Peskine24827022018-09-25 18:49:23 +020094 self.arguments_for['curve'] = sorted(self.ecc_curves)
95
96 def format_arguments(self, name, arguments):
97 '''Format a macro call with arguments..'''
98 return name + '(' + ', '.join(arguments) + ')'
99
100 def distribute_arguments(self, name):
101 '''Generate macro calls with each tested argument set.
102If name is a macro without arguments, just yield "name".
103If name is a macro with arguments, yield a series of "name(arg1,...,argN)"
104where each argument takes each possible value at least once.'''
Gilles Peskinea0a315c2018-10-19 11:27:10 +0200105 try:
106 if name not in self.argspecs:
107 yield name
108 return
109 argspec = self.argspecs[name]
110 if argspec == []:
111 yield name + '()'
112 return
113 argument_lists = [self.arguments_for[arg] for arg in argspec]
114 arguments = [values[0] for values in argument_lists]
115 yield self.format_arguments(name, arguments)
116 for i in range(len(arguments)):
117 for value in argument_lists[i][1:]:
118 arguments[i] = value
119 yield self.format_arguments(name, arguments)
Gilles Peskinef96ed662018-10-19 11:29:56 +0200120 arguments[i] = argument_lists[0][0]
Gilles Peskinea0a315c2018-10-19 11:27:10 +0200121 except BaseException as e:
122 raise Exception('distribute_arguments({})'.format(name)) from e
Gilles Peskine24827022018-09-25 18:49:23 +0200123
124 # Regex for interesting header lines.
125 # Groups: 1=macro name, 2=type, 3=argument list (optional).
126 header_line_re = \
127 re.compile(r'#define +' +
128 r'(PSA_((?:KEY_)?[A-Z]+)_\w+)' +
129 r'(?:\(([^\n()]*)\))?')
130 # Regex of macro names to exclude.
131 excluded_name_re = re.compile('_(?:GET|IS|OF)_|_(?:BASE|FLAG|MASK)\Z')
Gilles Peskinec68ce962018-10-19 11:31:52 +0200132 # Additional excluded macros.
133 excluded_names = set(['PSA_ALG_AEAD_WITH_DEFAULT_TAG_LENGTH',
Darryl Greenec079502019-01-29 15:48:00 +0000134 'PSA_ALG_FULL_LENGTH_MAC',
135 'PSA_ALG_ECDH',
136 'PSA_ALG_FFDH'])
Gilles Peskine24827022018-09-25 18:49:23 +0200137 argument_split_re = re.compile(r' *, *')
138 def parse_header_line(self, line):
139 '''Parse a C header line, looking for "#define PSA_xxx".'''
140 m = re.match(self.header_line_re, line)
141 if not m:
142 return
143 name = m.group(1)
Gilles Peskinec68ce962018-10-19 11:31:52 +0200144 if re.search(self.excluded_name_re, name) or \
145 name in self.excluded_names:
Gilles Peskine24827022018-09-25 18:49:23 +0200146 return
147 dest = self.table_by_prefix.get(m.group(2))
148 if dest is None:
149 return
150 dest.add(name)
151 if m.group(3):
152 self.argspecs[name] = re.split(self.argument_split_re, m.group(3))
153
154 def parse_header(self, filename):
155 '''Parse a C header file, looking for "#define PSA_xxx".'''
Gilles Peskinea0a315c2018-10-19 11:27:10 +0200156 with read_file_lines(filename) as lines:
157 for line in lines:
Gilles Peskine24827022018-09-25 18:49:23 +0200158 self.parse_header_line(line)
159
160 def add_test_case_line(self, function, argument):
161 '''Parse a test case data line, looking for algorithm metadata tests.'''
162 if function.endswith('_algorithm'):
Darryl Greenec079502019-01-29 15:48:00 +0000163 if 'ECDH' in argument or 'FFDH' in argument:
164 return
Gilles Peskine24827022018-09-25 18:49:23 +0200165 self.algorithms.add(argument)
166 if function == 'hash_algorithm':
167 self.hash_algorithms.add(argument)
Gilles Peskine434899f2018-10-19 11:30:26 +0200168 elif function in ['mac_algorithm', 'hmac_algorithm']:
169 self.mac_algorithms.add(argument)
170 elif function == 'aead_algorithm':
171 self.aead_algorithms.add(argument)
Gilles Peskine24827022018-09-25 18:49:23 +0200172 elif function == 'key_type':
173 self.key_types.add(argument)
174 elif function == 'ecc_key_types':
175 self.ecc_curves.add(argument)
176
177 # Regex matching a *.data line containing a test function call and
178 # its arguments. The actual definition is partly positional, but this
179 # regex is good enough in practice.
180 test_case_line_re = re.compile('(?!depends_on:)(\w+):([^\n :][^:\n]*)')
181 def parse_test_cases(self, filename):
182 '''Parse a test case file (*.data), looking for algorithm metadata tests.'''
Gilles Peskinea0a315c2018-10-19 11:27:10 +0200183 with read_file_lines(filename) as lines:
184 for line in lines:
Gilles Peskine24827022018-09-25 18:49:23 +0200185 m = re.match(self.test_case_line_re, line)
186 if m:
187 self.add_test_case_line(m.group(1), m.group(2))
188
189def gather_inputs(headers, test_suites):
190 '''Read the list of inputs to test psa_constant_names with.'''
191 inputs = Inputs()
192 for header in headers:
193 inputs.parse_header(header)
194 for test_cases in test_suites:
195 inputs.parse_test_cases(test_cases)
196 inputs.gather_arguments()
197 return inputs
198
199def remove_file_if_exists(filename):
200 '''Remove the specified file, ignoring errors.'''
201 if not filename:
202 return
203 try:
204 os.remove(filename)
205 except:
206 pass
207
Gilles Peskinecf9c18e2018-10-19 11:28:42 +0200208def run_c(options, type, names):
Gilles Peskine24827022018-09-25 18:49:23 +0200209 '''Generate and run a program to print out numerical values for names.'''
210 c_name = None
211 exe_name = None
212 try:
Gilles Peskine95ab71a2019-01-04 19:46:59 +0100213 c_fd, c_name = tempfile.mkstemp(prefix='tmp-{}-'.format(type),
214 suffix='.c',
Gilles Peskine24827022018-09-25 18:49:23 +0200215 dir='programs/psa')
216 exe_suffix = '.exe' if platform.system() == 'Windows' else ''
217 exe_name = c_name[:-2] + exe_suffix
218 remove_file_if_exists(exe_name)
219 c_file = os.fdopen(c_fd, 'w', encoding='ascii')
Gilles Peskine95ab71a2019-01-04 19:46:59 +0100220 c_file.write('/* Generated by test_psa_constant_names.py for {} values */'
221 .format(type))
222 c_file.write('''
Gilles Peskine24827022018-09-25 18:49:23 +0200223#include <stdio.h>
224#include <psa/crypto.h>
225int main(void)
226{
227''')
228 for name in names:
229 c_file.write(' printf("0x%08x\\n", {});\n'.format(name))
230 c_file.write(''' return 0;
231}
232''')
233 c_file.close()
234 cc = os.getenv('CC', 'cc')
235 subprocess.check_call([cc] +
236 ['-I' + dir for dir in options.include] +
237 ['-o', exe_name, c_name])
Gilles Peskinecf9c18e2018-10-19 11:28:42 +0200238 if options.keep_c:
239 sys.stderr.write('List of {} tests kept at {}\n'
240 .format(type, c_name))
241 else:
242 os.remove(c_name)
Gilles Peskine24827022018-09-25 18:49:23 +0200243 output = subprocess.check_output([exe_name])
244 return output.decode('ascii').strip().split('\n')
245 finally:
246 remove_file_if_exists(exe_name)
247
248normalize_strip_re = re.compile(r'\s+')
249def normalize(expr):
250 '''Normalize the C expression so as not to care about trivial differences.
251Currently "trivial differences" means whitespace.'''
252 expr = re.sub(normalize_strip_re, '', expr, len(expr))
253 return expr.strip().split('\n')
254
255def do_test(options, inputs, type, names):
256 '''Test psa_constant_names for the specified type.
257Run program on names.
258Use inputs to figure out what arguments to pass to macros that take arguments.'''
259 names = sorted(itertools.chain(*map(inputs.distribute_arguments, names)))
Gilles Peskinecf9c18e2018-10-19 11:28:42 +0200260 values = run_c(options, type, names)
Gilles Peskine24827022018-09-25 18:49:23 +0200261 output = subprocess.check_output([options.program, type] + values)
262 outputs = output.decode('ascii').strip().split('\n')
263 errors = [(type, name, value, output)
264 for (name, value, output) in zip(names, values, outputs)
265 if normalize(name) != normalize(output)]
266 return len(names), errors
267
268def report_errors(errors):
269 '''Describe each case where the output is not as expected.'''
270 for type, name, value, output in errors:
271 print('For {} "{}", got "{}" (value: {})'
272 .format(type, name, output, value))
273
274def run_tests(options, inputs):
275 '''Run psa_constant_names on all the gathered inputs.
276Return a tuple (count, errors) where count is the total number of inputs
277that were tested and errors is the list of cases where the output was
278not as expected.'''
279 count = 0
280 errors = []
281 for type, names in [('status', inputs.statuses),
282 ('algorithm', inputs.algorithms),
283 ('ecc_curve', inputs.ecc_curves),
284 ('key_type', inputs.key_types),
285 ('key_usage', inputs.key_usage_flags)]:
286 c, e = do_test(options, inputs, type, names)
287 count += c
288 errors += e
289 return count, errors
290
291if __name__ == '__main__':
292 parser = argparse.ArgumentParser(description=globals()['__doc__'])
293 parser.add_argument('--include', '-I',
294 action='append', default=['include'],
295 help='Directory for header files')
296 parser.add_argument('--program',
297 default='programs/psa/psa_constant_names',
298 help='Program to test')
Gilles Peskinecf9c18e2018-10-19 11:28:42 +0200299 parser.add_argument('--keep-c',
300 action='store_true', dest='keep_c', default=False,
301 help='Keep the intermediate C file')
302 parser.add_argument('--no-keep-c',
303 action='store_false', dest='keep_c',
304 help='Don\'t keep the intermediate C file (default)')
Gilles Peskine24827022018-09-25 18:49:23 +0200305 options = parser.parse_args()
Gilles Peskine6d194bd2019-01-04 19:44:59 +0100306 headers = [os.path.join(options.include[0], 'psa', h)
307 for h in ['crypto.h', 'crypto_extra.h', 'crypto_values.h']]
Gilles Peskine24827022018-09-25 18:49:23 +0200308 test_suites = ['tests/suites/test_suite_psa_crypto_metadata.data']
309 inputs = gather_inputs(headers, test_suites)
310 count, errors = run_tests(options, inputs)
311 report_errors(errors)
312 if errors == []:
313 print('{} test cases PASS'.format(count))
314 else:
315 print('{} test cases, {} FAIL'.format(count, len(errors)))
316 exit(1)