blob: c63e5d1a3791a28d9bef738f020ffda690e0076b [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
Kelvin Zhang79775642021-02-19 16:05:08 -050024import mmap
Gilad Arnold553b0ec2013-01-26 01:00:39 -080025import struct
Kelvin Zhang9e7a6db2020-08-13 14:55:58 -040026import zipfile
Gilad Arnold553b0ec2013-01-26 01:00:39 -080027
Kelvin Zhang73202a92022-06-02 10:19:54 -070028import update_metadata_pb2
29
Sen Jiangc2527f42017-09-27 16:35:03 -070030from update_payload import checker
31from update_payload import common
Amin Hassanib05a65a2017-12-18 15:15:32 -080032from update_payload.error import PayloadError
Gilad Arnold553b0ec2013-01-26 01:00:39 -080033
34
35#
36# Helper functions.
37#
38def _ReadInt(file_obj, size, is_unsigned, hasher=None):
Gilad Arnold5502b562013-03-08 13:22:31 -080039 """Reads a binary-encoded integer from a file.
Gilad Arnold553b0ec2013-01-26 01:00:39 -080040
41 It will do the correct conversion based on the reported size and whether or
42 not a signed number is expected. Assumes a network (big-endian) byte
43 ordering.
44
45 Args:
46 file_obj: a file object
47 size: the integer size in bytes (2, 4 or 8)
48 is_unsigned: whether it is signed or not
49 hasher: an optional hasher to pass the value through
Sen Jiang349fd292015-11-16 17:28:09 -080050
Gilad Arnold553b0ec2013-01-26 01:00:39 -080051 Returns:
52 An "unpacked" (Python) integer value.
Sen Jiang349fd292015-11-16 17:28:09 -080053
Gilad Arnold553b0ec2013-01-26 01:00:39 -080054 Raises:
55 PayloadError if an read error occurred.
Gilad Arnold553b0ec2013-01-26 01:00:39 -080056 """
Gilad Arnold5502b562013-03-08 13:22:31 -080057 return struct.unpack(common.IntPackingFmtStr(size, is_unsigned),
58 common.Read(file_obj, size, hasher=hasher))[0]
Gilad Arnold553b0ec2013-01-26 01:00:39 -080059
60
61#
62# Update payload.
63#
64class Payload(object):
65 """Chrome OS update payload processor."""
66
67 class _PayloadHeader(object):
68 """Update payload header struct."""
69
Alex Deymoef497352015-10-15 09:14:58 -070070 # Header constants; sizes are in bytes.
Andrew Lassalle165843c2019-11-05 13:30:34 -080071 _MAGIC = b'CrAU'
Alex Deymoef497352015-10-15 09:14:58 -070072 _VERSION_SIZE = 8
73 _MANIFEST_LEN_SIZE = 8
74 _METADATA_SIGNATURE_LEN_SIZE = 4
Gilad Arnold553b0ec2013-01-26 01:00:39 -080075
Alex Deymoef497352015-10-15 09:14:58 -070076 def __init__(self):
77 self.version = None
78 self.manifest_len = None
79 self.metadata_signature_len = None
80 self.size = None
81
82 def ReadFromPayload(self, payload_file, hasher=None):
83 """Reads the payload header from a file.
84
85 Reads the payload header from the |payload_file| and updates the |hasher|
86 if one is passed. The parsed header is stored in the _PayloadHeader
87 instance attributes.
88
89 Args:
90 payload_file: a file object
91 hasher: an optional hasher to pass the value through
Sen Jiang349fd292015-11-16 17:28:09 -080092
Alex Deymoef497352015-10-15 09:14:58 -070093 Returns:
94 None.
Sen Jiang349fd292015-11-16 17:28:09 -080095
Alex Deymoef497352015-10-15 09:14:58 -070096 Raises:
97 PayloadError if a read error occurred or the header is invalid.
98 """
99 # Verify magic
100 magic = common.Read(payload_file, len(self._MAGIC), hasher=hasher)
101 if magic != self._MAGIC:
102 raise PayloadError('invalid payload magic: %s' % magic)
103
104 self.version = _ReadInt(payload_file, self._VERSION_SIZE, True,
105 hasher=hasher)
106 self.manifest_len = _ReadInt(payload_file, self._MANIFEST_LEN_SIZE, True,
107 hasher=hasher)
108 self.size = (len(self._MAGIC) + self._VERSION_SIZE +
109 self._MANIFEST_LEN_SIZE)
110 self.metadata_signature_len = 0
111
112 if self.version == common.BRILLO_MAJOR_PAYLOAD_VERSION:
113 self.size += self._METADATA_SIGNATURE_LEN_SIZE
114 self.metadata_signature_len = _ReadInt(
115 payload_file, self._METADATA_SIGNATURE_LEN_SIZE, True,
116 hasher=hasher)
117
Sen Jiang3b15b592017-09-26 18:21:04 -0700118 def __init__(self, payload_file, payload_file_offset=0):
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800119 """Initialize the payload object.
120
121 Args:
122 payload_file: update payload file object open for reading
Sen Jiang3b15b592017-09-26 18:21:04 -0700123 payload_file_offset: the offset of the actual payload
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800124 """
Kelvin Zhang9e7a6db2020-08-13 14:55:58 -0400125 if zipfile.is_zipfile(payload_file):
Kelvin Zhang0a2493d2022-08-26 17:45:42 +0000126 self.name = payload_file
Kelvin Zhang9e7a6db2020-08-13 14:55:58 -0400127 with zipfile.ZipFile(payload_file) as zfp:
Kelvin Zhangb7162c12022-08-24 23:15:04 +0000128 if "payload.bin" not in zfp.namelist():
129 raise ValueError(f"payload.bin missing in archive {payload_file}")
Kelvin Zhang79775642021-02-19 16:05:08 -0500130 self.payload_file = zfp.open("payload.bin", "r")
Kelvin Zhang576efc52020-12-01 12:06:40 -0500131 elif isinstance(payload_file, str):
Kelvin Zhang0a2493d2022-08-26 17:45:42 +0000132 self.name = payload_file
Kelvin Zhang79775642021-02-19 16:05:08 -0500133 payload_fp = open(payload_file, "rb")
Kelvin Zhangfaddb7e2021-06-23 15:53:48 -0400134 payload_bytes = mmap.mmap(
135 payload_fp.fileno(), 0, access=mmap.ACCESS_READ)
Kelvin Zhang79775642021-02-19 16:05:08 -0500136 self.payload_file = io.BytesIO(payload_bytes)
Kelvin Zhang576efc52020-12-01 12:06:40 -0500137 else:
Kelvin Zhang0a2493d2022-08-26 17:45:42 +0000138 self.name = payload_file.name
Kelvin Zhang576efc52020-12-01 12:06:40 -0500139 self.payload_file = payload_file
Sen Jiang3b15b592017-09-26 18:21:04 -0700140 self.payload_file_offset = payload_file_offset
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800141 self.manifest_hasher = None
142 self.is_init = False
143 self.header = None
144 self.manifest = None
Alex Deymoef497352015-10-15 09:14:58 -0700145 self.data_offset = None
146 self.metadata_signature = None
Kelvin Zhangfaddb7e2021-06-23 15:53:48 -0400147 self.payload_signature = None
Alex Deymoef497352015-10-15 09:14:58 -0700148 self.metadata_size = None
Kelvin Zhangf9f99b02022-08-24 23:02:07 +0000149 self.Init()
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800150
Kelvin Zhang8c856552021-09-07 21:15:49 -0700151 @property
152 def is_incremental(self):
153 return any([part.HasField("old_partition_info") for part in self.manifest.partitions])
154
155 @property
156 def is_partial(self):
157 return self.manifest.partial_update
158
Kelvin Zhangb7162c12022-08-24 23:15:04 +0000159 @property
160 def total_data_length(self):
161 """Return the total data length of this payload, excluding payload
162 signature at the very end.
163 """
164 # Operations are sorted in ascending data_offset order, so iterating
165 # backwards and find the first one with non zero data_offset will tell
166 # us total data length
167 for partition in reversed(self.manifest.partitions):
168 for op in reversed(partition.operations):
169 if op.data_offset > 0:
170 return op.data_offset + op.data_length
171 return 0
172
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800173 def _ReadHeader(self):
174 """Reads and returns the payload header.
175
176 Returns:
177 A payload header object.
Sen Jiang349fd292015-11-16 17:28:09 -0800178
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800179 Raises:
180 PayloadError if a read error occurred.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800181 """
Alex Deymoef497352015-10-15 09:14:58 -0700182 header = self._PayloadHeader()
183 header.ReadFromPayload(self.payload_file, self.manifest_hasher)
184 return header
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800185
186 def _ReadManifest(self):
187 """Reads and returns the payload manifest.
188
189 Returns:
190 A string containing the payload manifest in binary form.
Sen Jiang349fd292015-11-16 17:28:09 -0800191
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800192 Raises:
193 PayloadError if a read error occurred.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800194 """
195 if not self.header:
196 raise PayloadError('payload header not present')
197
198 return common.Read(self.payload_file, self.header.manifest_len,
199 hasher=self.manifest_hasher)
200
Alex Deymoef497352015-10-15 09:14:58 -0700201 def _ReadMetadataSignature(self):
202 """Reads and returns the metadata signatures.
203
204 Returns:
205 A string containing the metadata signatures protobuf in binary form or
206 an empty string if no metadata signature found in the payload.
Sen Jiang349fd292015-11-16 17:28:09 -0800207
Alex Deymoef497352015-10-15 09:14:58 -0700208 Raises:
209 PayloadError if a read error occurred.
Alex Deymoef497352015-10-15 09:14:58 -0700210 """
211 if not self.header:
212 raise PayloadError('payload header not present')
213
214 return common.Read(
215 self.payload_file, self.header.metadata_signature_len,
Sen Jiang3b15b592017-09-26 18:21:04 -0700216 offset=self.payload_file_offset + self.header.size +
217 self.header.manifest_len)
Alex Deymoef497352015-10-15 09:14:58 -0700218
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800219 def ReadDataBlob(self, offset, length):
220 """Reads and returns a single data blob from the update payload.
221
222 Args:
223 offset: offset to the beginning of the blob from the end of the manifest
224 length: the blob's length
Sen Jiang349fd292015-11-16 17:28:09 -0800225
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800226 Returns:
227 A string containing the raw blob data.
Sen Jiang349fd292015-11-16 17:28:09 -0800228
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800229 Raises:
230 PayloadError if a read error occurred.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800231 """
232 return common.Read(self.payload_file, length,
Sen Jiang3b15b592017-09-26 18:21:04 -0700233 offset=self.payload_file_offset + self.data_offset +
234 offset)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800235
236 def Init(self):
237 """Initializes the payload object.
238
239 This is a prerequisite for any other public API call.
240
241 Raises:
242 PayloadError if object already initialized or fails to initialize
243 correctly.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800244 """
245 if self.is_init:
Kelvin Zhangf9f99b02022-08-24 23:02:07 +0000246 return
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800247
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800248 self.manifest_hasher = hashlib.sha256()
249
250 # Read the file header.
Sen Jiang3b15b592017-09-26 18:21:04 -0700251 self.payload_file.seek(self.payload_file_offset)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800252 self.header = self._ReadHeader()
253
254 # Read the manifest.
255 manifest_raw = self._ReadManifest()
256 self.manifest = update_metadata_pb2.DeltaArchiveManifest()
257 self.manifest.ParseFromString(manifest_raw)
258
Alex Deymoef497352015-10-15 09:14:58 -0700259 # Read the metadata signature (if any).
260 metadata_signature_raw = self._ReadMetadataSignature()
261 if metadata_signature_raw:
262 self.metadata_signature = update_metadata_pb2.Signatures()
263 self.metadata_signature.ParseFromString(metadata_signature_raw)
264
265 self.metadata_size = self.header.size + self.header.manifest_len
266 self.data_offset = self.metadata_size + self.header.metadata_signature_len
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800267
Kelvin Zhangfaddb7e2021-06-23 15:53:48 -0400268 if self.manifest.signatures_offset and self.manifest.signatures_size:
269 payload_signature_blob = self.ReadDataBlob(
270 self.manifest.signatures_offset, self.manifest.signatures_size)
271 payload_signature = update_metadata_pb2.Signatures()
272 payload_signature.ParseFromString(payload_signature_blob)
273 self.payload_signature = payload_signature
274
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800275 self.is_init = True
276
277 def _AssertInit(self):
278 """Raises an exception if the object was not initialized."""
279 if not self.is_init:
280 raise PayloadError('payload object not initialized')
281
282 def ResetFile(self):
283 """Resets the offset of the payload file to right past the manifest."""
Sen Jiang3b15b592017-09-26 18:21:04 -0700284 self.payload_file.seek(self.payload_file_offset + self.data_offset)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800285
286 def IsDelta(self):
287 """Returns True iff the payload appears to be a delta."""
288 self._AssertInit()
Amin Hassani55c75412019-10-07 11:20:39 -0700289 return (any(partition.HasField('old_partition_info')
Sen Jiang349fd292015-11-16 17:28:09 -0800290 for partition in self.manifest.partitions))
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800291
292 def IsFull(self):
293 """Returns True iff the payload appears to be a full."""
294 return not self.IsDelta()
295
296 def Check(self, pubkey_file_name=None, metadata_sig_file=None,
Amin Hassania86b1082018-03-08 15:48:59 -0800297 metadata_size=0, report_out_file=None, assert_type=None,
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700298 block_size=0, part_sizes=None, allow_unhashed=False,
299 disabled_tests=()):
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800300 """Checks the payload integrity.
301
302 Args:
303 pubkey_file_name: public key used for signature verification
304 metadata_sig_file: metadata signature, if verification is desired
Amin Hassania86b1082018-03-08 15:48:59 -0800305 metadata_size: metadata size, if verification is desired
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800306 report_out_file: file object to dump the report to
307 assert_type: assert that payload is either 'full' or 'delta'
308 block_size: expected filesystem / payload block size
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700309 part_sizes: map of partition label to (physical) size in bytes
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800310 allow_unhashed: allow unhashed operation blobs
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700311 disabled_tests: list of tests to disable
Sen Jiang349fd292015-11-16 17:28:09 -0800312
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800313 Raises:
314 PayloadError if payload verification failed.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800315 """
316 self._AssertInit()
317
318 # Create a short-lived payload checker object and run it.
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700319 helper = checker.PayloadChecker(
320 self, assert_type=assert_type, block_size=block_size,
321 allow_unhashed=allow_unhashed, disabled_tests=disabled_tests)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800322 helper.Run(pubkey_file_name=pubkey_file_name,
323 metadata_sig_file=metadata_sig_file,
Amin Hassania86b1082018-03-08 15:48:59 -0800324 metadata_size=metadata_size,
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700325 part_sizes=part_sizes,
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700326 report_out_file=report_out_file)