| Andrei Onea | 580f7b0 | 2022-08-17 16:50:48 +0000 | [diff] [blame] | 1 | #!/usr/bin/env python | 
 | 2 | # | 
 | 3 | # Copyright (C) 2022 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 | """A tool for modifying privileged permission allowlists.""" | 
 | 18 |  | 
 | 19 | from __future__ import print_function | 
 | 20 |  | 
 | 21 | import argparse | 
 | 22 | import sys | 
 | 23 | from xml.dom import minidom | 
 | 24 |  | 
 | 25 |  | 
 | 26 | class InvalidRootNodeException(Exception): | 
 | 27 |   pass | 
 | 28 |  | 
 | 29 |  | 
 | 30 | class InvalidNumberOfPrivappPermissionChildren(Exception): | 
 | 31 |   pass | 
 | 32 |  | 
 | 33 |  | 
 | 34 | def modify_allowlist(allowlist_dom, package_name): | 
 | 35 |   if allowlist_dom.documentElement.tagName != 'permissions': | 
 | 36 |     raise InvalidRootNodeException | 
 | 37 |   nodes = allowlist_dom.getElementsByTagName('privapp-permissions') | 
 | 38 |   if nodes.length != 1: | 
 | 39 |     raise InvalidNumberOfPrivappPermissionChildren | 
 | 40 |   privapp_permissions = nodes[0] | 
 | 41 |   privapp_permissions.setAttribute('package', package_name) | 
 | 42 |  | 
 | 43 |  | 
 | 44 | def parse_args(): | 
 | 45 |   """Parse commandline arguments.""" | 
 | 46 |  | 
 | 47 |   parser = argparse.ArgumentParser() | 
 | 48 |   parser.add_argument('input', help='input allowlist template file') | 
 | 49 |   parser.add_argument( | 
 | 50 |       'package_name', help='package name to use in the allowlist' | 
 | 51 |   ) | 
 | 52 |   parser.add_argument('output', help='output allowlist file') | 
 | 53 |  | 
 | 54 |   return parser.parse_args() | 
 | 55 |  | 
 | 56 |  | 
 | 57 | def main(): | 
 | 58 |   try: | 
 | 59 |     args = parse_args() | 
 | 60 |     doc = minidom.parse(args.input) | 
 | 61 |     modify_allowlist(doc, args.package_name) | 
 | 62 |     with open(args.output, 'w') as output_file: | 
 | 63 |       doc.writexml(output_file, encoding='utf-8') | 
 | 64 |   except Exception as err: | 
 | 65 |     print('error: ' + str(err), file=sys.stderr) | 
 | 66 |     sys.exit(-1) | 
 | 67 |  | 
 | 68 |  | 
 | 69 | if __name__ == '__main__': | 
 | 70 |   main() |