blob: b513f72d5758db14b0bc179b27c796c1eb3cfb55 [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
Kelvin Zhangb8d776c2022-09-07 03:12:49 +000021import binascii
Sen Jiang349fd292015-11-16 17:28:09 -080022
Gilad Arnold553b0ec2013-01-26 01:00:39 -080023import hashlib
Kelvin Zhang9e7a6db2020-08-13 14:55:58 -040024import io
Kelvin Zhang79775642021-02-19 16:05:08 -050025import mmap
Gilad Arnold553b0ec2013-01-26 01:00:39 -080026import struct
Kelvin Zhang9e7a6db2020-08-13 14:55:58 -040027import zipfile
Gilad Arnold553b0ec2013-01-26 01:00:39 -080028
Kelvin Zhang73202a92022-06-02 10:19:54 -070029import update_metadata_pb2
30
Sen Jiangc2527f42017-09-27 16:35:03 -070031from update_payload import checker
32from update_payload import common
Amin Hassanib05a65a2017-12-18 15:15:32 -080033from update_payload.error import PayloadError
Gilad Arnold553b0ec2013-01-26 01:00:39 -080034
35
36#
37# Helper functions.
38#
39def _ReadInt(file_obj, size, is_unsigned, hasher=None):
Gilad Arnold5502b562013-03-08 13:22:31 -080040 """Reads a binary-encoded integer from a file.
Gilad Arnold553b0ec2013-01-26 01:00:39 -080041
42 It will do the correct conversion based on the reported size and whether or
43 not a signed number is expected. Assumes a network (big-endian) byte
44 ordering.
45
46 Args:
47 file_obj: a file object
48 size: the integer size in bytes (2, 4 or 8)
49 is_unsigned: whether it is signed or not
50 hasher: an optional hasher to pass the value through
Sen Jiang349fd292015-11-16 17:28:09 -080051
Gilad Arnold553b0ec2013-01-26 01:00:39 -080052 Returns:
53 An "unpacked" (Python) integer value.
Sen Jiang349fd292015-11-16 17:28:09 -080054
Gilad Arnold553b0ec2013-01-26 01:00:39 -080055 Raises:
56 PayloadError if an read error occurred.
Gilad Arnold553b0ec2013-01-26 01:00:39 -080057 """
Gilad Arnold5502b562013-03-08 13:22:31 -080058 return struct.unpack(common.IntPackingFmtStr(size, is_unsigned),
59 common.Read(file_obj, size, hasher=hasher))[0]
Gilad Arnold553b0ec2013-01-26 01:00:39 -080060
61
62#
63# Update payload.
64#
65class Payload(object):
66 """Chrome OS update payload processor."""
67
68 class _PayloadHeader(object):
69 """Update payload header struct."""
70
Alex Deymoef497352015-10-15 09:14:58 -070071 # Header constants; sizes are in bytes.
Andrew Lassalle165843c2019-11-05 13:30:34 -080072 _MAGIC = b'CrAU'
Alex Deymoef497352015-10-15 09:14:58 -070073 _VERSION_SIZE = 8
74 _MANIFEST_LEN_SIZE = 8
75 _METADATA_SIGNATURE_LEN_SIZE = 4
Gilad Arnold553b0ec2013-01-26 01:00:39 -080076
Alex Deymoef497352015-10-15 09:14:58 -070077 def __init__(self):
78 self.version = None
79 self.manifest_len = None
80 self.metadata_signature_len = None
81 self.size = None
82
83 def ReadFromPayload(self, payload_file, hasher=None):
84 """Reads the payload header from a file.
85
86 Reads the payload header from the |payload_file| and updates the |hasher|
87 if one is passed. The parsed header is stored in the _PayloadHeader
88 instance attributes.
89
90 Args:
91 payload_file: a file object
92 hasher: an optional hasher to pass the value through
Sen Jiang349fd292015-11-16 17:28:09 -080093
Alex Deymoef497352015-10-15 09:14:58 -070094 Returns:
95 None.
Sen Jiang349fd292015-11-16 17:28:09 -080096
Alex Deymoef497352015-10-15 09:14:58 -070097 Raises:
98 PayloadError if a read error occurred or the header is invalid.
99 """
100 # Verify magic
101 magic = common.Read(payload_file, len(self._MAGIC), hasher=hasher)
102 if magic != self._MAGIC:
103 raise PayloadError('invalid payload magic: %s' % magic)
104
105 self.version = _ReadInt(payload_file, self._VERSION_SIZE, True,
106 hasher=hasher)
107 self.manifest_len = _ReadInt(payload_file, self._MANIFEST_LEN_SIZE, True,
108 hasher=hasher)
109 self.size = (len(self._MAGIC) + self._VERSION_SIZE +
110 self._MANIFEST_LEN_SIZE)
111 self.metadata_signature_len = 0
112
113 if self.version == common.BRILLO_MAJOR_PAYLOAD_VERSION:
114 self.size += self._METADATA_SIGNATURE_LEN_SIZE
115 self.metadata_signature_len = _ReadInt(
116 payload_file, self._METADATA_SIGNATURE_LEN_SIZE, True,
117 hasher=hasher)
118
Sen Jiang3b15b592017-09-26 18:21:04 -0700119 def __init__(self, payload_file, payload_file_offset=0):
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800120 """Initialize the payload object.
121
122 Args:
123 payload_file: update payload file object open for reading
Sen Jiang3b15b592017-09-26 18:21:04 -0700124 payload_file_offset: the offset of the actual payload
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800125 """
Kelvin Zhang9e7a6db2020-08-13 14:55:58 -0400126 if zipfile.is_zipfile(payload_file):
Kelvin Zhang0a2493d2022-08-26 17:45:42 +0000127 self.name = payload_file
Kelvin Zhang9e7a6db2020-08-13 14:55:58 -0400128 with zipfile.ZipFile(payload_file) as zfp:
Kelvin Zhangb7162c12022-08-24 23:15:04 +0000129 if "payload.bin" not in zfp.namelist():
130 raise ValueError(f"payload.bin missing in archive {payload_file}")
Kelvin Zhang79775642021-02-19 16:05:08 -0500131 self.payload_file = zfp.open("payload.bin", "r")
Kelvin Zhang576efc52020-12-01 12:06:40 -0500132 elif isinstance(payload_file, str):
Kelvin Zhang0a2493d2022-08-26 17:45:42 +0000133 self.name = payload_file
Kelvin Zhang79775642021-02-19 16:05:08 -0500134 payload_fp = open(payload_file, "rb")
Kelvin Zhangfaddb7e2021-06-23 15:53:48 -0400135 payload_bytes = mmap.mmap(
136 payload_fp.fileno(), 0, access=mmap.ACCESS_READ)
Kelvin Zhang79775642021-02-19 16:05:08 -0500137 self.payload_file = io.BytesIO(payload_bytes)
Kelvin Zhang576efc52020-12-01 12:06:40 -0500138 else:
Kelvin Zhang0a2493d2022-08-26 17:45:42 +0000139 self.name = payload_file.name
Kelvin Zhang576efc52020-12-01 12:06:40 -0500140 self.payload_file = payload_file
Sen Jiang3b15b592017-09-26 18:21:04 -0700141 self.payload_file_offset = payload_file_offset
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800142 self.manifest_hasher = None
143 self.is_init = False
144 self.header = None
145 self.manifest = None
Alex Deymoef497352015-10-15 09:14:58 -0700146 self.data_offset = None
147 self.metadata_signature = None
Kelvin Zhangfaddb7e2021-06-23 15:53:48 -0400148 self.payload_signature = None
Alex Deymoef497352015-10-15 09:14:58 -0700149 self.metadata_size = None
Kelvin Zhangf9f99b02022-08-24 23:02:07 +0000150 self.Init()
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800151
Kelvin Zhang8c856552021-09-07 21:15:49 -0700152 @property
153 def is_incremental(self):
154 return any([part.HasField("old_partition_info") for part in self.manifest.partitions])
155
156 @property
157 def is_partial(self):
158 return self.manifest.partial_update
159
Kelvin Zhangb7162c12022-08-24 23:15:04 +0000160 @property
161 def total_data_length(self):
162 """Return the total data length of this payload, excluding payload
163 signature at the very end.
164 """
165 # Operations are sorted in ascending data_offset order, so iterating
166 # backwards and find the first one with non zero data_offset will tell
167 # us total data length
168 for partition in reversed(self.manifest.partitions):
169 for op in reversed(partition.operations):
Kelvin Zhang4decfcd2022-09-07 03:21:25 +0000170 if op.data_length > 0:
Kelvin Zhangb7162c12022-08-24 23:15:04 +0000171 return op.data_offset + op.data_length
172 return 0
173
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800174 def _ReadHeader(self):
175 """Reads and returns the payload header.
176
177 Returns:
178 A payload header object.
Sen Jiang349fd292015-11-16 17:28:09 -0800179
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800180 Raises:
181 PayloadError if a read error occurred.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800182 """
Alex Deymoef497352015-10-15 09:14:58 -0700183 header = self._PayloadHeader()
184 header.ReadFromPayload(self.payload_file, self.manifest_hasher)
185 return header
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800186
187 def _ReadManifest(self):
188 """Reads and returns the payload manifest.
189
190 Returns:
191 A string containing the payload manifest in binary form.
Sen Jiang349fd292015-11-16 17:28:09 -0800192
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800193 Raises:
194 PayloadError if a read error occurred.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800195 """
196 if not self.header:
197 raise PayloadError('payload header not present')
198
199 return common.Read(self.payload_file, self.header.manifest_len,
200 hasher=self.manifest_hasher)
201
Alex Deymoef497352015-10-15 09:14:58 -0700202 def _ReadMetadataSignature(self):
203 """Reads and returns the metadata signatures.
204
205 Returns:
206 A string containing the metadata signatures protobuf in binary form or
207 an empty string if no metadata signature found in the payload.
Sen Jiang349fd292015-11-16 17:28:09 -0800208
Alex Deymoef497352015-10-15 09:14:58 -0700209 Raises:
210 PayloadError if a read error occurred.
Alex Deymoef497352015-10-15 09:14:58 -0700211 """
212 if not self.header:
213 raise PayloadError('payload header not present')
214
215 return common.Read(
216 self.payload_file, self.header.metadata_signature_len,
Sen Jiang3b15b592017-09-26 18:21:04 -0700217 offset=self.payload_file_offset + self.header.size +
218 self.header.manifest_len)
Alex Deymoef497352015-10-15 09:14:58 -0700219
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800220 def ReadDataBlob(self, offset, length):
221 """Reads and returns a single data blob from the update payload.
222
223 Args:
224 offset: offset to the beginning of the blob from the end of the manifest
225 length: the blob's length
Sen Jiang349fd292015-11-16 17:28:09 -0800226
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800227 Returns:
228 A string containing the raw blob data.
Sen Jiang349fd292015-11-16 17:28:09 -0800229
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800230 Raises:
231 PayloadError if a read error occurred.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800232 """
233 return common.Read(self.payload_file, length,
Sen Jiang3b15b592017-09-26 18:21:04 -0700234 offset=self.payload_file_offset + self.data_offset +
235 offset)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800236
237 def Init(self):
238 """Initializes the payload object.
239
240 This is a prerequisite for any other public API call.
241
242 Raises:
243 PayloadError if object already initialized or fails to initialize
244 correctly.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800245 """
246 if self.is_init:
Kelvin Zhangf9f99b02022-08-24 23:02:07 +0000247 return
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800248
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800249 self.manifest_hasher = hashlib.sha256()
250
251 # Read the file header.
Sen Jiang3b15b592017-09-26 18:21:04 -0700252 self.payload_file.seek(self.payload_file_offset)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800253 self.header = self._ReadHeader()
254
255 # Read the manifest.
256 manifest_raw = self._ReadManifest()
257 self.manifest = update_metadata_pb2.DeltaArchiveManifest()
258 self.manifest.ParseFromString(manifest_raw)
259
Alex Deymoef497352015-10-15 09:14:58 -0700260 # Read the metadata signature (if any).
261 metadata_signature_raw = self._ReadMetadataSignature()
262 if metadata_signature_raw:
263 self.metadata_signature = update_metadata_pb2.Signatures()
264 self.metadata_signature.ParseFromString(metadata_signature_raw)
265
266 self.metadata_size = self.header.size + self.header.manifest_len
267 self.data_offset = self.metadata_size + self.header.metadata_signature_len
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800268
Kelvin Zhangfaddb7e2021-06-23 15:53:48 -0400269 if self.manifest.signatures_offset and self.manifest.signatures_size:
270 payload_signature_blob = self.ReadDataBlob(
271 self.manifest.signatures_offset, self.manifest.signatures_size)
272 payload_signature = update_metadata_pb2.Signatures()
273 payload_signature.ParseFromString(payload_signature_blob)
274 self.payload_signature = payload_signature
275
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800276 self.is_init = True
277
278 def _AssertInit(self):
279 """Raises an exception if the object was not initialized."""
280 if not self.is_init:
281 raise PayloadError('payload object not initialized')
282
283 def ResetFile(self):
284 """Resets the offset of the payload file to right past the manifest."""
Sen Jiang3b15b592017-09-26 18:21:04 -0700285 self.payload_file.seek(self.payload_file_offset + self.data_offset)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800286
287 def IsDelta(self):
288 """Returns True iff the payload appears to be a delta."""
289 self._AssertInit()
Amin Hassani55c75412019-10-07 11:20:39 -0700290 return (any(partition.HasField('old_partition_info')
Sen Jiang349fd292015-11-16 17:28:09 -0800291 for partition in self.manifest.partitions))
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800292
293 def IsFull(self):
294 """Returns True iff the payload appears to be a full."""
295 return not self.IsDelta()
296
297 def Check(self, pubkey_file_name=None, metadata_sig_file=None,
Amin Hassania86b1082018-03-08 15:48:59 -0800298 metadata_size=0, report_out_file=None, assert_type=None,
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700299 block_size=0, part_sizes=None, allow_unhashed=False,
300 disabled_tests=()):
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800301 """Checks the payload integrity.
302
303 Args:
304 pubkey_file_name: public key used for signature verification
305 metadata_sig_file: metadata signature, if verification is desired
Amin Hassania86b1082018-03-08 15:48:59 -0800306 metadata_size: metadata size, if verification is desired
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800307 report_out_file: file object to dump the report to
308 assert_type: assert that payload is either 'full' or 'delta'
309 block_size: expected filesystem / payload block size
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700310 part_sizes: map of partition label to (physical) size in bytes
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800311 allow_unhashed: allow unhashed operation blobs
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700312 disabled_tests: list of tests to disable
Sen Jiang349fd292015-11-16 17:28:09 -0800313
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800314 Raises:
315 PayloadError if payload verification failed.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800316 """
317 self._AssertInit()
318
319 # Create a short-lived payload checker object and run it.
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700320 helper = checker.PayloadChecker(
321 self, assert_type=assert_type, block_size=block_size,
322 allow_unhashed=allow_unhashed, disabled_tests=disabled_tests)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800323 helper.Run(pubkey_file_name=pubkey_file_name,
324 metadata_sig_file=metadata_sig_file,
Amin Hassania86b1082018-03-08 15:48:59 -0800325 metadata_size=metadata_size,
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700326 part_sizes=part_sizes,
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700327 report_out_file=report_out_file)
Kelvin Zhangb8d776c2022-09-07 03:12:49 +0000328
329 def CheckDataHash(self):
330 for part in self.manifest.partitions:
331 for op in part.operations:
332 if op.data_length == 0:
333 continue
334 if not op.data_sha256_hash:
335 raise PayloadError(
336 f"Operation {op} in partition {part.partition_name} missing data_sha256_hash")
337 blob = self.ReadDataBlob(op.data_offset, op.data_length)
338 blob_hash = hashlib.sha256(blob)
339 if blob_hash.digest() != op.data_sha256_hash:
340 raise PayloadError(
341 f"Operation {op} in partition {part.partition_name} has unexpected hash, expected: {binascii.hexlify(op.data_sha256_hash)}, actual: {blob_hash.hexdigest()}")