test_vboot.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. # SPDX-License-Identifier: GPL-2.0+
  2. # Copyright (c) 2016, Google Inc.
  3. #
  4. # U-Boot Verified Boot Test
  5. """
  6. This tests verified boot in the following ways:
  7. For image verification:
  8. - Create FIT (unsigned) with mkimage
  9. - Check that verification shows that no keys are verified
  10. - Sign image
  11. - Check that verification shows that a key is now verified
  12. For configuration verification:
  13. - Corrupt signature and check for failure
  14. - Create FIT (with unsigned configuration) with mkimage
  15. - Check that image verification works
  16. - Sign the FIT and mark the key as 'required' for verification
  17. - Check that image verification works
  18. - Corrupt the signature
  19. - Check that image verification no-longer works
  20. Tests run with both SHA1 and SHA256 hashing.
  21. """
  22. import struct
  23. import pytest
  24. import u_boot_utils as util
  25. import vboot_forge
  26. TESTDATA = [
  27. ['sha1', '', None, False],
  28. ['sha1', '', '-E -p 0x10000', False],
  29. ['sha1', '-pss', None, False],
  30. ['sha1', '-pss', '-E -p 0x10000', False],
  31. ['sha256', '', None, False],
  32. ['sha256', '', '-E -p 0x10000', False],
  33. ['sha256', '-pss', None, False],
  34. ['sha256', '-pss', '-E -p 0x10000', False],
  35. ['sha256', '-pss', None, True],
  36. ['sha256', '-pss', '-E -p 0x10000', True],
  37. ]
  38. @pytest.mark.boardspec('sandbox')
  39. @pytest.mark.buildconfigspec('fit_signature')
  40. @pytest.mark.requiredtool('dtc')
  41. @pytest.mark.requiredtool('fdtget')
  42. @pytest.mark.requiredtool('fdtput')
  43. @pytest.mark.requiredtool('openssl')
  44. @pytest.mark.parametrize("sha_algo,padding,sign_options,required", TESTDATA)
  45. def test_vboot(u_boot_console, sha_algo, padding, sign_options, required):
  46. """Test verified boot signing with mkimage and verification with 'bootm'.
  47. This works using sandbox only as it needs to update the device tree used
  48. by U-Boot to hold public keys from the signing process.
  49. The SHA1 and SHA256 tests are combined into a single test since the
  50. key-generation process is quite slow and we want to avoid doing it twice.
  51. """
  52. def dtc(dts):
  53. """Run the device tree compiler to compile a .dts file
  54. The output file will be the same as the input file but with a .dtb
  55. extension.
  56. Args:
  57. dts: Device tree file to compile.
  58. """
  59. dtb = dts.replace('.dts', '.dtb')
  60. util.run_and_log(cons, 'dtc %s %s%s -O dtb '
  61. '-o %s%s' % (dtc_args, datadir, dts, tmpdir, dtb))
  62. def run_bootm(sha_algo, test_type, expect_string, boots):
  63. """Run a 'bootm' command U-Boot.
  64. This always starts a fresh U-Boot instance since the device tree may
  65. contain a new public key.
  66. Args:
  67. test_type: A string identifying the test type.
  68. expect_string: A string which is expected in the output.
  69. sha_algo: Either 'sha1' or 'sha256', to select the algorithm to
  70. use.
  71. boots: A boolean that is True if Linux should boot and False if
  72. we are expected to not boot
  73. """
  74. cons.restart_uboot()
  75. with cons.log.section('Verified boot %s %s' % (sha_algo, test_type)):
  76. output = cons.run_command_list(
  77. ['host load hostfs - 100 %stest.fit' % tmpdir,
  78. 'fdt addr 100',
  79. 'bootm 100'])
  80. assert expect_string in ''.join(output)
  81. if boots:
  82. assert 'sandbox: continuing, as we cannot run' in ''.join(output)
  83. else:
  84. assert('sandbox: continuing, as we cannot run'
  85. not in ''.join(output))
  86. def make_fit(its):
  87. """Make a new FIT from the .its source file.
  88. This runs 'mkimage -f' to create a new FIT.
  89. Args:
  90. its: Filename containing .its source.
  91. """
  92. util.run_and_log(cons, [mkimage, '-D', dtc_args, '-f',
  93. '%s%s' % (datadir, its), fit])
  94. def sign_fit(sha_algo, options):
  95. """Sign the FIT
  96. Signs the FIT and writes the signature into it. It also writes the
  97. public key into the dtb.
  98. Args:
  99. sha_algo: Either 'sha1' or 'sha256', to select the algorithm to
  100. use.
  101. options: Options to provide to mkimage.
  102. """
  103. args = [mkimage, '-F', '-k', tmpdir, '-K', dtb, '-r', fit]
  104. if options:
  105. args += options.split(' ')
  106. cons.log.action('%s: Sign images' % sha_algo)
  107. util.run_and_log(cons, args)
  108. def replace_fit_totalsize(size):
  109. """Replace FIT header's totalsize with something greater.
  110. The totalsize must be less than or equal to FIT_SIGNATURE_MAX_SIZE.
  111. If the size is greater, the signature verification should return false.
  112. Args:
  113. size: The new totalsize of the header
  114. Returns:
  115. prev_size: The previous totalsize read from the header
  116. """
  117. total_size = 0
  118. with open(fit, 'r+b') as handle:
  119. handle.seek(4)
  120. total_size = handle.read(4)
  121. handle.seek(4)
  122. handle.write(struct.pack(">I", size))
  123. return struct.unpack(">I", total_size)[0]
  124. def create_rsa_pair(name):
  125. """Generate a new RSA key paid and certificate
  126. Args:
  127. name: Name of of the key (e.g. 'dev')
  128. """
  129. public_exponent = 65537
  130. util.run_and_log(cons, 'openssl genpkey -algorithm RSA -out %s%s.key '
  131. '-pkeyopt rsa_keygen_bits:2048 '
  132. '-pkeyopt rsa_keygen_pubexp:%d' %
  133. (tmpdir, name, public_exponent))
  134. # Create a certificate containing the public key
  135. util.run_and_log(cons, 'openssl req -batch -new -x509 -key %s%s.key '
  136. '-out %s%s.crt' % (tmpdir, name, tmpdir, name))
  137. def test_with_algo(sha_algo, padding, sign_options):
  138. """Test verified boot with the given hash algorithm.
  139. This is the main part of the test code. The same procedure is followed
  140. for both hashing algorithms.
  141. Args:
  142. sha_algo: Either 'sha1' or 'sha256', to select the algorithm to
  143. use.
  144. padding: Either '' or '-pss', to select the padding to use for the
  145. rsa signature algorithm.
  146. sign_options: Options to mkimage when signing a fit image.
  147. """
  148. # Compile our device tree files for kernel and U-Boot. These are
  149. # regenerated here since mkimage will modify them (by adding a
  150. # public key) below.
  151. dtc('sandbox-kernel.dts')
  152. dtc('sandbox-u-boot.dts')
  153. # Build the FIT, but don't sign anything yet
  154. cons.log.action('%s: Test FIT with signed images' % sha_algo)
  155. make_fit('sign-images-%s%s.its' % (sha_algo, padding))
  156. run_bootm(sha_algo, 'unsigned images', 'dev-', True)
  157. # Sign images with our dev keys
  158. sign_fit(sha_algo, sign_options)
  159. run_bootm(sha_algo, 'signed images', 'dev+', True)
  160. # Create a fresh .dtb without the public keys
  161. dtc('sandbox-u-boot.dts')
  162. cons.log.action('%s: Test FIT with signed configuration' % sha_algo)
  163. make_fit('sign-configs-%s%s.its' % (sha_algo, padding))
  164. run_bootm(sha_algo, 'unsigned config', '%s+ OK' % sha_algo, True)
  165. # Sign images with our dev keys
  166. sign_fit(sha_algo, sign_options)
  167. run_bootm(sha_algo, 'signed config', 'dev+', True)
  168. cons.log.action('%s: Check signed config on the host' % sha_algo)
  169. util.run_and_log(cons, [fit_check_sign, '-f', fit, '-k', dtb])
  170. # Make sure that U-Boot checks that the config is in the list of hashed
  171. # nodes. If it isn't, a security bypass is possible.
  172. with open(fit, 'rb') as fd:
  173. root, strblock = vboot_forge.read_fdt(fd)
  174. root, strblock = vboot_forge.manipulate(root, strblock)
  175. with open(fit, 'w+b') as fd:
  176. vboot_forge.write_fdt(root, strblock, fd)
  177. util.run_and_log_expect_exception(
  178. cons, [fit_check_sign, '-f', fit, '-k', dtb],
  179. 1, 'Failed to verify required signature')
  180. run_bootm(sha_algo, 'forged config', 'Bad Data Hash', False)
  181. # Create a new properly signed fit and replace header bytes
  182. make_fit('sign-configs-%s%s.its' % (sha_algo, padding))
  183. sign_fit(sha_algo, sign_options)
  184. bcfg = u_boot_console.config.buildconfig
  185. max_size = int(bcfg.get('config_fit_signature_max_size', 0x10000000), 0)
  186. existing_size = replace_fit_totalsize(max_size + 1)
  187. run_bootm(sha_algo, 'Signed config with bad hash', 'Bad Data Hash',
  188. False)
  189. cons.log.action('%s: Check overflowed FIT header totalsize' % sha_algo)
  190. # Replace with existing header bytes
  191. replace_fit_totalsize(existing_size)
  192. run_bootm(sha_algo, 'signed config', 'dev+', True)
  193. cons.log.action('%s: Check default FIT header totalsize' % sha_algo)
  194. # Increment the first byte of the signature, which should cause failure
  195. sig = util.run_and_log(cons, 'fdtget -t bx %s %s value' %
  196. (fit, sig_node))
  197. byte_list = sig.split()
  198. byte = int(byte_list[0], 16)
  199. byte_list[0] = '%x' % (byte + 1)
  200. sig = ' '.join(byte_list)
  201. util.run_and_log(cons, 'fdtput -t bx %s %s value %s' %
  202. (fit, sig_node, sig))
  203. run_bootm(sha_algo, 'Signed config with bad hash', 'Bad Data Hash',
  204. False)
  205. cons.log.action('%s: Check bad config on the host' % sha_algo)
  206. util.run_and_log_expect_exception(
  207. cons, [fit_check_sign, '-f', fit, '-k', dtb],
  208. 1, 'Failed to verify required signature')
  209. def test_required_key(sha_algo, padding, sign_options):
  210. """Test verified boot with the given hash algorithm.
  211. This function tests if U-Boot rejects an image when a required key isn't
  212. used to sign a FIT.
  213. Args:
  214. sha_algo: Either 'sha1' or 'sha256', to select the algorithm to use
  215. padding: Either '' or '-pss', to select the padding to use for the
  216. rsa signature algorithm.
  217. sign_options: Options to mkimage when signing a fit image.
  218. """
  219. # Compile our device tree files for kernel and U-Boot. These are
  220. # regenerated here since mkimage will modify them (by adding a
  221. # public key) below.
  222. dtc('sandbox-kernel.dts')
  223. dtc('sandbox-u-boot.dts')
  224. cons.log.action('%s: Test FIT with configs images' % sha_algo)
  225. # Build the FIT with prod key (keys required) and sign it. This puts the
  226. # signature into sandbox-u-boot.dtb, marked 'required'
  227. make_fit('sign-configs-%s%s-prod.its' % (sha_algo, padding))
  228. sign_fit(sha_algo, sign_options)
  229. # Build the FIT with dev key (keys NOT required). This adds the
  230. # signature into sandbox-u-boot.dtb, NOT marked 'required'.
  231. make_fit('sign-configs-%s%s.its' % (sha_algo, padding))
  232. sign_fit(sha_algo, sign_options)
  233. # So now sandbox-u-boot.dtb two signatures, for the prod and dev keys.
  234. # Only the prod key is set as 'required'. But FIT we just built has
  235. # a dev signature only (sign_fit() overwrites the FIT).
  236. # Try to boot the FIT with dev key. This FIT should not be accepted by
  237. # U-Boot because the prod key is required.
  238. run_bootm(sha_algo, 'required key', '', False)
  239. cons = u_boot_console
  240. tmpdir = cons.config.result_dir + '/'
  241. datadir = cons.config.source_dir + '/test/py/tests/vboot/'
  242. fit = '%stest.fit' % tmpdir
  243. mkimage = cons.config.build_dir + '/tools/mkimage'
  244. fit_check_sign = cons.config.build_dir + '/tools/fit_check_sign'
  245. dtc_args = '-I dts -O dtb -i %s' % tmpdir
  246. dtb = '%ssandbox-u-boot.dtb' % tmpdir
  247. sig_node = '/configurations/conf-1/signature'
  248. create_rsa_pair('dev')
  249. create_rsa_pair('prod')
  250. # Create a number kernel image with zeroes
  251. with open('%stest-kernel.bin' % tmpdir, 'w') as fd:
  252. fd.write(500 * chr(0))
  253. try:
  254. # We need to use our own device tree file. Remember to restore it
  255. # afterwards.
  256. old_dtb = cons.config.dtb
  257. cons.config.dtb = dtb
  258. if required:
  259. test_required_key(sha_algo, padding, sign_options)
  260. else:
  261. test_with_algo(sha_algo, padding, sign_options)
  262. finally:
  263. # Go back to the original U-Boot with the correct dtb.
  264. cons.config.dtb = old_dtb
  265. cons.restart_uboot()