blob: 52d2b4b9a63a25aaebb9c486c5fc6f44a6121cb7 [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 Jiang5a652862017-09-27 16:35:03 -070024from update_payload import applier
Sen Jiang5a652862017-09-27 16:35:03 -070025from update_payload import checker
26from update_payload import common
Sen Jiang5a652862017-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
115 def __init__(self, payload_file):
116 """Initialize the payload object.
117
118 Args:
119 payload_file: update payload file object open for reading
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800120 """
121 self.payload_file = payload_file
122 self.manifest_hasher = None
123 self.is_init = False
124 self.header = None
125 self.manifest = None
Alex Deymoef497352015-10-15 09:14:58 -0700126 self.data_offset = None
127 self.metadata_signature = None
128 self.metadata_size = None
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800129
130 def _ReadHeader(self):
131 """Reads and returns the payload header.
132
133 Returns:
134 A payload header object.
Sen Jiang349fd292015-11-16 17:28:09 -0800135
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800136 Raises:
137 PayloadError if a read error occurred.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800138 """
Alex Deymoef497352015-10-15 09:14:58 -0700139 header = self._PayloadHeader()
140 header.ReadFromPayload(self.payload_file, self.manifest_hasher)
141 return header
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800142
143 def _ReadManifest(self):
144 """Reads and returns the payload manifest.
145
146 Returns:
147 A string containing the payload manifest in binary form.
Sen Jiang349fd292015-11-16 17:28:09 -0800148
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800149 Raises:
150 PayloadError if a read error occurred.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800151 """
152 if not self.header:
153 raise PayloadError('payload header not present')
154
155 return common.Read(self.payload_file, self.header.manifest_len,
156 hasher=self.manifest_hasher)
157
Alex Deymoef497352015-10-15 09:14:58 -0700158 def _ReadMetadataSignature(self):
159 """Reads and returns the metadata signatures.
160
161 Returns:
162 A string containing the metadata signatures protobuf in binary form or
163 an empty string if no metadata signature found in the payload.
Sen Jiang349fd292015-11-16 17:28:09 -0800164
Alex Deymoef497352015-10-15 09:14:58 -0700165 Raises:
166 PayloadError if a read error occurred.
Alex Deymoef497352015-10-15 09:14:58 -0700167 """
168 if not self.header:
169 raise PayloadError('payload header not present')
170
171 return common.Read(
172 self.payload_file, self.header.metadata_signature_len,
173 offset=self.header.size + self.header.manifest_len)
174
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800175 def ReadDataBlob(self, offset, length):
176 """Reads and returns a single data blob from the update payload.
177
178 Args:
179 offset: offset to the beginning of the blob from the end of the manifest
180 length: the blob's length
Sen Jiang349fd292015-11-16 17:28:09 -0800181
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800182 Returns:
183 A string containing the raw blob data.
Sen Jiang349fd292015-11-16 17:28:09 -0800184
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800185 Raises:
186 PayloadError if a read error occurred.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800187 """
188 return common.Read(self.payload_file, length,
189 offset=self.data_offset + offset)
190
191 def Init(self):
192 """Initializes the payload object.
193
194 This is a prerequisite for any other public API call.
195
196 Raises:
197 PayloadError if object already initialized or fails to initialize
198 correctly.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800199 """
200 if self.is_init:
201 raise PayloadError('payload object already initialized')
202
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800203 self.manifest_hasher = hashlib.sha256()
204
205 # Read the file header.
206 self.header = self._ReadHeader()
207
208 # Read the manifest.
209 manifest_raw = self._ReadManifest()
210 self.manifest = update_metadata_pb2.DeltaArchiveManifest()
211 self.manifest.ParseFromString(manifest_raw)
212
Alex Deymoef497352015-10-15 09:14:58 -0700213 # Read the metadata signature (if any).
214 metadata_signature_raw = self._ReadMetadataSignature()
215 if metadata_signature_raw:
216 self.metadata_signature = update_metadata_pb2.Signatures()
217 self.metadata_signature.ParseFromString(metadata_signature_raw)
218
219 self.metadata_size = self.header.size + self.header.manifest_len
220 self.data_offset = self.metadata_size + self.header.metadata_signature_len
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800221
222 self.is_init = True
223
Don Garrett432d6012013-05-10 15:01:36 -0700224 def Describe(self):
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700225 """Emits the payload embedded description data to standard output."""
Don Garrett432d6012013-05-10 15:01:36 -0700226 def _DescribeImageInfo(description, image_info):
Sen Jiang5a652862017-09-27 16:35:03 -0700227 """Display info about the image."""
Don Garrett432d6012013-05-10 15:01:36 -0700228 def _DisplayIndentedValue(name, value):
Sen Jiang349fd292015-11-16 17:28:09 -0800229 print(' {:<14} {}'.format(name+':', value))
Don Garrett432d6012013-05-10 15:01:36 -0700230
Sen Jiang349fd292015-11-16 17:28:09 -0800231 print('%s:' % description)
Don Garrett432d6012013-05-10 15:01:36 -0700232 _DisplayIndentedValue('Channel', image_info.channel)
233 _DisplayIndentedValue('Board', image_info.board)
234 _DisplayIndentedValue('Version', image_info.version)
235 _DisplayIndentedValue('Key', image_info.key)
236
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700237 if image_info.build_channel != image_info.channel:
Don Garrett432d6012013-05-10 15:01:36 -0700238 _DisplayIndentedValue('Build channel', image_info.build_channel)
239
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700240 if image_info.build_version != image_info.version:
Don Garrett432d6012013-05-10 15:01:36 -0700241 _DisplayIndentedValue('Build version', image_info.build_version)
242
243 if self.manifest.HasField('old_image_info'):
244 _DescribeImageInfo('Old Image', self.manifest.old_image_info)
245
246 if self.manifest.HasField('new_image_info'):
247 _DescribeImageInfo('New Image', self.manifest.new_image_info)
248
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800249 def _AssertInit(self):
250 """Raises an exception if the object was not initialized."""
251 if not self.is_init:
252 raise PayloadError('payload object not initialized')
253
254 def ResetFile(self):
255 """Resets the offset of the payload file to right past the manifest."""
256 self.payload_file.seek(self.data_offset)
257
258 def IsDelta(self):
259 """Returns True iff the payload appears to be a delta."""
260 self._AssertInit()
261 return (self.manifest.HasField('old_kernel_info') or
Sen Jiang349fd292015-11-16 17:28:09 -0800262 self.manifest.HasField('old_rootfs_info') or
263 any(partition.HasField('old_partition_info')
264 for partition in self.manifest.partitions))
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800265
266 def IsFull(self):
267 """Returns True iff the payload appears to be a full."""
268 return not self.IsDelta()
269
270 def Check(self, pubkey_file_name=None, metadata_sig_file=None,
271 report_out_file=None, assert_type=None, block_size=0,
Gilad Arnold382df5c2013-05-03 12:49:28 -0700272 rootfs_part_size=0, kernel_part_size=0, allow_unhashed=False,
273 disabled_tests=()):
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800274 """Checks the payload integrity.
275
276 Args:
277 pubkey_file_name: public key used for signature verification
278 metadata_sig_file: metadata signature, if verification is desired
279 report_out_file: file object to dump the report to
280 assert_type: assert that payload is either 'full' or 'delta'
281 block_size: expected filesystem / payload block size
Gilad Arnold382df5c2013-05-03 12:49:28 -0700282 rootfs_part_size: the size of (physical) rootfs partitions in bytes
283 kernel_part_size: the size of (physical) kernel partitions in bytes
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800284 allow_unhashed: allow unhashed operation blobs
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700285 disabled_tests: list of tests to disable
Sen Jiang349fd292015-11-16 17:28:09 -0800286
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800287 Raises:
288 PayloadError if payload verification failed.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800289 """
290 self._AssertInit()
291
292 # Create a short-lived payload checker object and run it.
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700293 helper = checker.PayloadChecker(
294 self, assert_type=assert_type, block_size=block_size,
295 allow_unhashed=allow_unhashed, disabled_tests=disabled_tests)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800296 helper.Run(pubkey_file_name=pubkey_file_name,
297 metadata_sig_file=metadata_sig_file,
Gilad Arnold382df5c2013-05-03 12:49:28 -0700298 rootfs_part_size=rootfs_part_size,
299 kernel_part_size=kernel_part_size,
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700300 report_out_file=report_out_file)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800301
Gilad Arnold16416602013-05-04 21:40:39 -0700302 def Apply(self, new_kernel_part, new_rootfs_part, old_kernel_part=None,
Gilad Arnold21a02502013-08-22 16:59:48 -0700303 old_rootfs_part=None, bsdiff_in_place=True, bspatch_path=None,
Amin Hassani6be71682017-12-01 10:46:45 -0800304 puffpatch_path=None, truncate_to_expected_size=True):
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800305 """Applies the update payload.
306
307 Args:
Gilad Arnold16416602013-05-04 21:40:39 -0700308 new_kernel_part: name of dest kernel partition file
309 new_rootfs_part: name of dest rootfs partition file
310 old_kernel_part: name of source kernel partition file (optional)
311 old_rootfs_part: name of source rootfs partition file (optional)
Gilad Arnold272a4992013-05-08 13:12:53 -0700312 bsdiff_in_place: whether to perform BSDIFF operations in-place (optional)
Gilad Arnold21a02502013-08-22 16:59:48 -0700313 bspatch_path: path to the bspatch binary (optional)
Amin Hassani6be71682017-12-01 10:46:45 -0800314 puffpatch_path: path to the puffpatch binary (optional)
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700315 truncate_to_expected_size: whether to truncate the resulting partitions
316 to their expected sizes, as specified in the
317 payload (optional)
Sen Jiang349fd292015-11-16 17:28:09 -0800318
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800319 Raises:
320 PayloadError if payload application failed.
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800321 """
322 self._AssertInit()
323
324 # Create a short-lived payload applier object and run it.
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700325 helper = applier.PayloadApplier(
Gilad Arnold21a02502013-08-22 16:59:48 -0700326 self, bsdiff_in_place=bsdiff_in_place, bspatch_path=bspatch_path,
Amin Hassani6be71682017-12-01 10:46:45 -0800327 puffpatch_path=puffpatch_path,
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700328 truncate_to_expected_size=truncate_to_expected_size)
Gilad Arnold16416602013-05-04 21:40:39 -0700329 helper.Run(new_kernel_part, new_rootfs_part,
330 old_kernel_part=old_kernel_part,
331 old_rootfs_part=old_rootfs_part)