blob: 59292428faf83cf31a92b1e836d66c43c76fb70d [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
18class Inputs:
19 '''Accumulate information about macros to test.
20This includes macro names as well as information about their arguments
21when applicable.'''
22 def __init__(self):
23 # Sets of names per type
24 self.statuses = set(['PSA_SUCCESS'])
25 self.algorithms = set(['0xffffffff'])
26 self.ecc_curves = set(['0xffff'])
27 self.key_types = set(['0xffffffff'])
28 self.key_usage_flags = set(['0x80000000'])
29 # Hard-coded value for an unknown hash algorithm
30 self.hash_algorithms = set(['0x010000ff'])
31 # Identifier prefixes
32 self.table_by_prefix = {
33 'ERROR': self.statuses,
34 'ALG': self.algorithms,
35 'CURVE': self.ecc_curves,
36 'KEY_TYPE': self.key_types,
37 'KEY_USAGE': self.key_usage_flags,
38 }
39 # macro name -> list of argument names
40 self.argspecs = {}
41 # argument name -> list of values
42 self.arguments_for = {}
43
44 def gather_arguments(self):
45 '''Populate the list of values for macro arguments.
46Call this after parsing all the inputs.'''
47 self.arguments_for['hash_alg'] = sorted(self.hash_algorithms)
48 self.arguments_for['curve'] = sorted(self.ecc_curves)
49
50 def format_arguments(self, name, arguments):
51 '''Format a macro call with arguments..'''
52 return name + '(' + ', '.join(arguments) + ')'
53
54 def distribute_arguments(self, name):
55 '''Generate macro calls with each tested argument set.
56If name is a macro without arguments, just yield "name".
57If name is a macro with arguments, yield a series of "name(arg1,...,argN)"
58where each argument takes each possible value at least once.'''
59 if name not in self.argspecs:
60 yield name
61 return
62 argspec = self.argspecs[name]
63 if argspec == []:
64 yield name + '()'
65 return
66 argument_lists = [self.arguments_for[arg] for arg in argspec]
67 arguments = [values[0] for values in argument_lists]
68 yield self.format_arguments(name, arguments)
69 for i in range(len(arguments)):
70 for value in argument_lists[i][1:]:
71 arguments[i] = value
72 yield self.format_arguments(name, arguments)
73 arguments[i] = argument_lists[0]
74
75 # Regex for interesting header lines.
76 # Groups: 1=macro name, 2=type, 3=argument list (optional).
77 header_line_re = \
78 re.compile(r'#define +' +
79 r'(PSA_((?:KEY_)?[A-Z]+)_\w+)' +
80 r'(?:\(([^\n()]*)\))?')
81 # Regex of macro names to exclude.
82 excluded_name_re = re.compile('_(?:GET|IS|OF)_|_(?:BASE|FLAG|MASK)\Z')
83 argument_split_re = re.compile(r' *, *')
84 def parse_header_line(self, line):
85 '''Parse a C header line, looking for "#define PSA_xxx".'''
86 m = re.match(self.header_line_re, line)
87 if not m:
88 return
89 name = m.group(1)
90 if re.search(self.excluded_name_re, name):
91 return
92 dest = self.table_by_prefix.get(m.group(2))
93 if dest is None:
94 return
95 dest.add(name)
96 if m.group(3):
97 self.argspecs[name] = re.split(self.argument_split_re, m.group(3))
98
99 def parse_header(self, filename):
100 '''Parse a C header file, looking for "#define PSA_xxx".'''
101 with open(filename, 'r') as input:
102 for line in input:
103 self.parse_header_line(line)
104
105 def add_test_case_line(self, function, argument):
106 '''Parse a test case data line, looking for algorithm metadata tests.'''
107 if function.endswith('_algorithm'):
108 self.algorithms.add(argument)
109 if function == 'hash_algorithm':
110 self.hash_algorithms.add(argument)
111 elif function == 'key_type':
112 self.key_types.add(argument)
113 elif function == 'ecc_key_types':
114 self.ecc_curves.add(argument)
115
116 # Regex matching a *.data line containing a test function call and
117 # its arguments. The actual definition is partly positional, but this
118 # regex is good enough in practice.
119 test_case_line_re = re.compile('(?!depends_on:)(\w+):([^\n :][^:\n]*)')
120 def parse_test_cases(self, filename):
121 '''Parse a test case file (*.data), looking for algorithm metadata tests.'''
122 with open(filename, 'r') as input:
123 for line in input:
124 m = re.match(self.test_case_line_re, line)
125 if m:
126 self.add_test_case_line(m.group(1), m.group(2))
127
128def gather_inputs(headers, test_suites):
129 '''Read the list of inputs to test psa_constant_names with.'''
130 inputs = Inputs()
131 for header in headers:
132 inputs.parse_header(header)
133 for test_cases in test_suites:
134 inputs.parse_test_cases(test_cases)
135 inputs.gather_arguments()
136 return inputs
137
138def remove_file_if_exists(filename):
139 '''Remove the specified file, ignoring errors.'''
140 if not filename:
141 return
142 try:
143 os.remove(filename)
144 except:
145 pass
146
147def run_c(options, names):
148 '''Generate and run a program to print out numerical values for names.'''
149 c_name = None
150 exe_name = None
151 try:
152 c_fd, c_name = tempfile.mkstemp(suffix='.c',
153 dir='programs/psa')
154 exe_suffix = '.exe' if platform.system() == 'Windows' else ''
155 exe_name = c_name[:-2] + exe_suffix
156 remove_file_if_exists(exe_name)
157 c_file = os.fdopen(c_fd, 'w', encoding='ascii')
158 c_file.write('''/* Generated by test_psa_constant_names.py */
159#include <stdio.h>
160#include <psa/crypto.h>
161int main(void)
162{
163''')
164 for name in names:
165 c_file.write(' printf("0x%08x\\n", {});\n'.format(name))
166 c_file.write(''' return 0;
167}
168''')
169 c_file.close()
170 cc = os.getenv('CC', 'cc')
171 subprocess.check_call([cc] +
172 ['-I' + dir for dir in options.include] +
173 ['-o', exe_name, c_name])
174 os.remove(c_name)
175 output = subprocess.check_output([exe_name])
176 return output.decode('ascii').strip().split('\n')
177 finally:
178 remove_file_if_exists(exe_name)
179
180normalize_strip_re = re.compile(r'\s+')
181def normalize(expr):
182 '''Normalize the C expression so as not to care about trivial differences.
183Currently "trivial differences" means whitespace.'''
184 expr = re.sub(normalize_strip_re, '', expr, len(expr))
185 return expr.strip().split('\n')
186
187def do_test(options, inputs, type, names):
188 '''Test psa_constant_names for the specified type.
189Run program on names.
190Use inputs to figure out what arguments to pass to macros that take arguments.'''
191 names = sorted(itertools.chain(*map(inputs.distribute_arguments, names)))
192 values = run_c(options, names)
193 output = subprocess.check_output([options.program, type] + values)
194 outputs = output.decode('ascii').strip().split('\n')
195 errors = [(type, name, value, output)
196 for (name, value, output) in zip(names, values, outputs)
197 if normalize(name) != normalize(output)]
198 return len(names), errors
199
200def report_errors(errors):
201 '''Describe each case where the output is not as expected.'''
202 for type, name, value, output in errors:
203 print('For {} "{}", got "{}" (value: {})'
204 .format(type, name, output, value))
205
206def run_tests(options, inputs):
207 '''Run psa_constant_names on all the gathered inputs.
208Return a tuple (count, errors) where count is the total number of inputs
209that were tested and errors is the list of cases where the output was
210not as expected.'''
211 count = 0
212 errors = []
213 for type, names in [('status', inputs.statuses),
214 ('algorithm', inputs.algorithms),
215 ('ecc_curve', inputs.ecc_curves),
216 ('key_type', inputs.key_types),
217 ('key_usage', inputs.key_usage_flags)]:
218 c, e = do_test(options, inputs, type, names)
219 count += c
220 errors += e
221 return count, errors
222
223if __name__ == '__main__':
224 parser = argparse.ArgumentParser(description=globals()['__doc__'])
225 parser.add_argument('--include', '-I',
226 action='append', default=['include'],
227 help='Directory for header files')
228 parser.add_argument('--program',
229 default='programs/psa/psa_constant_names',
230 help='Program to test')
231 options = parser.parse_args()
232 headers = [os.path.join(options.include[0], 'psa/crypto.h')]
233 test_suites = ['tests/suites/test_suite_psa_crypto_metadata.data']
234 inputs = gather_inputs(headers, test_suites)
235 count, errors = run_tests(options, inputs)
236 report_errors(errors)
237 if errors == []:
238 print('{} test cases PASS'.format(count))
239 else:
240 print('{} test cases, {} FAIL'.format(count, len(errors)))
241 exit(1)