blob: cb1713f0093759842c06bfd42358d27c349cdaec [file] [log] [blame]
Andrew Lassalle165843c2019-11-05 13:30:34 -08001#!/usr/bin/env python
Gilad Arnold553b0ec2013-01-26 01:00:39 -08002#
Amin Hassanif94b6432018-01-26 17:39:47 -08003# Copyright (C) 2013 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16#
Gilad Arnold553b0ec2013-01-26 01:00:39 -080017
18"""Command-line tool for checking and applying Chrome OS update payloads."""
19
Andrew Lassalle165843c2019-11-05 13:30:34 -080020from __future__ import absolute_import
Gilad Arnoldb92167f2015-07-15 16:49:00 -070021from __future__ import print_function
22
Amin Hassani52b60392017-12-19 10:53:24 -080023# pylint: disable=import-error
24import argparse
Amin Hassanie20eb912018-02-21 12:39:42 -080025import filecmp
Gilad Arnold553b0ec2013-01-26 01:00:39 -080026import os
27import sys
Amin Hassanie20eb912018-02-21 12:39:42 -080028import tempfile
29
Amin Hassani42c2f982020-10-29 12:10:05 -070030# pylint: disable=redefined-builtin
Andrew Lassalle165843c2019-11-05 13:30:34 -080031from six.moves import zip
Amin Hassanie20eb912018-02-21 12:39:42 -080032from update_payload import error
Gilad Arnold553b0ec2013-01-26 01:00:39 -080033
Andrew Lassalle165843c2019-11-05 13:30:34 -080034
Gilad Arnold553b0ec2013-01-26 01:00:39 -080035lib_dir = os.path.join(os.path.dirname(__file__), 'lib')
36if os.path.exists(lib_dir) and os.path.isdir(lib_dir):
37 sys.path.insert(1, lib_dir)
Andrew Lassalle165843c2019-11-05 13:30:34 -080038import update_payload # pylint: disable=wrong-import-position
Gilad Arnold553b0ec2013-01-26 01:00:39 -080039
40
41_TYPE_FULL = 'full'
42_TYPE_DELTA = 'delta'
43
Xiaochu Liu6cf8e672019-03-14 16:15:42 -070044def CheckApplyPayload(args):
45 """Whether to check the result after applying the payload.
46
47 Args:
48 args: Parsed command arguments (the return value of
49 ArgumentParser.parse_args).
50
51 Returns:
52 Boolean value whether to check.
53 """
54 return args.dst_part_paths is not None
55
56def ApplyPayload(args):
57 """Whether to apply the payload.
58
59 Args:
60 args: Parsed command arguments (the return value of
61 ArgumentParser.parse_args).
62
63 Returns:
64 Boolean value whether to apply the payload.
65 """
66 return CheckApplyPayload(args) or args.out_dst_part_paths is not None
Gilad Arnold553b0ec2013-01-26 01:00:39 -080067
Gilad Arnold4fbe4092013-04-17 10:00:55 -070068def ParseArguments(argv):
Gilad Arnold553b0ec2013-01-26 01:00:39 -080069 """Parse and validate command-line arguments.
70
71 Args:
Gilad Arnold4fbe4092013-04-17 10:00:55 -070072 argv: command-line arguments to parse (excluding the program name)
Gilad Arnoldb92167f2015-07-15 16:49:00 -070073
Gilad Arnold553b0ec2013-01-26 01:00:39 -080074 Returns:
Amin Hassani52b60392017-12-19 10:53:24 -080075 Returns the arguments returned by the argument parser.
Gilad Arnold553b0ec2013-01-26 01:00:39 -080076 """
Amin Hassani52b60392017-12-19 10:53:24 -080077 parser = argparse.ArgumentParser(
Xiaochu Liu6cf8e672019-03-14 16:15:42 -070078 description=('Applies a Chrome OS update PAYLOAD to src_part_paths'
79 'emitting dst_part_paths, respectively. '
80 'src_part_paths are only needed for delta payloads. '
Gilad Arnold4fbe4092013-04-17 10:00:55 -070081 'When no partitions are provided, verifies the payload '
82 'integrity.'),
83 epilog=('Note: a payload may verify correctly but fail to apply, and '
84 'vice versa; this is by design and can be thought of as static '
85 'vs dynamic correctness. A payload that both verifies and '
86 'applies correctly should be safe for use by the Chrome OS '
87 'Update Engine. Use --check to verify a payload prior to '
Amin Hassani52b60392017-12-19 10:53:24 -080088 'applying it.'),
89 formatter_class=argparse.RawDescriptionHelpFormatter
90 )
Gilad Arnold553b0ec2013-01-26 01:00:39 -080091
Amin Hassani52b60392017-12-19 10:53:24 -080092 check_args = parser.add_argument_group('Checking payload integrity')
93 check_args.add_argument('-c', '--check', action='store_true', default=False,
94 help=('force payload integrity check (e.g. before '
95 'applying)'))
Amin Hassani52b60392017-12-19 10:53:24 -080096 check_args.add_argument('-r', '--report', metavar='FILE',
97 help="dump payload report (`-' for stdout)")
98 check_args.add_argument('-t', '--type', dest='assert_type',
99 help='assert the payload type',
100 choices=[_TYPE_FULL, _TYPE_DELTA])
101 check_args.add_argument('-z', '--block-size', metavar='NUM', default=0,
102 type=int,
103 help='assert a non-default (4096) payload block size')
104 check_args.add_argument('-u', '--allow-unhashed', action='store_true',
105 default=False, help='allow unhashed operations')
106 check_args.add_argument('-d', '--disabled_tests', default=(), metavar='',
107 help=('space separated list of tests to disable. '
108 'allowed options include: ' +
109 ', '.join(update_payload.CHECKS_TO_DISABLE)),
110 choices=update_payload.CHECKS_TO_DISABLE)
111 check_args.add_argument('-k', '--key', metavar='FILE',
112 help=('override standard key used for signature '
113 'validation'))
114 check_args.add_argument('-m', '--meta-sig', metavar='FILE',
115 help='verify metadata against its signature')
Amin Hassania86b1082018-03-08 15:48:59 -0800116 check_args.add_argument('-s', '--metadata-size', metavar='NUM', default=0,
117 help='the metadata size to verify with the one in'
118 ' payload')
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700119 check_args.add_argument('--part_sizes', metavar='NUM', nargs='+', type=int,
120 help='override partition size auto-inference')
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800121
Amin Hassani52b60392017-12-19 10:53:24 -0800122 apply_args = parser.add_argument_group('Applying payload')
123 # TODO(ahassani): Extent extract-bsdiff to puffdiff too.
124 apply_args.add_argument('-x', '--extract-bsdiff', action='store_true',
125 default=False,
126 help=('use temp input/output files with BSDIFF '
127 'operations (not in-place)'))
128 apply_args.add_argument('--bspatch-path', metavar='FILE',
129 help='use the specified bspatch binary')
130 apply_args.add_argument('--puffpatch-path', metavar='FILE',
131 help='use the specified puffpatch binary')
Gilad Arnold272a4992013-05-08 13:12:53 -0700132
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700133 apply_args.add_argument('--src_part_paths', metavar='FILE', nargs='+',
134 help='source partitition files')
135 apply_args.add_argument('--dst_part_paths', metavar='FILE', nargs='+',
136 help='destination partition files')
137 apply_args.add_argument('--out_dst_part_paths', metavar='FILE', nargs='+',
138 help='created destination partition files')
139
Amin Hassani52b60392017-12-19 10:53:24 -0800140 parser.add_argument('payload', metavar='PAYLOAD', help='the payload file')
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700141 parser.add_argument('--part_names', metavar='NAME', nargs='+',
142 help='names of partitions')
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800143
Gilad Arnold4fbe4092013-04-17 10:00:55 -0700144 # Parse command-line arguments.
Amin Hassani52b60392017-12-19 10:53:24 -0800145 args = parser.parse_args(argv)
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700146
Gilad Arnold4fbe4092013-04-17 10:00:55 -0700147 # There are several options that imply --check.
Amin Hassani52b60392017-12-19 10:53:24 -0800148 args.check = (args.check or args.report or args.assert_type or
149 args.block_size or args.allow_unhashed or
150 args.disabled_tests or args.meta_sig or args.key or
Xiaochu Liu6cf8e672019-03-14 16:15:42 -0700151 args.part_sizes is not None or args.metadata_size)
Gilad Arnold4fbe4092013-04-17 10:00:55 -0700152
Xiaochu Liu6cf8e672019-03-14 16:15:42 -0700153 # Makes sure the following arguments have the same length as |part_names| if
154 # set.
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700155 for arg in ['part_sizes', 'src_part_paths', 'dst_part_paths',
156 'out_dst_part_paths']:
Xiaochu Liu6cf8e672019-03-14 16:15:42 -0700157 if getattr(args, arg) is None:
158 # Parameter is not set.
159 continue
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700160 if len(args.part_names) != len(getattr(args, arg, [])):
161 parser.error('partitions in --%s do not match --part_names' % arg)
Amin Hassani52b60392017-12-19 10:53:24 -0800162
Xiaochu Liu6cf8e672019-03-14 16:15:42 -0700163 def _IsSrcPartPathsProvided(args):
164 return args.src_part_paths is not None
165
166 # Makes sure parameters are coherent with payload type.
167 if ApplyPayload(args):
168 if _IsSrcPartPathsProvided(args):
Amin Hassani52b60392017-12-19 10:53:24 -0800169 if args.assert_type == _TYPE_FULL:
170 parser.error('%s payload does not accept source partition arguments'
171 % _TYPE_FULL)
172 else:
173 args.assert_type = _TYPE_DELTA
174 else:
175 if args.assert_type == _TYPE_DELTA:
176 parser.error('%s payload requires source partitions arguments'
177 % _TYPE_DELTA)
178 else:
179 args.assert_type = _TYPE_FULL
180 else:
Amin Hassania5489022018-01-26 11:23:26 -0800181 # Not applying payload.
Amin Hassani52b60392017-12-19 10:53:24 -0800182 if args.extract_bsdiff:
Gilad Arnold272a4992013-05-08 13:12:53 -0700183 parser.error('--extract-bsdiff can only be used when applying payloads')
Amin Hassani52b60392017-12-19 10:53:24 -0800184 if args.bspatch_path:
Gilad Arnold21a02502013-08-22 16:59:48 -0700185 parser.error('--bspatch-path can only be used when applying payloads')
Amin Hassani52b60392017-12-19 10:53:24 -0800186 if args.puffpatch_path:
Amin Hassani6be71682017-12-01 10:46:45 -0800187 parser.error('--puffpatch-path can only be used when applying payloads')
Gilad Arnold4fbe4092013-04-17 10:00:55 -0700188
Don Garrett30027fd2013-05-01 16:56:16 -0700189 # By default, look for a metadata-signature file with a name based on the name
Gilad Arnold9b90c932013-05-22 17:12:56 -0700190 # of the payload we are checking. We only do it if check was triggered.
Amin Hassani52b60392017-12-19 10:53:24 -0800191 if args.check and not args.meta_sig:
192 default_meta_sig = args.payload + '.metadata-signature'
Don Garrett30027fd2013-05-01 16:56:16 -0700193 if os.path.isfile(default_meta_sig):
Amin Hassani52b60392017-12-19 10:53:24 -0800194 args.meta_sig = default_meta_sig
195 print('Using default metadata signature', args.meta_sig, file=sys.stderr)
Don Garrett30027fd2013-05-01 16:56:16 -0700196
Amin Hassani52b60392017-12-19 10:53:24 -0800197 return args
Gilad Arnold4fbe4092013-04-17 10:00:55 -0700198
199
200def main(argv):
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800201 # Parse and validate arguments.
Amin Hassani52b60392017-12-19 10:53:24 -0800202 args = ParseArguments(argv[1:])
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800203
Andrew1f6bcab2019-11-21 11:34:22 -0800204 with open(args.payload, 'rb') as payload_file:
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800205 payload = update_payload.Payload(payload_file)
206 try:
207 # Initialize payload.
208 payload.Init()
209
210 # Perform payload integrity checks.
Amin Hassani52b60392017-12-19 10:53:24 -0800211 if args.check:
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800212 report_file = None
213 do_close_report_file = False
Gilad Arnold7a7edfd2013-05-22 17:21:58 -0700214 metadata_sig_file = None
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800215 try:
Amin Hassani52b60392017-12-19 10:53:24 -0800216 if args.report:
217 if args.report == '-':
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800218 report_file = sys.stdout
219 else:
Amin Hassani52b60392017-12-19 10:53:24 -0800220 report_file = open(args.report, 'w')
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800221 do_close_report_file = True
Gilad Arnold03959b72013-05-07 17:08:18 -0700222
Xiaochu Liu6cf8e672019-03-14 16:15:42 -0700223 part_sizes = (args.part_sizes and
224 dict(zip(args.part_names, args.part_sizes)))
Andrew1f6bcab2019-11-21 11:34:22 -0800225 metadata_sig_file = args.meta_sig and open(args.meta_sig, 'rb')
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800226 payload.Check(
Amin Hassani52b60392017-12-19 10:53:24 -0800227 pubkey_file_name=args.key,
Gilad Arnold4f8c17c2013-05-04 22:57:45 -0700228 metadata_sig_file=metadata_sig_file,
Amin Hassania86b1082018-03-08 15:48:59 -0800229 metadata_size=int(args.metadata_size),
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800230 report_out_file=report_file,
Amin Hassani52b60392017-12-19 10:53:24 -0800231 assert_type=args.assert_type,
232 block_size=int(args.block_size),
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700233 part_sizes=part_sizes,
Amin Hassani52b60392017-12-19 10:53:24 -0800234 allow_unhashed=args.allow_unhashed,
235 disabled_tests=args.disabled_tests)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800236 finally:
Gilad Arnold7a7edfd2013-05-22 17:21:58 -0700237 if metadata_sig_file:
238 metadata_sig_file.close()
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800239 if do_close_report_file:
240 report_file.close()
241
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800242 # Apply payload.
Xiaochu Liu6cf8e672019-03-14 16:15:42 -0700243 if ApplyPayload(args):
Amin Hassani52b60392017-12-19 10:53:24 -0800244 dargs = {'bsdiff_in_place': not args.extract_bsdiff}
245 if args.bspatch_path:
246 dargs['bspatch_path'] = args.bspatch_path
247 if args.puffpatch_path:
248 dargs['puffpatch_path'] = args.puffpatch_path
249 if args.assert_type == _TYPE_DELTA:
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700250 dargs['old_parts'] = dict(zip(args.part_names, args.src_part_paths))
Gilad Arnold272a4992013-05-08 13:12:53 -0700251
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700252 out_dst_parts = {}
253 file_handles = []
Xiaochu Liu6cf8e672019-03-14 16:15:42 -0700254 if args.out_dst_part_paths is not None:
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700255 for name, path in zip(args.part_names, args.out_dst_part_paths):
Andrew1f6bcab2019-11-21 11:34:22 -0800256 handle = open(path, 'wb+')
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700257 file_handles.append(handle)
258 out_dst_parts[name] = handle.name
Amin Hassanie20eb912018-02-21 12:39:42 -0800259 else:
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700260 for name in args.part_names:
261 handle = tempfile.NamedTemporaryFile()
262 file_handles.append(handle)
263 out_dst_parts[name] = handle.name
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800264
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700265 payload.Apply(out_dst_parts, **dargs)
Amin Hassanie20eb912018-02-21 12:39:42 -0800266
267 # If destination kernel and rootfs partitions are not given, then this
268 # just becomes an apply operation with no check.
Xiaochu Liu6cf8e672019-03-14 16:15:42 -0700269 if CheckApplyPayload(args):
Amin Hassanie20eb912018-02-21 12:39:42 -0800270 # Prior to comparing, add the unused space past the filesystem
271 # boundary in the new target partitions to become the same size as
272 # the given partitions. This will truncate to larger size.
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700273 for part_name, out_dst_part, dst_part in zip(args.part_names,
274 file_handles,
275 args.dst_part_paths):
276 out_dst_part.truncate(os.path.getsize(dst_part))
Amin Hassanie20eb912018-02-21 12:39:42 -0800277
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700278 # Compare resulting partitions with the ones from the target image.
279 if not filecmp.cmp(out_dst_part.name, dst_part):
280 raise error.PayloadError(
281 'Resulting %s partition corrupted.' % part_name)
Amin Hassanie20eb912018-02-21 12:39:42 -0800282
283 # Close the output files. If args.out_dst_* was not given, then these
284 # files are created as temp files and will be deleted upon close().
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700285 for handle in file_handles:
286 handle.close()
Andrew Lassalle165843c2019-11-05 13:30:34 -0800287 except error.PayloadError as e:
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800288 sys.stderr.write('Error: %s\n' % e)
289 return 1
290
291 return 0
292
293
294if __name__ == '__main__':
295 sys.exit(main(sys.argv))