Gilles Peskine | 2482702 | 2018-09-25 18:49:23 +0200 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
| 2 | '''Test the program psa_constant_names. |
| 3 | Gather constant names from header files and test cases. Compile a C program |
| 4 | to print out their numerical values, feed these numerical values to |
| 5 | psa_constant_names, and check that the output is the original name. |
| 6 | Return 0 if all test cases pass, 1 if the output was not always as expected, |
| 7 | or 1 (with a Python backtrace) if there was an operational error.''' |
| 8 | |
| 9 | import argparse |
| 10 | import itertools |
| 11 | import os |
| 12 | import platform |
| 13 | import re |
| 14 | import subprocess |
| 15 | import sys |
| 16 | import tempfile |
| 17 | |
Gilles Peskine | a0a315c | 2018-10-19 11:27:10 +0200 | [diff] [blame] | 18 | class 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 | |
| 25 | class read_file_lines: |
| 26 | '''Context manager to read a text file line by line. |
| 27 | with read_file_lines(filename) as lines: |
| 28 | for line in lines: |
| 29 | process(line) |
| 30 | is equivalent to |
| 31 | with open(filename, 'r') as input_file: |
| 32 | for line in input_file: |
| 33 | process(line) |
| 34 | except that if process(line) raises an exception, then the read_file_lines |
| 35 | snippet 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 Peskine | 2482702 | 2018-09-25 18:49:23 +0200 | [diff] [blame] | 52 | class Inputs: |
| 53 | '''Accumulate information about macros to test. |
| 54 | This includes macro names as well as information about their arguments |
| 55 | when 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 Peskine | 434899f | 2018-10-19 11:30:26 +0200 | [diff] [blame^] | 63 | # Hard-coded value for unknown algorithms |
Gilles Peskine | 2482702 | 2018-09-25 18:49:23 +0200 | [diff] [blame] | 64 | self.hash_algorithms = set(['0x010000ff']) |
Gilles Peskine | 434899f | 2018-10-19 11:30:26 +0200 | [diff] [blame^] | 65 | 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 Peskine | 2482702 | 2018-09-25 18:49:23 +0200 | [diff] [blame] | 70 | # 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 Peskine | 434899f | 2018-10-19 11:30:26 +0200 | [diff] [blame^] | 81 | self.arguments_for = { |
| 82 | 'mac_length': ['1', '63'], |
| 83 | 'tag_length': ['1', '63'], |
| 84 | } |
Gilles Peskine | 2482702 | 2018-09-25 18:49:23 +0200 | [diff] [blame] | 85 | |
| 86 | def gather_arguments(self): |
| 87 | '''Populate the list of values for macro arguments. |
| 88 | Call this after parsing all the inputs.''' |
| 89 | self.arguments_for['hash_alg'] = sorted(self.hash_algorithms) |
Gilles Peskine | 434899f | 2018-10-19 11:30:26 +0200 | [diff] [blame^] | 90 | self.arguments_for['mac_alg'] = sorted(self.mac_algorithms) |
| 91 | self.arguments_for['aead_alg'] = sorted(self.aead_algorithms) |
Gilles Peskine | 2482702 | 2018-09-25 18:49:23 +0200 | [diff] [blame] | 92 | 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. |
| 100 | If name is a macro without arguments, just yield "name". |
| 101 | If name is a macro with arguments, yield a series of "name(arg1,...,argN)" |
| 102 | where each argument takes each possible value at least once.''' |
Gilles Peskine | a0a315c | 2018-10-19 11:27:10 +0200 | [diff] [blame] | 103 | 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 Peskine | f96ed66 | 2018-10-19 11:29:56 +0200 | [diff] [blame] | 118 | arguments[i] = argument_lists[0][0] |
Gilles Peskine | a0a315c | 2018-10-19 11:27:10 +0200 | [diff] [blame] | 119 | except BaseException as e: |
| 120 | raise Exception('distribute_arguments({})'.format(name)) from e |
Gilles Peskine | 2482702 | 2018-09-25 18:49:23 +0200 | [diff] [blame] | 121 | |
| 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') |
| 130 | argument_split_re = re.compile(r' *, *') |
| 131 | def parse_header_line(self, line): |
| 132 | '''Parse a C header line, looking for "#define PSA_xxx".''' |
| 133 | m = re.match(self.header_line_re, line) |
| 134 | if not m: |
| 135 | return |
| 136 | name = m.group(1) |
| 137 | if re.search(self.excluded_name_re, name): |
| 138 | return |
| 139 | dest = self.table_by_prefix.get(m.group(2)) |
| 140 | if dest is None: |
| 141 | return |
| 142 | dest.add(name) |
| 143 | if m.group(3): |
| 144 | self.argspecs[name] = re.split(self.argument_split_re, m.group(3)) |
| 145 | |
| 146 | def parse_header(self, filename): |
| 147 | '''Parse a C header file, looking for "#define PSA_xxx".''' |
Gilles Peskine | a0a315c | 2018-10-19 11:27:10 +0200 | [diff] [blame] | 148 | with read_file_lines(filename) as lines: |
| 149 | for line in lines: |
Gilles Peskine | 2482702 | 2018-09-25 18:49:23 +0200 | [diff] [blame] | 150 | self.parse_header_line(line) |
| 151 | |
| 152 | def add_test_case_line(self, function, argument): |
| 153 | '''Parse a test case data line, looking for algorithm metadata tests.''' |
| 154 | if function.endswith('_algorithm'): |
| 155 | self.algorithms.add(argument) |
| 156 | if function == 'hash_algorithm': |
| 157 | self.hash_algorithms.add(argument) |
Gilles Peskine | 434899f | 2018-10-19 11:30:26 +0200 | [diff] [blame^] | 158 | elif function in ['mac_algorithm', 'hmac_algorithm']: |
| 159 | self.mac_algorithms.add(argument) |
| 160 | elif function == 'aead_algorithm': |
| 161 | self.aead_algorithms.add(argument) |
Gilles Peskine | 2482702 | 2018-09-25 18:49:23 +0200 | [diff] [blame] | 162 | elif function == 'key_type': |
| 163 | self.key_types.add(argument) |
| 164 | elif function == 'ecc_key_types': |
| 165 | self.ecc_curves.add(argument) |
| 166 | |
| 167 | # Regex matching a *.data line containing a test function call and |
| 168 | # its arguments. The actual definition is partly positional, but this |
| 169 | # regex is good enough in practice. |
| 170 | test_case_line_re = re.compile('(?!depends_on:)(\w+):([^\n :][^:\n]*)') |
| 171 | def parse_test_cases(self, filename): |
| 172 | '''Parse a test case file (*.data), looking for algorithm metadata tests.''' |
Gilles Peskine | a0a315c | 2018-10-19 11:27:10 +0200 | [diff] [blame] | 173 | with read_file_lines(filename) as lines: |
| 174 | for line in lines: |
Gilles Peskine | 2482702 | 2018-09-25 18:49:23 +0200 | [diff] [blame] | 175 | m = re.match(self.test_case_line_re, line) |
| 176 | if m: |
| 177 | self.add_test_case_line(m.group(1), m.group(2)) |
| 178 | |
| 179 | def gather_inputs(headers, test_suites): |
| 180 | '''Read the list of inputs to test psa_constant_names with.''' |
| 181 | inputs = Inputs() |
| 182 | for header in headers: |
| 183 | inputs.parse_header(header) |
| 184 | for test_cases in test_suites: |
| 185 | inputs.parse_test_cases(test_cases) |
| 186 | inputs.gather_arguments() |
| 187 | return inputs |
| 188 | |
| 189 | def remove_file_if_exists(filename): |
| 190 | '''Remove the specified file, ignoring errors.''' |
| 191 | if not filename: |
| 192 | return |
| 193 | try: |
| 194 | os.remove(filename) |
| 195 | except: |
| 196 | pass |
| 197 | |
Gilles Peskine | cf9c18e | 2018-10-19 11:28:42 +0200 | [diff] [blame] | 198 | def run_c(options, type, names): |
Gilles Peskine | 2482702 | 2018-09-25 18:49:23 +0200 | [diff] [blame] | 199 | '''Generate and run a program to print out numerical values for names.''' |
| 200 | c_name = None |
| 201 | exe_name = None |
| 202 | try: |
| 203 | c_fd, c_name = tempfile.mkstemp(suffix='.c', |
| 204 | dir='programs/psa') |
| 205 | exe_suffix = '.exe' if platform.system() == 'Windows' else '' |
| 206 | exe_name = c_name[:-2] + exe_suffix |
| 207 | remove_file_if_exists(exe_name) |
| 208 | c_file = os.fdopen(c_fd, 'w', encoding='ascii') |
| 209 | c_file.write('''/* Generated by test_psa_constant_names.py */ |
| 210 | #include <stdio.h> |
| 211 | #include <psa/crypto.h> |
| 212 | int main(void) |
| 213 | { |
| 214 | ''') |
| 215 | for name in names: |
| 216 | c_file.write(' printf("0x%08x\\n", {});\n'.format(name)) |
| 217 | c_file.write(''' return 0; |
| 218 | } |
| 219 | ''') |
| 220 | c_file.close() |
| 221 | cc = os.getenv('CC', 'cc') |
| 222 | subprocess.check_call([cc] + |
| 223 | ['-I' + dir for dir in options.include] + |
| 224 | ['-o', exe_name, c_name]) |
Gilles Peskine | cf9c18e | 2018-10-19 11:28:42 +0200 | [diff] [blame] | 225 | if options.keep_c: |
| 226 | sys.stderr.write('List of {} tests kept at {}\n' |
| 227 | .format(type, c_name)) |
| 228 | else: |
| 229 | os.remove(c_name) |
Gilles Peskine | 2482702 | 2018-09-25 18:49:23 +0200 | [diff] [blame] | 230 | output = subprocess.check_output([exe_name]) |
| 231 | return output.decode('ascii').strip().split('\n') |
| 232 | finally: |
| 233 | remove_file_if_exists(exe_name) |
| 234 | |
| 235 | normalize_strip_re = re.compile(r'\s+') |
| 236 | def normalize(expr): |
| 237 | '''Normalize the C expression so as not to care about trivial differences. |
| 238 | Currently "trivial differences" means whitespace.''' |
| 239 | expr = re.sub(normalize_strip_re, '', expr, len(expr)) |
| 240 | return expr.strip().split('\n') |
| 241 | |
| 242 | def do_test(options, inputs, type, names): |
| 243 | '''Test psa_constant_names for the specified type. |
| 244 | Run program on names. |
| 245 | Use inputs to figure out what arguments to pass to macros that take arguments.''' |
| 246 | names = sorted(itertools.chain(*map(inputs.distribute_arguments, names))) |
Gilles Peskine | cf9c18e | 2018-10-19 11:28:42 +0200 | [diff] [blame] | 247 | values = run_c(options, type, names) |
Gilles Peskine | 2482702 | 2018-09-25 18:49:23 +0200 | [diff] [blame] | 248 | output = subprocess.check_output([options.program, type] + values) |
| 249 | outputs = output.decode('ascii').strip().split('\n') |
| 250 | errors = [(type, name, value, output) |
| 251 | for (name, value, output) in zip(names, values, outputs) |
| 252 | if normalize(name) != normalize(output)] |
| 253 | return len(names), errors |
| 254 | |
| 255 | def report_errors(errors): |
| 256 | '''Describe each case where the output is not as expected.''' |
| 257 | for type, name, value, output in errors: |
| 258 | print('For {} "{}", got "{}" (value: {})' |
| 259 | .format(type, name, output, value)) |
| 260 | |
| 261 | def run_tests(options, inputs): |
| 262 | '''Run psa_constant_names on all the gathered inputs. |
| 263 | Return a tuple (count, errors) where count is the total number of inputs |
| 264 | that were tested and errors is the list of cases where the output was |
| 265 | not as expected.''' |
| 266 | count = 0 |
| 267 | errors = [] |
| 268 | for type, names in [('status', inputs.statuses), |
| 269 | ('algorithm', inputs.algorithms), |
| 270 | ('ecc_curve', inputs.ecc_curves), |
| 271 | ('key_type', inputs.key_types), |
| 272 | ('key_usage', inputs.key_usage_flags)]: |
| 273 | c, e = do_test(options, inputs, type, names) |
| 274 | count += c |
| 275 | errors += e |
| 276 | return count, errors |
| 277 | |
| 278 | if __name__ == '__main__': |
| 279 | parser = argparse.ArgumentParser(description=globals()['__doc__']) |
| 280 | parser.add_argument('--include', '-I', |
| 281 | action='append', default=['include'], |
| 282 | help='Directory for header files') |
| 283 | parser.add_argument('--program', |
| 284 | default='programs/psa/psa_constant_names', |
| 285 | help='Program to test') |
Gilles Peskine | cf9c18e | 2018-10-19 11:28:42 +0200 | [diff] [blame] | 286 | parser.add_argument('--keep-c', |
| 287 | action='store_true', dest='keep_c', default=False, |
| 288 | help='Keep the intermediate C file') |
| 289 | parser.add_argument('--no-keep-c', |
| 290 | action='store_false', dest='keep_c', |
| 291 | help='Don\'t keep the intermediate C file (default)') |
Gilles Peskine | 2482702 | 2018-09-25 18:49:23 +0200 | [diff] [blame] | 292 | options = parser.parse_args() |
| 293 | headers = [os.path.join(options.include[0], 'psa/crypto.h')] |
| 294 | test_suites = ['tests/suites/test_suite_psa_crypto_metadata.data'] |
| 295 | inputs = gather_inputs(headers, test_suites) |
| 296 | count, errors = run_tests(options, inputs) |
| 297 | report_errors(errors) |
| 298 | if errors == []: |
| 299 | print('{} test cases PASS'.format(count)) |
| 300 | else: |
| 301 | print('{} test cases, {} FAIL'.format(count, len(errors))) |
| 302 | exit(1) |