post_process_mac_perms 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. #!/usr/bin/env python
  2. #
  3. # 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. """
  17. Tool to help modify an existing mac_permissions.xml with additional app
  18. certs not already found in that policy. This becomes useful when a directory
  19. containing apps is searched and the certs from those apps are added to the
  20. policy not already explicitly listed.
  21. """
  22. import sys
  23. import os
  24. import argparse
  25. from base64 import b16encode, b64decode
  26. import fileinput
  27. import re
  28. import subprocess
  29. import zipfile
  30. PEM_CERT_RE = """-----BEGIN CERTIFICATE-----
  31. (.+?)
  32. -----END CERTIFICATE-----
  33. """
  34. def collect_certs_for_app(filename):
  35. app_certs = set()
  36. with zipfile.ZipFile(filename, 'r') as apkzip:
  37. for info in apkzip.infolist():
  38. name = info.filename
  39. if name.startswith('META-INF/') and name.endswith(('.DSA', '.RSA')):
  40. cmd = ['openssl', 'pkcs7', '-inform', 'DER',
  41. '-outform', 'PEM', '-print_certs']
  42. p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  43. stderr=subprocess.PIPE)
  44. pem_string, err = p.communicate(apkzip.read(name))
  45. if err and err.strip():
  46. raise RuntimeError('Problem running openssl on %s (%s)' % (filename, e))
  47. # turn multiline base64 to single line base16
  48. transform = lambda x: b16encode(b64decode(x.replace('\n', ''))).lower()
  49. results = re.findall(PEM_CERT_RE, pem_string, re.DOTALL)
  50. certs = [transform(i) for i in results]
  51. app_certs.update(certs)
  52. return app_certs
  53. def add_leftover_certs(args):
  54. all_app_certs = set()
  55. for dirpath, _, files in os.walk(args.dir):
  56. transform = lambda x: os.path.join(dirpath, x)
  57. condition = lambda x: x.endswith('.apk')
  58. apps = [transform(i) for i in files if condition(i)]
  59. # Collect certs for each app found
  60. for app in apps:
  61. app_certs = collect_certs_for_app(app)
  62. all_app_certs.update(app_certs)
  63. if all_app_certs:
  64. policy_certs = set()
  65. with open(args.policy, 'r') as f:
  66. cert_pattern = 'signature="([a-fA-F0-9]+)"'
  67. policy_certs = re.findall(cert_pattern, f.read())
  68. cert_diff = all_app_certs.difference(policy_certs)
  69. # Build xml stanzas
  70. inner_tag = '<seinfo value="%s"/>' % args.seinfo
  71. stanza = '<signer signature="%s">%s</signer>'
  72. new_stanzas = [stanza % (cert, inner_tag) for cert in cert_diff]
  73. mac_perms_string = ''.join(new_stanzas)
  74. mac_perms_string += '</policy>'
  75. # Inline replace with new policy stanzas
  76. for line in fileinput.input(args.policy, inplace=True):
  77. sys.stdout.write(line.replace('</policy>', mac_perms_string))
  78. def main(argv):
  79. parser = argparse.ArgumentParser(description=__doc__)
  80. parser.add_argument('-s', '--seinfo', dest='seinfo', required=True,
  81. help='seinfo tag for each generated stanza')
  82. parser.add_argument('-d', '--dir', dest='dir', required=True,
  83. help='Directory to search for apks')
  84. parser.add_argument('-f', '--file', dest='policy', required=True,
  85. help='mac_permissions.xml policy file')
  86. parser.set_defaults(func=add_leftover_certs)
  87. args = parser.parse_args()
  88. args.func(args)
  89. if __name__ == '__main__':
  90. main(sys.argv)