blob: 9c674e5da943b9494f936853ad15032c4d87d59f [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'])
63 # Hard-coded value for an unknown hash algorithm
64 self.hash_algorithms = set(['0x010000ff'])
65 # Identifier prefixes
66 self.table_by_prefix = {
67 'ERROR': self.statuses,
68 'ALG': self.algorithms,
69 'CURVE': self.ecc_curves,
70 'KEY_TYPE': self.key_types,
71 'KEY_USAGE': self.key_usage_flags,
72 }
73 # macro name -> list of argument names
74 self.argspecs = {}
75 # argument name -> list of values
76 self.arguments_for = {}
77
78 def gather_arguments(self):
79 '''Populate the list of values for macro arguments.
80Call this after parsing all the inputs.'''
81 self.arguments_for['hash_alg'] = sorted(self.hash_algorithms)
82 self.arguments_for['curve'] = sorted(self.ecc_curves)
83
84 def format_arguments(self, name, arguments):
85 '''Format a macro call with arguments..'''
86 return name + '(' + ', '.join(arguments) + ')'
87
88 def distribute_arguments(self, name):
89 '''Generate macro calls with each tested argument set.
90If name is a macro without arguments, just yield "name".
91If name is a macro with arguments, yield a series of "name(arg1,...,argN)"
92where each argument takes each possible value at least once.'''
Gilles Peskinea0a315c2018-10-19 11:27:10 +020093 try:
94 if name not in self.argspecs:
95 yield name
96 return
97 argspec = self.argspecs[name]
98 if argspec == []:
99 yield name + '()'
100 return
101 argument_lists = [self.arguments_for[arg] for arg in argspec]
102 arguments = [values[0] for values in argument_lists]
103 yield self.format_arguments(name, arguments)
104 for i in range(len(arguments)):
105 for value in argument_lists[i][1:]:
106 arguments[i] = value
107 yield self.format_arguments(name, arguments)
Gilles Peskinef96ed662018-10-19 11:29:56 +0200108 arguments[i] = argument_lists[0][0]
Gilles Peskinea0a315c2018-10-19 11:27:10 +0200109 except BaseException as e:
110 raise Exception('distribute_arguments({})'.format(name)) from e
Gilles Peskine24827022018-09-25 18:49:23 +0200111
112 # Regex for interesting header lines.
113 # Groups: 1=macro name, 2=type, 3=argument list (optional).
114 header_line_re = \
115 re.compile(r'#define +' +
116 r'(PSA_((?:KEY_)?[A-Z]+)_\w+)' +
117 r'(?:\(([^\n()]*)\))?')
118 # Regex of macro names to exclude.
119 excluded_name_re = re.compile('_(?:GET|IS|OF)_|_(?:BASE|FLAG|MASK)\Z')
120 argument_split_re = re.compile(r' *, *')
121 def parse_header_line(self, line):
122 '''Parse a C header line, looking for "#define PSA_xxx".'''
123 m = re.match(self.header_line_re, line)
124 if not m:
125 return
126 name = m.group(1)
127 if re.search(self.excluded_name_re, name):
128 return
129 dest = self.table_by_prefix.get(m.group(2))
130 if dest is None:
131 return
132 dest.add(name)
133 if m.group(3):
134 self.argspecs[name] = re.split(self.argument_split_re, m.group(3))
135
136 def parse_header(self, filename):
137 '''Parse a C header file, looking for "#define PSA_xxx".'''
Gilles Peskinea0a315c2018-10-19 11:27:10 +0200138 with read_file_lines(filename) as lines:
139 for line in lines:
Gilles Peskine24827022018-09-25 18:49:23 +0200140 self.parse_header_line(line)
141
142 def add_test_case_line(self, function, argument):
143 '''Parse a test case data line, looking for algorithm metadata tests.'''
144 if function.endswith('_algorithm'):
145 self.algorithms.add(argument)
146 if function == 'hash_algorithm':
147 self.hash_algorithms.add(argument)
148 elif function == 'key_type':
149 self.key_types.add(argument)
150 elif function == 'ecc_key_types':
151 self.ecc_curves.add(argument)
152
153 # Regex matching a *.data line containing a test function call and
154 # its arguments. The actual definition is partly positional, but this
155 # regex is good enough in practice.
156 test_case_line_re = re.compile('(?!depends_on:)(\w+):([^\n :][^:\n]*)')
157 def parse_test_cases(self, filename):
158 '''Parse a test case file (*.data), looking for algorithm metadata tests.'''
Gilles Peskinea0a315c2018-10-19 11:27:10 +0200159 with read_file_lines(filename) as lines:
160 for line in lines:
Gilles Peskine24827022018-09-25 18:49:23 +0200161 m = re.match(self.test_case_line_re, line)
162 if m:
163 self.add_test_case_line(m.group(1), m.group(2))
164
165def gather_inputs(headers, test_suites):
166 '''Read the list of inputs to test psa_constant_names with.'''
167 inputs = Inputs()
168 for header in headers:
169 inputs.parse_header(header)
170 for test_cases in test_suites:
171 inputs.parse_test_cases(test_cases)
172 inputs.gather_arguments()
173 return inputs
174
175def remove_file_if_exists(filename):
176 '''Remove the specified file, ignoring errors.'''
177 if not filename:
178 return
179 try:
180 os.remove(filename)
181 except:
182 pass
183
Gilles Peskinecf9c18e2018-10-19 11:28:42 +0200184def run_c(options, type, names):
Gilles Peskine24827022018-09-25 18:49:23 +0200185 '''Generate and run a program to print out numerical values for names.'''
186 c_name = None
187 exe_name = None
188 try:
189 c_fd, c_name = tempfile.mkstemp(suffix='.c',
190 dir='programs/psa')
191 exe_suffix = '.exe' if platform.system() == 'Windows' else ''
192 exe_name = c_name[:-2] + exe_suffix
193 remove_file_if_exists(exe_name)
194 c_file = os.fdopen(c_fd, 'w', encoding='ascii')
195 c_file.write('''/* Generated by test_psa_constant_names.py */
196#include <stdio.h>
197#include <psa/crypto.h>
198int main(void)
199{
200''')
201 for name in names:
202 c_file.write(' printf("0x%08x\\n", {});\n'.format(name))
203 c_file.write(''' return 0;
204}
205''')
206 c_file.close()
207 cc = os.getenv('CC', 'cc')
208 subprocess.check_call([cc] +
209 ['-I' + dir for dir in options.include] +
210 ['-o', exe_name, c_name])
Gilles Peskinecf9c18e2018-10-19 11:28:42 +0200211 if options.keep_c:
212 sys.stderr.write('List of {} tests kept at {}\n'
213 .format(type, c_name))
214 else:
215 os.remove(c_name)
Gilles Peskine24827022018-09-25 18:49:23 +0200216 output = subprocess.check_output([exe_name])
217 return output.decode('ascii').strip().split('\n')
218 finally:
219 remove_file_if_exists(exe_name)
220
221normalize_strip_re = re.compile(r'\s+')
222def normalize(expr):
223 '''Normalize the C expression so as not to care about trivial differences.
224Currently "trivial differences" means whitespace.'''
225 expr = re.sub(normalize_strip_re, '', expr, len(expr))
226 return expr.strip().split('\n')
227
228def do_test(options, inputs, type, names):
229 '''Test psa_constant_names for the specified type.
230Run program on names.
231Use inputs to figure out what arguments to pass to macros that take arguments.'''
232 names = sorted(itertools.chain(*map(inputs.distribute_arguments, names)))
Gilles Peskinecf9c18e2018-10-19 11:28:42 +0200233 values = run_c(options, type, names)
Gilles Peskine24827022018-09-25 18:49:23 +0200234 output = subprocess.check_output([options.program, type] + values)
235 outputs = output.decode('ascii').strip().split('\n')
236 errors = [(type, name, value, output)
237 for (name, value, output) in zip(names, values, outputs)
238 if normalize(name) != normalize(output)]
239 return len(names), errors
240
241def report_errors(errors):
242 '''Describe each case where the output is not as expected.'''
243 for type, name, value, output in errors:
244 print('For {} "{}", got "{}" (value: {})'
245 .format(type, name, output, value))
246
247def run_tests(options, inputs):
248 '''Run psa_constant_names on all the gathered inputs.
249Return a tuple (count, errors) where count is the total number of inputs
250that were tested and errors is the list of cases where the output was
251not as expected.'''
252 count = 0
253 errors = []
254 for type, names in [('status', inputs.statuses),
255 ('algorithm', inputs.algorithms),
256 ('ecc_curve', inputs.ecc_curves),
257 ('key_type', inputs.key_types),
258 ('key_usage', inputs.key_usage_flags)]:
259 c, e = do_test(options, inputs, type, names)
260 count += c
261 errors += e
262 return count, errors
263
264if __name__ == '__main__':
265 parser = argparse.ArgumentParser(description=globals()['__doc__'])
266 parser.add_argument('--include', '-I',
267 action='append', default=['include'],
268 help='Directory for header files')
269 parser.add_argument('--program',
270 default='programs/psa/psa_constant_names',
271 help='Program to test')
Gilles Peskinecf9c18e2018-10-19 11:28:42 +0200272 parser.add_argument('--keep-c',
273 action='store_true', dest='keep_c', default=False,
274 help='Keep the intermediate C file')
275 parser.add_argument('--no-keep-c',
276 action='store_false', dest='keep_c',
277 help='Don\'t keep the intermediate C file (default)')
Gilles Peskine24827022018-09-25 18:49:23 +0200278 options = parser.parse_args()
279 headers = [os.path.join(options.include[0], 'psa/crypto.h')]
280 test_suites = ['tests/suites/test_suite_psa_crypto_metadata.data']
281 inputs = gather_inputs(headers, test_suites)
282 count, errors = run_tests(options, inputs)
283 report_errors(errors)
284 if errors == []:
285 print('{} test cases PASS'.format(count))
286 else:
287 print('{} test cases, {} FAIL'.format(count, len(errors)))
288 exit(1)