-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprivapp_permissions.py
414 lines (348 loc) · 13.7 KB
/
privapp_permissions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
#!/usr/bin/env python
#
# Copyright 2017 - The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Custom version made: 09-10-2021 03:31
# Does not include external device (adb / serial) support.
# For use with AOSP's newly PATH restricted build system.
from __future__ import print_function
from xml.dom import minidom
import argparse
import itertools
import os
import re
import subprocess
import sys
import tempfile
import shutil
DEVICE_PREFIX = 'device:'
ANDROID_NAME_REGEX = r'A: android:name\([\S]+\)=\"([\S]+)\"'
ANDROID_PROTECTION_LEVEL_REGEX = \
r'A: android:protectionLevel\([^\)]+\)=\(type [\S]+\)0x([\S]+)'
BASE_XML_FILENAME = 'privapp-permissions-platform.xml'
HELP_MESSAGE = """\
Generates privapp-permissions.xml file for priv-apps.
Usage:
Specify which apk to generate priv-app permissions for. If no apk is \
specified, this will default to all APKs under "<PRODUCT_OUT>/ \
system/priv-app".
Examples:
For all APKs under $PRODUCT_OUT:
# If the build environment has not been set up, do so:
. build/envsetup.sh
lunch product_name
m -j32
# then use:
cd development/tools/privapp_permissions/
./privapp_permissions.py
For a given apk:
./privapp_permissions.py path/to/the.apk
Note: This is a custom version of privapp_permissions.py for use with the AOSP
build system. This version doesn't include support for generating permissions
based on a device, nor does it include support for autodetection of the needed
utilities due to AOSP build system restrictions.
"""
# An array of all generated temp directories.
temp_dirs = []
# An array of all generated temp files.
temp_files = []
class MissingResourceError(Exception):
"""Raised when a dependency cannot be located."""
class Aapt(object):
def __init__(self, path):
self.path = path
def call(self, arguments):
"""Run an aapt command with the given args.
Args:
arguments: a list of string arguments
Returns:
The output of the aapt command as a string.
"""
output = subprocess.check_output([self.path] + arguments,
stderr=subprocess.STDOUT)
return output.decode(encoding='UTF-8')
class Resources(object):
"""A class that contains the resources needed to generate permissions.
Attributes:
adb: Disabled in this build
_aapt_path: The path to aapt.
output_xml: Path to the generated XML permissions file.
"""
def __init__(self, adb_path=None, aapt_path=None, use_device=None,
serial=None, apks=None, output_xml=None):
self.aapt = Resources._resolve_aapt(aapt_path)
self._is_android_env = 'PRODUCT_OUT' in os.environ and \
'HOST_OUT' in os.environ
self.output_xml = output_xml
self.privapp_apks = self._resolve_apks(apks)
self.permissions_dir = self._resolve_sys_path('system/etc/permissions')
self.sysconfig_dir = self._resolve_sys_path('system/etc/sysconfig')
self.framework_res_apk = self._resolve_sys_path('system/framework/'
'framework-res.apk')
@staticmethod
def _resolve_aapt(aapt_path):
"""Resolves AAPT from either the cmdline argument.
Note: In this version, support for locating via OS path resolution is removed
due to AOSP restricting access to the host's PATH.
Returns:
An Aapt Object
"""
if aapt_path:
if os.path.isfile(aapt_path):
return Aapt(aapt_path)
else:
raise MissingResourceError('Cannot resolve aapt: No such file '
'%s exists.' % aapt_path)
else:
raise MissingResourceError('Cannot resolve aapt: Path to AAPT not defined on cmdline. '
'Did you forget to setup the build environment or set '
'--aapt?')
def _resolve_apks(self, apks):
"""Resolves all APKs to run against.
Returns:
If no apk is specified in the arguments, return all apks in
system/priv-app. Otherwise, returns a list with the specified apk.
Throws:
MissingResourceError if the specified apk or system/priv-app cannot
be found.
"""
if not apks:
return self._resolve_all_privapps()
ret_apks = []
for apk in apks:
if not os.path.isfile(apk):
raise MissingResourceError('File "%s" does not exist.' % apk)
else:
ret_apks.append(apk)
return ret_apks
def _resolve_all_privapps(self):
"""Extract package name and requested permissions."""
if self._is_android_env:
priv_app_dir = os.path.join(os.environ['PRODUCT_OUT'],
'system/priv-app')
else:
raise MissingResourceError(
'Directory "/system/priv-app" cannot be pulled from a device. This version of privapp_permissions.py does not support this method.')
return get_output('find %s -name "*.apk"' % priv_app_dir).split()
def _resolve_sys_path(self, file_path):
"""Resolves a path that is a part of an Android System Image."""
if self._is_android_env:
return os.path.join(os.environ['PRODUCT_OUT'], file_path)
else:
raise MissingResourceError(
'Cannot resolve path. This version of privapp_permissions.py lacks adb / serial support.')
def get_output(command):
"""Returns the output of the command as a string.
Throws:
subprocess.CalledProcessError if exit status is non-zero.
"""
output = subprocess.check_output(command, shell=True)
# For Python3.4, decode the byte string so it is usable.
return output.decode(encoding='UTF-8')
def parse_args():
"""Parses the CLI."""
parser = argparse.ArgumentParser(
description=HELP_MESSAGE,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument(
'--aapt',
type=str,
required=True,
metavar='<AAPT_PATH>',
help='Path to aapt.'
)
parser.add_argument(
'--output',
dest='output_xml',
type=str,
required=True,
help='Path to the generated output file.'
)
parser.add_argument(
'apks',
nargs='*',
type=str,
help='A list of paths to priv-app APKs to generate permissions for. '
'To make a path device-side, prefix the path with "device:".'
)
cmd_args = parser.parse_args()
return cmd_args
def create_permission_file(resources):
# Parse base XML files in /etc dir, permissions listed there don't have
# to be re-added
base_permissions = {}
base_xml_files = itertools.chain(list_xml_files(resources.permissions_dir),
list_xml_files(resources.sysconfig_dir))
for xml_file in base_xml_files:
parse_config_xml(xml_file, base_permissions)
priv_permissions = extract_priv_permissions(resources.aapt,
resources.framework_res_apk)
apps_redefine_base = []
results = {}
for priv_app in resources.privapp_apks:
pkg_info = extract_pkg_and_requested_permissions(resources.aapt,
priv_app)
pkg_name = pkg_info['package_name']
priv_perms = get_priv_permissions(pkg_info['permissions'],
priv_permissions)
# Compute diff against permissions defined in base file
if base_permissions and (pkg_name in base_permissions):
base_permissions_pkg = base_permissions[pkg_name]
priv_perms = remove_base_permissions(priv_perms,
base_permissions_pkg)
if priv_perms:
apps_redefine_base.append(pkg_name)
if priv_perms:
results[pkg_name] = sorted(priv_perms)
print_xml(results, apps_redefine_base, resources.output_xml)
def print_xml(results, apps_redefine_base, outputFile):
"""Print results to the given file."""
fd = open(outputFile, 'w')
# Make a variable to omit output if we don't have additional permissions to
# apply.
bWrittenHeader = 0
for package_name in sorted(results):
if bWrittenHeader == 0:
bWrittenHeader = 1
fd.write('<?xml version="1.0" encoding="utf-8"?>\n<permissions>\n')
pass
if package_name in apps_redefine_base:
fd.write(' <!-- Additional permissions on top of %s -->\n' %
BASE_XML_FILENAME)
fd.write(' <privapp-permissions package="%s">\n' % package_name)
for p in results[package_name]:
fd.write(' <permission name="%s"/>\n' % p)
fd.write(' </privapp-permissions>\n')
fd.write('\n')
if bWrittenHeader == 1:
fd.write('</permissions>\n')
fd.close()
else:
fd.close()
os.remove(outputFile)
pass
def remove_base_permissions(priv_perms, base_perms):
"""Removes set of base_perms from set of priv_perms."""
if (not priv_perms) or (not base_perms):
return priv_perms
return set(priv_perms) - set(base_perms)
def get_priv_permissions(requested_perms, priv_perms):
"""Return only permissions that are in priv_perms set."""
return set(requested_perms).intersection(set(priv_perms))
def list_xml_files(directory):
"""Returns a list of all .xml files within a given directory.
Args:
directory: the directory to look for xml files in.
"""
xml_files = []
for dirName, subdirList, file_list in os.walk(directory):
for file in file_list:
if file.endswith('.xml'):
file_path = os.path.join(dirName, file)
xml_files.append(file_path)
return xml_files
def extract_pkg_and_requested_permissions(aapt, apk_path):
"""
Extract package name and list of requested permissions from the
dump of manifest file
"""
aapt_args = ['d', 'permissions', apk_path]
txt = aapt.call(aapt_args)
permissions = []
package_name = None
raw_lines = txt.split('\n')
for line in raw_lines:
regex = r"uses-permission.*: name='([\S]+)'"
matches = re.search(regex, line)
if matches:
name = matches.group(1)
permissions.append(name)
regex = r'package: ([\S]+)'
matches = re.search(regex, line)
if matches:
package_name = matches.group(1)
return {'package_name': package_name, 'permissions': permissions}
def extract_priv_permissions(aapt, apk_path):
"""Extract signature|privileged permissions from dump of manifest file."""
aapt_args = ['d', 'xmltree', apk_path, 'AndroidManifest.xml']
txt = aapt.call(aapt_args)
raw_lines = txt.split('\n')
n = len(raw_lines)
i = 0
permissions_list = []
while i < n:
line = raw_lines[i]
if line.find('E: permission (') != -1:
i += 1
name = None
level = None
while i < n:
line = raw_lines[i]
if line.find('E: ') != -1:
break
matches = re.search(ANDROID_NAME_REGEX, line)
if matches:
name = matches.group(1)
i += 1
continue
matches = re.search(ANDROID_PROTECTION_LEVEL_REGEX, line)
if matches:
level = int(matches.group(1), 16)
i += 1
continue
i += 1
if name and level and level & 0x12 == 0x12:
permissions_list.append(name)
else:
i += 1
return permissions_list
def parse_config_xml(base_xml, results):
"""Parse an XML file that will be used as base."""
dom = minidom.parse(base_xml)
nodes = dom.getElementsByTagName('privapp-permissions')
for node in nodes:
permissions = (node.getElementsByTagName('permission') +
node.getElementsByTagName('deny-permission'))
package_name = node.getAttribute('package')
plist = []
if package_name in results:
plist = results[package_name]
for p in permissions:
perm_name = p.getAttribute('name')
if perm_name:
plist.append(perm_name)
results[package_name] = plist
return results
def cleanup():
"""Cleans up temp files."""
for directory in temp_dirs:
shutil.rmtree(directory, ignore_errors=True)
for file in temp_files:
os.remove(file)
del temp_dirs[:]
del temp_files[:]
if __name__ == '__main__':
args = parse_args()
try:
tool_resources = Resources(
aapt_path=args.aapt,
output_xml=args.output_xml,
apks=args.apks
)
create_permission_file(tool_resources)
except MissingResourceError as e:
print(str(e), file=sys.stderr)
exit(1)
finally:
cleanup()