1# SPDX-License-Identifier:	GPL-2.0+
2# Copyright (c) 2016, Google Inc.
3#
4# U-Boot Verified Boot Test
5
6"""
7This tests verified boot in the following ways:
8
9For image verification:
10- Create FIT (unsigned) with mkimage
11- Check that verification shows that no keys are verified
12- Sign image
13- Check that verification shows that a key is now verified
14
15For configuration verification:
16- Corrupt signature and check for failure
17- Create FIT (with unsigned configuration) with mkimage
18- Check that image verification works
19- Sign the FIT and mark the key as 'required' for verification
20- Check that image verification works
21- Corrupt the signature
22- Check that image verification no-longer works
23
24Tests run with both SHA1 and SHA256 hashing.
25"""
26
27import pytest
28import sys
29import struct
30import u_boot_utils as util
31
32@pytest.mark.boardspec('sandbox')
33@pytest.mark.buildconfigspec('fit_signature')
34@pytest.mark.requiredtool('dtc')
35@pytest.mark.requiredtool('fdtget')
36@pytest.mark.requiredtool('fdtput')
37@pytest.mark.requiredtool('openssl')
38def test_vboot(u_boot_console):
39    """Test verified boot signing with mkimage and verification with 'bootm'.
40
41    This works using sandbox only as it needs to update the device tree used
42    by U-Boot to hold public keys from the signing process.
43
44    The SHA1 and SHA256 tests are combined into a single test since the
45    key-generation process is quite slow and we want to avoid doing it twice.
46    """
47    def dtc(dts):
48        """Run the device tree compiler to compile a .dts file
49
50        The output file will be the same as the input file but with a .dtb
51        extension.
52
53        Args:
54            dts: Device tree file to compile.
55        """
56        dtb = dts.replace('.dts', '.dtb')
57        util.run_and_log(cons, 'dtc %s %s%s -O dtb '
58                         '-o %s%s' % (dtc_args, datadir, dts, tmpdir, dtb))
59
60    def run_bootm(sha_algo, test_type, expect_string, boots):
61        """Run a 'bootm' command U-Boot.
62
63        This always starts a fresh U-Boot instance since the device tree may
64        contain a new public key.
65
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
84    def make_fit(its):
85        """Make a new FIT from the .its source file.
86
87        This runs 'mkimage -f' to create a new FIT.
88
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
95    def sign_fit(sha_algo):
96        """Sign the FIT
97
98        Signs the FIT and writes the signature into it. It also writes the
99        public key into the dtb.
100
101        Args:
102            sha_algo: Either 'sha1' or 'sha256', to select the algorithm to
103                    use.
104        """
105        cons.log.action('%s: Sign images' % sha_algo)
106        util.run_and_log(cons, [mkimage, '-F', '-k', tmpdir, '-K', dtb,
107                                '-r', fit])
108
109    def replace_fit_totalsize(size):
110        """Replace FIT header's totalsize with something greater.
111
112        The totalsize must be less than or equal to FIT_SIGNATURE_MAX_SIZE.
113        If the size is greater, the signature verification should return false.
114
115        Args:
116            size: The new totalsize of the header
117
118        Returns:
119            prev_size: The previous totalsize read from the header
120        """
121        total_size = 0
122        with open(fit, 'r+b') as handle:
123            handle.seek(4)
124            total_size = handle.read(4)
125            handle.seek(4)
126            handle.write(struct.pack(">I", size))
127        return struct.unpack(">I", total_size)[0]
128
129    def test_with_algo(sha_algo, padding):
130        """Test verified boot with the given hash algorithm.
131
132        This is the main part of the test code. The same procedure is followed
133        for both hashing algorithms.
134
135        Args:
136            sha_algo: Either 'sha1' or 'sha256', to select the algorithm to
137                    use.
138        """
139        # Compile our device tree files for kernel and U-Boot. These are
140        # regenerated here since mkimage will modify them (by adding a
141        # public key) below.
142        dtc('sandbox-kernel.dts')
143        dtc('sandbox-u-boot.dts')
144
145        # Build the FIT, but don't sign anything yet
146        cons.log.action('%s: Test FIT with signed images' % sha_algo)
147        make_fit('sign-images-%s%s.its' % (sha_algo , padding))
148        run_bootm(sha_algo, 'unsigned images', 'dev-', True)
149
150        # Sign images with our dev keys
151        sign_fit(sha_algo)
152        run_bootm(sha_algo, 'signed images', 'dev+', True)
153
154        # Create a fresh .dtb without the public keys
155        dtc('sandbox-u-boot.dts')
156
157        cons.log.action('%s: Test FIT with signed configuration' % sha_algo)
158        make_fit('sign-configs-%s%s.its' % (sha_algo , padding))
159        run_bootm(sha_algo, 'unsigned config', '%s+ OK' % sha_algo, True)
160
161        # Sign images with our dev keys
162        sign_fit(sha_algo)
163        run_bootm(sha_algo, 'signed config', 'dev+', True)
164
165        cons.log.action('%s: Check signed config on the host' % sha_algo)
166
167        util.run_and_log(cons, [fit_check_sign, '-f', fit, '-k', tmpdir,
168                                '-k', dtb])
169
170        # Replace header bytes
171        bcfg = u_boot_console.config.buildconfig
172        max_size = int(bcfg.get('config_fit_signature_max_size', 0x10000000), 0)
173        existing_size = replace_fit_totalsize(max_size + 1)
174        run_bootm(sha_algo, 'Signed config with bad hash', 'Bad Data Hash', False)
175        cons.log.action('%s: Check overflowed FIT header totalsize' % sha_algo)
176
177        # Replace with existing header bytes
178        replace_fit_totalsize(existing_size)
179        run_bootm(sha_algo, 'signed config', 'dev+', True)
180        cons.log.action('%s: Check default FIT header totalsize' % sha_algo)
181
182        # Increment the first byte of the signature, which should cause failure
183        sig = util.run_and_log(cons, 'fdtget -t bx %s %s value' %
184                               (fit, sig_node))
185        byte_list = sig.split()
186        byte = int(byte_list[0], 16)
187        byte_list[0] = '%x' % (byte + 1)
188        sig = ' '.join(byte_list)
189        util.run_and_log(cons, 'fdtput -t bx %s %s value %s' %
190                         (fit, sig_node, sig))
191
192        run_bootm(sha_algo, 'Signed config with bad hash', 'Bad Data Hash', False)
193
194        cons.log.action('%s: Check bad config on the host' % sha_algo)
195        util.run_and_log_expect_exception(cons, [fit_check_sign, '-f', fit,
196                '-k', dtb], 1, 'Failed to verify required signature')
197
198    cons = u_boot_console
199    tmpdir = cons.config.result_dir + '/'
200    tmp = tmpdir + 'vboot.tmp'
201    datadir = cons.config.source_dir + '/test/py/tests/vboot/'
202    fit = '%stest.fit' % tmpdir
203    mkimage = cons.config.build_dir + '/tools/mkimage'
204    fit_check_sign = cons.config.build_dir + '/tools/fit_check_sign'
205    dtc_args = '-I dts -O dtb -i %s' % tmpdir
206    dtb = '%ssandbox-u-boot.dtb' % tmpdir
207    sig_node = '/configurations/conf-1/signature'
208
209    # Create an RSA key pair
210    public_exponent = 65537
211    util.run_and_log(cons, 'openssl genpkey -algorithm RSA -out %sdev.key '
212                     '-pkeyopt rsa_keygen_bits:2048 '
213                     '-pkeyopt rsa_keygen_pubexp:%d' %
214                     (tmpdir, public_exponent))
215
216    # Create a certificate containing the public key
217    util.run_and_log(cons, 'openssl req -batch -new -x509 -key %sdev.key -out '
218                     '%sdev.crt' % (tmpdir, tmpdir))
219
220    # Create a number kernel image with zeroes
221    with open('%stest-kernel.bin' % tmpdir, 'w') as fd:
222        fd.write(5000 * chr(0))
223
224    try:
225        # We need to use our own device tree file. Remember to restore it
226        # afterwards.
227        old_dtb = cons.config.dtb
228        cons.config.dtb = dtb
229        test_with_algo('sha1','')
230        test_with_algo('sha1','-pss')
231        test_with_algo('sha256','')
232        test_with_algo('sha256','-pss')
233    finally:
234        # Go back to the original U-Boot with the correct dtb.
235        cons.config.dtb = old_dtb
236        cons.restart_uboot()
237