blob: 78b8e2ca5de5bce0cde28d8fcfe0d17c40fdee4e [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
Kelvin Zhang9e7a6db2020-08-13 14:55:58 -040023import io
Gilad Arnold553b0ec2013-01-26 01:00:39 -080024import struct
Kelvin Zhang9e7a6db2020-08-13 14:55:58 -040025import zipfile
Gilad Arnold553b0ec2013-01-26 01:00:39 -080026
Sen Jiangc2527f42017-09-27 16:35:03 -070027from update_payload import applier
Sen Jiangc2527f42017-09-27 16:35:03 -070028from update_payload import checker
29from update_payload import common
Sen Jiangc2527f42017-09-27 16:35:03 -070030from update_payload import update_metadata_pb2
Amin Hassanib05a65a2017-12-18 15:15:32 -080031from update_payload.error import PayloadError
Gilad Arnold553b0ec2013-01-26 01:00:39 -080032
33
34#
35# Helper functions.
36#
37def _ReadInt(file_obj, size, is_unsigned, hasher=None):
Gilad Arnold5502b562013-03-08 13:22:31 -080038 """Reads a binary-encoded integer from a file.
Gilad Arnold553b0ec2013-01-26 01:00:39 -080039
40 It will do the correct conversion based on the reported size and whether or
41 not a signed number is expected. Assumes a network (big-endian) byte
42 ordering.
43
44 Args:
45 file_obj: a file object
46 size: the integer size in bytes (2, 4 or 8)
47 is_unsigned: whether it is signed or not
48 hasher: an optional hasher to pass the value through
Sen Jiang349fd292015-11-16 17:28:09 -080049
Gilad Arnold553b0ec2013-01-26 01:00:39 -080050 Returns:
51 An "unpacked" (Python) integer value.
Sen Jiang349fd292015-11-16 17:28:09 -080052
Gilad Arnold553b0ec2013-01-26 01:00:39 -080053 Raises:
54 PayloadError if an read error occurred.
Gilad Arnold553b0ec2013-01-26 01:00:39 -080055 """
Gilad Arnold5502b562013-03-08 13:22:31 -080056 return struct.unpack(common.IntPackingFmtStr(size, is_unsigned),
57 common.Read(file_obj, size, hasher=hasher))[0]
Gilad Arnold553b0ec2013-01-26 01:00:39 -080058
59
60#
61# Update payload.
62#
63class Payload(object):
64 """Chrome OS update payload processor."""
65
66 class _PayloadHeader(object):
67 """Update payload header struct."""
68
Alex Deymoef497352015-10-15 09:14:58 -070069 # Header constants; sizes are in bytes.
Andrew Lassalle165843c2019-11-05 13:30:34 -080070 _MAGIC = b'CrAU'
Alex Deymoef497352015-10-15 09:14:58 -070071 _VERSION_SIZE = 8
72 _MANIFEST_LEN_SIZE = 8
73 _METADATA_SIGNATURE_LEN_SIZE = 4
Gilad Arnold553b0ec2013-01-26 01:00:39 -080074
Alex Deymoef497352015-10-15 09:14:58 -070075 def __init__(self):
76 self.version = None
77 self.manifest_len = None
78 self.metadata_signature_len = None
79 self.size = None
80
81 def ReadFromPayload(self, payload_file, hasher=None):
82 """Reads the payload header from a file.
83
84 Reads the payload header from the |payload_file| and updates the |hasher|
85 if one is passed. The parsed header is stored in the _PayloadHeader
86 instance attributes.
87
88 Args:
89 payload_file: a file object
90 hasher: an optional hasher to pass the value through
Sen Jiang349fd292015-11-16 17:28:09 -080091
Alex Deymoef497352015-10-15 09:14:58 -070092 Returns:
93 None.
Sen Jiang349fd292015-11-16 17:28:09 -080094
Alex Deymoef497352015-10-15 09:14:58 -070095 Raises:
96 PayloadError if a read error occurred or the header is invalid.
97 """
98 # Verify magic
99 magic = common.Read(payload_file, len(self._MAGIC), hasher=hasher)
100 if magic != self._MAGIC:
101 raise PayloadError('invalid payload magic: %s' % magic)
102
103 self.version = _ReadInt(payload_file, self._VERSION_SIZE, True,
104 hasher=hasher)
105 self.manifest_len = _ReadInt(payload_file, self._MANIFEST_LEN_SIZE, True,
106 hasher=hasher)
107 self.size = (len(self._MAGIC) + self._VERSION_SIZE +
108 self._MANIFEST_LEN_SIZE)
109 self.metadata_signature_len = 0
110
111 if self.version == common.BRILLO_MAJOR_PAYLOAD_VERSION:
112 self.size += self._METADATA_SIGNATURE_LEN_SIZE
113 self.metadata_signature_len = _ReadInt(
114 payload_file, self._METADATA_SIGNATURE_LEN_SIZE, True,
115 hasher=hasher)
116
Sen Jiang3b15b592017-09-26 18:21:04 -0700117 def __init__(self, payload_file, payload_file_offset=0):
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800118 """Initialize the payload object.
119
120 Args:
121 payload_file: update payload file object open for reading
Sen Jiang3b15b592017-09-26 18:21:04 -0700122 payload_file_offset: the offset of the actual payload
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800123 """
Kelvin Zhang9e7a6db2020-08-13 14:55:58 -0400124 if zipfile.is_zipfile(payload_file):
125 with zipfile.ZipFile(payload_file) as zfp:
126 with zfp.open("payload.bin") as payload_fp:
127 payload_file = io.BytesIO(payload_fp.read())
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800128 self.payload_file = payload_file
Sen Jiang3b15b592017-09-26 18:21:04 -0700129 self.payload_file_offset = payload_file_offset
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800130 self.manifest_hasher = None
131 self.is_init = False
132 self.header = None
133 self.manifest = None
Alex Deymoef497352015-10-15 09:14:58 -0700134 self.data_offset = None
135 self.metadata_signature = None
136 self.metadata_size = None
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800137
138 def _ReadHeader(self):
139 """Reads and returns the payload header.
140
141 Returns:
142 A payload header object.
Sen Jiang349fd292015-11-16 17:28:09 -0800143
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800144 Raises:
145 PayloadError if a read error occurred.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800146 """
Alex Deymoef497352015-10-15 09:14:58 -0700147 header = self._PayloadHeader()
148 header.ReadFromPayload(self.payload_file, self.manifest_hasher)
149 return header
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800150
151 def _ReadManifest(self):
152 """Reads and returns the payload manifest.
153
154 Returns:
155 A string containing the payload manifest in binary form.
Sen Jiang349fd292015-11-16 17:28:09 -0800156
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800157 Raises:
158 PayloadError if a read error occurred.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800159 """
160 if not self.header:
161 raise PayloadError('payload header not present')
162
163 return common.Read(self.payload_file, self.header.manifest_len,
164 hasher=self.manifest_hasher)
165
Alex Deymoef497352015-10-15 09:14:58 -0700166 def _ReadMetadataSignature(self):
167 """Reads and returns the metadata signatures.
168
169 Returns:
170 A string containing the metadata signatures protobuf in binary form or
171 an empty string if no metadata signature found in the payload.
Sen Jiang349fd292015-11-16 17:28:09 -0800172
Alex Deymoef497352015-10-15 09:14:58 -0700173 Raises:
174 PayloadError if a read error occurred.
Alex Deymoef497352015-10-15 09:14:58 -0700175 """
176 if not self.header:
177 raise PayloadError('payload header not present')
178
179 return common.Read(
180 self.payload_file, self.header.metadata_signature_len,
Sen Jiang3b15b592017-09-26 18:21:04 -0700181 offset=self.payload_file_offset + self.header.size +
182 self.header.manifest_len)
Alex Deymoef497352015-10-15 09:14:58 -0700183
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800184 def ReadDataBlob(self, offset, length):
185 """Reads and returns a single data blob from the update payload.
186
187 Args:
188 offset: offset to the beginning of the blob from the end of the manifest
189 length: the blob's length
Sen Jiang349fd292015-11-16 17:28:09 -0800190
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800191 Returns:
192 A string containing the raw blob data.
Sen Jiang349fd292015-11-16 17:28:09 -0800193
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800194 Raises:
195 PayloadError if a read error occurred.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800196 """
197 return common.Read(self.payload_file, length,
Sen Jiang3b15b592017-09-26 18:21:04 -0700198 offset=self.payload_file_offset + self.data_offset +
199 offset)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800200
201 def Init(self):
202 """Initializes the payload object.
203
204 This is a prerequisite for any other public API call.
205
206 Raises:
207 PayloadError if object already initialized or fails to initialize
208 correctly.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800209 """
210 if self.is_init:
211 raise PayloadError('payload object already initialized')
212
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800213 self.manifest_hasher = hashlib.sha256()
214
215 # Read the file header.
Sen Jiang3b15b592017-09-26 18:21:04 -0700216 self.payload_file.seek(self.payload_file_offset)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800217 self.header = self._ReadHeader()
218
219 # Read the manifest.
220 manifest_raw = self._ReadManifest()
221 self.manifest = update_metadata_pb2.DeltaArchiveManifest()
222 self.manifest.ParseFromString(manifest_raw)
223
Alex Deymoef497352015-10-15 09:14:58 -0700224 # Read the metadata signature (if any).
225 metadata_signature_raw = self._ReadMetadataSignature()
226 if metadata_signature_raw:
227 self.metadata_signature = update_metadata_pb2.Signatures()
228 self.metadata_signature.ParseFromString(metadata_signature_raw)
229
230 self.metadata_size = self.header.size + self.header.manifest_len
231 self.data_offset = self.metadata_size + self.header.metadata_signature_len
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800232
233 self.is_init = True
234
Don Garrett432d6012013-05-10 15:01:36 -0700235 def Describe(self):
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700236 """Emits the payload embedded description data to standard output."""
Don Garrett432d6012013-05-10 15:01:36 -0700237 def _DescribeImageInfo(description, image_info):
Sen Jiangc2527f42017-09-27 16:35:03 -0700238 """Display info about the image."""
Don Garrett432d6012013-05-10 15:01:36 -0700239 def _DisplayIndentedValue(name, value):
Sen Jiang349fd292015-11-16 17:28:09 -0800240 print(' {:<14} {}'.format(name+':', value))
Don Garrett432d6012013-05-10 15:01:36 -0700241
Sen Jiang349fd292015-11-16 17:28:09 -0800242 print('%s:' % description)
Don Garrett432d6012013-05-10 15:01:36 -0700243 _DisplayIndentedValue('Channel', image_info.channel)
244 _DisplayIndentedValue('Board', image_info.board)
245 _DisplayIndentedValue('Version', image_info.version)
246 _DisplayIndentedValue('Key', image_info.key)
247
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700248 if image_info.build_channel != image_info.channel:
Don Garrett432d6012013-05-10 15:01:36 -0700249 _DisplayIndentedValue('Build channel', image_info.build_channel)
250
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700251 if image_info.build_version != image_info.version:
Don Garrett432d6012013-05-10 15:01:36 -0700252 _DisplayIndentedValue('Build version', image_info.build_version)
253
254 if self.manifest.HasField('old_image_info'):
255 _DescribeImageInfo('Old Image', self.manifest.old_image_info)
256
257 if self.manifest.HasField('new_image_info'):
258 _DescribeImageInfo('New Image', self.manifest.new_image_info)
259
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800260 def _AssertInit(self):
261 """Raises an exception if the object was not initialized."""
262 if not self.is_init:
263 raise PayloadError('payload object not initialized')
264
265 def ResetFile(self):
266 """Resets the offset of the payload file to right past the manifest."""
Sen Jiang3b15b592017-09-26 18:21:04 -0700267 self.payload_file.seek(self.payload_file_offset + self.data_offset)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800268
269 def IsDelta(self):
270 """Returns True iff the payload appears to be a delta."""
271 self._AssertInit()
Amin Hassani55c75412019-10-07 11:20:39 -0700272 return (any(partition.HasField('old_partition_info')
Sen Jiang349fd292015-11-16 17:28:09 -0800273 for partition in self.manifest.partitions))
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800274
275 def IsFull(self):
276 """Returns True iff the payload appears to be a full."""
277 return not self.IsDelta()
278
279 def Check(self, pubkey_file_name=None, metadata_sig_file=None,
Amin Hassania86b1082018-03-08 15:48:59 -0800280 metadata_size=0, report_out_file=None, assert_type=None,
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700281 block_size=0, part_sizes=None, allow_unhashed=False,
282 disabled_tests=()):
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800283 """Checks the payload integrity.
284
285 Args:
286 pubkey_file_name: public key used for signature verification
287 metadata_sig_file: metadata signature, if verification is desired
Amin Hassania86b1082018-03-08 15:48:59 -0800288 metadata_size: metadata size, if verification is desired
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800289 report_out_file: file object to dump the report to
290 assert_type: assert that payload is either 'full' or 'delta'
291 block_size: expected filesystem / payload block size
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700292 part_sizes: map of partition label to (physical) size in bytes
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800293 allow_unhashed: allow unhashed operation blobs
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700294 disabled_tests: list of tests to disable
Sen Jiang349fd292015-11-16 17:28:09 -0800295
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800296 Raises:
297 PayloadError if payload verification failed.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800298 """
299 self._AssertInit()
300
301 # Create a short-lived payload checker object and run it.
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700302 helper = checker.PayloadChecker(
303 self, assert_type=assert_type, block_size=block_size,
304 allow_unhashed=allow_unhashed, disabled_tests=disabled_tests)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800305 helper.Run(pubkey_file_name=pubkey_file_name,
306 metadata_sig_file=metadata_sig_file,
Amin Hassania86b1082018-03-08 15:48:59 -0800307 metadata_size=metadata_size,
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700308 part_sizes=part_sizes,
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700309 report_out_file=report_out_file)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800310
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700311 def Apply(self, new_parts, old_parts=None, bsdiff_in_place=True,
312 bspatch_path=None, puffpatch_path=None,
313 truncate_to_expected_size=True):
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800314 """Applies the update payload.
315
316 Args:
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700317 new_parts: map of partition name to dest partition file
318 old_parts: map of partition name to partition file (optional)
Gilad Arnold272a4992013-05-08 13:12:53 -0700319 bsdiff_in_place: whether to perform BSDIFF operations in-place (optional)
Gilad Arnold21a02502013-08-22 16:59:48 -0700320 bspatch_path: path to the bspatch binary (optional)
Amin Hassani6be71682017-12-01 10:46:45 -0800321 puffpatch_path: path to the puffpatch binary (optional)
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700322 truncate_to_expected_size: whether to truncate the resulting partitions
323 to their expected sizes, as specified in the
324 payload (optional)
Sen Jiang349fd292015-11-16 17:28:09 -0800325
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800326 Raises:
327 PayloadError if payload application failed.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800328 """
329 self._AssertInit()
330
331 # Create a short-lived payload applier object and run it.
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700332 helper = applier.PayloadApplier(
Gilad Arnold21a02502013-08-22 16:59:48 -0700333 self, bsdiff_in_place=bsdiff_in_place, bspatch_path=bspatch_path,
Amin Hassani6be71682017-12-01 10:46:45 -0800334 puffpatch_path=puffpatch_path,
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700335 truncate_to_expected_size=truncate_to_expected_size)
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700336 helper.Run(new_parts, old_parts=old_parts)