Support replacing AVB signing keys.

sign_target_files_apks.py now supports signing targets using verified
boot 2.0 (aka AVB). It allows replacing AVB signing keys for both of
chained and non-chained partitions.

An example command line looks as follows.
 $ ./build/tools/releasetools/sign_target_files_apks.py \
     --avb_vbmeta_key external/avb/test/data/testkey_rsa2048.pem \
     --avb_vbmeta_algorithm SHA256_RSA2048 \
     --avb_vbmeta_extra_args \
         "--signing_helper_with_files ./signing-helper.sh" \
     --avb_system_key external/avb/test/data/testkey_rsa4096.pem \
     --avb_system_algorithm SHA256_RSA4096 \
     --avb_system_extra_args \
         "--signing_helper_with_files ./signing-helper.sh" \
     product-target_files.eng.zip signed-product-target_files.zip

To verify the signed images:
 $ unzip signed-product-target_files.zip IMAGES/\*
 $ avbtool verify_image --image IMAGES/vbmeta.img \
     --expected_chain_partition system:1:testkey_rsa4096_pub.pem \
     --key external/avb/test/data/testkey_rsa2048.pem

Bug: 38315721
Test: sign_target_files_apks.py on AVB-enabled target w/ and w/o chained
      partitions respectively. Check the signing command lines; validate
      the signed images with 'avbtool verify_image'.
Change-Id: Ia009555b16ddb6d8ba6a0858d5ca7d983bbab887
(cherry picked from commit 639118ff4dc299a4a9b335ed9a7d6ec0b4ed33b0)
diff --git a/tools/releasetools/sign_target_files_apks.py b/tools/releasetools/sign_target_files_apks.py
index 9cdaa18..3cf8ce7 100755
--- a/tools/releasetools/sign_target_files_apks.py
+++ b/tools/releasetools/sign_target_files_apks.py
@@ -78,6 +78,16 @@
   --replace_verity_keyid <path_to_X509_PEM_cert_file>
       Replace the veritykeyid in BOOT/cmdline of input_target_file_zip
       with keyid of the cert pointed by <path_to_X509_PEM_cert_file>.
+
+  --avb_{boot,system,vendor,dtbo,vbmeta}_algorithm <algorithm>
+  --avb_{boot,system,vendor,dtbo,vbmeta}_key <key>
+      Use the specified algorithm (e.g. SHA256_RSA4096) and the key to AVB-sign
+      the specified image. Otherwise it uses the existing values in info dict.
+
+  --avb_{boot,system,vendor,dtbo,vbmeta}_extra_args <args>
+      Specify any additional args that are needed to AVB-sign the image
+      (e.g. "--signing_helper /path/to/helper"). The args will be appended to
+      the existing ones in info dict.
 """
 
 import sys
@@ -109,6 +119,9 @@
 OPTIONS.replace_verity_private_key = False
 OPTIONS.replace_verity_keyid = False
 OPTIONS.tag_changes = ("-test-keys", "-dev-keys", "+release-keys")
+OPTIONS.avb_keys = {}
+OPTIONS.avb_algorithms = {}
+OPTIONS.avb_extra_args = {}
 
 def GetApkCerts(tf_zip):
   certmap = common.ReadApkCerts(tf_zip)
@@ -291,6 +304,9 @@
     ReplaceVerityKeyId(input_tf_zip, output_tf_zip,
                        OPTIONS.replace_verity_keyid[1])
 
+  # Replace the AVB signing keys, if any.
+  ReplaceAvbSigningKeys(misc_info)
+
   # Write back misc_info with the latest values.
   ReplaceMiscInfoTxt(input_tf_zip, output_tf_zip, misc_info)
 
@@ -522,6 +538,41 @@
   common.ZipWriteStr(output_zip, "META/misc_info.txt", '\n'.join(items))
 
 
+def ReplaceAvbSigningKeys(misc_info):
+  """Replaces the AVB signing keys."""
+
+  AVB_FOOTER_ARGS_BY_PARTITION = {
+    'boot' : 'avb_boot_add_hash_footer_args',
+    'dtbo' : 'avb_dtbo_add_hash_footer_args',
+    'system' : 'avb_system_add_hashtree_footer_args',
+    'vendor' : 'avb_vendor_add_hashtree_footer_args',
+    'vbmeta' : 'avb_vbmeta_args',
+  }
+
+  def ReplaceAvbPartitionSigningKey(partition):
+    key = OPTIONS.avb_keys.get(partition)
+    if not key:
+      return
+
+    algorithm = OPTIONS.avb_algorithms.get(partition)
+    assert algorithm, 'Missing AVB signing algorithm for %s' % (partition,)
+
+    print 'Replacing AVB signing key for %s with "%s" (%s)' % (
+        partition, key, algorithm)
+    misc_info['avb_' + partition + '_algorithm'] = algorithm
+    misc_info['avb_' + partition + '_key_path'] = key
+
+    extra_args = OPTIONS.avb_extra_args.get(partition)
+    if extra_args:
+      print 'Setting extra AVB signing args for %s to "%s"' % (
+          partition, extra_args)
+      args_key = AVB_FOOTER_ARGS_BY_PARTITION[partition]
+      misc_info[args_key] = (misc_info.get(args_key, '') + ' ' + extra_args)
+
+  for partition in AVB_FOOTER_ARGS_BY_PARTITION:
+    ReplaceAvbPartitionSigningKey(partition)
+
+
 def BuildKeyMap(misc_info, key_mapping_options):
   for s, d in key_mapping_options:
     if s is None:   # -d option
@@ -619,21 +670,69 @@
       OPTIONS.replace_verity_private_key = (True, a)
     elif o == "--replace_verity_keyid":
       OPTIONS.replace_verity_keyid = (True, a)
+    elif o == "--avb_vbmeta_key":
+      OPTIONS.avb_keys['vbmeta'] = a
+    elif o == "--avb_vbmeta_algorithm":
+      OPTIONS.avb_algorithms['vbmeta'] = a
+    elif o == "--avb_vbmeta_extra_args":
+      OPTIONS.avb_extra_args['vbmeta'] = a
+    elif o == "--avb_boot_key":
+      OPTIONS.avb_keys['boot'] = a
+    elif o == "--avb_boot_algorithm":
+      OPTIONS.avb_algorithms['boot'] = a
+    elif o == "--avb_boot_extra_args":
+      OPTIONS.avb_extra_args['boot'] = a
+    elif o == "--avb_dtbo_key":
+      OPTIONS.avb_keys['dtbo'] = a
+    elif o == "--avb_dtbo_algorithm":
+      OPTIONS.avb_algorithms['dtbo'] = a
+    elif o == "--avb_dtbo_extra_args":
+      OPTIONS.avb_extra_args['dtbo'] = a
+    elif o == "--avb_system_key":
+      OPTIONS.avb_keys['system'] = a
+    elif o == "--avb_system_algorithm":
+      OPTIONS.avb_algorithms['system'] = a
+    elif o == "--avb_system_extra_args":
+      OPTIONS.avb_extra_args['system'] = a
+    elif o == "--avb_vendor_key":
+      OPTIONS.avb_keys['vendor'] = a
+    elif o == "--avb_vendor_algorithm":
+      OPTIONS.avb_algorithms['vendor'] = a
+    elif o == "--avb_vendor_extra_args":
+      OPTIONS.avb_extra_args['vendor'] = a
     else:
       return False
     return True
 
-  args = common.ParseOptions(argv, __doc__,
-                             extra_opts="e:d:k:ot:",
-                             extra_long_opts=["extra_apks=",
-                                              "default_key_mappings=",
-                                              "key_mapping=",
-                                              "replace_ota_keys",
-                                              "tag_changes=",
-                                              "replace_verity_public_key=",
-                                              "replace_verity_private_key=",
-                                              "replace_verity_keyid="],
-                             extra_option_handler=option_handler)
+  args = common.ParseOptions(
+      argv, __doc__,
+      extra_opts="e:d:k:ot:",
+      extra_long_opts=[
+        "extra_apks=",
+        "default_key_mappings=",
+        "key_mapping=",
+        "replace_ota_keys",
+        "tag_changes=",
+        "replace_verity_public_key=",
+        "replace_verity_private_key=",
+        "replace_verity_keyid=",
+        "avb_vbmeta_algorithm=",
+        "avb_vbmeta_key=",
+        "avb_vbmeta_extra_args=",
+        "avb_boot_algorithm=",
+        "avb_boot_key=",
+        "avb_boot_extra_args=",
+        "avb_dtbo_algorithm=",
+        "avb_dtbo_key=",
+        "avb_dtbo_extra_args=",
+        "avb_system_algorithm=",
+        "avb_system_key=",
+        "avb_system_extra_args=",
+        "avb_vendor_algorithm=",
+        "avb_vendor_key=",
+        "avb_vendor_extra_args=",
+      ],
+      extra_option_handler=option_handler)
 
   if len(args) != 2:
     common.Usage(__doc__)
@@ -681,3 +780,5 @@
     print "   ERROR: %s" % (e,)
     print
     sys.exit(1)
+  finally:
+    common.Cleanup()