test_vboot.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  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. For pre-load header verification:
  21. - Create FIT image with a pre-load header
  22. - Check that signature verification succeeds
  23. - Corrupt the FIT image
  24. - Check that signature verification fails
  25. - Launch an FIT image without a pre-load header
  26. - Check that image verification fails
  27. Tests run with both SHA1 and SHA256 hashing.
  28. This also tests fdt_add_pubkey utility in the simple way:
  29. - Create DTB and FIT files
  30. - Add keys with fdt_add_pubkey to DTB
  31. - Sign FIT image
  32. - Check with fit_check_sign that keys properly added to DTB file
  33. """
  34. import os
  35. import shutil
  36. import struct
  37. import pytest
  38. import u_boot_utils as util
  39. import vboot_forge
  40. import vboot_evil
  41. # Common helper functions
  42. def dtc(dts, cons, dtc_args, datadir, tmpdir, dtb):
  43. """Run the device tree compiler to compile a .dts file
  44. The output file will be the same as the input file but with a .dtb
  45. extension.
  46. Args:
  47. dts: Device tree file to compile.
  48. cons: U-Boot console.
  49. dtc_args: DTC arguments.
  50. datadir: Path to data directory.
  51. tmpdir: Path to temp directory.
  52. dtb: Resulting DTB file.
  53. """
  54. dtb = dts.replace('.dts', '.dtb')
  55. util.run_and_log(cons, 'dtc %s %s%s -O dtb '
  56. '-o %s%s' % (dtc_args, datadir, dts, tmpdir, dtb))
  57. def make_fit(its, cons, mkimage, dtc_args, datadir, fit):
  58. """Make a new FIT from the .its source file.
  59. This runs 'mkimage -f' to create a new FIT.
  60. Args:
  61. its: Filename containing .its source.
  62. cons: U-Boot console.
  63. mkimage: Path to mkimage utility.
  64. dtc_args: DTC arguments.
  65. datadir: Path to data directory.
  66. fit: Resulting FIT file.
  67. """
  68. util.run_and_log(cons, [mkimage, '-D', dtc_args, '-f',
  69. '%s%s' % (datadir, its), fit])
  70. # Only run the full suite on a few combinations, since it doesn't add any more
  71. # test coverage.
  72. TESTDATA_IN = [
  73. ['sha1-basic', 'sha1', '', None, False, True, False, False],
  74. ['sha1-pad', 'sha1', '', '-E -p 0x10000', False, False, False, False],
  75. ['sha1-pss', 'sha1', '-pss', None, False, False, False, False],
  76. ['sha1-pss-pad', 'sha1', '-pss', '-E -p 0x10000', False, False, False, False],
  77. ['sha256-basic', 'sha256', '', None, False, False, False, False],
  78. ['sha256-pad', 'sha256', '', '-E -p 0x10000', False, False, False, False],
  79. ['sha256-pss', 'sha256', '-pss', None, False, False, False, False],
  80. ['sha256-pss-pad', 'sha256', '-pss', '-E -p 0x10000', False, False, False, False],
  81. ['sha256-pss-required', 'sha256', '-pss', None, True, False, False, False],
  82. ['sha256-pss-pad-required', 'sha256', '-pss', '-E -p 0x10000', True, True, False, False],
  83. ['sha384-basic', 'sha384', '', None, False, False, False, False],
  84. ['sha384-pad', 'sha384', '', '-E -p 0x10000', False, False, False, False],
  85. ['algo-arg', 'algo-arg', '', '-o sha256,rsa2048', False, False, True, False],
  86. ['sha256-global-sign', 'sha256', '', '', False, False, False, True],
  87. ['sha256-global-sign-pss', 'sha256', '-pss', '', False, False, False, True],
  88. ]
  89. # Mark all but the first test as slow, so they are not run with '-k not slow'
  90. TESTDATA = [TESTDATA_IN[0]]
  91. TESTDATA += [pytest.param(*v, marks=pytest.mark.slow) for v in TESTDATA_IN[1:]]
  92. @pytest.mark.boardspec('sandbox')
  93. @pytest.mark.buildconfigspec('fit_signature')
  94. @pytest.mark.requiredtool('dtc')
  95. @pytest.mark.requiredtool('fdtget')
  96. @pytest.mark.requiredtool('fdtput')
  97. @pytest.mark.requiredtool('openssl')
  98. @pytest.mark.parametrize("name,sha_algo,padding,sign_options,required,full_test,algo_arg,global_sign",
  99. TESTDATA)
  100. def test_vboot(u_boot_console, name, sha_algo, padding, sign_options, required,
  101. full_test, algo_arg, global_sign):
  102. """Test verified boot signing with mkimage and verification with 'bootm'.
  103. This works using sandbox only as it needs to update the device tree used
  104. by U-Boot to hold public keys from the signing process.
  105. The SHA1 and SHA256 tests are combined into a single test since the
  106. key-generation process is quite slow and we want to avoid doing it twice.
  107. """
  108. def dtc_options(dts, options):
  109. """Run the device tree compiler to compile a .dts file
  110. The output file will be the same as the input file but with a .dtb
  111. extension.
  112. Args:
  113. dts: Device tree file to compile.
  114. options: Options provided to the compiler.
  115. """
  116. dtb = dts.replace('.dts', '.dtb')
  117. util.run_and_log(cons, 'dtc %s %s%s -O dtb '
  118. '-o %s%s %s' % (dtc_args, datadir, dts, tmpdir, dtb, options))
  119. def run_binman(dtb):
  120. """Run binman to build an image
  121. Args:
  122. dtb: Device tree file used as input file.
  123. """
  124. pythonpath = os.environ.get('PYTHONPATH', '')
  125. os.environ['PYTHONPATH'] = pythonpath + ':' + '%s/../scripts/dtc/pylibfdt' % tmpdir
  126. util.run_and_log(cons, [binman, 'build', '-d', "%s/%s" % (tmpdir,dtb),
  127. '-a', "pre-load-key-path=%s" % tmpdir, '-O',
  128. tmpdir, '-I', tmpdir])
  129. os.environ['PYTHONPATH'] = pythonpath
  130. def run_bootm(sha_algo, test_type, expect_string, boots, fit=None):
  131. """Run a 'bootm' command U-Boot.
  132. This always starts a fresh U-Boot instance since the device tree may
  133. contain a new public key.
  134. Args:
  135. test_type: A string identifying the test type.
  136. expect_string: A string which is expected in the output.
  137. sha_algo: Either 'sha1' or 'sha256', to select the algorithm to
  138. use.
  139. boots: A boolean that is True if Linux should boot and False if
  140. we are expected to not boot
  141. fit: FIT filename to load and verify
  142. """
  143. if not fit:
  144. fit = '%stest.fit' % tmpdir
  145. cons.restart_uboot()
  146. with cons.log.section('Verified boot %s %s' % (sha_algo, test_type)):
  147. output = cons.run_command_list(
  148. ['host load hostfs - 100 %s' % fit,
  149. 'fdt addr 100',
  150. 'bootm 100'])
  151. assert expect_string in ''.join(output)
  152. if boots:
  153. assert 'sandbox: continuing, as we cannot run' in ''.join(output)
  154. else:
  155. assert('sandbox: continuing, as we cannot run'
  156. not in ''.join(output))
  157. def sign_fit(sha_algo, options):
  158. """Sign the FIT
  159. Signs the FIT and writes the signature into it. It also writes the
  160. public key into the dtb.
  161. Args:
  162. sha_algo: Either 'sha1' or 'sha256', to select the algorithm to
  163. use.
  164. options: Options to provide to mkimage.
  165. """
  166. args = [mkimage, '-F', '-k', tmpdir, '-K', dtb, '-r', fit]
  167. if options:
  168. args += options.split(' ')
  169. cons.log.action('%s: Sign images' % sha_algo)
  170. util.run_and_log(cons, args)
  171. def sign_fit_dtb(sha_algo, options, dtb):
  172. """Sign the FIT
  173. Signs the FIT and writes the signature into it. It also writes the
  174. public key into the dtb.
  175. Args:
  176. sha_algo: Either 'sha1' or 'sha256', to select the algorithm to
  177. use.
  178. options: Options to provide to mkimage.
  179. """
  180. args = [mkimage, '-F', '-k', tmpdir, '-K', dtb, '-r', fit]
  181. if options:
  182. args += options.split(' ')
  183. cons.log.action('%s: Sign images' % sha_algo)
  184. util.run_and_log(cons, args)
  185. def sign_fit_norequire(sha_algo, options):
  186. """Sign the FIT
  187. Signs the FIT and writes the signature into it. It also writes the
  188. public key into the dtb. It does not mark key as 'required' in dtb.
  189. Args:
  190. sha_algo: Either 'sha1' or 'sha256', to select the algorithm to
  191. use.
  192. options: Options to provide to mkimage.
  193. """
  194. args = [mkimage, '-F', '-k', tmpdir, '-K', dtb, fit]
  195. if options:
  196. args += options.split(' ')
  197. cons.log.action('%s: Sign images' % sha_algo)
  198. util.run_and_log(cons, args)
  199. def replace_fit_totalsize(size):
  200. """Replace FIT header's totalsize with something greater.
  201. The totalsize must be less than or equal to FIT_SIGNATURE_MAX_SIZE.
  202. If the size is greater, the signature verification should return false.
  203. Args:
  204. size: The new totalsize of the header
  205. Returns:
  206. prev_size: The previous totalsize read from the header
  207. """
  208. total_size = 0
  209. with open(fit, 'r+b') as handle:
  210. handle.seek(4)
  211. total_size = handle.read(4)
  212. handle.seek(4)
  213. handle.write(struct.pack(">I", size))
  214. return struct.unpack(">I", total_size)[0]
  215. def corrupt_file(fit, offset, value):
  216. """Corrupt a file
  217. To corrupt a file, a value is written at the specified offset
  218. Args:
  219. fit: The file to corrupt
  220. offset: Offset to write
  221. value: Value written
  222. """
  223. with open(fit, 'r+b') as handle:
  224. handle.seek(offset)
  225. handle.write(struct.pack(">I", value))
  226. def create_rsa_pair(name):
  227. """Generate a new RSA key paid and certificate
  228. Args:
  229. name: Name of of the key (e.g. 'dev')
  230. """
  231. public_exponent = 65537
  232. if sha_algo == "sha384":
  233. rsa_keygen_bits = 3072
  234. else:
  235. rsa_keygen_bits = 2048
  236. util.run_and_log(cons, 'openssl genpkey -algorithm RSA -out %s%s.key '
  237. '-pkeyopt rsa_keygen_bits:%d '
  238. '-pkeyopt rsa_keygen_pubexp:%d' %
  239. (tmpdir, name, rsa_keygen_bits, public_exponent))
  240. # Create a certificate containing the public key
  241. util.run_and_log(cons, 'openssl req -batch -new -x509 -key %s%s.key '
  242. '-out %s%s.crt' % (tmpdir, name, tmpdir, name))
  243. def test_with_algo(sha_algo, padding, sign_options):
  244. """Test verified boot with the given hash algorithm.
  245. This is the main part of the test code. The same procedure is followed
  246. for both hashing algorithms.
  247. Args:
  248. sha_algo: Either 'sha1' or 'sha256', to select the algorithm to
  249. use.
  250. padding: Either '' or '-pss', to select the padding to use for the
  251. rsa signature algorithm.
  252. sign_options: Options to mkimage when signing a fit image.
  253. """
  254. # Compile our device tree files for kernel and U-Boot. These are
  255. # regenerated here since mkimage will modify them (by adding a
  256. # public key) below.
  257. dtc('sandbox-kernel.dts', cons, dtc_args, datadir, tmpdir, dtb)
  258. dtc('sandbox-u-boot.dts', cons, dtc_args, datadir, tmpdir, dtb)
  259. # Build the FIT, but don't sign anything yet
  260. cons.log.action('%s: Test FIT with signed images' % sha_algo)
  261. make_fit('sign-images-%s%s.its' % (sha_algo, padding), cons, mkimage, dtc_args, datadir, fit)
  262. run_bootm(sha_algo, 'unsigned images', ' - OK' if algo_arg else 'dev-', True)
  263. # Sign images with our dev keys
  264. sign_fit(sha_algo, sign_options)
  265. run_bootm(sha_algo, 'signed images', 'dev+', True)
  266. # Create a fresh .dtb without the public keys
  267. dtc('sandbox-u-boot.dts', cons, dtc_args, datadir, tmpdir, dtb)
  268. cons.log.action('%s: Test FIT with signed configuration' % sha_algo)
  269. make_fit('sign-configs-%s%s.its' % (sha_algo, padding), cons, mkimage, dtc_args, datadir, fit)
  270. run_bootm(sha_algo, 'unsigned config', '%s+ OK' % ('sha256' if algo_arg else sha_algo), True)
  271. # Sign images with our dev keys
  272. sign_fit(sha_algo, sign_options)
  273. run_bootm(sha_algo, 'signed config', 'dev+', True)
  274. cons.log.action('%s: Check signed config on the host' % sha_algo)
  275. util.run_and_log(cons, [fit_check_sign, '-f', fit, '-k', dtb])
  276. if full_test:
  277. # Make sure that U-Boot checks that the config is in the list of
  278. # hashed nodes. If it isn't, a security bypass is possible.
  279. ffit = '%stest.forged.fit' % tmpdir
  280. shutil.copyfile(fit, ffit)
  281. with open(ffit, 'rb') as fd:
  282. root, strblock = vboot_forge.read_fdt(fd)
  283. root, strblock = vboot_forge.manipulate(root, strblock)
  284. with open(ffit, 'w+b') as fd:
  285. vboot_forge.write_fdt(root, strblock, fd)
  286. util.run_and_log_expect_exception(
  287. cons, [fit_check_sign, '-f', ffit, '-k', dtb],
  288. 1, 'Failed to verify required signature')
  289. run_bootm(sha_algo, 'forged config', 'Bad Data Hash', False, ffit)
  290. # Try adding an evil root node. This should be detected.
  291. efit = '%stest.evilf.fit' % tmpdir
  292. shutil.copyfile(fit, efit)
  293. vboot_evil.add_evil_node(fit, efit, evil_kernel, 'fakeroot')
  294. util.run_and_log_expect_exception(
  295. cons, [fit_check_sign, '-f', efit, '-k', dtb],
  296. 1, 'Failed to verify required signature')
  297. run_bootm(sha_algo, 'evil fakeroot', 'Bad FIT kernel image format',
  298. False, efit)
  299. # Try adding an @ to the kernel node name. This should be detected.
  300. efit = '%stest.evilk.fit' % tmpdir
  301. shutil.copyfile(fit, efit)
  302. vboot_evil.add_evil_node(fit, efit, evil_kernel, 'kernel@')
  303. msg = 'Signature checking prevents use of unit addresses (@) in nodes'
  304. util.run_and_log_expect_exception(
  305. cons, [fit_check_sign, '-f', efit, '-k', dtb],
  306. 1, msg)
  307. run_bootm(sha_algo, 'evil kernel@', msg, False, efit)
  308. # Create a new properly signed fit and replace header bytes
  309. make_fit('sign-configs-%s%s.its' % (sha_algo, padding), cons, mkimage, dtc_args, datadir, fit)
  310. sign_fit(sha_algo, sign_options)
  311. bcfg = u_boot_console.config.buildconfig
  312. max_size = int(bcfg.get('config_fit_signature_max_size', 0x10000000), 0)
  313. existing_size = replace_fit_totalsize(max_size + 1)
  314. run_bootm(sha_algo, 'Signed config with bad hash', 'Bad Data Hash',
  315. False)
  316. cons.log.action('%s: Check overflowed FIT header totalsize' % sha_algo)
  317. # Replace with existing header bytes
  318. replace_fit_totalsize(existing_size)
  319. run_bootm(sha_algo, 'signed config', 'dev+', True)
  320. cons.log.action('%s: Check default FIT header totalsize' % sha_algo)
  321. # Increment the first byte of the signature, which should cause failure
  322. sig = util.run_and_log(cons, 'fdtget -t bx %s %s value' %
  323. (fit, sig_node))
  324. byte_list = sig.split()
  325. byte = int(byte_list[0], 16)
  326. byte_list[0] = '%x' % (byte + 1)
  327. sig = ' '.join(byte_list)
  328. util.run_and_log(cons, 'fdtput -t bx %s %s value %s' %
  329. (fit, sig_node, sig))
  330. run_bootm(sha_algo, 'Signed config with bad hash', 'Bad Data Hash',
  331. False)
  332. cons.log.action('%s: Check bad config on the host' % sha_algo)
  333. util.run_and_log_expect_exception(
  334. cons, [fit_check_sign, '-f', fit, '-k', dtb],
  335. 1, 'Failed to verify required signature')
  336. def test_required_key(sha_algo, padding, sign_options):
  337. """Test verified boot with the given hash algorithm.
  338. This function tests if U-Boot rejects an image when a required key isn't
  339. used to sign a FIT.
  340. Args:
  341. sha_algo: Either 'sha1' or 'sha256', to select the algorithm to use
  342. padding: Either '' or '-pss', to select the padding to use for the
  343. rsa signature algorithm.
  344. sign_options: Options to mkimage when signing a fit image.
  345. """
  346. # Compile our device tree files for kernel and U-Boot. These are
  347. # regenerated here since mkimage will modify them (by adding a
  348. # public key) below.
  349. dtc('sandbox-kernel.dts', cons, dtc_args, datadir, tmpdir, dtb)
  350. dtc('sandbox-u-boot.dts', cons, dtc_args, datadir, tmpdir, dtb)
  351. cons.log.action('%s: Test FIT with configs images' % sha_algo)
  352. # Build the FIT with prod key (keys required) and sign it. This puts the
  353. # signature into sandbox-u-boot.dtb, marked 'required'
  354. make_fit('sign-configs-%s%s-prod.its' % (sha_algo, padding), cons, mkimage, dtc_args, datadir, fit)
  355. sign_fit(sha_algo, sign_options)
  356. # Build the FIT with dev key (keys NOT required). This adds the
  357. # signature into sandbox-u-boot.dtb, NOT marked 'required'.
  358. make_fit('sign-configs-%s%s.its' % (sha_algo, padding), cons, mkimage, dtc_args, datadir, fit)
  359. sign_fit_norequire(sha_algo, sign_options)
  360. # So now sandbox-u-boot.dtb two signatures, for the prod and dev keys.
  361. # Only the prod key is set as 'required'. But FIT we just built has
  362. # a dev signature only (sign_fit_norequire() overwrites the FIT).
  363. # Try to boot the FIT with dev key. This FIT should not be accepted by
  364. # U-Boot because the prod key is required.
  365. run_bootm(sha_algo, 'required key', '', False)
  366. # Build the FIT with dev key (keys required) and sign it. This puts the
  367. # signature into sandbox-u-boot.dtb, marked 'required'.
  368. make_fit('sign-configs-%s%s.its' % (sha_algo, padding), cons, mkimage, dtc_args, datadir, fit)
  369. sign_fit(sha_algo, sign_options)
  370. # Set the required-mode policy to "any".
  371. # So now sandbox-u-boot.dtb two signatures, for the prod and dev keys.
  372. # Both the dev and prod key are set as 'required'. But FIT we just built has
  373. # a dev signature only (sign_fit() overwrites the FIT).
  374. # Try to boot the FIT with dev key. This FIT should be accepted by
  375. # U-Boot because the dev key is required and policy is "any" required key.
  376. util.run_and_log(cons, 'fdtput -t s %s /signature required-mode any' %
  377. (dtb))
  378. run_bootm(sha_algo, 'multi required key', 'dev+', True)
  379. # Set the required-mode policy to "all".
  380. # So now sandbox-u-boot.dtb two signatures, for the prod and dev keys.
  381. # Both the dev and prod key are set as 'required'. But FIT we just built has
  382. # a dev signature only (sign_fit() overwrites the FIT).
  383. # Try to boot the FIT with dev key. This FIT should not be accepted by
  384. # U-Boot because the prod key is required and policy is "all" required key
  385. util.run_and_log(cons, 'fdtput -t s %s /signature required-mode all' %
  386. (dtb))
  387. run_bootm(sha_algo, 'multi required key', '', False)
  388. def test_global_sign(sha_algo, padding, sign_options):
  389. """Test global image signature with the given hash algorithm and padding.
  390. Args:
  391. sha_algo: Either 'sha1' or 'sha256', to select the algorithm to use
  392. padding: Either '' or '-pss', to select the padding to use for the
  393. rsa signature algorithm.
  394. """
  395. dtb = '%ssandbox-u-boot-global%s.dtb' % (tmpdir, padding)
  396. cons.config.dtb = dtb
  397. # Compile our device tree files for kernel and U-Boot. These are
  398. # regenerated here since mkimage will modify them (by adding a
  399. # public key) below.
  400. dtc('sandbox-kernel.dts', cons, dtc_args, datadir, tmpdir, dtb)
  401. dtc_options('sandbox-u-boot-global%s.dts' % padding, '-p 1024')
  402. # Build the FIT with dev key (keys NOT required). This adds the
  403. # signature into sandbox-u-boot.dtb, NOT marked 'required'.
  404. make_fit('simple-images.its', cons, mkimage, dtc_args, datadir, fit)
  405. sign_fit_dtb(sha_algo, '', dtb)
  406. # Build the dtb for binman that define the pre-load header
  407. # with the global sigature.
  408. dtc('sandbox-binman%s.dts' % padding, cons, dtc_args, datadir, tmpdir, dtb)
  409. # Run binman to create the final image with the not signed fit
  410. # and the pre-load header that contains the global signature.
  411. run_binman('sandbox-binman%s.dtb' % padding)
  412. # Check that the signature is correctly verified by u-boot
  413. run_bootm(sha_algo, 'global image signature',
  414. 'signature check has succeed', True, "%ssandbox.img" % tmpdir)
  415. # Corrupt the image (just one byte after the pre-load header)
  416. corrupt_file("%ssandbox.img" % tmpdir, 4096, 255);
  417. # Check that the signature verification fails
  418. run_bootm(sha_algo, 'global image signature',
  419. 'signature check has failed', False, "%ssandbox.img" % tmpdir)
  420. # Check that the boot fails if the global signature is not provided
  421. run_bootm(sha_algo, 'global image signature', 'signature is mandatory', False)
  422. cons = u_boot_console
  423. tmpdir = os.path.join(cons.config.result_dir, name) + '/'
  424. if not os.path.exists(tmpdir):
  425. os.mkdir(tmpdir)
  426. datadir = cons.config.source_dir + '/test/py/tests/vboot/'
  427. fit = '%stest.fit' % tmpdir
  428. mkimage = cons.config.build_dir + '/tools/mkimage'
  429. binman = cons.config.source_dir + '/tools/binman/binman'
  430. fit_check_sign = cons.config.build_dir + '/tools/fit_check_sign'
  431. dtc_args = '-I dts -O dtb -i %s' % tmpdir
  432. dtb = '%ssandbox-u-boot.dtb' % tmpdir
  433. sig_node = '/configurations/conf-1/signature'
  434. create_rsa_pair('dev')
  435. create_rsa_pair('prod')
  436. # Create a number kernel image with zeroes
  437. with open('%stest-kernel.bin' % tmpdir, 'wb') as fd:
  438. fd.write(500 * b'\0')
  439. # Create a second kernel image with ones
  440. evil_kernel = '%stest-kernel1.bin' % tmpdir
  441. with open(evil_kernel, 'wb') as fd:
  442. fd.write(500 * b'\x01')
  443. try:
  444. # We need to use our own device tree file. Remember to restore it
  445. # afterwards.
  446. old_dtb = cons.config.dtb
  447. cons.config.dtb = dtb
  448. if global_sign:
  449. test_global_sign(sha_algo, padding, sign_options)
  450. elif required:
  451. test_required_key(sha_algo, padding, sign_options)
  452. else:
  453. test_with_algo(sha_algo, padding, sign_options)
  454. finally:
  455. # Go back to the original U-Boot with the correct dtb.
  456. cons.config.dtb = old_dtb
  457. cons.restart_uboot()
  458. TESTDATA_IN = [
  459. ['sha1-basic', 'sha1', '', None, False],
  460. ['sha1-pad', 'sha1', '', '-E -p 0x10000', False],
  461. ['sha1-pss', 'sha1', '-pss', None, False],
  462. ['sha1-pss-pad', 'sha1', '-pss', '-E -p 0x10000', False],
  463. ['sha256-basic', 'sha256', '', None, False],
  464. ['sha256-pad', 'sha256', '', '-E -p 0x10000', False],
  465. ['sha256-pss', 'sha256', '-pss', None, False],
  466. ['sha256-pss-pad', 'sha256', '-pss', '-E -p 0x10000', False],
  467. ['sha256-pss-required', 'sha256', '-pss', None, False],
  468. ['sha256-pss-pad-required', 'sha256', '-pss', '-E -p 0x10000', False],
  469. ['sha384-basic', 'sha384', '', None, False],
  470. ['sha384-pad', 'sha384', '', '-E -p 0x10000', False],
  471. ['algo-arg', 'algo-arg', '', '-o sha256,rsa2048', True],
  472. ['sha256-global-sign', 'sha256', '', '', False],
  473. ['sha256-global-sign-pss', 'sha256', '-pss', '', False],
  474. ]
  475. # Mark all but the first test as slow, so they are not run with '-k not slow'
  476. TESTDATA = [TESTDATA_IN[0]]
  477. TESTDATA += [pytest.param(*v, marks=pytest.mark.slow) for v in TESTDATA_IN[1:]]
  478. @pytest.mark.boardspec('sandbox')
  479. @pytest.mark.buildconfigspec('fit_signature')
  480. @pytest.mark.requiredtool('dtc')
  481. @pytest.mark.requiredtool('openssl')
  482. @pytest.mark.parametrize("name,sha_algo,padding,sign_options,algo_arg", TESTDATA)
  483. def test_fdt_add_pubkey(u_boot_console, name, sha_algo, padding, sign_options, algo_arg):
  484. """Test fdt_add_pubkey utility with bunch of different algo options."""
  485. def sign_fit(sha_algo, options):
  486. """Sign the FIT
  487. Signs the FIT and writes the signature into it.
  488. Args:
  489. sha_algo: Either 'sha1' or 'sha256', to select the algorithm to
  490. use.
  491. options: Options to provide to mkimage.
  492. """
  493. args = [mkimage, '-F', '-k', tmpdir, fit]
  494. if options:
  495. args += options.split(' ')
  496. cons.log.action('%s: Sign images' % sha_algo)
  497. util.run_and_log(cons, args)
  498. def test_add_pubkey(sha_algo, padding, sign_options):
  499. """Test fdt_add_pubkey utility with given hash algorithm and padding.
  500. This function tests if fdt_add_pubkey utility may add public keys into dtb.
  501. Args:
  502. sha_algo: Either 'sha1' or 'sha256', to select the algorithm to use
  503. padding: Either '' or '-pss', to select the padding to use for the
  504. rsa signature algorithm.
  505. sign_options: Options to mkimage when signing a fit image.
  506. """
  507. # Create a fresh .dtb without the public keys
  508. dtc('sandbox-u-boot.dts', cons, dtc_args, datadir, tmpdir, dtb)
  509. cons.log.action('%s: Test fdt_add_pubkey with signed configuration' % sha_algo)
  510. # Then add the dev key via the fdt_add_pubkey tool
  511. util.run_and_log(cons, [fdt_add_pubkey, '-a', '%s,%s' % ('sha256' if algo_arg else sha_algo, \
  512. 'rsa3072' if sha_algo == 'sha384' else 'rsa2048'),
  513. '-k', tmpdir, '-n', 'dev', '-r', 'conf', dtb])
  514. make_fit('sign-configs-%s%s.its' % (sha_algo, padding), cons, mkimage, dtc_args, datadir, fit)
  515. # Sign images with our dev keys
  516. sign_fit(sha_algo, sign_options)
  517. # Check with fit_check_sign that FIT is signed with key
  518. util.run_and_log(cons, [fit_check_sign, '-f', fit, '-k', dtb])
  519. cons = u_boot_console
  520. tmpdir = os.path.join(cons.config.result_dir, name) + '/'
  521. if not os.path.exists(tmpdir):
  522. os.mkdir(tmpdir)
  523. datadir = cons.config.source_dir + '/test/py/tests/vboot/'
  524. fit = '%stest.fit' % tmpdir
  525. mkimage = cons.config.build_dir + '/tools/mkimage'
  526. binman = cons.config.source_dir + '/tools/binman/binman'
  527. fit_check_sign = cons.config.build_dir + '/tools/fit_check_sign'
  528. fdt_add_pubkey = cons.config.build_dir + '/tools/fdt_add_pubkey'
  529. dtc_args = '-I dts -O dtb -i %s' % tmpdir
  530. dtb = '%ssandbox-u-boot.dtb' % tmpdir
  531. # keys created in test_vboot test
  532. test_add_pubkey(sha_algo, padding, sign_options)