blob: ccd3240045073d51a7f4cd50bd8d020df210d43c [file] [log] [blame]
Gilad Arnold553b0ec2013-01-26 01:00:39 -08001# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""Tools for reading, verifying and applying Chrome OS update payloads."""
6
7import hashlib
8import struct
9
10import applier
11import block_tracer
12import checker
13import common
14from error import PayloadError
15import update_metadata_pb2
16
17
18#
19# Helper functions.
20#
21def _ReadInt(file_obj, size, is_unsigned, hasher=None):
Gilad Arnold5502b562013-03-08 13:22:31 -080022 """Reads a binary-encoded integer from a file.
Gilad Arnold553b0ec2013-01-26 01:00:39 -080023
24 It will do the correct conversion based on the reported size and whether or
25 not a signed number is expected. Assumes a network (big-endian) byte
26 ordering.
27
28 Args:
29 file_obj: a file object
30 size: the integer size in bytes (2, 4 or 8)
31 is_unsigned: whether it is signed or not
32 hasher: an optional hasher to pass the value through
33 Returns:
34 An "unpacked" (Python) integer value.
35 Raises:
36 PayloadError if an read error occurred.
37
38 """
Gilad Arnold5502b562013-03-08 13:22:31 -080039 return struct.unpack(common.IntPackingFmtStr(size, is_unsigned),
40 common.Read(file_obj, size, hasher=hasher))[0]
Gilad Arnold553b0ec2013-01-26 01:00:39 -080041
42
43#
44# Update payload.
45#
46class Payload(object):
47 """Chrome OS update payload processor."""
48
49 class _PayloadHeader(object):
50 """Update payload header struct."""
51
Alex Deymoef497352015-10-15 09:14:58 -070052 # Header constants; sizes are in bytes.
53 _MAGIC = 'CrAU'
54 _VERSION_SIZE = 8
55 _MANIFEST_LEN_SIZE = 8
56 _METADATA_SIGNATURE_LEN_SIZE = 4
Gilad Arnold553b0ec2013-01-26 01:00:39 -080057
Alex Deymoef497352015-10-15 09:14:58 -070058 def __init__(self):
59 self.version = None
60 self.manifest_len = None
61 self.metadata_signature_len = None
62 self.size = None
63
64 def ReadFromPayload(self, payload_file, hasher=None):
65 """Reads the payload header from a file.
66
67 Reads the payload header from the |payload_file| and updates the |hasher|
68 if one is passed. The parsed header is stored in the _PayloadHeader
69 instance attributes.
70
71 Args:
72 payload_file: a file object
73 hasher: an optional hasher to pass the value through
74 Returns:
75 None.
76 Raises:
77 PayloadError if a read error occurred or the header is invalid.
78 """
79 # Verify magic
80 magic = common.Read(payload_file, len(self._MAGIC), hasher=hasher)
81 if magic != self._MAGIC:
82 raise PayloadError('invalid payload magic: %s' % magic)
83
84 self.version = _ReadInt(payload_file, self._VERSION_SIZE, True,
85 hasher=hasher)
86 self.manifest_len = _ReadInt(payload_file, self._MANIFEST_LEN_SIZE, True,
87 hasher=hasher)
88 self.size = (len(self._MAGIC) + self._VERSION_SIZE +
89 self._MANIFEST_LEN_SIZE)
90 self.metadata_signature_len = 0
91
92 if self.version == common.BRILLO_MAJOR_PAYLOAD_VERSION:
93 self.size += self._METADATA_SIGNATURE_LEN_SIZE
94 self.metadata_signature_len = _ReadInt(
95 payload_file, self._METADATA_SIGNATURE_LEN_SIZE, True,
96 hasher=hasher)
97
Gilad Arnold553b0ec2013-01-26 01:00:39 -080098
99 def __init__(self, payload_file):
100 """Initialize the payload object.
101
102 Args:
103 payload_file: update payload file object open for reading
104
105 """
106 self.payload_file = payload_file
107 self.manifest_hasher = None
108 self.is_init = False
109 self.header = None
110 self.manifest = None
Alex Deymoef497352015-10-15 09:14:58 -0700111 self.data_offset = None
112 self.metadata_signature = None
113 self.metadata_size = None
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800114
115 def _ReadHeader(self):
116 """Reads and returns the payload header.
117
118 Returns:
119 A payload header object.
120 Raises:
121 PayloadError if a read error occurred.
122
123 """
Alex Deymoef497352015-10-15 09:14:58 -0700124 header = self._PayloadHeader()
125 header.ReadFromPayload(self.payload_file, self.manifest_hasher)
126 return header
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800127
128 def _ReadManifest(self):
129 """Reads and returns the payload manifest.
130
131 Returns:
132 A string containing the payload manifest in binary form.
133 Raises:
134 PayloadError if a read error occurred.
135
136 """
137 if not self.header:
138 raise PayloadError('payload header not present')
139
140 return common.Read(self.payload_file, self.header.manifest_len,
141 hasher=self.manifest_hasher)
142
Alex Deymoef497352015-10-15 09:14:58 -0700143 def _ReadMetadataSignature(self):
144 """Reads and returns the metadata signatures.
145
146 Returns:
147 A string containing the metadata signatures protobuf in binary form or
148 an empty string if no metadata signature found in the payload.
149 Raises:
150 PayloadError if a read error occurred.
151
152 """
153 if not self.header:
154 raise PayloadError('payload header not present')
155
156 return common.Read(
157 self.payload_file, self.header.metadata_signature_len,
158 offset=self.header.size + self.header.manifest_len)
159
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800160 def ReadDataBlob(self, offset, length):
161 """Reads and returns a single data blob from the update payload.
162
163 Args:
164 offset: offset to the beginning of the blob from the end of the manifest
165 length: the blob's length
166 Returns:
167 A string containing the raw blob data.
168 Raises:
169 PayloadError if a read error occurred.
170
171 """
172 return common.Read(self.payload_file, length,
173 offset=self.data_offset + offset)
174
175 def Init(self):
176 """Initializes the payload object.
177
178 This is a prerequisite for any other public API call.
179
180 Raises:
181 PayloadError if object already initialized or fails to initialize
182 correctly.
183
184 """
185 if self.is_init:
186 raise PayloadError('payload object already initialized')
187
188 # Initialize hash context.
189 # pylint: disable=E1101
190 self.manifest_hasher = hashlib.sha256()
191
192 # Read the file header.
193 self.header = self._ReadHeader()
194
195 # Read the manifest.
196 manifest_raw = self._ReadManifest()
197 self.manifest = update_metadata_pb2.DeltaArchiveManifest()
198 self.manifest.ParseFromString(manifest_raw)
199
Alex Deymoef497352015-10-15 09:14:58 -0700200 # Read the metadata signature (if any).
201 metadata_signature_raw = self._ReadMetadataSignature()
202 if metadata_signature_raw:
203 self.metadata_signature = update_metadata_pb2.Signatures()
204 self.metadata_signature.ParseFromString(metadata_signature_raw)
205
206 self.metadata_size = self.header.size + self.header.manifest_len
207 self.data_offset = self.metadata_size + self.header.metadata_signature_len
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800208
209 self.is_init = True
210
Don Garrett432d6012013-05-10 15:01:36 -0700211 def Describe(self):
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700212 """Emits the payload embedded description data to standard output."""
Don Garrett432d6012013-05-10 15:01:36 -0700213 def _DescribeImageInfo(description, image_info):
214 def _DisplayIndentedValue(name, value):
215 print ' {:<14} {}'.format(name+':', value)
216
217 print '%s:' % description
218 _DisplayIndentedValue('Channel', image_info.channel)
219 _DisplayIndentedValue('Board', image_info.board)
220 _DisplayIndentedValue('Version', image_info.version)
221 _DisplayIndentedValue('Key', image_info.key)
222
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700223 if image_info.build_channel != image_info.channel:
Don Garrett432d6012013-05-10 15:01:36 -0700224 _DisplayIndentedValue('Build channel', image_info.build_channel)
225
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700226 if image_info.build_version != image_info.version:
Don Garrett432d6012013-05-10 15:01:36 -0700227 _DisplayIndentedValue('Build version', image_info.build_version)
228
229 if self.manifest.HasField('old_image_info'):
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700230 # pylint: disable=E1101
Don Garrett432d6012013-05-10 15:01:36 -0700231 _DescribeImageInfo('Old Image', self.manifest.old_image_info)
232
233 if self.manifest.HasField('new_image_info'):
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700234 # pylint: disable=E1101
Don Garrett432d6012013-05-10 15:01:36 -0700235 _DescribeImageInfo('New Image', self.manifest.new_image_info)
236
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800237 def _AssertInit(self):
238 """Raises an exception if the object was not initialized."""
239 if not self.is_init:
240 raise PayloadError('payload object not initialized')
241
242 def ResetFile(self):
243 """Resets the offset of the payload file to right past the manifest."""
244 self.payload_file.seek(self.data_offset)
245
246 def IsDelta(self):
247 """Returns True iff the payload appears to be a delta."""
248 self._AssertInit()
249 return (self.manifest.HasField('old_kernel_info') or
250 self.manifest.HasField('old_rootfs_info'))
251
252 def IsFull(self):
253 """Returns True iff the payload appears to be a full."""
254 return not self.IsDelta()
255
256 def Check(self, pubkey_file_name=None, metadata_sig_file=None,
257 report_out_file=None, assert_type=None, block_size=0,
Gilad Arnold382df5c2013-05-03 12:49:28 -0700258 rootfs_part_size=0, kernel_part_size=0, allow_unhashed=False,
259 disabled_tests=()):
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800260 """Checks the payload integrity.
261
262 Args:
263 pubkey_file_name: public key used for signature verification
264 metadata_sig_file: metadata signature, if verification is desired
265 report_out_file: file object to dump the report to
266 assert_type: assert that payload is either 'full' or 'delta'
267 block_size: expected filesystem / payload block size
Gilad Arnold382df5c2013-05-03 12:49:28 -0700268 rootfs_part_size: the size of (physical) rootfs partitions in bytes
269 kernel_part_size: the size of (physical) kernel partitions in bytes
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800270 allow_unhashed: allow unhashed operation blobs
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700271 disabled_tests: list of tests to disable
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800272 Raises:
273 PayloadError if payload verification failed.
274
275 """
276 self._AssertInit()
277
278 # Create a short-lived payload checker object and run it.
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700279 helper = checker.PayloadChecker(
280 self, assert_type=assert_type, block_size=block_size,
281 allow_unhashed=allow_unhashed, disabled_tests=disabled_tests)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800282 helper.Run(pubkey_file_name=pubkey_file_name,
283 metadata_sig_file=metadata_sig_file,
Gilad Arnold382df5c2013-05-03 12:49:28 -0700284 rootfs_part_size=rootfs_part_size,
285 kernel_part_size=kernel_part_size,
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700286 report_out_file=report_out_file)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800287
Gilad Arnold16416602013-05-04 21:40:39 -0700288 def Apply(self, new_kernel_part, new_rootfs_part, old_kernel_part=None,
Gilad Arnold21a02502013-08-22 16:59:48 -0700289 old_rootfs_part=None, bsdiff_in_place=True, bspatch_path=None,
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700290 truncate_to_expected_size=True):
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800291 """Applies the update payload.
292
293 Args:
Gilad Arnold16416602013-05-04 21:40:39 -0700294 new_kernel_part: name of dest kernel partition file
295 new_rootfs_part: name of dest rootfs partition file
296 old_kernel_part: name of source kernel partition file (optional)
297 old_rootfs_part: name of source rootfs partition file (optional)
Gilad Arnold272a4992013-05-08 13:12:53 -0700298 bsdiff_in_place: whether to perform BSDIFF operations in-place (optional)
Gilad Arnold21a02502013-08-22 16:59:48 -0700299 bspatch_path: path to the bspatch binary (optional)
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700300 truncate_to_expected_size: whether to truncate the resulting partitions
301 to their expected sizes, as specified in the
302 payload (optional)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800303 Raises:
304 PayloadError if payload application failed.
305
306 """
307 self._AssertInit()
308
309 # Create a short-lived payload applier object and run it.
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700310 helper = applier.PayloadApplier(
Gilad Arnold21a02502013-08-22 16:59:48 -0700311 self, bsdiff_in_place=bsdiff_in_place, bspatch_path=bspatch_path,
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700312 truncate_to_expected_size=truncate_to_expected_size)
Gilad Arnold16416602013-05-04 21:40:39 -0700313 helper.Run(new_kernel_part, new_rootfs_part,
314 old_kernel_part=old_kernel_part,
315 old_rootfs_part=old_rootfs_part)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800316
317 def TraceBlock(self, block, skip, trace_out_file, is_kernel):
318 """Traces the origin(s) of a given dest partition block.
319
320 The tracing tries to find origins transitively, when possible (it currently
321 only works for move operations, where the mapping of src/dst is
322 one-to-one). It will dump a list of operations and source blocks
323 responsible for the data in the given dest block.
324
325 Args:
326 block: the block number whose origin to trace
327 skip: the number of first origin mappings to skip
328 trace_out_file: file object to dump the trace to
329 is_kernel: trace through kernel (True) or rootfs (False) operations
330
331 """
332 self._AssertInit()
333
334 # Create a short-lived payload block tracer object and run it.
335 helper = block_tracer.PayloadBlockTracer(self)
336 helper.Run(block, skip, trace_out_file, is_kernel)