generate_psa_constants.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. #!/usr/bin/env python3
  2. """Generate psa_constant_names_generated.c
  3. which is included by programs/psa/psa_constant_names.c.
  4. The code generated by this module is only meant to be used in the context
  5. of that program.
  6. An argument passed to this script will modify the output directory where the
  7. file is written:
  8. * by default (no arguments passed): writes to programs/psa/
  9. * OUTPUT_FILE_DIR passed: writes to OUTPUT_FILE_DIR/
  10. """
  11. # Copyright The Mbed TLS Contributors
  12. # SPDX-License-Identifier: Apache-2.0
  13. #
  14. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  15. # not use this file except in compliance with the License.
  16. # You may obtain a copy of the License at
  17. #
  18. # http://www.apache.org/licenses/LICENSE-2.0
  19. #
  20. # Unless required by applicable law or agreed to in writing, software
  21. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  22. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  23. # See the License for the specific language governing permissions and
  24. # limitations under the License.
  25. import os
  26. import sys
  27. from mbedtls_dev import macro_collector
  28. OUTPUT_TEMPLATE = '''\
  29. /* Automatically generated by generate_psa_constant.py. DO NOT EDIT. */
  30. static const char *psa_strerror(psa_status_t status)
  31. {
  32. switch (status) {
  33. %(status_cases)s
  34. default: return NULL;
  35. }
  36. }
  37. static const char *psa_ecc_family_name(psa_ecc_family_t curve)
  38. {
  39. switch (curve) {
  40. %(ecc_curve_cases)s
  41. default: return NULL;
  42. }
  43. }
  44. static const char *psa_dh_family_name(psa_dh_family_t group)
  45. {
  46. switch (group) {
  47. %(dh_group_cases)s
  48. default: return NULL;
  49. }
  50. }
  51. static const char *psa_hash_algorithm_name(psa_algorithm_t hash_alg)
  52. {
  53. switch (hash_alg) {
  54. %(hash_algorithm_cases)s
  55. default: return NULL;
  56. }
  57. }
  58. static const char *psa_ka_algorithm_name(psa_algorithm_t ka_alg)
  59. {
  60. switch (ka_alg) {
  61. %(ka_algorithm_cases)s
  62. default: return NULL;
  63. }
  64. }
  65. static int psa_snprint_key_type(char *buffer, size_t buffer_size,
  66. psa_key_type_t type)
  67. {
  68. size_t required_size = 0;
  69. switch (type) {
  70. %(key_type_cases)s
  71. default:
  72. %(key_type_code)s{
  73. return snprintf(buffer, buffer_size,
  74. "0x%%04x", (unsigned) type);
  75. }
  76. break;
  77. }
  78. buffer[0] = 0;
  79. return (int) required_size;
  80. }
  81. #define NO_LENGTH_MODIFIER 0xfffffffflu
  82. static int psa_snprint_algorithm(char *buffer, size_t buffer_size,
  83. psa_algorithm_t alg)
  84. {
  85. size_t required_size = 0;
  86. psa_algorithm_t core_alg = alg;
  87. unsigned long length_modifier = NO_LENGTH_MODIFIER;
  88. if (PSA_ALG_IS_MAC(alg)) {
  89. core_alg = PSA_ALG_TRUNCATED_MAC(alg, 0);
  90. if (alg & PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG) {
  91. append(&buffer, buffer_size, &required_size,
  92. "PSA_ALG_AT_LEAST_THIS_LENGTH_MAC(", 33);
  93. length_modifier = PSA_MAC_TRUNCATED_LENGTH(alg);
  94. } else if (core_alg != alg) {
  95. append(&buffer, buffer_size, &required_size,
  96. "PSA_ALG_TRUNCATED_MAC(", 22);
  97. length_modifier = PSA_MAC_TRUNCATED_LENGTH(alg);
  98. }
  99. } else if (PSA_ALG_IS_AEAD(alg)) {
  100. core_alg = PSA_ALG_AEAD_WITH_DEFAULT_LENGTH_TAG(alg);
  101. if (core_alg == 0) {
  102. /* For unknown AEAD algorithms, there is no "default tag length". */
  103. core_alg = alg;
  104. } else if (alg & PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG) {
  105. append(&buffer, buffer_size, &required_size,
  106. "PSA_ALG_AEAD_WITH_AT_LEAST_THIS_LENGTH_TAG(", 43);
  107. length_modifier = PSA_ALG_AEAD_GET_TAG_LENGTH(alg);
  108. } else if (core_alg != alg) {
  109. append(&buffer, buffer_size, &required_size,
  110. "PSA_ALG_AEAD_WITH_SHORTENED_TAG(", 32);
  111. length_modifier = PSA_ALG_AEAD_GET_TAG_LENGTH(alg);
  112. }
  113. } else if (PSA_ALG_IS_KEY_AGREEMENT(alg) &&
  114. !PSA_ALG_IS_RAW_KEY_AGREEMENT(alg)) {
  115. core_alg = PSA_ALG_KEY_AGREEMENT_GET_KDF(alg);
  116. append(&buffer, buffer_size, &required_size,
  117. "PSA_ALG_KEY_AGREEMENT(", 22);
  118. append_with_alg(&buffer, buffer_size, &required_size,
  119. psa_ka_algorithm_name,
  120. PSA_ALG_KEY_AGREEMENT_GET_BASE(alg));
  121. append(&buffer, buffer_size, &required_size, ", ", 2);
  122. }
  123. switch (core_alg) {
  124. %(algorithm_cases)s
  125. default:
  126. %(algorithm_code)s{
  127. append_integer(&buffer, buffer_size, &required_size,
  128. "0x%%08lx", (unsigned long) core_alg);
  129. }
  130. break;
  131. }
  132. if (core_alg != alg) {
  133. if (length_modifier != NO_LENGTH_MODIFIER) {
  134. append(&buffer, buffer_size, &required_size, ", ", 2);
  135. append_integer(&buffer, buffer_size, &required_size,
  136. "%%lu", length_modifier);
  137. }
  138. append(&buffer, buffer_size, &required_size, ")", 1);
  139. }
  140. buffer[0] = 0;
  141. return (int) required_size;
  142. }
  143. static int psa_snprint_key_usage(char *buffer, size_t buffer_size,
  144. psa_key_usage_t usage)
  145. {
  146. size_t required_size = 0;
  147. if (usage == 0) {
  148. if (buffer_size > 1) {
  149. buffer[0] = '0';
  150. buffer[1] = 0;
  151. } else if (buffer_size == 1) {
  152. buffer[0] = 0;
  153. }
  154. return 1;
  155. }
  156. %(key_usage_code)s
  157. if (usage != 0) {
  158. if (required_size != 0) {
  159. append(&buffer, buffer_size, &required_size, " | ", 3);
  160. }
  161. append_integer(&buffer, buffer_size, &required_size,
  162. "0x%%08lx", (unsigned long) usage);
  163. } else {
  164. buffer[0] = 0;
  165. }
  166. return (int) required_size;
  167. }
  168. /* End of automatically generated file. */
  169. '''
  170. KEY_TYPE_FROM_CURVE_TEMPLATE = '''if (%(tester)s(type)) {
  171. append_with_curve(&buffer, buffer_size, &required_size,
  172. "%(builder)s", %(builder_length)s,
  173. PSA_KEY_TYPE_ECC_GET_FAMILY(type));
  174. } else '''
  175. KEY_TYPE_FROM_GROUP_TEMPLATE = '''if (%(tester)s(type)) {
  176. append_with_group(&buffer, buffer_size, &required_size,
  177. "%(builder)s", %(builder_length)s,
  178. PSA_KEY_TYPE_DH_GET_FAMILY(type));
  179. } else '''
  180. ALGORITHM_FROM_HASH_TEMPLATE = '''if (%(tester)s(core_alg)) {
  181. append(&buffer, buffer_size, &required_size,
  182. "%(builder)s(", %(builder_length)s + 1);
  183. append_with_alg(&buffer, buffer_size, &required_size,
  184. psa_hash_algorithm_name,
  185. PSA_ALG_GET_HASH(core_alg));
  186. append(&buffer, buffer_size, &required_size, ")", 1);
  187. } else '''
  188. BIT_TEST_TEMPLATE = '''\
  189. if (%(var)s & %(flag)s) {
  190. if (required_size != 0) {
  191. append(&buffer, buffer_size, &required_size, " | ", 3);
  192. }
  193. append(&buffer, buffer_size, &required_size, "%(flag)s", %(length)d);
  194. %(var)s ^= %(flag)s;
  195. }\
  196. '''
  197. class CaseBuilder(macro_collector.PSAMacroCollector):
  198. """Collect PSA crypto macro definitions and write value recognition functions.
  199. 1. Call `read_file` on the input header file(s).
  200. 2. Call `write_file` to write ``psa_constant_names_generated.c``.
  201. """
  202. def __init__(self):
  203. super().__init__(include_intermediate=True)
  204. @staticmethod
  205. def _make_return_case(name):
  206. return 'case %(name)s: return "%(name)s";' % {'name': name}
  207. @staticmethod
  208. def _make_append_case(name):
  209. template = ('case %(name)s: '
  210. 'append(&buffer, buffer_size, &required_size, "%(name)s", %(length)d); '
  211. 'break;')
  212. return template % {'name': name, 'length': len(name)}
  213. @staticmethod
  214. def _make_bit_test(var, flag):
  215. return BIT_TEST_TEMPLATE % {'var': var,
  216. 'flag': flag,
  217. 'length': len(flag)}
  218. def _make_status_cases(self):
  219. return '\n '.join(map(self._make_return_case,
  220. sorted(self.statuses)))
  221. def _make_ecc_curve_cases(self):
  222. return '\n '.join(map(self._make_return_case,
  223. sorted(self.ecc_curves)))
  224. def _make_dh_group_cases(self):
  225. return '\n '.join(map(self._make_return_case,
  226. sorted(self.dh_groups)))
  227. def _make_key_type_cases(self):
  228. return '\n '.join(map(self._make_append_case,
  229. sorted(self.key_types)))
  230. @staticmethod
  231. def _make_key_type_from_curve_code(builder, tester):
  232. return KEY_TYPE_FROM_CURVE_TEMPLATE % {'builder': builder,
  233. 'builder_length': len(builder),
  234. 'tester': tester}
  235. @staticmethod
  236. def _make_key_type_from_group_code(builder, tester):
  237. return KEY_TYPE_FROM_GROUP_TEMPLATE % {'builder': builder,
  238. 'builder_length': len(builder),
  239. 'tester': tester}
  240. def _make_ecc_key_type_code(self):
  241. d = self.key_types_from_curve
  242. make = self._make_key_type_from_curve_code
  243. return ''.join([make(k, d[k]) for k in sorted(d.keys())])
  244. def _make_dh_key_type_code(self):
  245. d = self.key_types_from_group
  246. make = self._make_key_type_from_group_code
  247. return ''.join([make(k, d[k]) for k in sorted(d.keys())])
  248. def _make_hash_algorithm_cases(self):
  249. return '\n '.join(map(self._make_return_case,
  250. sorted(self.hash_algorithms)))
  251. def _make_ka_algorithm_cases(self):
  252. return '\n '.join(map(self._make_return_case,
  253. sorted(self.ka_algorithms)))
  254. def _make_algorithm_cases(self):
  255. return '\n '.join(map(self._make_append_case,
  256. sorted(self.algorithms)))
  257. @staticmethod
  258. def _make_algorithm_from_hash_code(builder, tester):
  259. return ALGORITHM_FROM_HASH_TEMPLATE % {'builder': builder,
  260. 'builder_length': len(builder),
  261. 'tester': tester}
  262. def _make_algorithm_code(self):
  263. d = self.algorithms_from_hash
  264. make = self._make_algorithm_from_hash_code
  265. return ''.join([make(k, d[k]) for k in sorted(d.keys())])
  266. def _make_key_usage_code(self):
  267. return '\n'.join([self._make_bit_test('usage', bit)
  268. for bit in sorted(self.key_usage_flags)])
  269. def write_file(self, output_file):
  270. """Generate the pretty-printer function code from the gathered
  271. constant definitions.
  272. """
  273. data = {}
  274. data['status_cases'] = self._make_status_cases()
  275. data['ecc_curve_cases'] = self._make_ecc_curve_cases()
  276. data['dh_group_cases'] = self._make_dh_group_cases()
  277. data['key_type_cases'] = self._make_key_type_cases()
  278. data['key_type_code'] = (self._make_ecc_key_type_code() +
  279. self._make_dh_key_type_code())
  280. data['hash_algorithm_cases'] = self._make_hash_algorithm_cases()
  281. data['ka_algorithm_cases'] = self._make_ka_algorithm_cases()
  282. data['algorithm_cases'] = self._make_algorithm_cases()
  283. data['algorithm_code'] = self._make_algorithm_code()
  284. data['key_usage_code'] = self._make_key_usage_code()
  285. output_file.write(OUTPUT_TEMPLATE % data)
  286. def generate_psa_constants(header_file_names, output_file_name):
  287. collector = CaseBuilder()
  288. for header_file_name in header_file_names:
  289. with open(header_file_name, 'rb') as header_file:
  290. collector.read_file(header_file)
  291. temp_file_name = output_file_name + '.tmp'
  292. with open(temp_file_name, 'w') as output_file:
  293. collector.write_file(output_file)
  294. os.replace(temp_file_name, output_file_name)
  295. if __name__ == '__main__':
  296. if not os.path.isdir('programs') and os.path.isdir('../programs'):
  297. os.chdir('..')
  298. # Allow to change the directory where psa_constant_names_generated.c is written to.
  299. OUTPUT_FILE_DIR = sys.argv[1] if len(sys.argv) == 2 else "programs/psa"
  300. generate_psa_constants(['include/psa/crypto_values.h',
  301. 'include/psa/crypto_extra.h'],
  302. OUTPUT_FILE_DIR + '/psa_constant_names_generated.c')