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 |
Darryl Green | 61b7f61 | 2019-02-04 16:00:21 +0000 | [diff] [blame] | 64 | self.hash_algorithms = set(['0x010000fe']) |
Gilles Peskine | 434899f | 2018-10-19 11:30:26 +0200 | [diff] [blame] | 65 | self.mac_algorithms = set(['0x02ff00ff']) |
Gilles Peskine | 1754208 | 2019-01-04 19:46:31 +0100 | [diff] [blame] | 66 | self.kdf_algorithms = set(['0x300000ff', '0x310000ff']) |
Gilles Peskine | 434899f | 2018-10-19 11:30:26 +0200 | [diff] [blame] | 67 | # 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 Peskine | 2482702 | 2018-09-25 18:49:23 +0200 | [diff] [blame] | 71 | # 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 Peskine | 434899f | 2018-10-19 11:30:26 +0200 | [diff] [blame] | 82 | self.arguments_for = { |
| 83 | 'mac_length': ['1', '63'], |
| 84 | 'tag_length': ['1', '63'], |
| 85 | } |
Gilles Peskine | 2482702 | 2018-09-25 18:49:23 +0200 | [diff] [blame] | 86 | |
| 87 | def gather_arguments(self): |
| 88 | '''Populate the list of values for macro arguments. |
| 89 | Call this after parsing all the inputs.''' |
| 90 | self.arguments_for['hash_alg'] = sorted(self.hash_algorithms) |
Gilles Peskine | 434899f | 2018-10-19 11:30:26 +0200 | [diff] [blame] | 91 | self.arguments_for['mac_alg'] = sorted(self.mac_algorithms) |
Gilles Peskine | 1754208 | 2019-01-04 19:46:31 +0100 | [diff] [blame] | 92 | self.arguments_for['kdf_alg'] = sorted(self.kdf_algorithms) |
Gilles Peskine | 434899f | 2018-10-19 11:30:26 +0200 | [diff] [blame] | 93 | self.arguments_for['aead_alg'] = sorted(self.aead_algorithms) |
Gilles Peskine | 2482702 | 2018-09-25 18:49:23 +0200 | [diff] [blame] | 94 | 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. |
| 102 | If name is a macro without arguments, just yield "name". |
| 103 | If name is a macro with arguments, yield a series of "name(arg1,...,argN)" |
| 104 | where each argument takes each possible value at least once.''' |
Gilles Peskine | a0a315c | 2018-10-19 11:27:10 +0200 | [diff] [blame] | 105 | 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 Peskine | f96ed66 | 2018-10-19 11:29:56 +0200 | [diff] [blame] | 120 | arguments[i] = argument_lists[0][0] |
Gilles Peskine | a0a315c | 2018-10-19 11:27:10 +0200 | [diff] [blame] | 121 | except BaseException as e: |
| 122 | raise Exception('distribute_arguments({})'.format(name)) from e |
Gilles Peskine | 2482702 | 2018-09-25 18:49:23 +0200 | [diff] [blame] | 123 | |
| 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 Peskine | c68ce96 | 2018-10-19 11:31:52 +0200 | [diff] [blame] | 132 | # Additional excluded macros. |
Darryl Green | b8fe068 | 2019-02-06 13:21:31 +0000 | [diff] [blame] | 133 | # PSA_ALG_ECDH and PSA_ALG_FFDH are excluded for now as the script |
| 134 | # currently doesn't support them. |
Gilles Peskine | c68ce96 | 2018-10-19 11:31:52 +0200 | [diff] [blame] | 135 | excluded_names = set(['PSA_ALG_AEAD_WITH_DEFAULT_TAG_LENGTH', |
Darryl Green | ec07950 | 2019-01-29 15:48:00 +0000 | [diff] [blame] | 136 | 'PSA_ALG_FULL_LENGTH_MAC', |
| 137 | 'PSA_ALG_ECDH', |
| 138 | 'PSA_ALG_FFDH']) |
Gilles Peskine | 2482702 | 2018-09-25 18:49:23 +0200 | [diff] [blame] | 139 | argument_split_re = re.compile(r' *, *') |
| 140 | def parse_header_line(self, line): |
| 141 | '''Parse a C header line, looking for "#define PSA_xxx".''' |
| 142 | m = re.match(self.header_line_re, line) |
| 143 | if not m: |
| 144 | return |
| 145 | name = m.group(1) |
Gilles Peskine | c68ce96 | 2018-10-19 11:31:52 +0200 | [diff] [blame] | 146 | if re.search(self.excluded_name_re, name) or \ |
| 147 | name in self.excluded_names: |
Gilles Peskine | 2482702 | 2018-09-25 18:49:23 +0200 | [diff] [blame] | 148 | return |
| 149 | dest = self.table_by_prefix.get(m.group(2)) |
| 150 | if dest is None: |
| 151 | return |
| 152 | dest.add(name) |
| 153 | if m.group(3): |
| 154 | self.argspecs[name] = re.split(self.argument_split_re, m.group(3)) |
| 155 | |
| 156 | def parse_header(self, filename): |
| 157 | '''Parse a C header file, looking for "#define PSA_xxx".''' |
Gilles Peskine | a0a315c | 2018-10-19 11:27:10 +0200 | [diff] [blame] | 158 | with read_file_lines(filename) as lines: |
| 159 | for line in lines: |
Gilles Peskine | 2482702 | 2018-09-25 18:49:23 +0200 | [diff] [blame] | 160 | self.parse_header_line(line) |
| 161 | |
| 162 | def add_test_case_line(self, function, argument): |
| 163 | '''Parse a test case data line, looking for algorithm metadata tests.''' |
| 164 | if function.endswith('_algorithm'): |
Darryl Green | b8fe068 | 2019-02-06 13:21:31 +0000 | [diff] [blame] | 165 | # As above, ECDH and FFDH algorithms are excluded for now. |
| 166 | # Support for them will be added in the future. |
Darryl Green | ec07950 | 2019-01-29 15:48:00 +0000 | [diff] [blame] | 167 | if 'ECDH' in argument or 'FFDH' in argument: |
| 168 | return |
Gilles Peskine | 2482702 | 2018-09-25 18:49:23 +0200 | [diff] [blame] | 169 | self.algorithms.add(argument) |
| 170 | if function == 'hash_algorithm': |
| 171 | self.hash_algorithms.add(argument) |
Gilles Peskine | 434899f | 2018-10-19 11:30:26 +0200 | [diff] [blame] | 172 | elif function in ['mac_algorithm', 'hmac_algorithm']: |
| 173 | self.mac_algorithms.add(argument) |
| 174 | elif function == 'aead_algorithm': |
| 175 | self.aead_algorithms.add(argument) |
Gilles Peskine | 2482702 | 2018-09-25 18:49:23 +0200 | [diff] [blame] | 176 | elif function == 'key_type': |
| 177 | self.key_types.add(argument) |
| 178 | elif function == 'ecc_key_types': |
| 179 | self.ecc_curves.add(argument) |
| 180 | |
| 181 | # Regex matching a *.data line containing a test function call and |
| 182 | # its arguments. The actual definition is partly positional, but this |
| 183 | # regex is good enough in practice. |
| 184 | test_case_line_re = re.compile('(?!depends_on:)(\w+):([^\n :][^:\n]*)') |
| 185 | def parse_test_cases(self, filename): |
| 186 | '''Parse a test case file (*.data), looking for algorithm metadata tests.''' |
Gilles Peskine | a0a315c | 2018-10-19 11:27:10 +0200 | [diff] [blame] | 187 | with read_file_lines(filename) as lines: |
| 188 | for line in lines: |
Gilles Peskine | 2482702 | 2018-09-25 18:49:23 +0200 | [diff] [blame] | 189 | m = re.match(self.test_case_line_re, line) |
| 190 | if m: |
| 191 | self.add_test_case_line(m.group(1), m.group(2)) |
| 192 | |
| 193 | def gather_inputs(headers, test_suites): |
| 194 | '''Read the list of inputs to test psa_constant_names with.''' |
| 195 | inputs = Inputs() |
| 196 | for header in headers: |
| 197 | inputs.parse_header(header) |
| 198 | for test_cases in test_suites: |
| 199 | inputs.parse_test_cases(test_cases) |
| 200 | inputs.gather_arguments() |
| 201 | return inputs |
| 202 | |
| 203 | def remove_file_if_exists(filename): |
| 204 | '''Remove the specified file, ignoring errors.''' |
| 205 | if not filename: |
| 206 | return |
| 207 | try: |
| 208 | os.remove(filename) |
| 209 | except: |
| 210 | pass |
| 211 | |
Gilles Peskine | cf9c18e | 2018-10-19 11:28:42 +0200 | [diff] [blame] | 212 | def run_c(options, type, names): |
Gilles Peskine | 2482702 | 2018-09-25 18:49:23 +0200 | [diff] [blame] | 213 | '''Generate and run a program to print out numerical values for names.''' |
| 214 | c_name = None |
| 215 | exe_name = None |
| 216 | try: |
Gilles Peskine | 95ab71a | 2019-01-04 19:46:59 +0100 | [diff] [blame] | 217 | c_fd, c_name = tempfile.mkstemp(prefix='tmp-{}-'.format(type), |
| 218 | suffix='.c', |
Gilles Peskine | 2482702 | 2018-09-25 18:49:23 +0200 | [diff] [blame] | 219 | dir='programs/psa') |
| 220 | exe_suffix = '.exe' if platform.system() == 'Windows' else '' |
| 221 | exe_name = c_name[:-2] + exe_suffix |
| 222 | remove_file_if_exists(exe_name) |
| 223 | c_file = os.fdopen(c_fd, 'w', encoding='ascii') |
Gilles Peskine | 95ab71a | 2019-01-04 19:46:59 +0100 | [diff] [blame] | 224 | c_file.write('/* Generated by test_psa_constant_names.py for {} values */' |
| 225 | .format(type)) |
| 226 | c_file.write(''' |
Gilles Peskine | 2482702 | 2018-09-25 18:49:23 +0200 | [diff] [blame] | 227 | #include <stdio.h> |
| 228 | #include <psa/crypto.h> |
| 229 | int main(void) |
| 230 | { |
| 231 | ''') |
| 232 | for name in names: |
| 233 | c_file.write(' printf("0x%08x\\n", {});\n'.format(name)) |
| 234 | c_file.write(''' return 0; |
| 235 | } |
| 236 | ''') |
| 237 | c_file.close() |
| 238 | cc = os.getenv('CC', 'cc') |
| 239 | subprocess.check_call([cc] + |
| 240 | ['-I' + dir for dir in options.include] + |
| 241 | ['-o', exe_name, c_name]) |
Gilles Peskine | cf9c18e | 2018-10-19 11:28:42 +0200 | [diff] [blame] | 242 | if options.keep_c: |
| 243 | sys.stderr.write('List of {} tests kept at {}\n' |
| 244 | .format(type, c_name)) |
| 245 | else: |
| 246 | os.remove(c_name) |
Gilles Peskine | 2482702 | 2018-09-25 18:49:23 +0200 | [diff] [blame] | 247 | output = subprocess.check_output([exe_name]) |
| 248 | return output.decode('ascii').strip().split('\n') |
| 249 | finally: |
| 250 | remove_file_if_exists(exe_name) |
| 251 | |
| 252 | normalize_strip_re = re.compile(r'\s+') |
| 253 | def normalize(expr): |
| 254 | '''Normalize the C expression so as not to care about trivial differences. |
| 255 | Currently "trivial differences" means whitespace.''' |
| 256 | expr = re.sub(normalize_strip_re, '', expr, len(expr)) |
| 257 | return expr.strip().split('\n') |
| 258 | |
| 259 | def do_test(options, inputs, type, names): |
| 260 | '''Test psa_constant_names for the specified type. |
| 261 | Run program on names. |
| 262 | Use inputs to figure out what arguments to pass to macros that take arguments.''' |
| 263 | names = sorted(itertools.chain(*map(inputs.distribute_arguments, names))) |
Gilles Peskine | cf9c18e | 2018-10-19 11:28:42 +0200 | [diff] [blame] | 264 | values = run_c(options, type, names) |
Gilles Peskine | 2482702 | 2018-09-25 18:49:23 +0200 | [diff] [blame] | 265 | output = subprocess.check_output([options.program, type] + values) |
| 266 | outputs = output.decode('ascii').strip().split('\n') |
| 267 | errors = [(type, name, value, output) |
| 268 | for (name, value, output) in zip(names, values, outputs) |
| 269 | if normalize(name) != normalize(output)] |
| 270 | return len(names), errors |
| 271 | |
| 272 | def report_errors(errors): |
| 273 | '''Describe each case where the output is not as expected.''' |
| 274 | for type, name, value, output in errors: |
| 275 | print('For {} "{}", got "{}" (value: {})' |
| 276 | .format(type, name, output, value)) |
| 277 | |
| 278 | def run_tests(options, inputs): |
| 279 | '''Run psa_constant_names on all the gathered inputs. |
| 280 | Return a tuple (count, errors) where count is the total number of inputs |
| 281 | that were tested and errors is the list of cases where the output was |
| 282 | not as expected.''' |
| 283 | count = 0 |
| 284 | errors = [] |
| 285 | for type, names in [('status', inputs.statuses), |
| 286 | ('algorithm', inputs.algorithms), |
| 287 | ('ecc_curve', inputs.ecc_curves), |
| 288 | ('key_type', inputs.key_types), |
| 289 | ('key_usage', inputs.key_usage_flags)]: |
| 290 | c, e = do_test(options, inputs, type, names) |
| 291 | count += c |
| 292 | errors += e |
| 293 | return count, errors |
| 294 | |
| 295 | if __name__ == '__main__': |
| 296 | parser = argparse.ArgumentParser(description=globals()['__doc__']) |
| 297 | parser.add_argument('--include', '-I', |
| 298 | action='append', default=['include'], |
| 299 | help='Directory for header files') |
| 300 | parser.add_argument('--program', |
| 301 | default='programs/psa/psa_constant_names', |
| 302 | help='Program to test') |
Gilles Peskine | cf9c18e | 2018-10-19 11:28:42 +0200 | [diff] [blame] | 303 | parser.add_argument('--keep-c', |
| 304 | action='store_true', dest='keep_c', default=False, |
| 305 | help='Keep the intermediate C file') |
| 306 | parser.add_argument('--no-keep-c', |
| 307 | action='store_false', dest='keep_c', |
| 308 | help='Don\'t keep the intermediate C file (default)') |
Gilles Peskine | 2482702 | 2018-09-25 18:49:23 +0200 | [diff] [blame] | 309 | options = parser.parse_args() |
Gilles Peskine | 6d194bd | 2019-01-04 19:44:59 +0100 | [diff] [blame] | 310 | headers = [os.path.join(options.include[0], 'psa', h) |
| 311 | for h in ['crypto.h', 'crypto_extra.h', 'crypto_values.h']] |
Gilles Peskine | 2482702 | 2018-09-25 18:49:23 +0200 | [diff] [blame] | 312 | test_suites = ['tests/suites/test_suite_psa_crypto_metadata.data'] |
| 313 | inputs = gather_inputs(headers, test_suites) |
| 314 | count, errors = run_tests(options, inputs) |
| 315 | report_errors(errors) |
| 316 | if errors == []: |
| 317 | print('{} test cases PASS'.format(count)) |
| 318 | else: |
| 319 | print('{} test cases, {} FAIL'.format(count, len(errors))) |
| 320 | exit(1) |