blob: d8f00050fe93b83a8233fe158a8b2a87b20c4e58 [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
Gilles Peskine24827022018-09-25 18:49:23 +020064 self.hash_algorithms = set(['0x010000ff'])
Gilles Peskine434899f2018-10-19 11:30:26 +020065 self.mac_algorithms = set(['0x02ff00ff'])
66 # For AEAD algorithms, the only variability is over the tag length,
67 # and this only applies to known algorithms, so don't test an
68 # unknown algorithm.
69 self.aead_algorithms = set()
Gilles Peskine24827022018-09-25 18:49:23 +020070 # Identifier prefixes
71 self.table_by_prefix = {
72 'ERROR': self.statuses,
73 'ALG': self.algorithms,
74 'CURVE': self.ecc_curves,
75 'KEY_TYPE': self.key_types,
76 'KEY_USAGE': self.key_usage_flags,
77 }
78 # macro name -> list of argument names
79 self.argspecs = {}
80 # argument name -> list of values
Gilles Peskine434899f2018-10-19 11:30:26 +020081 self.arguments_for = {
82 'mac_length': ['1', '63'],
83 'tag_length': ['1', '63'],
84 }
Gilles Peskine24827022018-09-25 18:49:23 +020085
86 def gather_arguments(self):
87 '''Populate the list of values for macro arguments.
88Call this after parsing all the inputs.'''
89 self.arguments_for['hash_alg'] = sorted(self.hash_algorithms)
Gilles Peskine434899f2018-10-19 11:30:26 +020090 self.arguments_for['mac_alg'] = sorted(self.mac_algorithms)
91 self.arguments_for['aead_alg'] = sorted(self.aead_algorithms)
Gilles Peskine24827022018-09-25 18:49:23 +020092 self.arguments_for['curve'] = sorted(self.ecc_curves)
93
94 def format_arguments(self, name, arguments):
95 '''Format a macro call with arguments..'''
96 return name + '(' + ', '.join(arguments) + ')'
97
98 def distribute_arguments(self, name):
99 '''Generate macro calls with each tested argument set.
100If name is a macro without arguments, just yield "name".
101If name is a macro with arguments, yield a series of "name(arg1,...,argN)"
102where each argument takes each possible value at least once.'''
Gilles Peskinea0a315c2018-10-19 11:27:10 +0200103 try:
104 if name not in self.argspecs:
105 yield name
106 return
107 argspec = self.argspecs[name]
108 if argspec == []:
109 yield name + '()'
110 return
111 argument_lists = [self.arguments_for[arg] for arg in argspec]
112 arguments = [values[0] for values in argument_lists]
113 yield self.format_arguments(name, arguments)
114 for i in range(len(arguments)):
115 for value in argument_lists[i][1:]:
116 arguments[i] = value
117 yield self.format_arguments(name, arguments)
Gilles Peskinef96ed662018-10-19 11:29:56 +0200118 arguments[i] = argument_lists[0][0]
Gilles Peskinea0a315c2018-10-19 11:27:10 +0200119 except BaseException as e:
120 raise Exception('distribute_arguments({})'.format(name)) from e
Gilles Peskine24827022018-09-25 18:49:23 +0200121
122 # Regex for interesting header lines.
123 # Groups: 1=macro name, 2=type, 3=argument list (optional).
124 header_line_re = \
125 re.compile(r'#define +' +
126 r'(PSA_((?:KEY_)?[A-Z]+)_\w+)' +
127 r'(?:\(([^\n()]*)\))?')
128 # Regex of macro names to exclude.
129 excluded_name_re = re.compile('_(?:GET|IS|OF)_|_(?:BASE|FLAG|MASK)\Z')
Gilles Peskinec68ce962018-10-19 11:31:52 +0200130 # Additional excluded macros.
131 excluded_names = set(['PSA_ALG_AEAD_WITH_DEFAULT_TAG_LENGTH',
132 'PSA_ALG_FULL_LENGTH_MAC'])
Gilles Peskine24827022018-09-25 18:49:23 +0200133 argument_split_re = re.compile(r' *, *')
134 def parse_header_line(self, line):
135 '''Parse a C header line, looking for "#define PSA_xxx".'''
136 m = re.match(self.header_line_re, line)
137 if not m:
138 return
139 name = m.group(1)
Gilles Peskinec68ce962018-10-19 11:31:52 +0200140 if re.search(self.excluded_name_re, name) or \
141 name in self.excluded_names:
Gilles Peskine24827022018-09-25 18:49:23 +0200142 return
143 dest = self.table_by_prefix.get(m.group(2))
144 if dest is None:
145 return
146 dest.add(name)
147 if m.group(3):
148 self.argspecs[name] = re.split(self.argument_split_re, m.group(3))
149
150 def parse_header(self, filename):
151 '''Parse a C header file, looking for "#define PSA_xxx".'''
Gilles Peskinea0a315c2018-10-19 11:27:10 +0200152 with read_file_lines(filename) as lines:
153 for line in lines:
Gilles Peskine24827022018-09-25 18:49:23 +0200154 self.parse_header_line(line)
155
156 def add_test_case_line(self, function, argument):
157 '''Parse a test case data line, looking for algorithm metadata tests.'''
158 if function.endswith('_algorithm'):
159 self.algorithms.add(argument)
160 if function == 'hash_algorithm':
161 self.hash_algorithms.add(argument)
Gilles Peskine434899f2018-10-19 11:30:26 +0200162 elif function in ['mac_algorithm', 'hmac_algorithm']:
163 self.mac_algorithms.add(argument)
164 elif function == 'aead_algorithm':
165 self.aead_algorithms.add(argument)
Gilles Peskine24827022018-09-25 18:49:23 +0200166 elif function == 'key_type':
167 self.key_types.add(argument)
168 elif function == 'ecc_key_types':
169 self.ecc_curves.add(argument)
170
171 # Regex matching a *.data line containing a test function call and
172 # its arguments. The actual definition is partly positional, but this
173 # regex is good enough in practice.
174 test_case_line_re = re.compile('(?!depends_on:)(\w+):([^\n :][^:\n]*)')
175 def parse_test_cases(self, filename):
176 '''Parse a test case file (*.data), looking for algorithm metadata tests.'''
Gilles Peskinea0a315c2018-10-19 11:27:10 +0200177 with read_file_lines(filename) as lines:
178 for line in lines:
Gilles Peskine24827022018-09-25 18:49:23 +0200179 m = re.match(self.test_case_line_re, line)
180 if m:
181 self.add_test_case_line(m.group(1), m.group(2))
182
183def gather_inputs(headers, test_suites):
184 '''Read the list of inputs to test psa_constant_names with.'''
185 inputs = Inputs()
186 for header in headers:
187 inputs.parse_header(header)
188 for test_cases in test_suites:
189 inputs.parse_test_cases(test_cases)
190 inputs.gather_arguments()
191 return inputs
192
193def remove_file_if_exists(filename):
194 '''Remove the specified file, ignoring errors.'''
195 if not filename:
196 return
197 try:
198 os.remove(filename)
199 except:
200 pass
201
Gilles Peskinecf9c18e2018-10-19 11:28:42 +0200202def run_c(options, type, names):
Gilles Peskine24827022018-09-25 18:49:23 +0200203 '''Generate and run a program to print out numerical values for names.'''
204 c_name = None
205 exe_name = None
206 try:
207 c_fd, c_name = tempfile.mkstemp(suffix='.c',
208 dir='programs/psa')
209 exe_suffix = '.exe' if platform.system() == 'Windows' else ''
210 exe_name = c_name[:-2] + exe_suffix
211 remove_file_if_exists(exe_name)
212 c_file = os.fdopen(c_fd, 'w', encoding='ascii')
213 c_file.write('''/* Generated by test_psa_constant_names.py */
214#include <stdio.h>
215#include <psa/crypto.h>
216int main(void)
217{
218''')
219 for name in names:
220 c_file.write(' printf("0x%08x\\n", {});\n'.format(name))
221 c_file.write(''' return 0;
222}
223''')
224 c_file.close()
225 cc = os.getenv('CC', 'cc')
226 subprocess.check_call([cc] +
227 ['-I' + dir for dir in options.include] +
228 ['-o', exe_name, c_name])
Gilles Peskinecf9c18e2018-10-19 11:28:42 +0200229 if options.keep_c:
230 sys.stderr.write('List of {} tests kept at {}\n'
231 .format(type, c_name))
232 else:
233 os.remove(c_name)
Gilles Peskine24827022018-09-25 18:49:23 +0200234 output = subprocess.check_output([exe_name])
235 return output.decode('ascii').strip().split('\n')
236 finally:
237 remove_file_if_exists(exe_name)
238
239normalize_strip_re = re.compile(r'\s+')
240def normalize(expr):
241 '''Normalize the C expression so as not to care about trivial differences.
242Currently "trivial differences" means whitespace.'''
243 expr = re.sub(normalize_strip_re, '', expr, len(expr))
244 return expr.strip().split('\n')
245
246def do_test(options, inputs, type, names):
247 '''Test psa_constant_names for the specified type.
248Run program on names.
249Use inputs to figure out what arguments to pass to macros that take arguments.'''
250 names = sorted(itertools.chain(*map(inputs.distribute_arguments, names)))
Gilles Peskinecf9c18e2018-10-19 11:28:42 +0200251 values = run_c(options, type, names)
Gilles Peskine24827022018-09-25 18:49:23 +0200252 output = subprocess.check_output([options.program, type] + values)
253 outputs = output.decode('ascii').strip().split('\n')
254 errors = [(type, name, value, output)
255 for (name, value, output) in zip(names, values, outputs)
256 if normalize(name) != normalize(output)]
257 return len(names), errors
258
259def report_errors(errors):
260 '''Describe each case where the output is not as expected.'''
261 for type, name, value, output in errors:
262 print('For {} "{}", got "{}" (value: {})'
263 .format(type, name, output, value))
264
265def run_tests(options, inputs):
266 '''Run psa_constant_names on all the gathered inputs.
267Return a tuple (count, errors) where count is the total number of inputs
268that were tested and errors is the list of cases where the output was
269not as expected.'''
270 count = 0
271 errors = []
272 for type, names in [('status', inputs.statuses),
273 ('algorithm', inputs.algorithms),
274 ('ecc_curve', inputs.ecc_curves),
275 ('key_type', inputs.key_types),
276 ('key_usage', inputs.key_usage_flags)]:
277 c, e = do_test(options, inputs, type, names)
278 count += c
279 errors += e
280 return count, errors
281
282if __name__ == '__main__':
283 parser = argparse.ArgumentParser(description=globals()['__doc__'])
284 parser.add_argument('--include', '-I',
285 action='append', default=['include'],
286 help='Directory for header files')
287 parser.add_argument('--program',
288 default='programs/psa/psa_constant_names',
289 help='Program to test')
Gilles Peskinecf9c18e2018-10-19 11:28:42 +0200290 parser.add_argument('--keep-c',
291 action='store_true', dest='keep_c', default=False,
292 help='Keep the intermediate C file')
293 parser.add_argument('--no-keep-c',
294 action='store_false', dest='keep_c',
295 help='Don\'t keep the intermediate C file (default)')
Gilles Peskine24827022018-09-25 18:49:23 +0200296 options = parser.parse_args()
Gilles Peskine6d194bd2019-01-04 19:44:59 +0100297 headers = [os.path.join(options.include[0], 'psa', h)
298 for h in ['crypto.h', 'crypto_extra.h', 'crypto_values.h']]
Gilles Peskine24827022018-09-25 18:49:23 +0200299 test_suites = ['tests/suites/test_suite_psa_crypto_metadata.data']
300 inputs = gather_inputs(headers, test_suites)
301 count, errors = run_tests(options, inputs)
302 report_errors(errors)
303 if errors == []:
304 print('{} test cases PASS'.format(count))
305 else:
306 print('{} test cases, {} FAIL'.format(count, len(errors)))
307 exit(1)