blob: 184f805784563f431507e7a2b29d06d51abb7d8a [file] [log] [blame]
Gilad Arnold553b0ec2013-01-26 01:00:39 -08001# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""Tools for reading, verifying and applying Chrome OS update payloads."""
6
Sen Jiang349fd292015-11-16 17:28:09 -08007from __future__ import print_function
8
Gilad Arnold553b0ec2013-01-26 01:00:39 -08009import hashlib
10import struct
11
Sen Jiangc2527f42017-09-27 16:35:03 -070012from update_payload import applier
13from update_payload import block_tracer
14from update_payload import checker
15from update_payload import common
16from update_payload.error import PayloadError
17from update_payload import update_metadata_pb2
Gilad Arnold553b0ec2013-01-26 01:00:39 -080018
19
20#
21# Helper functions.
22#
23def _ReadInt(file_obj, size, is_unsigned, hasher=None):
Gilad Arnold5502b562013-03-08 13:22:31 -080024 """Reads a binary-encoded integer from a file.
Gilad Arnold553b0ec2013-01-26 01:00:39 -080025
26 It will do the correct conversion based on the reported size and whether or
27 not a signed number is expected. Assumes a network (big-endian) byte
28 ordering.
29
30 Args:
31 file_obj: a file object
32 size: the integer size in bytes (2, 4 or 8)
33 is_unsigned: whether it is signed or not
34 hasher: an optional hasher to pass the value through
Sen Jiang349fd292015-11-16 17:28:09 -080035
Gilad Arnold553b0ec2013-01-26 01:00:39 -080036 Returns:
37 An "unpacked" (Python) integer value.
Sen Jiang349fd292015-11-16 17:28:09 -080038
Gilad Arnold553b0ec2013-01-26 01:00:39 -080039 Raises:
40 PayloadError if an read error occurred.
Gilad Arnold553b0ec2013-01-26 01:00:39 -080041 """
Gilad Arnold5502b562013-03-08 13:22:31 -080042 return struct.unpack(common.IntPackingFmtStr(size, is_unsigned),
43 common.Read(file_obj, size, hasher=hasher))[0]
Gilad Arnold553b0ec2013-01-26 01:00:39 -080044
45
46#
47# Update payload.
48#
49class Payload(object):
50 """Chrome OS update payload processor."""
51
52 class _PayloadHeader(object):
53 """Update payload header struct."""
54
Alex Deymoef497352015-10-15 09:14:58 -070055 # Header constants; sizes are in bytes.
56 _MAGIC = 'CrAU'
57 _VERSION_SIZE = 8
58 _MANIFEST_LEN_SIZE = 8
59 _METADATA_SIGNATURE_LEN_SIZE = 4
Gilad Arnold553b0ec2013-01-26 01:00:39 -080060
Alex Deymoef497352015-10-15 09:14:58 -070061 def __init__(self):
62 self.version = None
63 self.manifest_len = None
64 self.metadata_signature_len = None
65 self.size = None
66
67 def ReadFromPayload(self, payload_file, hasher=None):
68 """Reads the payload header from a file.
69
70 Reads the payload header from the |payload_file| and updates the |hasher|
71 if one is passed. The parsed header is stored in the _PayloadHeader
72 instance attributes.
73
74 Args:
75 payload_file: a file object
76 hasher: an optional hasher to pass the value through
Sen Jiang349fd292015-11-16 17:28:09 -080077
Alex Deymoef497352015-10-15 09:14:58 -070078 Returns:
79 None.
Sen Jiang349fd292015-11-16 17:28:09 -080080
Alex Deymoef497352015-10-15 09:14:58 -070081 Raises:
82 PayloadError if a read error occurred or the header is invalid.
83 """
84 # Verify magic
85 magic = common.Read(payload_file, len(self._MAGIC), hasher=hasher)
86 if magic != self._MAGIC:
87 raise PayloadError('invalid payload magic: %s' % magic)
88
89 self.version = _ReadInt(payload_file, self._VERSION_SIZE, True,
90 hasher=hasher)
91 self.manifest_len = _ReadInt(payload_file, self._MANIFEST_LEN_SIZE, True,
92 hasher=hasher)
93 self.size = (len(self._MAGIC) + self._VERSION_SIZE +
94 self._MANIFEST_LEN_SIZE)
95 self.metadata_signature_len = 0
96
97 if self.version == common.BRILLO_MAJOR_PAYLOAD_VERSION:
98 self.size += self._METADATA_SIGNATURE_LEN_SIZE
99 self.metadata_signature_len = _ReadInt(
100 payload_file, self._METADATA_SIGNATURE_LEN_SIZE, True,
101 hasher=hasher)
102
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800103
Sen Jiang3b15b592017-09-26 18:21:04 -0700104 def __init__(self, payload_file, payload_file_offset=0):
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800105 """Initialize the payload object.
106
107 Args:
108 payload_file: update payload file object open for reading
Sen Jiang3b15b592017-09-26 18:21:04 -0700109 payload_file_offset: the offset of the actual payload
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800110 """
111 self.payload_file = payload_file
Sen Jiang3b15b592017-09-26 18:21:04 -0700112 self.payload_file_offset = payload_file_offset
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800113 self.manifest_hasher = None
114 self.is_init = False
115 self.header = None
116 self.manifest = None
Alex Deymoef497352015-10-15 09:14:58 -0700117 self.data_offset = None
118 self.metadata_signature = None
119 self.metadata_size = None
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800120
121 def _ReadHeader(self):
122 """Reads and returns the payload header.
123
124 Returns:
125 A payload header object.
Sen Jiang349fd292015-11-16 17:28:09 -0800126
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800127 Raises:
128 PayloadError if a read error occurred.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800129 """
Alex Deymoef497352015-10-15 09:14:58 -0700130 header = self._PayloadHeader()
131 header.ReadFromPayload(self.payload_file, self.manifest_hasher)
132 return header
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800133
134 def _ReadManifest(self):
135 """Reads and returns the payload manifest.
136
137 Returns:
138 A string containing the payload manifest in binary form.
Sen Jiang349fd292015-11-16 17:28:09 -0800139
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800140 Raises:
141 PayloadError if a read error occurred.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800142 """
143 if not self.header:
144 raise PayloadError('payload header not present')
145
146 return common.Read(self.payload_file, self.header.manifest_len,
147 hasher=self.manifest_hasher)
148
Alex Deymoef497352015-10-15 09:14:58 -0700149 def _ReadMetadataSignature(self):
150 """Reads and returns the metadata signatures.
151
152 Returns:
153 A string containing the metadata signatures protobuf in binary form or
154 an empty string if no metadata signature found in the payload.
Sen Jiang349fd292015-11-16 17:28:09 -0800155
Alex Deymoef497352015-10-15 09:14:58 -0700156 Raises:
157 PayloadError if a read error occurred.
Alex Deymoef497352015-10-15 09:14:58 -0700158 """
159 if not self.header:
160 raise PayloadError('payload header not present')
161
162 return common.Read(
163 self.payload_file, self.header.metadata_signature_len,
Sen Jiang3b15b592017-09-26 18:21:04 -0700164 offset=self.payload_file_offset + self.header.size +
165 self.header.manifest_len)
Alex Deymoef497352015-10-15 09:14:58 -0700166
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800167 def ReadDataBlob(self, offset, length):
168 """Reads and returns a single data blob from the update payload.
169
170 Args:
171 offset: offset to the beginning of the blob from the end of the manifest
172 length: the blob's length
Sen Jiang349fd292015-11-16 17:28:09 -0800173
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800174 Returns:
175 A string containing the raw blob data.
Sen Jiang349fd292015-11-16 17:28:09 -0800176
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800177 Raises:
178 PayloadError if a read error occurred.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800179 """
180 return common.Read(self.payload_file, length,
Sen Jiang3b15b592017-09-26 18:21:04 -0700181 offset=self.payload_file_offset + self.data_offset +
182 offset)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800183
184 def Init(self):
185 """Initializes the payload object.
186
187 This is a prerequisite for any other public API call.
188
189 Raises:
190 PayloadError if object already initialized or fails to initialize
191 correctly.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800192 """
193 if self.is_init:
194 raise PayloadError('payload object already initialized')
195
196 # Initialize hash context.
197 # pylint: disable=E1101
198 self.manifest_hasher = hashlib.sha256()
199
200 # Read the file header.
Sen Jiang3b15b592017-09-26 18:21:04 -0700201 self.payload_file.seek(self.payload_file_offset)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800202 self.header = self._ReadHeader()
203
204 # Read the manifest.
205 manifest_raw = self._ReadManifest()
206 self.manifest = update_metadata_pb2.DeltaArchiveManifest()
207 self.manifest.ParseFromString(manifest_raw)
208
Alex Deymoef497352015-10-15 09:14:58 -0700209 # Read the metadata signature (if any).
210 metadata_signature_raw = self._ReadMetadataSignature()
211 if metadata_signature_raw:
212 self.metadata_signature = update_metadata_pb2.Signatures()
213 self.metadata_signature.ParseFromString(metadata_signature_raw)
214
215 self.metadata_size = self.header.size + self.header.manifest_len
216 self.data_offset = self.metadata_size + self.header.metadata_signature_len
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800217
218 self.is_init = True
219
Don Garrett432d6012013-05-10 15:01:36 -0700220 def Describe(self):
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700221 """Emits the payload embedded description data to standard output."""
Don Garrett432d6012013-05-10 15:01:36 -0700222 def _DescribeImageInfo(description, image_info):
Sen Jiangc2527f42017-09-27 16:35:03 -0700223 """Display info about the image."""
Don Garrett432d6012013-05-10 15:01:36 -0700224 def _DisplayIndentedValue(name, value):
Sen Jiang349fd292015-11-16 17:28:09 -0800225 print(' {:<14} {}'.format(name+':', value))
Don Garrett432d6012013-05-10 15:01:36 -0700226
Sen Jiang349fd292015-11-16 17:28:09 -0800227 print('%s:' % description)
Don Garrett432d6012013-05-10 15:01:36 -0700228 _DisplayIndentedValue('Channel', image_info.channel)
229 _DisplayIndentedValue('Board', image_info.board)
230 _DisplayIndentedValue('Version', image_info.version)
231 _DisplayIndentedValue('Key', image_info.key)
232
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700233 if image_info.build_channel != image_info.channel:
Don Garrett432d6012013-05-10 15:01:36 -0700234 _DisplayIndentedValue('Build channel', image_info.build_channel)
235
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700236 if image_info.build_version != image_info.version:
Don Garrett432d6012013-05-10 15:01:36 -0700237 _DisplayIndentedValue('Build version', image_info.build_version)
238
239 if self.manifest.HasField('old_image_info'):
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700240 # pylint: disable=E1101
Don Garrett432d6012013-05-10 15:01:36 -0700241 _DescribeImageInfo('Old Image', self.manifest.old_image_info)
242
243 if self.manifest.HasField('new_image_info'):
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700244 # pylint: disable=E1101
Don Garrett432d6012013-05-10 15:01:36 -0700245 _DescribeImageInfo('New Image', self.manifest.new_image_info)
246
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800247 def _AssertInit(self):
248 """Raises an exception if the object was not initialized."""
249 if not self.is_init:
250 raise PayloadError('payload object not initialized')
251
252 def ResetFile(self):
253 """Resets the offset of the payload file to right past the manifest."""
Sen Jiang3b15b592017-09-26 18:21:04 -0700254 self.payload_file.seek(self.payload_file_offset + self.data_offset)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800255
256 def IsDelta(self):
257 """Returns True iff the payload appears to be a delta."""
258 self._AssertInit()
259 return (self.manifest.HasField('old_kernel_info') or
Sen Jiang349fd292015-11-16 17:28:09 -0800260 self.manifest.HasField('old_rootfs_info') or
261 any(partition.HasField('old_partition_info')
262 for partition in self.manifest.partitions))
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800263
264 def IsFull(self):
265 """Returns True iff the payload appears to be a full."""
266 return not self.IsDelta()
267
268 def Check(self, pubkey_file_name=None, metadata_sig_file=None,
269 report_out_file=None, assert_type=None, block_size=0,
Gilad Arnold382df5c2013-05-03 12:49:28 -0700270 rootfs_part_size=0, kernel_part_size=0, allow_unhashed=False,
271 disabled_tests=()):
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800272 """Checks the payload integrity.
273
274 Args:
275 pubkey_file_name: public key used for signature verification
276 metadata_sig_file: metadata signature, if verification is desired
277 report_out_file: file object to dump the report to
278 assert_type: assert that payload is either 'full' or 'delta'
279 block_size: expected filesystem / payload block size
Gilad Arnold382df5c2013-05-03 12:49:28 -0700280 rootfs_part_size: the size of (physical) rootfs partitions in bytes
281 kernel_part_size: the size of (physical) kernel partitions in bytes
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800282 allow_unhashed: allow unhashed operation blobs
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700283 disabled_tests: list of tests to disable
Sen Jiang349fd292015-11-16 17:28:09 -0800284
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800285 Raises:
286 PayloadError if payload verification failed.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800287 """
288 self._AssertInit()
289
290 # Create a short-lived payload checker object and run it.
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700291 helper = checker.PayloadChecker(
292 self, assert_type=assert_type, block_size=block_size,
293 allow_unhashed=allow_unhashed, disabled_tests=disabled_tests)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800294 helper.Run(pubkey_file_name=pubkey_file_name,
295 metadata_sig_file=metadata_sig_file,
Gilad Arnold382df5c2013-05-03 12:49:28 -0700296 rootfs_part_size=rootfs_part_size,
297 kernel_part_size=kernel_part_size,
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700298 report_out_file=report_out_file)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800299
Gilad Arnold16416602013-05-04 21:40:39 -0700300 def Apply(self, new_kernel_part, new_rootfs_part, old_kernel_part=None,
Gilad Arnold21a02502013-08-22 16:59:48 -0700301 old_rootfs_part=None, bsdiff_in_place=True, bspatch_path=None,
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700302 truncate_to_expected_size=True):
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800303 """Applies the update payload.
304
305 Args:
Gilad Arnold16416602013-05-04 21:40:39 -0700306 new_kernel_part: name of dest kernel partition file
307 new_rootfs_part: name of dest rootfs partition file
308 old_kernel_part: name of source kernel partition file (optional)
309 old_rootfs_part: name of source rootfs partition file (optional)
Gilad Arnold272a4992013-05-08 13:12:53 -0700310 bsdiff_in_place: whether to perform BSDIFF operations in-place (optional)
Gilad Arnold21a02502013-08-22 16:59:48 -0700311 bspatch_path: path to the bspatch binary (optional)
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700312 truncate_to_expected_size: whether to truncate the resulting partitions
313 to their expected sizes, as specified in the
314 payload (optional)
Sen Jiang349fd292015-11-16 17:28:09 -0800315
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800316 Raises:
317 PayloadError if payload application failed.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800318 """
319 self._AssertInit()
320
321 # Create a short-lived payload applier object and run it.
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700322 helper = applier.PayloadApplier(
Gilad Arnold21a02502013-08-22 16:59:48 -0700323 self, bsdiff_in_place=bsdiff_in_place, bspatch_path=bspatch_path,
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700324 truncate_to_expected_size=truncate_to_expected_size)
Gilad Arnold16416602013-05-04 21:40:39 -0700325 helper.Run(new_kernel_part, new_rootfs_part,
326 old_kernel_part=old_kernel_part,
327 old_rootfs_part=old_rootfs_part)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800328
329 def TraceBlock(self, block, skip, trace_out_file, is_kernel):
330 """Traces the origin(s) of a given dest partition block.
331
332 The tracing tries to find origins transitively, when possible (it currently
333 only works for move operations, where the mapping of src/dst is
334 one-to-one). It will dump a list of operations and source blocks
335 responsible for the data in the given dest block.
336
337 Args:
338 block: the block number whose origin to trace
339 skip: the number of first origin mappings to skip
340 trace_out_file: file object to dump the trace to
341 is_kernel: trace through kernel (True) or rootfs (False) operations
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800342 """
343 self._AssertInit()
344
345 # Create a short-lived payload block tracer object and run it.
346 helper = block_tracer.PayloadBlockTracer(self)
347 helper.Run(block, skip, trace_out_file, is_kernel)