• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python
2#
3# Copyright (C) 2019 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
17import logging
18import os.path
19import re
20import shlex
21import shutil
22import zipfile
23
24import apex_manifest
25import common
26from common import UnzipTemp, RunAndCheckOutput, MakeTempFile, OPTIONS
27
28import ota_metadata_pb2
29
30
31logger = logging.getLogger(__name__)
32
33OPTIONS = common.OPTIONS
34
35APEX_PAYLOAD_IMAGE = 'apex_payload.img'
36
37APEX_PUBKEY = 'apex_pubkey'
38
39
40class ApexInfoError(Exception):
41  """An Exception raised during Apex Information command."""
42
43  def __init__(self, message):
44    Exception.__init__(self, message)
45
46
47class ApexSigningError(Exception):
48  """An Exception raised during Apex Payload signing."""
49
50  def __init__(self, message):
51    Exception.__init__(self, message)
52
53
54class ApexApkSigner(object):
55  """Class to sign the apk files and other files in an apex payload image and repack the apex"""
56
57  def __init__(self, apex_path, key_passwords, codename_to_api_level_map, avbtool=None, sign_tool=None):
58    self.apex_path = apex_path
59    if not key_passwords:
60      self.key_passwords = dict()
61    else:
62      self.key_passwords = key_passwords
63    self.codename_to_api_level_map = codename_to_api_level_map
64    self.debugfs_path = os.path.join(
65        OPTIONS.search_path, "bin", "debugfs_static")
66    self.avbtool = avbtool if avbtool else "avbtool"
67    self.sign_tool = sign_tool
68
69  def ProcessApexFile(self, apk_keys, payload_key, signing_args=None):
70    """Scans and signs the payload files and repack the apex
71
72    Args:
73      apk_keys: A dict that holds the signing keys for apk files.
74
75    Returns:
76      The repacked apex file containing the signed apk files.
77    """
78    if not os.path.exists(self.debugfs_path):
79      raise ApexSigningError(
80          "Couldn't find location of debugfs_static: " +
81          "Path {} does not exist. ".format(self.debugfs_path) +
82          "Make sure bin/debugfs_static can be found in -p <path>")
83    list_cmd = ['deapexer', '--debugfs_path',
84                self.debugfs_path, 'list', self.apex_path]
85    entries_names = common.RunAndCheckOutput(list_cmd).split()
86    apk_entries = [name for name in entries_names if name.endswith('.apk')]
87
88    # No need to sign and repack, return the original apex path.
89    if not apk_entries and self.sign_tool is None:
90      logger.info('No apk file to sign in %s', self.apex_path)
91      return self.apex_path
92
93    for entry in apk_entries:
94      apk_name = os.path.basename(entry)
95      if apk_name not in apk_keys:
96        raise ApexSigningError('Failed to find signing keys for apk file {} in'
97                               ' apex {}.  Use "-e <apkname>=" to specify a key'
98                               .format(entry, self.apex_path))
99      if not any(dirname in entry for dirname in ['app/', 'priv-app/',
100                                                  'overlay/']):
101        logger.warning('Apk path does not contain the intended directory name:'
102                       ' %s', entry)
103
104    payload_dir, has_signed_content = self.ExtractApexPayloadAndSignContents(
105        apk_entries, apk_keys, payload_key, signing_args)
106    if not has_signed_content:
107      logger.info('No contents has been signed in %s', self.apex_path)
108      return self.apex_path
109
110    return self.RepackApexPayload(payload_dir, payload_key, signing_args)
111
112  def ExtractApexPayloadAndSignContents(self, apk_entries, apk_keys, payload_key, signing_args):
113    """Extracts the payload image and signs the containing apk files."""
114    if not os.path.exists(self.debugfs_path):
115      raise ApexSigningError(
116          "Couldn't find location of debugfs_static: " +
117          "Path {} does not exist. ".format(self.debugfs_path) +
118          "Make sure bin/debugfs_static can be found in -p <path>")
119    payload_dir = common.MakeTempDir()
120    extract_cmd = ['deapexer', '--debugfs_path',
121                   self.debugfs_path, 'extract', self.apex_path, payload_dir]
122    common.RunAndCheckOutput(extract_cmd)
123
124    has_signed_content = False
125    for entry in apk_entries:
126      apk_path = os.path.join(payload_dir, entry)
127      assert os.path.exists(self.apex_path)
128
129      key_name = apk_keys.get(os.path.basename(entry))
130      if key_name in common.SPECIAL_CERT_STRINGS:
131        logger.info('Not signing: %s due to special cert string', apk_path)
132        continue
133
134      logger.info('Signing apk file %s in apex %s', apk_path, self.apex_path)
135      # Rename the unsigned apk and overwrite the original apk path with the
136      # signed apk file.
137      unsigned_apk = common.MakeTempFile()
138      os.rename(apk_path, unsigned_apk)
139      common.SignFile(
140          unsigned_apk, apk_path, key_name, self.key_passwords.get(key_name),
141          codename_to_api_level_map=self.codename_to_api_level_map)
142      has_signed_content = True
143
144    if self.sign_tool:
145      logger.info('Signing payload contents in apex %s with %s', self.apex_path, self.sign_tool)
146      # Pass avbtool to the custom signing tool
147      cmd = [self.sign_tool, '--avbtool', self.avbtool]
148      # Pass signing_args verbatim which will be forwarded to avbtool (e.g. --signing_helper=...)
149      if signing_args:
150        cmd.extend(['--signing_args', '"{}"'.format(signing_args)])
151      cmd.extend([payload_key, payload_dir])
152      common.RunAndCheckOutput(cmd)
153      has_signed_content = True
154
155    return payload_dir, has_signed_content
156
157  def RepackApexPayload(self, payload_dir, payload_key, signing_args=None):
158    """Rebuilds the apex file with the updated payload directory."""
159    apex_dir = common.MakeTempDir()
160    # Extract the apex file and reuse its meta files as repack parameters.
161    common.UnzipToDir(self.apex_path, apex_dir)
162    arguments_dict = {
163        'manifest': os.path.join(apex_dir, 'apex_manifest.pb'),
164        'build_info': os.path.join(apex_dir, 'apex_build_info.pb'),
165        'key': payload_key,
166    }
167    for filename in arguments_dict.values():
168      assert os.path.exists(filename), 'file {} not found'.format(filename)
169
170    # The repack process will add back these files later in the payload image.
171    for name in ['apex_manifest.pb', 'apex_manifest.json', 'lost+found']:
172      path = os.path.join(payload_dir, name)
173      if os.path.isfile(path):
174        os.remove(path)
175      elif os.path.isdir(path):
176        shutil.rmtree(path, ignore_errors=True)
177
178    # TODO(xunchang) the signing process can be improved by using
179    # '--unsigned_payload_only'. But we need to parse the vbmeta earlier for
180    # the signing arguments, e.g. algorithm, salt, etc.
181    payload_img = os.path.join(apex_dir, APEX_PAYLOAD_IMAGE)
182    generate_image_cmd = ['apexer', '--force', '--payload_only',
183                          '--do_not_check_keyname', '--apexer_tool_path',
184                          os.getenv('PATH')]
185    for key, val in arguments_dict.items():
186      generate_image_cmd.extend(['--' + key, val])
187
188    # Add quote to the signing_args as we will pass
189    # --signing_args "--signing_helper_with_files=%path" to apexer
190    if signing_args:
191      generate_image_cmd.extend(
192          ['--signing_args', '"{}"'.format(signing_args)])
193
194    # optional arguments for apex repacking
195    manifest_json = os.path.join(apex_dir, 'apex_manifest.json')
196    if os.path.exists(manifest_json):
197      generate_image_cmd.extend(['--manifest_json', manifest_json])
198    generate_image_cmd.extend([payload_dir, payload_img])
199    if OPTIONS.verbose:
200      generate_image_cmd.append('-v')
201    common.RunAndCheckOutput(generate_image_cmd)
202
203    # Add the payload image back to the apex file.
204    common.ZipDelete(self.apex_path, APEX_PAYLOAD_IMAGE)
205    with zipfile.ZipFile(self.apex_path, 'a', allowZip64=True) as output_apex:
206      common.ZipWrite(output_apex, payload_img, APEX_PAYLOAD_IMAGE,
207                      compress_type=zipfile.ZIP_STORED)
208    return self.apex_path
209
210
211def SignApexPayload(avbtool, payload_file, payload_key_path, payload_key_name,
212                    algorithm, salt, hash_algorithm, no_hashtree, signing_args=None):
213  """Signs a given payload_file with the payload key."""
214  # Add the new footer. Old footer, if any, will be replaced by avbtool.
215  cmd = [avbtool, 'add_hashtree_footer',
216         '--do_not_generate_fec',
217         '--algorithm', algorithm,
218         '--key', payload_key_path,
219         '--prop', 'apex.key:{}'.format(payload_key_name),
220         '--image', payload_file,
221         '--salt', salt,
222         '--hash_algorithm', hash_algorithm]
223  if no_hashtree:
224    cmd.append('--no_hashtree')
225  if signing_args:
226    cmd.extend(shlex.split(signing_args))
227
228  try:
229    common.RunAndCheckOutput(cmd)
230  except common.ExternalError as e:
231    raise ApexSigningError(
232        'Failed to sign APEX payload {} with {}:\n{}'.format(
233            payload_file, payload_key_path, e))
234
235  # Verify the signed payload image with specified public key.
236  logger.info('Verifying %s', payload_file)
237  VerifyApexPayload(avbtool, payload_file, payload_key_path, no_hashtree)
238
239
240def VerifyApexPayload(avbtool, payload_file, payload_key, no_hashtree=False):
241  """Verifies the APEX payload signature with the given key."""
242  cmd = [avbtool, 'verify_image', '--image', payload_file,
243         '--key', payload_key]
244  if no_hashtree:
245    cmd.append('--accept_zeroed_hashtree')
246  try:
247    common.RunAndCheckOutput(cmd)
248  except common.ExternalError as e:
249    raise ApexSigningError(
250        'Failed to validate payload signing for {} with {}:\n{}'.format(
251            payload_file, payload_key, e))
252
253
254def ParseApexPayloadInfo(avbtool, payload_path):
255  """Parses the APEX payload info.
256
257  Args:
258    avbtool: The AVB tool to use.
259    payload_path: The path to the payload image.
260
261  Raises:
262    ApexInfoError on parsing errors.
263
264  Returns:
265    A dict that contains payload property-value pairs. The dict should at least
266    contain Algorithm, Salt, Tree Size and apex.key.
267  """
268  if not os.path.exists(payload_path):
269    raise ApexInfoError('Failed to find image: {}'.format(payload_path))
270
271  cmd = [avbtool, 'info_image', '--image', payload_path]
272  try:
273    output = common.RunAndCheckOutput(cmd)
274  except common.ExternalError as e:
275    raise ApexInfoError(
276        'Failed to get APEX payload info for {}:\n{}'.format(
277            payload_path, e))
278
279  # Extract the Algorithm / Hash Algorithm / Salt / Prop info / Tree size from
280  # payload (i.e. an image signed with avbtool). For example,
281  # Algorithm:                SHA256_RSA4096
282  PAYLOAD_INFO_PATTERN = (
283      r'^\s*(?P<key>Algorithm|Hash Algorithm|Salt|Prop|Tree Size)\:\s*(?P<value>.*?)$')
284  payload_info_matcher = re.compile(PAYLOAD_INFO_PATTERN)
285
286  payload_info = {}
287  for line in output.split('\n'):
288    line_info = payload_info_matcher.match(line)
289    if not line_info:
290      continue
291
292    key, value = line_info.group('key'), line_info.group('value')
293
294    if key == 'Prop':
295      # Further extract the property key-value pair, from a 'Prop:' line. For
296      # example,
297      #   Prop: apex.key -> 'com.android.runtime'
298      # Note that avbtool writes single or double quotes around values.
299      PROPERTY_DESCRIPTOR_PATTERN = r'^\s*(?P<key>.*?)\s->\s*(?P<value>.*?)$'
300
301      prop_matcher = re.compile(PROPERTY_DESCRIPTOR_PATTERN)
302      prop = prop_matcher.match(value)
303      if not prop:
304        raise ApexInfoError(
305            'Failed to parse prop string {}'.format(value))
306
307      prop_key, prop_value = prop.group('key'), prop.group('value')
308      if prop_key == 'apex.key':
309        # avbtool dumps the prop value with repr(), which contains single /
310        # double quotes that we don't want.
311        payload_info[prop_key] = prop_value.strip('\"\'')
312
313    else:
314      payload_info[key] = value
315
316  # Validation check.
317  for key in ('Algorithm', 'Salt', 'apex.key', 'Hash Algorithm'):
318    if key not in payload_info:
319      raise ApexInfoError(
320          'Failed to find {} prop in {}'.format(key, payload_path))
321
322  return payload_info
323
324
325def SignUncompressedApex(avbtool, apex_file, payload_key, container_key,
326                         container_pw, apk_keys, codename_to_api_level_map,
327                         no_hashtree, signing_args=None, sign_tool=None):
328  """Signs the current uncompressed APEX with the given payload/container keys.
329
330  Args:
331    apex_file: Uncompressed APEX file.
332    payload_key: The path to payload signing key (w/ extension).
333    container_key: The path to container signing key (w/o extension).
334    container_pw: The matching password of the container_key, or None.
335    apk_keys: A dict that holds the signing keys for apk files.
336    codename_to_api_level_map: A dict that maps from codename to API level.
337    no_hashtree: Don't include hashtree in the signed APEX.
338    signing_args: Additional args to be passed to the payload signer.
339    sign_tool: A tool to sign the contents of the APEX.
340
341  Returns:
342    The path to the signed APEX file.
343  """
344  # 1. Extract the apex payload image and sign the files (e.g. APKs). Repack
345  # the apex file after signing.
346  apk_signer = ApexApkSigner(apex_file, container_pw,
347                             codename_to_api_level_map,
348                             avbtool, sign_tool)
349  apex_file = apk_signer.ProcessApexFile(apk_keys, payload_key, signing_args)
350
351  # 2a. Extract and sign the APEX_PAYLOAD_IMAGE entry with the given
352  # payload_key.
353  payload_dir = common.MakeTempDir(prefix='apex-payload-')
354  with zipfile.ZipFile(apex_file) as apex_fd:
355    payload_file = apex_fd.extract(APEX_PAYLOAD_IMAGE, payload_dir)
356    zip_items = apex_fd.namelist()
357
358  payload_info = ParseApexPayloadInfo(avbtool, payload_file)
359  if no_hashtree is None:
360    no_hashtree = payload_info.get("Tree Size", 0) == 0
361  SignApexPayload(
362      avbtool,
363      payload_file,
364      payload_key,
365      payload_info['apex.key'],
366      payload_info['Algorithm'],
367      payload_info['Salt'],
368      payload_info['Hash Algorithm'],
369      no_hashtree,
370      signing_args)
371
372  # 2b. Update the embedded payload public key.
373  payload_public_key = common.ExtractAvbPublicKey(avbtool, payload_key)
374  common.ZipDelete(apex_file, APEX_PAYLOAD_IMAGE)
375  if APEX_PUBKEY in zip_items:
376    common.ZipDelete(apex_file, APEX_PUBKEY)
377  apex_zip = zipfile.ZipFile(apex_file, 'a', allowZip64=True)
378  common.ZipWrite(apex_zip, payload_file, arcname=APEX_PAYLOAD_IMAGE)
379  common.ZipWrite(apex_zip, payload_public_key, arcname=APEX_PUBKEY)
380  common.ZipClose(apex_zip)
381
382  # 3. Sign the APEX container with container_key.
383  signed_apex = common.MakeTempFile(prefix='apex-container-', suffix='.apex')
384
385  # Specify the 4K alignment when calling SignApk.
386  extra_signapk_args = OPTIONS.extra_signapk_args[:]
387  extra_signapk_args.extend(['-a', '4096', '--align-file-size'])
388
389  password = container_pw.get(container_key) if container_pw else None
390  common.SignFile(
391      apex_file,
392      signed_apex,
393      container_key,
394      password,
395      codename_to_api_level_map=codename_to_api_level_map,
396      extra_signapk_args=extra_signapk_args)
397
398  return signed_apex
399
400
401def SignCompressedApex(avbtool, apex_file, payload_key, container_key,
402                       container_pw, apk_keys, codename_to_api_level_map,
403                       no_hashtree, signing_args=None, sign_tool=None):
404  """Signs the current compressed APEX with the given payload/container keys.
405
406  Args:
407    apex_file: Raw uncompressed APEX data.
408    payload_key: The path to payload signing key (w/ extension).
409    container_key: The path to container signing key (w/o extension).
410    container_pw: The matching password of the container_key, or None.
411    apk_keys: A dict that holds the signing keys for apk files.
412    codename_to_api_level_map: A dict that maps from codename to API level.
413    no_hashtree: Don't include hashtree in the signed APEX.
414    signing_args: Additional args to be passed to the payload signer.
415
416  Returns:
417    The path to the signed APEX file.
418  """
419  debugfs_path = os.path.join(OPTIONS.search_path, 'bin', 'debugfs_static')
420
421  # 1. Decompress original_apex inside compressed apex.
422  original_apex_file = common.MakeTempFile(prefix='original-apex-',
423                                           suffix='.apex')
424  # Decompression target path should not exist
425  os.remove(original_apex_file)
426  common.RunAndCheckOutput(['deapexer', '--debugfs_path', debugfs_path,
427                            'decompress', '--input', apex_file,
428                            '--output', original_apex_file])
429
430  # 2. Sign original_apex
431  signed_original_apex_file = SignUncompressedApex(
432      avbtool,
433      original_apex_file,
434      payload_key,
435      container_key,
436      container_pw,
437      apk_keys,
438      codename_to_api_level_map,
439      no_hashtree,
440      signing_args,
441      sign_tool)
442
443  # 3. Compress signed original apex.
444  compressed_apex_file = common.MakeTempFile(prefix='apex-container-',
445                                             suffix='.capex')
446  common.RunAndCheckOutput(['apex_compression_tool',
447                            'compress',
448                            '--apex_compression_tool_path', os.getenv('PATH'),
449                            '--input', signed_original_apex_file,
450                            '--output', compressed_apex_file])
451
452  # 4. Sign the APEX container with container_key.
453  signed_apex = common.MakeTempFile(prefix='apex-container-', suffix='.capex')
454
455  password = container_pw.get(container_key) if container_pw else None
456  common.SignFile(
457      compressed_apex_file,
458      signed_apex,
459      container_key,
460      password,
461      codename_to_api_level_map=codename_to_api_level_map,
462      extra_signapk_args=OPTIONS.extra_signapk_args)
463
464  return signed_apex
465
466
467def SignApex(avbtool, apex_data, payload_key, container_key, container_pw,
468             apk_keys, codename_to_api_level_map,
469             no_hashtree, signing_args=None, sign_tool=None):
470  """Signs the current APEX with the given payload/container keys.
471
472  Args:
473    apex_file: Path to apex file path.
474    payload_key: The path to payload signing key (w/ extension).
475    container_key: The path to container signing key (w/o extension).
476    container_pw: The matching password of the container_key, or None.
477    apk_keys: A dict that holds the signing keys for apk files.
478    codename_to_api_level_map: A dict that maps from codename to API level.
479    no_hashtree: Don't include hashtree in the signed APEX.
480    signing_args: Additional args to be passed to the payload signer.
481
482  Returns:
483    The path to the signed APEX file.
484  """
485  apex_file = common.MakeTempFile(prefix='apex-container-', suffix='.apex')
486  with open(apex_file, 'wb') as output_fp:
487    output_fp.write(apex_data)
488
489  debugfs_path = os.path.join(OPTIONS.search_path, 'bin', 'debugfs_static')
490  cmd = ['deapexer', '--debugfs_path', debugfs_path,
491         'info', '--print-type', apex_file]
492
493  try:
494    apex_type = common.RunAndCheckOutput(cmd).strip()
495    if apex_type == 'UNCOMPRESSED':
496      return SignUncompressedApex(
497          avbtool,
498          apex_file,
499          payload_key=payload_key,
500          container_key=container_key,
501          container_pw=None,
502          codename_to_api_level_map=codename_to_api_level_map,
503          no_hashtree=no_hashtree,
504          apk_keys=apk_keys,
505          signing_args=signing_args,
506          sign_tool=sign_tool)
507    elif apex_type == 'COMPRESSED':
508      return SignCompressedApex(
509          avbtool,
510          apex_file,
511          payload_key=payload_key,
512          container_key=container_key,
513          container_pw=None,
514          codename_to_api_level_map=codename_to_api_level_map,
515          no_hashtree=no_hashtree,
516          apk_keys=apk_keys,
517          signing_args=signing_args,
518          sign_tool=sign_tool)
519    else:
520      # TODO(b/172912232): support signing compressed apex
521      raise ApexInfoError('Unsupported apex type {}'.format(apex_type))
522
523  except common.ExternalError as e:
524    raise ApexInfoError(
525        'Failed to get type for {}:\n{}'.format(apex_file, e))
526
527
528def GetApexInfoFromTargetFiles(input_file, partition, compressed_only=True):
529  """
530  Get information about system APEX stored in the input_file zip
531
532  Args:
533    input_file: The filename of the target build target-files zip or directory.
534
535  Return:
536    A list of ota_metadata_pb2.ApexInfo() populated using the APEX stored in
537    /system partition of the input_file
538  """
539
540  # Extract the apex files so that we can run checks on them
541  if not isinstance(input_file, str):
542    raise RuntimeError("must pass filepath to target-files zip or directory")
543
544  apex_subdir = os.path.join(partition.upper(), 'apex')
545  if os.path.isdir(input_file):
546    tmp_dir = input_file
547  else:
548    tmp_dir = UnzipTemp(input_file, [os.path.join(apex_subdir, '*')])
549  target_dir = os.path.join(tmp_dir, apex_subdir)
550
551  # Partial target-files packages for vendor-only builds may not contain
552  # a system apex directory.
553  if not os.path.exists(target_dir):
554    logger.info('No APEX directory at path: %s', target_dir)
555    return []
556
557  apex_infos = []
558
559  debugfs_path = "debugfs"
560  if OPTIONS.search_path:
561    debugfs_path = os.path.join(OPTIONS.search_path, "bin", "debugfs_static")
562  deapexer = 'deapexer'
563  if OPTIONS.search_path:
564    deapexer_path = os.path.join(OPTIONS.search_path, "bin", "deapexer")
565    if os.path.isfile(deapexer_path):
566      deapexer = deapexer_path
567  for apex_filename in os.listdir(target_dir):
568    apex_filepath = os.path.join(target_dir, apex_filename)
569    if not os.path.isfile(apex_filepath) or \
570            not zipfile.is_zipfile(apex_filepath):
571      logger.info("Skipping %s because it's not a zipfile", apex_filepath)
572      continue
573    apex_info = ota_metadata_pb2.ApexInfo()
574    # Open the apex file to retrieve information
575    manifest = apex_manifest.fromApex(apex_filepath)
576    apex_info.package_name = manifest.name
577    apex_info.version = manifest.version
578    # Check if the file is compressed or not
579    apex_type = RunAndCheckOutput([
580        deapexer, "--debugfs_path", debugfs_path,
581        'info', '--print-type', apex_filepath]).rstrip()
582    if apex_type == 'COMPRESSED':
583      apex_info.is_compressed = True
584    elif apex_type == 'UNCOMPRESSED':
585      apex_info.is_compressed = False
586    else:
587      raise RuntimeError('Not an APEX file: ' + apex_type)
588
589    # Decompress compressed APEX to determine its size
590    if apex_info.is_compressed:
591      decompressed_file_path = MakeTempFile(prefix="decompressed-",
592                                            suffix=".apex")
593      # Decompression target path should not exist
594      os.remove(decompressed_file_path)
595      RunAndCheckOutput([deapexer, 'decompress', '--input', apex_filepath,
596                         '--output', decompressed_file_path])
597      apex_info.decompressed_size = os.path.getsize(decompressed_file_path)
598
599    if not compressed_only or apex_info.is_compressed:
600      apex_infos.append(apex_info)
601
602  return apex_infos
603