blob: da6141227c4915cae070497157aad88c8305de9e [file] [log] [blame]
Tianjie Xu67c7cbb2018-08-30 00:32:07 -07001#!/usr/bin/env python
2#
3# Copyright (C) 2018 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17from __future__ import print_function
18
Tao Bao32fcdab2018-10-12 10:30:39 -070019import logging
Tao Bao71197512018-10-11 14:08:45 -070020import os.path
21import shlex
Tianjie Xu67c7cbb2018-08-30 00:32:07 -070022import struct
23
24import common
Tao Bao71197512018-10-11 14:08:45 -070025import sparse_img
Tianjie Xu67c7cbb2018-08-30 00:32:07 -070026from rangelib import RangeSet
27
Tao Bao32fcdab2018-10-12 10:30:39 -070028logger = logging.getLogger(__name__)
29
Tao Bao71197512018-10-11 14:08:45 -070030OPTIONS = common.OPTIONS
31BLOCK_SIZE = common.BLOCK_SIZE
32FIXED_SALT = "aee087a5be3b982978c923f566a94613496b417f2af592639bc80d141e34dfe7"
33
34
35class BuildVerityImageError(Exception):
36 """An Exception raised during verity image building."""
37
38 def __init__(self, message):
39 Exception.__init__(self, message)
40
41
42def GetVerityFECSize(partition_size):
43 cmd = ["fec", "-s", str(partition_size)]
44 output = common.RunAndCheckOutput(cmd, verbose=False)
45 return int(output)
46
47
48def GetVerityTreeSize(partition_size):
49 cmd = ["build_verity_tree", "-s", str(partition_size)]
50 output = common.RunAndCheckOutput(cmd, verbose=False)
51 return int(output)
52
53
54def GetVerityMetadataSize(partition_size):
55 cmd = ["build_verity_metadata.py", "size", str(partition_size)]
56 output = common.RunAndCheckOutput(cmd, verbose=False)
57 return int(output)
58
59
60def GetVeritySize(partition_size, fec_supported):
61 verity_tree_size = GetVerityTreeSize(partition_size)
62 verity_metadata_size = GetVerityMetadataSize(partition_size)
63 verity_size = verity_tree_size + verity_metadata_size
64 if fec_supported:
65 fec_size = GetVerityFECSize(partition_size + verity_size)
66 return verity_size + fec_size
67 return verity_size
68
69
70def GetSimgSize(image_file):
71 simg = sparse_img.SparseImage(image_file, build_map=False)
72 return simg.blocksize * simg.total_blocks
73
74
75def ZeroPadSimg(image_file, pad_size):
76 blocks = pad_size // BLOCK_SIZE
Tao Bao32fcdab2018-10-12 10:30:39 -070077 logger.info("Padding %d blocks (%d bytes)", blocks, pad_size)
Tao Bao71197512018-10-11 14:08:45 -070078 simg = sparse_img.SparseImage(image_file, mode="r+b", build_map=False)
79 simg.AppendFillChunk(0, blocks)
80
81
82def AdjustPartitionSizeForVerity(partition_size, fec_supported):
83 """Modifies the provided partition size to account for the verity metadata.
84
85 This information is used to size the created image appropriately.
86
87 Args:
88 partition_size: the size of the partition to be verified.
89
90 Returns:
91 A tuple of the size of the partition adjusted for verity metadata, and
92 the size of verity metadata.
93 """
94 key = "%d %d" % (partition_size, fec_supported)
95 if key in AdjustPartitionSizeForVerity.results:
96 return AdjustPartitionSizeForVerity.results[key]
97
98 hi = partition_size
99 if hi % BLOCK_SIZE != 0:
100 hi = (hi // BLOCK_SIZE) * BLOCK_SIZE
101
102 # verity tree and fec sizes depend on the partition size, which
103 # means this estimate is always going to be unnecessarily small
104 verity_size = GetVeritySize(hi, fec_supported)
105 lo = partition_size - verity_size
106 result = lo
107
108 # do a binary search for the optimal size
109 while lo < hi:
110 i = ((lo + hi) // (2 * BLOCK_SIZE)) * BLOCK_SIZE
111 v = GetVeritySize(i, fec_supported)
112 if i + v <= partition_size:
113 if result < i:
114 result = i
115 verity_size = v
116 lo = i + BLOCK_SIZE
117 else:
118 hi = i
119
Tao Bao32fcdab2018-10-12 10:30:39 -0700120 logger.info(
121 "Adjusted partition size for verity, partition_size: %s, verity_size: %s",
122 result, verity_size)
Tao Bao71197512018-10-11 14:08:45 -0700123 AdjustPartitionSizeForVerity.results[key] = (result, verity_size)
124 return (result, verity_size)
125
126
127AdjustPartitionSizeForVerity.results = {}
128
129
130def BuildVerityFEC(sparse_image_path, verity_path, verity_fec_path,
131 padding_size):
132 cmd = ["fec", "-e", "-p", str(padding_size), sparse_image_path,
133 verity_path, verity_fec_path]
134 common.RunAndCheckOutput(cmd)
135
136
137def BuildVerityTree(sparse_image_path, verity_image_path):
138 cmd = ["build_verity_tree", "-A", FIXED_SALT, sparse_image_path,
139 verity_image_path]
140 output = common.RunAndCheckOutput(cmd)
141 root, salt = output.split()
142 return root, salt
143
144
145def BuildVerityMetadata(image_size, verity_metadata_path, root_hash, salt,
146 block_device, signer_path, key, signer_args,
147 verity_disable):
148 cmd = ["build_verity_metadata.py", "build", str(image_size),
149 verity_metadata_path, root_hash, salt, block_device, signer_path, key]
150 if signer_args:
151 cmd.append("--signer_args=\"%s\"" % (' '.join(signer_args),))
152 if verity_disable:
153 cmd.append("--verity_disable")
154 common.RunAndCheckOutput(cmd)
155
156
157def Append2Simg(sparse_image_path, unsparse_image_path, error_message):
158 """Appends the unsparse image to the given sparse image.
159
160 Args:
161 sparse_image_path: the path to the (sparse) image
162 unsparse_image_path: the path to the (unsparse) image
163
164 Raises:
165 BuildVerityImageError: On error.
166 """
167 cmd = ["append2simg", sparse_image_path, unsparse_image_path]
168 try:
169 common.RunAndCheckOutput(cmd)
170 except:
Tao Bao46901fb2018-11-06 10:26:21 -0800171 logger.exception(error_message)
Tao Bao71197512018-10-11 14:08:45 -0700172 raise BuildVerityImageError(error_message)
173
174
175def Append(target, file_to_append, error_message):
176 """Appends file_to_append to target.
177
178 Raises:
179 BuildVerityImageError: On error.
180 """
181 try:
182 with open(target, "a") as out_file, open(file_to_append, "r") as input_file:
183 for line in input_file:
184 out_file.write(line)
185 except IOError:
Tao Bao46901fb2018-11-06 10:26:21 -0800186 logger.exception(error_message)
Tao Bao71197512018-10-11 14:08:45 -0700187 raise BuildVerityImageError(error_message)
188
189
190def BuildVerifiedImage(data_image_path, verity_image_path,
191 verity_metadata_path, verity_fec_path,
192 padding_size, fec_supported):
193 Append(
194 verity_image_path, verity_metadata_path,
195 "Could not append verity metadata!")
196
197 if fec_supported:
198 # Build FEC for the entire partition, including metadata.
199 BuildVerityFEC(
200 data_image_path, verity_image_path, verity_fec_path, padding_size)
201 Append(verity_image_path, verity_fec_path, "Could not append FEC!")
202
203 Append2Simg(
204 data_image_path, verity_image_path, "Could not append verity data!")
205
206
207def MakeVerityEnabledImage(out_file, fec_supported, prop_dict):
208 """Creates an image that is verifiable using dm-verity.
209
210 Args:
211 out_file: the location to write the verifiable image at
212 prop_dict: a dictionary of properties required for image creation and
213 verification
214
215 Raises:
216 AssertionError: On invalid partition sizes.
217 """
218 # get properties
219 image_size = int(prop_dict["image_size"])
220 block_dev = prop_dict["verity_block_device"]
221 signer_key = prop_dict["verity_key"] + ".pk8"
222 if OPTIONS.verity_signer_path is not None:
223 signer_path = OPTIONS.verity_signer_path
224 else:
225 signer_path = prop_dict["verity_signer_cmd"]
226 signer_args = OPTIONS.verity_signer_args
227
228 tempdir_name = common.MakeTempDir(suffix="_verity_images")
229
230 # Get partial image paths.
231 verity_image_path = os.path.join(tempdir_name, "verity.img")
232 verity_metadata_path = os.path.join(tempdir_name, "verity_metadata.img")
233 verity_fec_path = os.path.join(tempdir_name, "verity_fec.img")
234
235 # Build the verity tree and get the root hash and salt.
236 root_hash, salt = BuildVerityTree(out_file, verity_image_path)
237
238 # Build the metadata blocks.
239 verity_disable = "verity_disable" in prop_dict
240 BuildVerityMetadata(
241 image_size, verity_metadata_path, root_hash, salt, block_dev, signer_path,
242 signer_key, signer_args, verity_disable)
243
244 # Build the full verified image.
245 partition_size = int(prop_dict["partition_size"])
246 verity_size = int(prop_dict["verity_size"])
247
248 padding_size = partition_size - image_size - verity_size
249 assert padding_size >= 0
250
251 BuildVerifiedImage(
252 out_file, verity_image_path, verity_metadata_path, verity_fec_path,
253 padding_size, fec_supported)
254
255
256def AVBCalcMaxImageSize(avbtool, footer_type, partition_size, additional_args):
257 """Calculates max image size for a given partition size.
258
259 Args:
260 avbtool: String with path to avbtool.
261 footer_type: 'hash' or 'hashtree' for generating footer.
262 partition_size: The size of the partition in question.
263 additional_args: Additional arguments to pass to "avbtool add_hash_footer"
264 or "avbtool add_hashtree_footer".
265
266 Returns:
267 The maximum image size.
268
269 Raises:
270 BuildVerityImageError: On invalid image size.
271 """
272 cmd = [avbtool, "add_%s_footer" % footer_type,
273 "--partition_size", str(partition_size), "--calc_max_image_size"]
274 cmd.extend(shlex.split(additional_args))
275
276 output = common.RunAndCheckOutput(cmd)
277 image_size = int(output)
278 if image_size <= 0:
279 raise BuildVerityImageError(
280 "Invalid max image size: {}".format(output))
281 return image_size
282
283
284def AVBCalcMinPartitionSize(image_size, size_calculator):
285 """Calculates min partition size for a given image size.
286
287 Args:
288 image_size: The size of the image in question.
289 size_calculator: The function to calculate max image size
290 for a given partition size.
291
292 Returns:
293 The minimum partition size required to accommodate the image size.
294 """
295 # Use image size as partition size to approximate final partition size.
296 image_ratio = size_calculator(image_size) / float(image_size)
297
298 # Prepare a binary search for the optimal partition size.
299 lo = int(image_size / image_ratio) // BLOCK_SIZE * BLOCK_SIZE - BLOCK_SIZE
300
301 # Ensure lo is small enough: max_image_size should <= image_size.
302 delta = BLOCK_SIZE
303 max_image_size = size_calculator(lo)
304 while max_image_size > image_size:
305 image_ratio = max_image_size / float(lo)
306 lo = int(image_size / image_ratio) // BLOCK_SIZE * BLOCK_SIZE - delta
307 delta *= 2
308 max_image_size = size_calculator(lo)
309
310 hi = lo + BLOCK_SIZE
311
312 # Ensure hi is large enough: max_image_size should >= image_size.
313 delta = BLOCK_SIZE
314 max_image_size = size_calculator(hi)
315 while max_image_size < image_size:
316 image_ratio = max_image_size / float(hi)
317 hi = int(image_size / image_ratio) // BLOCK_SIZE * BLOCK_SIZE + delta
318 delta *= 2
319 max_image_size = size_calculator(hi)
320
321 partition_size = hi
322
323 # Start to binary search.
324 while lo < hi:
325 mid = ((lo + hi) // (2 * BLOCK_SIZE)) * BLOCK_SIZE
326 max_image_size = size_calculator(mid)
327 if max_image_size >= image_size: # if mid can accommodate image_size
328 if mid < partition_size: # if a smaller partition size is found
329 partition_size = mid
330 hi = mid
331 else:
332 lo = mid + BLOCK_SIZE
333
Tao Bao32fcdab2018-10-12 10:30:39 -0700334 logger.info(
335 "AVBCalcMinPartitionSize(%d): partition_size: %d.",
336 image_size, partition_size)
Tao Bao71197512018-10-11 14:08:45 -0700337
338 return partition_size
339
340
341def AVBAddFooter(image_path, avbtool, footer_type, partition_size,
342 partition_name, key_path, algorithm, salt,
343 additional_args):
344 """Adds dm-verity hashtree and AVB metadata to an image.
345
346 Args:
347 image_path: Path to image to modify.
348 avbtool: String with path to avbtool.
349 footer_type: 'hash' or 'hashtree' for generating footer.
350 partition_size: The size of the partition in question.
351 partition_name: The name of the partition - will be embedded in metadata.
352 key_path: Path to key to use or None.
353 algorithm: Name of algorithm to use or None.
354 salt: The salt to use (a hexadecimal string) or None.
355 additional_args: Additional arguments to pass to "avbtool add_hash_footer"
356 or "avbtool add_hashtree_footer".
357 """
358 cmd = [avbtool, "add_%s_footer" % footer_type,
359 "--partition_size", partition_size,
360 "--partition_name", partition_name,
361 "--image", image_path]
362
363 if key_path and algorithm:
364 cmd.extend(["--key", key_path, "--algorithm", algorithm])
365 if salt:
366 cmd.extend(["--salt", salt])
367
368 cmd.extend(shlex.split(additional_args))
369
370 common.RunAndCheckOutput(cmd)
371
Tianjie Xu67c7cbb2018-08-30 00:32:07 -0700372
373class HashtreeInfoGenerationError(Exception):
374 """An Exception raised during hashtree info generation."""
375
376 def __init__(self, message):
377 Exception.__init__(self, message)
378
379
380class HashtreeInfo(object):
381 def __init__(self):
382 self.hashtree_range = None
383 self.filesystem_range = None
384 self.hash_algorithm = None
385 self.salt = None
386 self.root_hash = None
387
388
389def CreateHashtreeInfoGenerator(partition_name, block_size, info_dict):
390 generator = None
391 if (info_dict.get("verity") == "true" and
392 info_dict.get("{}_verity_block_device".format(partition_name))):
393 partition_size = info_dict["{}_size".format(partition_name)]
394 fec_supported = info_dict.get("verity_fec") == "true"
395 generator = VerifiedBootVersion1HashtreeInfoGenerator(
396 partition_size, block_size, fec_supported)
397
398 return generator
399
400
401class HashtreeInfoGenerator(object):
402 def Generate(self, image):
403 raise NotImplementedError
404
405 def DecomposeSparseImage(self, image):
406 raise NotImplementedError
407
408 def ValidateHashtree(self):
409 raise NotImplementedError
410
411
Tianjie Xu67c7cbb2018-08-30 00:32:07 -0700412class VerifiedBootVersion1HashtreeInfoGenerator(HashtreeInfoGenerator):
413 """A class that parses the metadata of hashtree for a given partition."""
414
415 def __init__(self, partition_size, block_size, fec_supported):
416 """Initialize VerityTreeInfo with the sparse image and input property.
417
418 Arguments:
419 partition_size: The whole size in bytes of a partition, including the
420 filesystem size, padding size, and verity size.
421 block_size: Expected size in bytes of each block for the sparse image.
422 fec_supported: True if the verity section contains fec data.
423 """
424
425 self.block_size = block_size
426 self.partition_size = partition_size
427 self.fec_supported = fec_supported
428
429 self.image = None
430 self.filesystem_size = None
431 self.hashtree_size = None
432 self.metadata_size = None
433
434 self.hashtree_info = HashtreeInfo()
435
436 def DecomposeSparseImage(self, image):
437 """Calculate the verity size based on the size of the input image.
438
439 Since we already know the structure of a verity enabled image to be:
440 [filesystem, verity_hashtree, verity_metadata, fec_data]. We can then
441 calculate the size and offset of each section.
442 """
443
444 self.image = image
445 assert self.block_size == image.blocksize
446 assert self.partition_size == image.total_blocks * self.block_size, \
447 "partition size {} doesn't match with the calculated image size." \
448 " total_blocks: {}".format(self.partition_size, image.total_blocks)
449
450 adjusted_size, _ = AdjustPartitionSizeForVerity(
451 self.partition_size, self.fec_supported)
452 assert adjusted_size % self.block_size == 0
453
454 verity_tree_size = GetVerityTreeSize(adjusted_size)
455 assert verity_tree_size % self.block_size == 0
456
457 metadata_size = GetVerityMetadataSize(adjusted_size)
458 assert metadata_size % self.block_size == 0
459
460 self.filesystem_size = adjusted_size
461 self.hashtree_size = verity_tree_size
462 self.metadata_size = metadata_size
463
464 self.hashtree_info.filesystem_range = RangeSet(
465 data=[0, adjusted_size / self.block_size])
466 self.hashtree_info.hashtree_range = RangeSet(
467 data=[adjusted_size / self.block_size,
468 (adjusted_size + verity_tree_size) / self.block_size])
469
470 def _ParseHashtreeMetadata(self):
471 """Parses the hash_algorithm, root_hash, salt from the metadata block."""
472
473 metadata_start = self.filesystem_size + self.hashtree_size
474 metadata_range = RangeSet(
475 data=[metadata_start / self.block_size,
476 (metadata_start + self.metadata_size) / self.block_size])
477 meta_data = ''.join(self.image.ReadRangeSet(metadata_range))
478
479 # More info about the metadata structure available in:
480 # system/extras/verity/build_verity_metadata.py
481 META_HEADER_SIZE = 268
482 header_bin = meta_data[0:META_HEADER_SIZE]
483 header = struct.unpack("II256sI", header_bin)
484
485 # header: magic_number, version, signature, table_len
486 assert header[0] == 0xb001b001, header[0]
487 table_len = header[3]
488 verity_table = meta_data[META_HEADER_SIZE: META_HEADER_SIZE + table_len]
489 table_entries = verity_table.rstrip().split()
490
491 # Expected verity table format: "1 block_device block_device block_size
492 # block_size data_blocks data_blocks hash_algorithm root_hash salt"
493 assert len(table_entries) == 10, "Unexpected verity table size {}".format(
494 len(table_entries))
495 assert (int(table_entries[3]) == self.block_size and
496 int(table_entries[4]) == self.block_size)
497 assert (int(table_entries[5]) * self.block_size == self.filesystem_size and
498 int(table_entries[6]) * self.block_size == self.filesystem_size)
499
500 self.hashtree_info.hash_algorithm = table_entries[7]
501 self.hashtree_info.root_hash = table_entries[8]
502 self.hashtree_info.salt = table_entries[9]
503
504 def ValidateHashtree(self):
505 """Checks that we can reconstruct the verity hash tree."""
506
507 # Writes the file system section to a temp file; and calls the executable
508 # build_verity_tree to construct the hash tree.
509 adjusted_partition = common.MakeTempFile(prefix="adjusted_partition")
510 with open(adjusted_partition, "wb") as fd:
511 self.image.WriteRangeDataToFd(self.hashtree_info.filesystem_range, fd)
512
513 generated_verity_tree = common.MakeTempFile(prefix="verity")
Tao Bao2f057462018-10-03 16:31:18 -0700514 root_hash, salt = BuildVerityTree(adjusted_partition, generated_verity_tree)
Tianjie Xu67c7cbb2018-08-30 00:32:07 -0700515
Tao Bao2f057462018-10-03 16:31:18 -0700516 # The salt should be always identical, as we use fixed value.
517 assert salt == self.hashtree_info.salt, \
518 "Calculated salt {} doesn't match the one in metadata {}".format(
519 salt, self.hashtree_info.salt)
520
521 if root_hash != self.hashtree_info.root_hash:
Tao Bao32fcdab2018-10-12 10:30:39 -0700522 logger.warning(
523 "Calculated root hash %s doesn't match the one in metadata %s",
524 root_hash, self.hashtree_info.root_hash)
Tianjie Xu67c7cbb2018-08-30 00:32:07 -0700525 return False
526
527 # Reads the generated hash tree and checks if it has the exact same bytes
528 # as the one in the sparse image.
529 with open(generated_verity_tree, "rb") as fd:
530 return fd.read() == ''.join(self.image.ReadRangeSet(
531 self.hashtree_info.hashtree_range))
532
533 def Generate(self, image):
534 """Parses and validates the hashtree info in a sparse image.
535
536 Returns:
537 hashtree_info: The information needed to reconstruct the hashtree.
Tao Bao2f057462018-10-03 16:31:18 -0700538
Tianjie Xu67c7cbb2018-08-30 00:32:07 -0700539 Raises:
540 HashtreeInfoGenerationError: If we fail to generate the exact bytes of
541 the hashtree.
542 """
543
544 self.DecomposeSparseImage(image)
545 self._ParseHashtreeMetadata()
546
547 if not self.ValidateHashtree():
548 raise HashtreeInfoGenerationError("Failed to reconstruct the verity tree")
549
550 return self.hashtree_info