blob: 2a0cb58dbb2f60c12604e86646eed2f15fb3debd [file] [log] [blame]
Amin Hassanif94b6432018-01-26 17:39:47 -08001#
2# Copyright (C) 2013 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#
Gilad Arnold553b0ec2013-01-26 01:00:39 -080016
17"""Tools for reading, verifying and applying Chrome OS update payloads."""
18
Sen Jiang349fd292015-11-16 17:28:09 -080019from __future__ import print_function
20
Gilad Arnold553b0ec2013-01-26 01:00:39 -080021import hashlib
22import struct
23
Sen Jiangc2527f42017-09-27 16:35:03 -070024from update_payload import applier
Sen Jiangc2527f42017-09-27 16:35:03 -070025from update_payload import checker
26from update_payload import common
Sen Jiangc2527f42017-09-27 16:35:03 -070027from update_payload import update_metadata_pb2
Amin Hassanib05a65a2017-12-18 15:15:32 -080028from update_payload.error import PayloadError
Gilad Arnold553b0ec2013-01-26 01:00:39 -080029
30
31#
32# Helper functions.
33#
34def _ReadInt(file_obj, size, is_unsigned, hasher=None):
Gilad Arnold5502b562013-03-08 13:22:31 -080035 """Reads a binary-encoded integer from a file.
Gilad Arnold553b0ec2013-01-26 01:00:39 -080036
37 It will do the correct conversion based on the reported size and whether or
38 not a signed number is expected. Assumes a network (big-endian) byte
39 ordering.
40
41 Args:
42 file_obj: a file object
43 size: the integer size in bytes (2, 4 or 8)
44 is_unsigned: whether it is signed or not
45 hasher: an optional hasher to pass the value through
Sen Jiang349fd292015-11-16 17:28:09 -080046
Gilad Arnold553b0ec2013-01-26 01:00:39 -080047 Returns:
48 An "unpacked" (Python) integer value.
Sen Jiang349fd292015-11-16 17:28:09 -080049
Gilad Arnold553b0ec2013-01-26 01:00:39 -080050 Raises:
51 PayloadError if an read error occurred.
Gilad Arnold553b0ec2013-01-26 01:00:39 -080052 """
Gilad Arnold5502b562013-03-08 13:22:31 -080053 return struct.unpack(common.IntPackingFmtStr(size, is_unsigned),
54 common.Read(file_obj, size, hasher=hasher))[0]
Gilad Arnold553b0ec2013-01-26 01:00:39 -080055
56
57#
58# Update payload.
59#
60class Payload(object):
61 """Chrome OS update payload processor."""
62
63 class _PayloadHeader(object):
64 """Update payload header struct."""
65
Alex Deymoef497352015-10-15 09:14:58 -070066 # Header constants; sizes are in bytes.
67 _MAGIC = 'CrAU'
68 _VERSION_SIZE = 8
69 _MANIFEST_LEN_SIZE = 8
70 _METADATA_SIGNATURE_LEN_SIZE = 4
Gilad Arnold553b0ec2013-01-26 01:00:39 -080071
Alex Deymoef497352015-10-15 09:14:58 -070072 def __init__(self):
73 self.version = None
74 self.manifest_len = None
75 self.metadata_signature_len = None
76 self.size = None
77
78 def ReadFromPayload(self, payload_file, hasher=None):
79 """Reads the payload header from a file.
80
81 Reads the payload header from the |payload_file| and updates the |hasher|
82 if one is passed. The parsed header is stored in the _PayloadHeader
83 instance attributes.
84
85 Args:
86 payload_file: a file object
87 hasher: an optional hasher to pass the value through
Sen Jiang349fd292015-11-16 17:28:09 -080088
Alex Deymoef497352015-10-15 09:14:58 -070089 Returns:
90 None.
Sen Jiang349fd292015-11-16 17:28:09 -080091
Alex Deymoef497352015-10-15 09:14:58 -070092 Raises:
93 PayloadError if a read error occurred or the header is invalid.
94 """
95 # Verify magic
96 magic = common.Read(payload_file, len(self._MAGIC), hasher=hasher)
97 if magic != self._MAGIC:
98 raise PayloadError('invalid payload magic: %s' % magic)
99
100 self.version = _ReadInt(payload_file, self._VERSION_SIZE, True,
101 hasher=hasher)
102 self.manifest_len = _ReadInt(payload_file, self._MANIFEST_LEN_SIZE, True,
103 hasher=hasher)
104 self.size = (len(self._MAGIC) + self._VERSION_SIZE +
105 self._MANIFEST_LEN_SIZE)
106 self.metadata_signature_len = 0
107
108 if self.version == common.BRILLO_MAJOR_PAYLOAD_VERSION:
109 self.size += self._METADATA_SIGNATURE_LEN_SIZE
110 self.metadata_signature_len = _ReadInt(
111 payload_file, self._METADATA_SIGNATURE_LEN_SIZE, True,
112 hasher=hasher)
113
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800114
Sen Jiang3b15b592017-09-26 18:21:04 -0700115 def __init__(self, payload_file, payload_file_offset=0):
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800116 """Initialize the payload object.
117
118 Args:
119 payload_file: update payload file object open for reading
Sen Jiang3b15b592017-09-26 18:21:04 -0700120 payload_file_offset: the offset of the actual payload
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800121 """
122 self.payload_file = payload_file
Sen Jiang3b15b592017-09-26 18:21:04 -0700123 self.payload_file_offset = payload_file_offset
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800124 self.manifest_hasher = None
125 self.is_init = False
126 self.header = None
127 self.manifest = None
Alex Deymoef497352015-10-15 09:14:58 -0700128 self.data_offset = None
129 self.metadata_signature = None
130 self.metadata_size = None
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800131
132 def _ReadHeader(self):
133 """Reads and returns the payload header.
134
135 Returns:
136 A payload header object.
Sen Jiang349fd292015-11-16 17:28:09 -0800137
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800138 Raises:
139 PayloadError if a read error occurred.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800140 """
Alex Deymoef497352015-10-15 09:14:58 -0700141 header = self._PayloadHeader()
142 header.ReadFromPayload(self.payload_file, self.manifest_hasher)
143 return header
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800144
145 def _ReadManifest(self):
146 """Reads and returns the payload manifest.
147
148 Returns:
149 A string containing the payload manifest in binary form.
Sen Jiang349fd292015-11-16 17:28:09 -0800150
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800151 Raises:
152 PayloadError if a read error occurred.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800153 """
154 if not self.header:
155 raise PayloadError('payload header not present')
156
157 return common.Read(self.payload_file, self.header.manifest_len,
158 hasher=self.manifest_hasher)
159
Alex Deymoef497352015-10-15 09:14:58 -0700160 def _ReadMetadataSignature(self):
161 """Reads and returns the metadata signatures.
162
163 Returns:
164 A string containing the metadata signatures protobuf in binary form or
165 an empty string if no metadata signature found in the payload.
Sen Jiang349fd292015-11-16 17:28:09 -0800166
Alex Deymoef497352015-10-15 09:14:58 -0700167 Raises:
168 PayloadError if a read error occurred.
Alex Deymoef497352015-10-15 09:14:58 -0700169 """
170 if not self.header:
171 raise PayloadError('payload header not present')
172
173 return common.Read(
174 self.payload_file, self.header.metadata_signature_len,
Sen Jiang3b15b592017-09-26 18:21:04 -0700175 offset=self.payload_file_offset + self.header.size +
176 self.header.manifest_len)
Alex Deymoef497352015-10-15 09:14:58 -0700177
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800178 def ReadDataBlob(self, offset, length):
179 """Reads and returns a single data blob from the update payload.
180
181 Args:
182 offset: offset to the beginning of the blob from the end of the manifest
183 length: the blob's length
Sen Jiang349fd292015-11-16 17:28:09 -0800184
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800185 Returns:
186 A string containing the raw blob data.
Sen Jiang349fd292015-11-16 17:28:09 -0800187
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800188 Raises:
189 PayloadError if a read error occurred.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800190 """
191 return common.Read(self.payload_file, length,
Sen Jiang3b15b592017-09-26 18:21:04 -0700192 offset=self.payload_file_offset + self.data_offset +
193 offset)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800194
195 def Init(self):
196 """Initializes the payload object.
197
198 This is a prerequisite for any other public API call.
199
200 Raises:
201 PayloadError if object already initialized or fails to initialize
202 correctly.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800203 """
204 if self.is_init:
205 raise PayloadError('payload object already initialized')
206
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800207 self.manifest_hasher = hashlib.sha256()
208
209 # Read the file header.
Sen Jiang3b15b592017-09-26 18:21:04 -0700210 self.payload_file.seek(self.payload_file_offset)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800211 self.header = self._ReadHeader()
212
213 # Read the manifest.
214 manifest_raw = self._ReadManifest()
215 self.manifest = update_metadata_pb2.DeltaArchiveManifest()
216 self.manifest.ParseFromString(manifest_raw)
217
Alex Deymoef497352015-10-15 09:14:58 -0700218 # Read the metadata signature (if any).
219 metadata_signature_raw = self._ReadMetadataSignature()
220 if metadata_signature_raw:
221 self.metadata_signature = update_metadata_pb2.Signatures()
222 self.metadata_signature.ParseFromString(metadata_signature_raw)
223
224 self.metadata_size = self.header.size + self.header.manifest_len
225 self.data_offset = self.metadata_size + self.header.metadata_signature_len
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800226
227 self.is_init = True
228
Don Garrett432d6012013-05-10 15:01:36 -0700229 def Describe(self):
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700230 """Emits the payload embedded description data to standard output."""
Don Garrett432d6012013-05-10 15:01:36 -0700231 def _DescribeImageInfo(description, image_info):
Sen Jiangc2527f42017-09-27 16:35:03 -0700232 """Display info about the image."""
Don Garrett432d6012013-05-10 15:01:36 -0700233 def _DisplayIndentedValue(name, value):
Sen Jiang349fd292015-11-16 17:28:09 -0800234 print(' {:<14} {}'.format(name+':', value))
Don Garrett432d6012013-05-10 15:01:36 -0700235
Sen Jiang349fd292015-11-16 17:28:09 -0800236 print('%s:' % description)
Don Garrett432d6012013-05-10 15:01:36 -0700237 _DisplayIndentedValue('Channel', image_info.channel)
238 _DisplayIndentedValue('Board', image_info.board)
239 _DisplayIndentedValue('Version', image_info.version)
240 _DisplayIndentedValue('Key', image_info.key)
241
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700242 if image_info.build_channel != image_info.channel:
Don Garrett432d6012013-05-10 15:01:36 -0700243 _DisplayIndentedValue('Build channel', image_info.build_channel)
244
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700245 if image_info.build_version != image_info.version:
Don Garrett432d6012013-05-10 15:01:36 -0700246 _DisplayIndentedValue('Build version', image_info.build_version)
247
248 if self.manifest.HasField('old_image_info'):
249 _DescribeImageInfo('Old Image', self.manifest.old_image_info)
250
251 if self.manifest.HasField('new_image_info'):
252 _DescribeImageInfo('New Image', self.manifest.new_image_info)
253
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800254 def _AssertInit(self):
255 """Raises an exception if the object was not initialized."""
256 if not self.is_init:
257 raise PayloadError('payload object not initialized')
258
259 def ResetFile(self):
260 """Resets the offset of the payload file to right past the manifest."""
Sen Jiang3b15b592017-09-26 18:21:04 -0700261 self.payload_file.seek(self.payload_file_offset + self.data_offset)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800262
263 def IsDelta(self):
264 """Returns True iff the payload appears to be a delta."""
265 self._AssertInit()
266 return (self.manifest.HasField('old_kernel_info') or
Sen Jiang349fd292015-11-16 17:28:09 -0800267 self.manifest.HasField('old_rootfs_info') or
268 any(partition.HasField('old_partition_info')
269 for partition in self.manifest.partitions))
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800270
271 def IsFull(self):
272 """Returns True iff the payload appears to be a full."""
273 return not self.IsDelta()
274
275 def Check(self, pubkey_file_name=None, metadata_sig_file=None,
Amin Hassania86b1082018-03-08 15:48:59 -0800276 metadata_size=0, report_out_file=None, assert_type=None,
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700277 block_size=0, part_sizes=None, allow_unhashed=False,
278 disabled_tests=()):
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800279 """Checks the payload integrity.
280
281 Args:
282 pubkey_file_name: public key used for signature verification
283 metadata_sig_file: metadata signature, if verification is desired
Amin Hassania86b1082018-03-08 15:48:59 -0800284 metadata_size: metadata size, if verification is desired
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800285 report_out_file: file object to dump the report to
286 assert_type: assert that payload is either 'full' or 'delta'
287 block_size: expected filesystem / payload block size
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700288 part_sizes: map of partition label to (physical) size in bytes
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800289 allow_unhashed: allow unhashed operation blobs
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700290 disabled_tests: list of tests to disable
Sen Jiang349fd292015-11-16 17:28:09 -0800291
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800292 Raises:
293 PayloadError if payload verification failed.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800294 """
295 self._AssertInit()
296
297 # Create a short-lived payload checker object and run it.
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700298 helper = checker.PayloadChecker(
299 self, assert_type=assert_type, block_size=block_size,
300 allow_unhashed=allow_unhashed, disabled_tests=disabled_tests)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800301 helper.Run(pubkey_file_name=pubkey_file_name,
302 metadata_sig_file=metadata_sig_file,
Amin Hassania86b1082018-03-08 15:48:59 -0800303 metadata_size=metadata_size,
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700304 part_sizes=part_sizes,
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700305 report_out_file=report_out_file)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800306
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700307 def Apply(self, new_parts, old_parts=None, bsdiff_in_place=True,
308 bspatch_path=None, puffpatch_path=None,
309 truncate_to_expected_size=True):
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800310 """Applies the update payload.
311
312 Args:
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700313 new_parts: map of partition name to dest partition file
314 old_parts: map of partition name to partition file (optional)
Gilad Arnold272a4992013-05-08 13:12:53 -0700315 bsdiff_in_place: whether to perform BSDIFF operations in-place (optional)
Gilad Arnold21a02502013-08-22 16:59:48 -0700316 bspatch_path: path to the bspatch binary (optional)
Amin Hassani6be71682017-12-01 10:46:45 -0800317 puffpatch_path: path to the puffpatch binary (optional)
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700318 truncate_to_expected_size: whether to truncate the resulting partitions
319 to their expected sizes, as specified in the
320 payload (optional)
Sen Jiang349fd292015-11-16 17:28:09 -0800321
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800322 Raises:
323 PayloadError if payload application failed.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800324 """
325 self._AssertInit()
326
327 # Create a short-lived payload applier object and run it.
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700328 helper = applier.PayloadApplier(
Gilad Arnold21a02502013-08-22 16:59:48 -0700329 self, bsdiff_in_place=bsdiff_in_place, bspatch_path=bspatch_path,
Amin Hassani6be71682017-12-01 10:46:45 -0800330 puffpatch_path=puffpatch_path,
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700331 truncate_to_expected_size=truncate_to_expected_size)
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700332 helper.Run(new_parts, old_parts=old_parts)