blob: 1cc539f2012f1359aeb0edb30274bd55ad34d46e [file] [log] [blame]
Tianjie Xu67c7cbb2018-08-30 00:32:07 -07001#
2# Copyright (C) 2018 The Android Open Source Project
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
16
17"""Unittests for verity_utils.py."""
18
Tao Bao4a0d5132018-10-17 22:53:54 -070019import copy
Tao Bao71197512018-10-11 14:08:45 -070020import math
Tianjie Xu67c7cbb2018-08-30 00:32:07 -070021import os.path
Tao Bao71197512018-10-11 14:08:45 -070022import random
Tianjie Xu67c7cbb2018-08-30 00:32:07 -070023
Tianjie Xu67c7cbb2018-08-30 00:32:07 -070024import common
25import sparse_img
Tianjie Xu67c7cbb2018-08-30 00:32:07 -070026from rangelib import RangeSet
Tao Bao82490d32019-04-09 00:12:30 -070027from test_utils import (
28 get_testdata_dir, ReleaseToolsTestCase, SkipIfExternalToolsUnavailable)
Tao Bao5fe287b2018-10-11 14:13:52 -070029from verity_utils import (
Tao Bao7549e5e2018-10-03 14:23:59 -070030 CreateHashtreeInfoGenerator, CreateVerityImageBuilder, HashtreeInfo,
Tao Bao5fe287b2018-10-11 14:13:52 -070031 VerifiedBootVersion1HashtreeInfoGenerator)
Tianjie Xu67c7cbb2018-08-30 00:32:07 -070032
Tao Bao7549e5e2018-10-03 14:23:59 -070033BLOCK_SIZE = common.BLOCK_SIZE
34
Tianjie Xu67c7cbb2018-08-30 00:32:07 -070035
Tao Bao65b94e92018-10-11 21:57:26 -070036class VerifiedBootVersion1HashtreeInfoGeneratorTest(ReleaseToolsTestCase):
Tao Bao5fe287b2018-10-11 14:13:52 -070037
Tianjie Xu67c7cbb2018-08-30 00:32:07 -070038 def setUp(self):
Tao Bao65b94e92018-10-11 21:57:26 -070039 self.testdata_dir = get_testdata_dir()
Tianjie Xu67c7cbb2018-08-30 00:32:07 -070040
41 self.partition_size = 1024 * 1024
42 self.prop_dict = {
43 'verity': 'true',
44 'verity_fec': 'true',
45 'system_verity_block_device': '/dev/block/system',
46 'system_size': self.partition_size
47 }
48
49 self.hash_algorithm = "sha256"
50 self.fixed_salt = \
51 "aee087a5be3b982978c923f566a94613496b417f2af592639bc80d141e34dfe7"
52 self.expected_root_hash = \
53 "0b7c4565e87b1026e11fbab91c0bc29e185c847a5b44d40e6e86e461e8adf80d"
54
Tianjie Xu67c7cbb2018-08-30 00:32:07 -070055 def _create_simg(self, raw_data):
56 output_file = common.MakeTempFile()
57 raw_image = common.MakeTempFile()
58 with open(raw_image, 'wb') as f:
59 f.write(raw_data)
60
61 cmd = ["img2simg", raw_image, output_file, '4096']
62 p = common.Run(cmd)
63 p.communicate()
64 self.assertEqual(0, p.returncode)
65
66 return output_file
67
68 def _generate_image(self):
69 partition_size = 1024 * 1024
Tao Bao7549e5e2018-10-03 14:23:59 -070070 prop_dict = {
71 'partition_size': str(partition_size),
72 'verity': 'true',
73 'verity_block_device': '/dev/block/system',
74 'verity_key': os.path.join(self.testdata_dir, 'testkey'),
75 'verity_fec': 'true',
76 'verity_signer_cmd': 'verity_signer',
77 }
78 verity_image_builder = CreateVerityImageBuilder(prop_dict)
79 self.assertIsNotNone(verity_image_builder)
80 adjusted_size = verity_image_builder.CalculateMaxImageSize()
Tianjie Xu67c7cbb2018-08-30 00:32:07 -070081
82 raw_image = ""
83 for i in range(adjusted_size):
84 raw_image += str(i % 10)
85
86 output_file = self._create_simg(raw_image)
87
88 # Append the verity metadata.
Tao Bao7549e5e2018-10-03 14:23:59 -070089 verity_image_builder.Build(output_file)
Tianjie Xu67c7cbb2018-08-30 00:32:07 -070090
91 return output_file
92
Tao Bao82490d32019-04-09 00:12:30 -070093 @SkipIfExternalToolsUnavailable()
Tao Bao5fe287b2018-10-11 14:13:52 -070094 def test_CreateHashtreeInfoGenerator(self):
Tianjie Xu67c7cbb2018-08-30 00:32:07 -070095 image_file = sparse_img.SparseImage(self._generate_image())
96
Tao Bao5fe287b2018-10-11 14:13:52 -070097 generator = CreateHashtreeInfoGenerator(
Tianjie Xu67c7cbb2018-08-30 00:32:07 -070098 'system', image_file, self.prop_dict)
99 self.assertEqual(
Tao Bao5fe287b2018-10-11 14:13:52 -0700100 VerifiedBootVersion1HashtreeInfoGenerator, type(generator))
Tianjie Xu67c7cbb2018-08-30 00:32:07 -0700101 self.assertEqual(self.partition_size, generator.partition_size)
102 self.assertTrue(generator.fec_supported)
103
Tao Bao82490d32019-04-09 00:12:30 -0700104 @SkipIfExternalToolsUnavailable()
Tao Bao5fe287b2018-10-11 14:13:52 -0700105 def test_DecomposeSparseImage(self):
Tianjie Xu67c7cbb2018-08-30 00:32:07 -0700106 image_file = sparse_img.SparseImage(self._generate_image())
107
Tao Bao5fe287b2018-10-11 14:13:52 -0700108 generator = VerifiedBootVersion1HashtreeInfoGenerator(
Tianjie Xu67c7cbb2018-08-30 00:32:07 -0700109 self.partition_size, 4096, True)
110 generator.DecomposeSparseImage(image_file)
111 self.assertEqual(991232, generator.filesystem_size)
112 self.assertEqual(12288, generator.hashtree_size)
113 self.assertEqual(32768, generator.metadata_size)
114
Tao Bao82490d32019-04-09 00:12:30 -0700115 @SkipIfExternalToolsUnavailable()
Tao Bao5fe287b2018-10-11 14:13:52 -0700116 def test_ParseHashtreeMetadata(self):
Tianjie Xu67c7cbb2018-08-30 00:32:07 -0700117 image_file = sparse_img.SparseImage(self._generate_image())
Tao Bao5fe287b2018-10-11 14:13:52 -0700118 generator = VerifiedBootVersion1HashtreeInfoGenerator(
Tianjie Xu67c7cbb2018-08-30 00:32:07 -0700119 self.partition_size, 4096, True)
120 generator.DecomposeSparseImage(image_file)
121
Tao Bao5fe287b2018-10-11 14:13:52 -0700122 # pylint: disable=protected-access
Tianjie Xu67c7cbb2018-08-30 00:32:07 -0700123 generator._ParseHashtreeMetadata()
124
125 self.assertEqual(
126 self.hash_algorithm, generator.hashtree_info.hash_algorithm)
127 self.assertEqual(self.fixed_salt, generator.hashtree_info.salt)
128 self.assertEqual(self.expected_root_hash, generator.hashtree_info.root_hash)
129
Tao Bao82490d32019-04-09 00:12:30 -0700130 @SkipIfExternalToolsUnavailable()
Tao Bao5fe287b2018-10-11 14:13:52 -0700131 def test_ValidateHashtree_smoke(self):
132 generator = VerifiedBootVersion1HashtreeInfoGenerator(
Tianjie Xu67c7cbb2018-08-30 00:32:07 -0700133 self.partition_size, 4096, True)
134 generator.image = sparse_img.SparseImage(self._generate_image())
135
Tao Bao5fe287b2018-10-11 14:13:52 -0700136 generator.hashtree_info = info = HashtreeInfo()
Tianjie Xu67c7cbb2018-08-30 00:32:07 -0700137 info.filesystem_range = RangeSet(data=[0, 991232 / 4096])
138 info.hashtree_range = RangeSet(
139 data=[991232 / 4096, (991232 + 12288) / 4096])
140 info.hash_algorithm = self.hash_algorithm
141 info.salt = self.fixed_salt
142 info.root_hash = self.expected_root_hash
143
144 self.assertTrue(generator.ValidateHashtree())
145
Tao Bao82490d32019-04-09 00:12:30 -0700146 @SkipIfExternalToolsUnavailable()
Tao Bao5fe287b2018-10-11 14:13:52 -0700147 def test_ValidateHashtree_failure(self):
148 generator = VerifiedBootVersion1HashtreeInfoGenerator(
Tianjie Xu67c7cbb2018-08-30 00:32:07 -0700149 self.partition_size, 4096, True)
150 generator.image = sparse_img.SparseImage(self._generate_image())
151
Tao Bao5fe287b2018-10-11 14:13:52 -0700152 generator.hashtree_info = info = HashtreeInfo()
Tianjie Xu67c7cbb2018-08-30 00:32:07 -0700153 info.filesystem_range = RangeSet(data=[0, 991232 / 4096])
154 info.hashtree_range = RangeSet(
155 data=[991232 / 4096, (991232 + 12288) / 4096])
156 info.hash_algorithm = self.hash_algorithm
157 info.salt = self.fixed_salt
158 info.root_hash = "a" + self.expected_root_hash[1:]
159
160 self.assertFalse(generator.ValidateHashtree())
161
Tao Bao82490d32019-04-09 00:12:30 -0700162 @SkipIfExternalToolsUnavailable()
Tao Bao5fe287b2018-10-11 14:13:52 -0700163 def test_Generate(self):
Tianjie Xu67c7cbb2018-08-30 00:32:07 -0700164 image_file = sparse_img.SparseImage(self._generate_image())
Tao Bao5fe287b2018-10-11 14:13:52 -0700165 generator = CreateHashtreeInfoGenerator('system', 4096, self.prop_dict)
Tianjie Xu67c7cbb2018-08-30 00:32:07 -0700166 info = generator.Generate(image_file)
167
168 self.assertEqual(RangeSet(data=[0, 991232 / 4096]), info.filesystem_range)
169 self.assertEqual(RangeSet(data=[991232 / 4096, (991232 + 12288) / 4096]),
170 info.hashtree_range)
171 self.assertEqual(self.hash_algorithm, info.hash_algorithm)
172 self.assertEqual(self.fixed_salt, info.salt)
173 self.assertEqual(self.expected_root_hash, info.root_hash)
Tao Bao71197512018-10-11 14:08:45 -0700174
175
Tao Bao4a0d5132018-10-17 22:53:54 -0700176class VerifiedBootVersion1VerityImageBuilderTest(ReleaseToolsTestCase):
177
178 DEFAULT_PARTITION_SIZE = 4096 * 1024
179 DEFAULT_PROP_DICT = {
180 'partition_size': str(DEFAULT_PARTITION_SIZE),
181 'verity': 'true',
182 'verity_block_device': '/dev/block/system',
183 'verity_key': os.path.join(get_testdata_dir(), 'testkey'),
184 'verity_fec': 'true',
185 'verity_signer_cmd': 'verity_signer',
186 }
187
188 def test_init(self):
189 prop_dict = copy.deepcopy(self.DEFAULT_PROP_DICT)
190 verity_image_builder = CreateVerityImageBuilder(prop_dict)
191 self.assertIsNotNone(verity_image_builder)
192 self.assertEqual(1, verity_image_builder.version)
193
194 def test_init_MissingProps(self):
195 prop_dict = copy.deepcopy(self.DEFAULT_PROP_DICT)
196 del prop_dict['verity']
197 self.assertIsNone(CreateVerityImageBuilder(prop_dict))
198
199 prop_dict = copy.deepcopy(self.DEFAULT_PROP_DICT)
200 del prop_dict['verity_block_device']
201 self.assertIsNone(CreateVerityImageBuilder(prop_dict))
202
Tao Bao82490d32019-04-09 00:12:30 -0700203 @SkipIfExternalToolsUnavailable()
Tao Bao4a0d5132018-10-17 22:53:54 -0700204 def test_CalculateMaxImageSize(self):
205 verity_image_builder = CreateVerityImageBuilder(self.DEFAULT_PROP_DICT)
206 size = verity_image_builder.CalculateMaxImageSize()
207 self.assertLess(size, self.DEFAULT_PARTITION_SIZE)
208
209 # Same result by explicitly passing the partition size.
210 self.assertEqual(
211 verity_image_builder.CalculateMaxImageSize(),
212 verity_image_builder.CalculateMaxImageSize(
213 self.DEFAULT_PARTITION_SIZE))
214
215 @staticmethod
216 def _BuildAndVerify(prop, verify_key):
217 verity_image_builder = CreateVerityImageBuilder(prop)
218 image_size = verity_image_builder.CalculateMaxImageSize()
219
220 # Build the sparse image with verity metadata.
221 input_dir = common.MakeTempDir()
222 image = common.MakeTempFile(suffix='.img')
223 cmd = ['mkuserimg_mke2fs', input_dir, image, 'ext4', '/system',
224 str(image_size), '-j', '0', '-s']
225 common.RunAndCheckOutput(cmd)
226 verity_image_builder.Build(image)
227
228 # Verify the verity metadata.
229 cmd = ['verity_verifier', image, '-mincrypt', verify_key]
230 common.RunAndCheckOutput(cmd)
231
Tao Bao82490d32019-04-09 00:12:30 -0700232 @SkipIfExternalToolsUnavailable()
Tao Bao4a0d5132018-10-17 22:53:54 -0700233 def test_Build(self):
234 self._BuildAndVerify(
235 self.DEFAULT_PROP_DICT,
236 os.path.join(get_testdata_dir(), 'testkey_mincrypt'))
237
Tao Bao82490d32019-04-09 00:12:30 -0700238 @SkipIfExternalToolsUnavailable()
Tao Bao4a0d5132018-10-17 22:53:54 -0700239 def test_Build_SanityCheck(self):
240 # A sanity check for the test itself: the image shouldn't be verifiable
241 # with wrong key.
242 self.assertRaises(
243 common.ExternalError,
244 self._BuildAndVerify,
245 self.DEFAULT_PROP_DICT,
246 os.path.join(get_testdata_dir(), 'verity_mincrypt'))
247
Tao Bao82490d32019-04-09 00:12:30 -0700248 @SkipIfExternalToolsUnavailable()
Tao Bao4a0d5132018-10-17 22:53:54 -0700249 def test_Build_FecDisabled(self):
250 prop_dict = copy.deepcopy(self.DEFAULT_PROP_DICT)
251 del prop_dict['verity_fec']
252 self._BuildAndVerify(
253 prop_dict,
254 os.path.join(get_testdata_dir(), 'testkey_mincrypt'))
255
Tao Bao82490d32019-04-09 00:12:30 -0700256 @SkipIfExternalToolsUnavailable()
Tao Bao4a0d5132018-10-17 22:53:54 -0700257 def test_Build_SquashFs(self):
258 verity_image_builder = CreateVerityImageBuilder(self.DEFAULT_PROP_DICT)
259 verity_image_builder.CalculateMaxImageSize()
260
261 # Build the sparse image with verity metadata.
262 input_dir = common.MakeTempDir()
263 image = common.MakeTempFile(suffix='.img')
264 cmd = ['mksquashfsimage.sh', input_dir, image, '-s']
265 common.RunAndCheckOutput(cmd)
266 verity_image_builder.PadSparseImage(image)
267 verity_image_builder.Build(image)
268
269 # Verify the verity metadata.
270 cmd = ["verity_verifier", image, '-mincrypt',
271 os.path.join(get_testdata_dir(), 'testkey_mincrypt')]
272 common.RunAndCheckOutput(cmd)
273
274
Tao Bao7549e5e2018-10-03 14:23:59 -0700275class VerifiedBootVersion2VerityImageBuilderTest(ReleaseToolsTestCase):
Tao Bao71197512018-10-11 14:08:45 -0700276
Tao Bao4a0d5132018-10-17 22:53:54 -0700277 DEFAULT_PROP_DICT = {
278 'partition_size': str(4096 * 1024),
279 'partition_name': 'system',
280 'avb_avbtool': 'avbtool',
281 'avb_hashtree_enable': 'true',
282 'avb_add_hashtree_footer_args': '',
283 }
284
285 def test_init(self):
286 prop_dict = copy.deepcopy(self.DEFAULT_PROP_DICT)
287 verity_image_builder = CreateVerityImageBuilder(prop_dict)
288 self.assertIsNotNone(verity_image_builder)
289 self.assertEqual(2, verity_image_builder.version)
290
291 def test_init_MissingProps(self):
292 prop_dict = copy.deepcopy(self.DEFAULT_PROP_DICT)
293 del prop_dict['avb_hashtree_enable']
294 verity_image_builder = CreateVerityImageBuilder(prop_dict)
295 self.assertIsNone(verity_image_builder)
296
Tao Bao82490d32019-04-09 00:12:30 -0700297 @SkipIfExternalToolsUnavailable()
Tao Bao4a0d5132018-10-17 22:53:54 -0700298 def test_Build(self):
299 prop_dict = copy.deepcopy(self.DEFAULT_PROP_DICT)
300 verity_image_builder = CreateVerityImageBuilder(prop_dict)
301 self.assertIsNotNone(verity_image_builder)
302 self.assertEqual(2, verity_image_builder.version)
303
304 input_dir = common.MakeTempDir()
305 image_dir = common.MakeTempDir()
306 system_image = os.path.join(image_dir, 'system.img')
307 system_image_size = verity_image_builder.CalculateMaxImageSize()
308 cmd = ['mkuserimg_mke2fs', input_dir, system_image, 'ext4', '/system',
309 str(system_image_size), '-j', '0', '-s']
310 common.RunAndCheckOutput(cmd)
311 verity_image_builder.Build(system_image)
312
313 # Additionally make vbmeta image so that we can verify with avbtool.
314 vbmeta_image = os.path.join(image_dir, 'vbmeta.img')
315 cmd = ['avbtool', 'make_vbmeta_image', '--include_descriptors_from_image',
316 system_image, '--output', vbmeta_image]
317 common.RunAndCheckOutput(cmd)
318
319 # Verify the verity metadata.
320 cmd = ['avbtool', 'verify_image', '--image', vbmeta_image]
321 common.RunAndCheckOutput(cmd)
322
323 def _test_CalculateMinPartitionSize_SetUp(self):
Tao Bao7549e5e2018-10-03 14:23:59 -0700324 # To test CalculateMinPartitionSize(), by using 200MB to 2GB image size.
Tao Bao71197512018-10-11 14:08:45 -0700325 # - 51200 = 200MB * 1024 * 1024 / 4096
326 # - 524288 = 2GB * 1024 * 1024 * 1024 / 4096
Tao Bao4a0d5132018-10-17 22:53:54 -0700327 image_sizes = [BLOCK_SIZE * random.randint(51200, 524288) + offset
328 for offset in range(BLOCK_SIZE)]
Tao Bao71197512018-10-11 14:08:45 -0700329
Tao Bao7549e5e2018-10-03 14:23:59 -0700330 prop_dict = {
331 'partition_size': None,
332 'partition_name': 'system',
333 'avb_avbtool': 'avbtool',
334 'avb_hashtree_enable': 'true',
335 'avb_add_hashtree_footer_args': None,
336 }
Tao Bao4a0d5132018-10-17 22:53:54 -0700337 builder = CreateVerityImageBuilder(prop_dict)
338 self.assertEqual(2, builder.version)
339 return image_sizes, builder
Tao Bao7549e5e2018-10-03 14:23:59 -0700340
341 def test_CalculateMinPartitionSize_LinearFooterSize(self):
Tao Bao71197512018-10-11 14:08:45 -0700342 """Tests with footer size which is linear to partition size."""
Tao Bao4a0d5132018-10-17 22:53:54 -0700343 image_sizes, builder = self._test_CalculateMinPartitionSize_SetUp()
344 for image_size in image_sizes:
Tao Bao71197512018-10-11 14:08:45 -0700345 for ratio in 0.95, 0.56, 0.22:
346 expected_size = common.RoundUpTo4K(int(math.ceil(image_size / ratio)))
347 self.assertEqual(
348 expected_size,
Tao Bao4a0d5132018-10-17 22:53:54 -0700349 builder.CalculateMinPartitionSize(
Tao Bao71197512018-10-11 14:08:45 -0700350 image_size, lambda x, ratio=ratio: int(x * ratio)))
351
352 def test_AVBCalcMinPartitionSize_SlowerGrowthFooterSize(self):
353 """Tests with footer size which grows slower than partition size."""
354
355 def _SizeCalculator(partition_size):
356 """Footer size is the power of 0.95 of partition size."""
357 # Minus footer size to return max image size.
358 return partition_size - int(math.pow(partition_size, 0.95))
359
Tao Bao4a0d5132018-10-17 22:53:54 -0700360 image_sizes, builder = self._test_CalculateMinPartitionSize_SetUp()
361 for image_size in image_sizes:
362 min_partition_size = builder.CalculateMinPartitionSize(
Tao Bao7549e5e2018-10-03 14:23:59 -0700363 image_size, _SizeCalculator)
Tao Bao71197512018-10-11 14:08:45 -0700364 # Checks min_partition_size can accommodate image_size.
365 self.assertGreaterEqual(
366 _SizeCalculator(min_partition_size),
367 image_size)
368 # Checks min_partition_size (round to BLOCK_SIZE) is the minimum.
369 self.assertLess(
370 _SizeCalculator(min_partition_size - BLOCK_SIZE),
371 image_size)
372
Tao Bao7549e5e2018-10-03 14:23:59 -0700373 def test_CalculateMinPartitionSize_FasterGrowthFooterSize(self):
Tao Bao71197512018-10-11 14:08:45 -0700374 """Tests with footer size which grows faster than partition size."""
375
376 def _SizeCalculator(partition_size):
377 """Max image size is the power of 0.95 of partition size."""
378 # Max image size grows less than partition size, which means
379 # footer size grows faster than partition size.
380 return int(math.pow(partition_size, 0.95))
381
Tao Bao4a0d5132018-10-17 22:53:54 -0700382 image_sizes, builder = self._test_CalculateMinPartitionSize_SetUp()
383 for image_size in image_sizes:
384 min_partition_size = builder.CalculateMinPartitionSize(
Tao Bao7549e5e2018-10-03 14:23:59 -0700385 image_size, _SizeCalculator)
Tao Bao71197512018-10-11 14:08:45 -0700386 # Checks min_partition_size can accommodate image_size.
387 self.assertGreaterEqual(
388 _SizeCalculator(min_partition_size),
389 image_size)
390 # Checks min_partition_size (round to BLOCK_SIZE) is the minimum.
391 self.assertLess(
392 _SizeCalculator(min_partition_size - BLOCK_SIZE),
393 image_size)