blob: ea5ed30872acb3013679cb295a42ba0e6fa3e0be [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
Andrew Lassalle165843c2019-11-05 13:30:34 -080019from __future__ import absolute_import
Sen Jiang349fd292015-11-16 17:28:09 -080020from __future__ import print_function
21
Gilad Arnold553b0ec2013-01-26 01:00:39 -080022import hashlib
23import struct
24
Sen Jiangc2527f42017-09-27 16:35:03 -070025from update_payload import applier
Sen Jiangc2527f42017-09-27 16:35:03 -070026from update_payload import checker
27from update_payload import common
Sen Jiangc2527f42017-09-27 16:35:03 -070028from update_payload import update_metadata_pb2
Amin Hassanib05a65a2017-12-18 15:15:32 -080029from update_payload.error import PayloadError
Gilad Arnold553b0ec2013-01-26 01:00:39 -080030
31
32#
33# Helper functions.
34#
35def _ReadInt(file_obj, size, is_unsigned, hasher=None):
Gilad Arnold5502b562013-03-08 13:22:31 -080036 """Reads a binary-encoded integer from a file.
Gilad Arnold553b0ec2013-01-26 01:00:39 -080037
38 It will do the correct conversion based on the reported size and whether or
39 not a signed number is expected. Assumes a network (big-endian) byte
40 ordering.
41
42 Args:
43 file_obj: a file object
44 size: the integer size in bytes (2, 4 or 8)
45 is_unsigned: whether it is signed or not
46 hasher: an optional hasher to pass the value through
Sen Jiang349fd292015-11-16 17:28:09 -080047
Gilad Arnold553b0ec2013-01-26 01:00:39 -080048 Returns:
49 An "unpacked" (Python) integer value.
Sen Jiang349fd292015-11-16 17:28:09 -080050
Gilad Arnold553b0ec2013-01-26 01:00:39 -080051 Raises:
52 PayloadError if an read error occurred.
Gilad Arnold553b0ec2013-01-26 01:00:39 -080053 """
Gilad Arnold5502b562013-03-08 13:22:31 -080054 return struct.unpack(common.IntPackingFmtStr(size, is_unsigned),
55 common.Read(file_obj, size, hasher=hasher))[0]
Gilad Arnold553b0ec2013-01-26 01:00:39 -080056
57
58#
59# Update payload.
60#
61class Payload(object):
62 """Chrome OS update payload processor."""
63
64 class _PayloadHeader(object):
65 """Update payload header struct."""
66
Alex Deymoef497352015-10-15 09:14:58 -070067 # Header constants; sizes are in bytes.
Andrew Lassalle165843c2019-11-05 13:30:34 -080068 _MAGIC = b'CrAU'
Alex Deymoef497352015-10-15 09:14:58 -070069 _VERSION_SIZE = 8
70 _MANIFEST_LEN_SIZE = 8
71 _METADATA_SIGNATURE_LEN_SIZE = 4
Gilad Arnold553b0ec2013-01-26 01:00:39 -080072
Alex Deymoef497352015-10-15 09:14:58 -070073 def __init__(self):
74 self.version = None
75 self.manifest_len = None
76 self.metadata_signature_len = None
77 self.size = None
78
79 def ReadFromPayload(self, payload_file, hasher=None):
80 """Reads the payload header from a file.
81
82 Reads the payload header from the |payload_file| and updates the |hasher|
83 if one is passed. The parsed header is stored in the _PayloadHeader
84 instance attributes.
85
86 Args:
87 payload_file: a file object
88 hasher: an optional hasher to pass the value through
Sen Jiang349fd292015-11-16 17:28:09 -080089
Alex Deymoef497352015-10-15 09:14:58 -070090 Returns:
91 None.
Sen Jiang349fd292015-11-16 17:28:09 -080092
Alex Deymoef497352015-10-15 09:14:58 -070093 Raises:
94 PayloadError if a read error occurred or the header is invalid.
95 """
96 # Verify magic
97 magic = common.Read(payload_file, len(self._MAGIC), hasher=hasher)
98 if magic != self._MAGIC:
99 raise PayloadError('invalid payload magic: %s' % magic)
100
101 self.version = _ReadInt(payload_file, self._VERSION_SIZE, True,
102 hasher=hasher)
103 self.manifest_len = _ReadInt(payload_file, self._MANIFEST_LEN_SIZE, True,
104 hasher=hasher)
105 self.size = (len(self._MAGIC) + self._VERSION_SIZE +
106 self._MANIFEST_LEN_SIZE)
107 self.metadata_signature_len = 0
108
109 if self.version == common.BRILLO_MAJOR_PAYLOAD_VERSION:
110 self.size += self._METADATA_SIGNATURE_LEN_SIZE
111 self.metadata_signature_len = _ReadInt(
112 payload_file, self._METADATA_SIGNATURE_LEN_SIZE, True,
113 hasher=hasher)
114
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()
Amin Hassani55c75412019-10-07 11:20:39 -0700266 return (any(partition.HasField('old_partition_info')
Sen Jiang349fd292015-11-16 17:28:09 -0800267 for partition in self.manifest.partitions))
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800268
269 def IsFull(self):
270 """Returns True iff the payload appears to be a full."""
271 return not self.IsDelta()
272
273 def Check(self, pubkey_file_name=None, metadata_sig_file=None,
Amin Hassania86b1082018-03-08 15:48:59 -0800274 metadata_size=0, report_out_file=None, assert_type=None,
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700275 block_size=0, part_sizes=None, allow_unhashed=False,
276 disabled_tests=()):
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800277 """Checks the payload integrity.
278
279 Args:
280 pubkey_file_name: public key used for signature verification
281 metadata_sig_file: metadata signature, if verification is desired
Amin Hassania86b1082018-03-08 15:48:59 -0800282 metadata_size: metadata size, if verification is desired
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800283 report_out_file: file object to dump the report to
284 assert_type: assert that payload is either 'full' or 'delta'
285 block_size: expected filesystem / payload block size
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700286 part_sizes: map of partition label to (physical) size in bytes
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800287 allow_unhashed: allow unhashed operation blobs
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700288 disabled_tests: list of tests to disable
Sen Jiang349fd292015-11-16 17:28:09 -0800289
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800290 Raises:
291 PayloadError if payload verification failed.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800292 """
293 self._AssertInit()
294
295 # Create a short-lived payload checker object and run it.
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700296 helper = checker.PayloadChecker(
297 self, assert_type=assert_type, block_size=block_size,
298 allow_unhashed=allow_unhashed, disabled_tests=disabled_tests)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800299 helper.Run(pubkey_file_name=pubkey_file_name,
300 metadata_sig_file=metadata_sig_file,
Amin Hassania86b1082018-03-08 15:48:59 -0800301 metadata_size=metadata_size,
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700302 part_sizes=part_sizes,
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700303 report_out_file=report_out_file)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800304
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700305 def Apply(self, new_parts, old_parts=None, bsdiff_in_place=True,
306 bspatch_path=None, puffpatch_path=None,
307 truncate_to_expected_size=True):
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800308 """Applies the update payload.
309
310 Args:
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700311 new_parts: map of partition name to dest partition file
312 old_parts: map of partition name to partition file (optional)
Gilad Arnold272a4992013-05-08 13:12:53 -0700313 bsdiff_in_place: whether to perform BSDIFF operations in-place (optional)
Gilad Arnold21a02502013-08-22 16:59:48 -0700314 bspatch_path: path to the bspatch binary (optional)
Amin Hassani6be71682017-12-01 10:46:45 -0800315 puffpatch_path: path to the puffpatch binary (optional)
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700316 truncate_to_expected_size: whether to truncate the resulting partitions
317 to their expected sizes, as specified in the
318 payload (optional)
Sen Jiang349fd292015-11-16 17:28:09 -0800319
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800320 Raises:
321 PayloadError if payload application failed.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800322 """
323 self._AssertInit()
324
325 # Create a short-lived payload applier object and run it.
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700326 helper = applier.PayloadApplier(
Gilad Arnold21a02502013-08-22 16:59:48 -0700327 self, bsdiff_in_place=bsdiff_in_place, bspatch_path=bspatch_path,
Amin Hassani6be71682017-12-01 10:46:45 -0800328 puffpatch_path=puffpatch_path,
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700329 truncate_to_expected_size=truncate_to_expected_size)
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700330 helper.Run(new_parts, old_parts=old_parts)