test_fit_auto_signed.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. # SPDX-License-Identifier: GPL-2.0+
  2. # Copyright (c) 2022 Massimo Pegorer
  3. """
  4. Test that mkimage generates auto-FIT with signatures and/or hashes as expected.
  5. The mkimage tool can create auto generated (i.e. without an ITS file
  6. provided as input) FIT in three different flavours: with crc32 checksums
  7. of 'images' subnodes; with signatures of 'images' subnodes; with sha1
  8. hashes of 'images' subnodes and signatures of 'configurations' subnodes.
  9. This test verifies that auto-FIT are generated as expected, in all of
  10. the three flavours, including check of hashes and signatures (except for
  11. configurations ones).
  12. The test does not run the sandbox. It only checks the host tool mkimage.
  13. """
  14. import os
  15. import pytest
  16. import u_boot_utils as util
  17. import binascii
  18. from Cryptodome.Hash import SHA1
  19. from Cryptodome.Hash import SHA256
  20. from Cryptodome.PublicKey import RSA
  21. from Cryptodome.Signature import pkcs1_15
  22. class SignedFitHelper(object):
  23. """Helper to manipulate a FIT with signed/hashed images/configs."""
  24. def __init__(self, cons, file_name):
  25. self.fit = file_name
  26. self.cons = cons
  27. self.images_nodes = set()
  28. self.confgs_nodes = set()
  29. def __fdt_list(self, path):
  30. return util.run_and_log(self.cons,
  31. f'fdtget -l {self.fit} {path}')
  32. def __fdt_get_string(self, node, prop):
  33. return util.run_and_log(self.cons,
  34. f'fdtget -ts {self.fit} {node} {prop}')
  35. def __fdt_get_binary(self, node, prop):
  36. numbers = util.run_and_log(self.cons,
  37. f'fdtget -tbi {self.fit} {node} {prop}')
  38. bignum = bytearray()
  39. for little_num in numbers.split():
  40. bignum.append(int(little_num))
  41. return bignum
  42. def build_nodes_sets(self):
  43. """Fill sets with FIT images and configurations subnodes."""
  44. for node in self.__fdt_list('/images').split():
  45. subnode = f'/images/{node}'
  46. self.images_nodes.add(subnode)
  47. for node in self.__fdt_list('/configurations').split():
  48. subnode = f'/configurations/{node}'
  49. self.confgs_nodes.add(subnode)
  50. return len(self.images_nodes) + len(self.confgs_nodes)
  51. def check_fit_crc32_images(self):
  52. """Test that all images in the set are hashed as expected.
  53. Each image must have an hash with algo=crc32 and hash value must match
  54. the one calculated over image data.
  55. """
  56. for node in self.images_nodes:
  57. algo = self.__fdt_get_string(f'{node}/hash', 'algo')
  58. assert algo == "crc32\n", "Missing expected crc32 image hash!"
  59. raw_crc32 = self.__fdt_get_binary(f'{node}/hash', 'value')
  60. raw_bin = self.__fdt_get_binary(node, 'data')
  61. assert raw_crc32 == (binascii.crc32(raw_bin) &
  62. 0xffffffff).to_bytes(4, 'big'), "Wrong crc32 hash!"
  63. def check_fit_signed_images(self, key_name, sign_algo, verifier):
  64. """Test that all images in the set are signed as expected.
  65. Each image must have a signature with: key-name-hint matching key_name
  66. argument; algo matching sign_algo argument; value matching the one
  67. calculated over image data using verifier argument.
  68. """
  69. for node in self.images_nodes:
  70. hint = self.__fdt_get_string(f'{node}/signature', 'key-name-hint')
  71. assert hint == key_name + "\n", "Missing expected key name hint!"
  72. algo = self.__fdt_get_string(f'{node}/signature', 'algo')
  73. assert algo == sign_algo + "\n", "Missing expected signature algo!"
  74. raw_sig = self.__fdt_get_binary(f'{node}/signature', 'value')
  75. raw_bin = self.__fdt_get_binary(node, 'data')
  76. verifier.verify(SHA256.new(raw_bin), bytes(raw_sig))
  77. def check_fit_signed_confgs(self, key_name, sign_algo):
  78. """Test that all configs are signed, and images hashed, as expected.
  79. Each image must have an hash with algo=sha1 and hash value must match
  80. the one calculated over image data. Each configuration must have a
  81. signature with key-name-hint matching key_name argument and algo
  82. matching sign_algo argument.
  83. TODO: configurations signature checking.
  84. """
  85. for node in self.images_nodes:
  86. algo = self.__fdt_get_string(f'{node}/hash', 'algo')
  87. assert algo == "sha1\n", "Missing expected sha1 image hash!"
  88. raw_hash = self.__fdt_get_binary(f'{node}/hash', 'value')
  89. raw_bin = self.__fdt_get_binary(node, 'data')
  90. assert raw_hash == SHA1.new(raw_bin).digest(), "Wrong sha1 hash!"
  91. for node in self.confgs_nodes:
  92. hint = self.__fdt_get_string(f'{node}/signature', 'key-name-hint')
  93. assert hint == key_name + "\n", "Missing expected key name hint!"
  94. algo = self.__fdt_get_string(f'{node}/signature', 'algo')
  95. assert algo == sign_algo + "\n", "Missing expected signature algo!"
  96. @pytest.mark.buildconfigspec('fit_signature')
  97. @pytest.mark.requiredtool('fdtget')
  98. def test_fit_auto_signed(u_boot_console):
  99. """Test that mkimage generates auto-FIT with signatures/hashes as expected.
  100. The mkimage tool can create auto generated (i.e. without an ITS file
  101. provided as input) FIT in three different flavours: with crc32 checksums
  102. of 'images' subnodes; with signatures of 'images' subnodes; with sha1
  103. hashes of 'images' subnodes and signatures of 'configurations' subnodes.
  104. This test verifies that auto-FIT are generated as expected, in all of
  105. the three flavours, including check of hashes and signatures (except for
  106. configurations ones).
  107. The test does not run the sandbox. It only checks the host tool mkimage.
  108. """
  109. cons = u_boot_console
  110. mkimage = cons.config.build_dir + '/tools/mkimage'
  111. tempdir = os.path.join(cons.config.result_dir, 'auto_fit')
  112. os.makedirs(tempdir, exist_ok=True)
  113. kernel_file = f'{tempdir}/vmlinuz'
  114. dt1_file = f'{tempdir}/dt-1.dtb'
  115. dt2_file = f'{tempdir}/dt-2.dtb'
  116. key_name = 'sign-key'
  117. sign_algo = 'sha256,rsa4096'
  118. key_file = f'{tempdir}/{key_name}.key'
  119. fit_file = f'{tempdir}/test.fit'
  120. # Create a fake kernel image and two dtb files with random data
  121. with open(kernel_file, 'wb') as fd:
  122. fd.write(os.urandom(512))
  123. with open(dt1_file, 'wb') as fd:
  124. fd.write(os.urandom(256))
  125. with open(dt2_file, 'wb') as fd:
  126. fd.write(os.urandom(256))
  127. # Create 4096 RSA key and write to file to be read by mkimage
  128. key = RSA.generate(bits=4096)
  129. verifier = pkcs1_15.new(key)
  130. with open(key_file, 'w') as fd:
  131. fd.write(str(key.export_key(format='PEM').decode('ascii')))
  132. b_args = " -d" + kernel_file + " -b" + dt1_file + " -b" + dt2_file
  133. s_args = " -k" + tempdir + " -g" + key_name + " -o" + sign_algo
  134. # 1 - Create auto FIT with images crc32 checksum, and verify it
  135. util.run_and_log(cons, mkimage + ' -fauto' + b_args + " " + fit_file)
  136. fit = SignedFitHelper(cons, fit_file)
  137. if fit.build_nodes_sets() == 0:
  138. raise ValueError('FIT-1 has no "/image" nor "/configuration" nodes')
  139. fit.check_fit_crc32_images()
  140. # 2 - Create auto FIT with signed images, and verify it
  141. util.run_and_log(cons, mkimage + ' -fauto' + b_args + s_args + " " +
  142. fit_file)
  143. fit = SignedFitHelper(cons, fit_file)
  144. if fit.build_nodes_sets() == 0:
  145. raise ValueError('FIT-2 has no "/image" nor "/configuration" nodes')
  146. fit.check_fit_signed_images(key_name, sign_algo, verifier)
  147. # 3 - Create auto FIT with signed configs and hashed images, and verify it
  148. util.run_and_log(cons, mkimage + ' -fauto-conf' + b_args + s_args + " " +
  149. fit_file)
  150. fit = SignedFitHelper(cons, fit_file)
  151. if fit.build_nodes_sets() == 0:
  152. raise ValueError('FIT-3 has no "/image" nor "/configuration" nodes')
  153. fit.check_fit_signed_confgs(key_name, sign_algo)