generate new public resources

This commit is contained in:
Sebastian Bachmann 2018-02-21 19:37:10 +01:00
parent a6404b3a90
commit 560cdabd75
14 changed files with 2615 additions and 3587 deletions

View File

@ -10,6 +10,7 @@ from androguard.core.bytecodes.apk import APK
from androguard.core.androconf import CONF
from androguard.core.bytecodes import mutf8
from androguard.core.bytecodes.dvm_types import TYPE_MAP_ITEM, ACCESS_FLAGS, TYPE_DESCRIPTOR
import sys
import re
@ -31,62 +32,6 @@ ODEX_FILE_MAGIC_35 = 'dey\n035\x00'
ODEX_FILE_MAGIC_36 = 'dey\n036\x00'
ODEX_FILE_MAGIC_37 = 'dey\n037\x00'
# https://source.android.com/devices/tech/dalvik/dex-format#type-codes
TYPE_MAP_ITEM = {
0x0: "TYPE_HEADER_ITEM",
0x1: "TYPE_STRING_ID_ITEM",
0x2: "TYPE_TYPE_ID_ITEM",
0x3: "TYPE_PROTO_ID_ITEM",
0x4: "TYPE_FIELD_ID_ITEM",
0x5: "TYPE_METHOD_ID_ITEM",
0x6: "TYPE_CLASS_DEF_ITEM",
0x1000: "TYPE_MAP_LIST",
0x1001: "TYPE_TYPE_LIST",
0x1002: "TYPE_ANNOTATION_SET_REF_LIST",
0x1003: "TYPE_ANNOTATION_SET_ITEM",
0x2000: "TYPE_CLASS_DATA_ITEM",
0x2001: "TYPE_CODE_ITEM",
0x2002: "TYPE_STRING_DATA_ITEM",
0x2003: "TYPE_DEBUG_INFO_ITEM",
0x2004: "TYPE_ANNOTATION_ITEM",
0x2005: "TYPE_ENCODED_ARRAY_ITEM",
0x2006: "TYPE_ANNOTATIONS_DIRECTORY_ITEM",
}
# https://source.android.com/devices/tech/dalvik/dex-format#access-flags
ACCESS_FLAGS = {
0x1: 'public',
0x2: 'private',
0x4: 'protected',
0x8: 'static',
0x10: 'final',
0x20: 'synchronized',
0x40: 'bridge',
0x80: 'varargs',
0x100: 'native',
0x200: 'interface',
0x400: 'abstract',
0x800: 'strictfp',
0x1000: 'synthetic',
0x4000: 'enum',
0x8000: 'unused',
0x10000: 'constructor',
0x20000: 'synchronized',
}
# https://source.android.com/devices/tech/dalvik/dex-format#typedescriptor
TYPE_DESCRIPTOR = {
'V': 'void',
'Z': 'boolean',
'B': 'byte',
'S': 'short',
'C': 'char',
'I': 'int',
'J': 'long',
'F': 'float',
'D': 'double',
}
# https://source.android.com/devices/tech/dalvik/dex-format#value-formats
VALUE_BYTE = 0x00 # (none; must be 0) ubyte[1] signed one-byte integer value
VALUE_SHORT = 0x02 # size - 1 (0..1) ubyte[size] signed two-byte integer value, sign-extended

View File

@ -0,0 +1,58 @@
# This file contains dictionaries used in the Dalvik Format.
# https://source.android.com/devices/tech/dalvik/dex-format#type-codes
TYPE_MAP_ITEM = {
0x0: "TYPE_HEADER_ITEM",
0x1: "TYPE_STRING_ID_ITEM",
0x2: "TYPE_TYPE_ID_ITEM",
0x3: "TYPE_PROTO_ID_ITEM",
0x4: "TYPE_FIELD_ID_ITEM",
0x5: "TYPE_METHOD_ID_ITEM",
0x6: "TYPE_CLASS_DEF_ITEM",
0x1000: "TYPE_MAP_LIST",
0x1001: "TYPE_TYPE_LIST",
0x1002: "TYPE_ANNOTATION_SET_REF_LIST",
0x1003: "TYPE_ANNOTATION_SET_ITEM",
0x2000: "TYPE_CLASS_DATA_ITEM",
0x2001: "TYPE_CODE_ITEM",
0x2002: "TYPE_STRING_DATA_ITEM",
0x2003: "TYPE_DEBUG_INFO_ITEM",
0x2004: "TYPE_ANNOTATION_ITEM",
0x2005: "TYPE_ENCODED_ARRAY_ITEM",
0x2006: "TYPE_ANNOTATIONS_DIRECTORY_ITEM",
}
# https://source.android.com/devices/tech/dalvik/dex-format#access-flags
ACCESS_FLAGS = {
0x1: 'public',
0x2: 'private',
0x4: 'protected',
0x8: 'static',
0x10: 'final',
0x20: 'synchronized',
0x40: 'bridge',
0x80: 'varargs',
0x100: 'native',
0x200: 'interface',
0x400: 'abstract',
0x800: 'strictfp',
0x1000: 'synthetic',
0x4000: 'enum',
0x8000: 'unused',
0x10000: 'constructor',
0x20000: 'synchronized',
}
# https://source.android.com/devices/tech/dalvik/dex-format#typedescriptor
TYPE_DESCRIPTOR = {
'V': 'void',
'Z': 'boolean',
'B': 'byte',
'S': 'short',
'C': 'char',
'I': 'int',
'J': 'long',
'F': 'float',
'D': 'double',
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

2
generators/README.md Normal file
View File

@ -0,0 +1,2 @@
These tools are used to make data useable for androguard, which is stored in
other repositories, locations, formats etc.

View File

@ -1,7 +1,6 @@
# Convert the Mappings from axplorer to JSON and convert to the format androguard uses.
# FIXME, we need to remove that from here, so we can generate them on install time
from androguard.core.bytecodes.dvm import TYPE_DESCRIPTOR
from androguard.core.bytecodes.dvm_types import TYPE_DESCRIPTOR
import os
import sys
import re

View File

@ -0,0 +1,24 @@
import requests
from lxml import etree
from collections import defaultdict
import json
import os
# At this URL, there should be the public.xml file
url = "https://raw.githubusercontent.com/aosp-mirror/platform_frameworks_base/master/core/res/res/values/public.xml"
r = requests.get(url)
if r.status_code == 200:
res = defaultdict(dict)
tree = etree.fromstring(r.text.encode("UTF-8"))
for m in tree.xpath('public'):
t = m.attrib['type']
name = m.attrib['name']
i = int(m.attrib['id'], 16)
res[t][name] = i
with open(os.path.join("androguard", "core", "resources", "public.json"), "w") as fp:
json.dump(res, fp, indent=" ")

View File

@ -58,6 +58,7 @@ setup(
# add the json files, residing in the api_specific_resources package
"androguard.core.api_specific_resources": ["aosp_permissions/*.json",
"api_permission_mappings/*.json"],
"androguard.core.resources": ["public.json"],
# Collect also the GUI files this way
"androguard.gui": ["annotation.ui", "search.ui", "androguard.ico"],
},

View File

@ -1,214 +0,0 @@
#!/usr/bin/env python
# This file is part of Androguard.
#
# Copyright (C) 2010, Anthony Desnos <desnos at t0t0.org>
# All rights reserved.
#
# 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.
from BeautifulSoup import BeautifulSoup, Tag
import os, sys, re
MANIFEST_PERMISSION_HTML = "docs/reference/android/Manifest.permission.html"
PERMS = {}
PERMS_RE = None
PERMS_API = {}
class Constant(object):
def __init__(self, name, perms, desc_return):
self.name = name
self.perms = perms
self.desc_return = desc_return
class Function(object):
def __init__(self, name, perms, desc_return):
self.name = name
self.perms = perms
self.desc_return = desc_return
def extractPerms(filename):
soup = BeautifulSoup(open(filename))
s = ""
for i in soup.findAll("table", attrs={'id': "constants"}):
for j in i.findChildren("tr"):
td = j.findChildren("td")
if td:
_type = str(td[0].text)
_name = str(td[1].text)
_desc = str(td[2].text)
PERMS[_name] = [_type, _desc]
PERMS_API[_name] = {}
s += _name + "|"
#PERMS_RE = re.compile(s[:-1])
def extractInformation(filename):
soup = BeautifulSoup(open(filename))
package = filename[filename.find("reference/android/"):][10:-5].replace(
"//", "/")
package = package.replace("/", ".")
for i in soup.findAll('a', attrs={'name': re.compile(".")}):
next_div = i.findNext("div")
perms = []
for perm in PERMS:
perm_access = next_div.findAll(text=re.compile(perm))
if perm_access:
perms.append(perm)
#print i.name, i.get("name"), perm_access
if perms:
element = None
descs = i.findNext("span", attrs={'class': 'normal'})
_descriptor_return = descs.__next__
_descriptor_return = _descriptor_return.replace('', '')
_descriptor_return = _descriptor_return.split()
_descriptor_return = ' '.join(str(_d) for _d in _descriptor_return)
if isinstance(descs.next.__next__, Tag):
_descriptor_return += " " + descs.next.next.text
if len(next_div.findNext("h4").findAll("span")) > 2:
element = Function(i.get("name"), perms, _descriptor_return)
else:
element = Constant(i.get("name"), perms, _descriptor_return)
for perm in perms:
if package not in PERMS_API[perm]:
PERMS_API[perm][package] = []
PERMS_API[perm][package].append(element)
def save_file(filename):
with open(filename, "w") as fd:
fd.write("PERMISSIONS = {\n")
for i in PERMS_API:
if len(PERMS_API[i]) > 0:
fd.write("\"%s\" : {\n" % i)
for package in PERMS_API[i]:
if len(PERMS_API[i][package]) > 0:
fd.write("\t\"%s\" : [\n" % package)
for j in PERMS_API[i][package]:
if isinstance(j, Function):
fd.write("\t\t[\"F\","
"\"" + j.name + "\"," + "\"" + j.desc_return +
"\"]" + ",\n")
else:
fd.write("\t\t[\"C\","
"\"" + j.name + "\"," + "\"" + j.desc_return +
"\"]" + ",\n")
if len(PERMS_API[i][package]) > 0:
fd.write("\t],\n")
if len(PERMS_API[i]) > 0:
fd.write("},\n\n")
fd.write("}")
BASE_DOCS = sys.argv[1]
extractPerms(BASE_DOCS + MANIFEST_PERMISSION_HTML)
ANDROID_PACKAGES = [
"accessibilityservice",
"accounts",
"animation",
"app",
"appwidget",
"bluetooth",
"content",
"database",
"drm",
"gesture",
"graphics",
"hardware",
"inputmethodservice",
"location",
"media",
"net",
"nfc",
"opengl",
"os",
"preference",
"provider",
"renderscript",
"sax",
"service",
"speech",
"telephony",
"text",
"util",
"view",
"webkit",
"widget",
]
ANDROID_PACKAGES2 = ["telephony"]
for i in ANDROID_PACKAGES:
for root, dirs, files in os.walk(BASE_DOCS + "docs/reference/android/" + i +
"/"):
for file in files:
print("Extracting from %s" % (root + "/" + file))
#extractInformation( "/home/pouik/Bureau/android/android-sdk-linux_86/docs/reference/android/accounts/AccountManager.html" )
extractInformation(root + "/" + file)
#BASE_DOCS + "docs/reference/android/telephony/TelephonyManager.html" )
#extractInformation( BASE_DOCS + "docs/reference/android/net/sip/SipAudioCall.html" ) #android/accounts/Account.html" ) #"docs/reference/android/accounts/AccountManager.html" )
for i in PERMS_API:
if len(PERMS_API[i]) > 0:
print("PERMISSION ", i)
for package in PERMS_API[i]:
print("\t package ", package)
for j in PERMS_API[i][package]:
if isinstance(j, Function):
print("\t\t function : ", j.name)
else:
print("\t\t constant : ", j.name)
save_file("./dvm_permissions_unformatted.py")
#for i in soup.findAll('a') : #, attrs={'name' : re.compile("ACTION")}):
# if i.get("name") != None:
# print i.name, i.get("name")#, i.findNextSlibing(text=re.compile("READ_PHONE_STATE"))
#for i in soup.findAll(text=re.compile("READ_PHONE_STATE")):
# print i, i.parent.name, i.findPrevious(re.compile('^A')), i.findPreviousSibling(re.compile('^A'))
# if i.contents != []:
# if i.contents[0] == "READ_PHONE_STATE":
# print "here", i.parent
# parent = i.parent
# while parent.name != "A":
# parent = parent.parent
# print "step", parent
# if "class" in parent:
# print "step2", parent["class"]
# time.sleep( 1 )
# print "end", previous.name

View File

@ -1,147 +0,0 @@
#!/usr/bin/env python
# This file is part of Androguard.
#
# Copyright (C) 2010, Anthony Desnos <desnos at t0t0.org>
# All rights reserved.
#
# 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.
import string
from dvm_permissions_unformatted import PERMISSIONS
from permissions_by_hand import PERMISSIONS_BY_HAND
BASIC_TYPES = {
"byte": "B",
"char": "C",
"double": "D",
"float": "F",
"int": "I",
"long": "J",
"short": "S",
"boolean": "B",
"void": "V",
}
ADVANCED_TYPES = {
"String": "Ljava/lang/String;",
"List": "Ljava/util/List;",
"AccountManagerFuture": "Landroid/accounts/AccountManagerFuture;",
"CellLocation": "Landroid/telephony/CellLocation;",
"Uri": "Landroid/net/Uri;",
"Cursor": "Landroid/database/Cursor;",
"Set": "Ljava/util/Set;",
"BluetoothServerSocket": "Landroid/bluetooth/BluetoothServerSocket;",
"BluetoothSocket": "Landroid/bluetooth/BluetoothSocket;",
"DownloadManager.Request": "Landroid/app/DownloadManager/Request;",
"PendingIntent": "Landroid/app/PendingIntent;",
"SmsManager": "Landroid/telephony/SmsManager;",
"Bitmap": "Landroid/graphics/Bitmap;",
"IBinder": "Landroid/os/IBinder;",
}
def translateDescParams(desc_params):
desc_params = desc_params.replace(" ", "")
buff = ""
for elem in desc_params.split(","):
if elem != "":
tab = ""
if "[" in elem:
tab = "[" * string.count(elem, "[")
elem = elem[:tab.find("[") - 2]
if elem not in BASIC_TYPES:
if elem in ADVANCED_TYPES:
buff += tab + ADVANCED_TYPES[elem] + " "
else:
buff += tab + "L" + elem.replace(".", "/") + "; "
else:
buff += tab + BASIC_TYPES[elem] + " "
buff = buff[:-1]
return buff
def translateDescReturn(desc_return):
buff = ""
for elem in desc_return.split(" "):
tab = ""
if "[" in elem:
tab = "[" * string.count(elem, "[")
elem = elem[:tab.find("[") - 2]
if elem in BASIC_TYPES:
buff += tab + BASIC_TYPES[elem] + " "
else:
if elem in ADVANCED_TYPES:
buff += tab + ADVANCED_TYPES[elem] + " "
else:
if "." in elem:
buff += tab + "L" + elem.replace(".", "/") + "; "
buff = buff[:-1]
return buff
def translateToCLASS(desc_params, desc_return):
print(desc_params, desc_return, end=' ')
buff = "(" + translateDescParams(desc_params[desc_params.find(
"(") + 1:-1]) + ")" + translateDescReturn(desc_return)
print("----->", buff)
return [desc_params[:desc_params.find("(")], buff]
def translateToCLASS2(constant_name, desc_return):
return [constant_name, translateDescReturn(desc_return)]
PERMISSIONS.update(PERMISSIONS_BY_HAND)
for perm in PERMISSIONS:
for package in PERMISSIONS[perm]:
for element in PERMISSIONS[perm][package]:
if element[0] == "F":
element.extend(translateToCLASS(element[1], element[2]))
elif element[0] == "C":
element.extend(translateToCLASS2(element[1], element[2]))
with open("./core/bytecodes/api_permissions.py", "w") as fd:
fd.write("DVM_PERMISSIONS_BY_PERMISSION = {\n")
for perm in PERMISSIONS:
fd.write("\"%s\" : {\n" % perm)
for package in PERMISSIONS[perm]:
fd.write("\t\"L%s;\" : [\n" % package.replace(".", "/"))
for element in PERMISSIONS[perm][package]:
fd.write("\t\t(\"%s\", \"%s\", \"%s\"),\n" %
(element[0], element[-2], element[-1]))
fd.write("\t],\n")
fd.write("},\n")
fd.write("}\n\n")
fd.write("DVM_PERMISSIONS_BY_ELEMENT = { \n")
for perm in PERMISSIONS:
for package in PERMISSIONS[perm]:
for element in PERMISSIONS[perm][package]:
fd.write("\t\"L%s;-%s-%s\" : \"%s\",\n" % (package.replace(
".", "/"), element[-2], element[-1], perm))
fd.write("}\n")

View File

@ -1,720 +0,0 @@
PERMISSIONS = {
"BIND_DEVICE_ADMIN": {
"android.app.admin.DeviceAdminReceiver": [
["C", "ACTION_DEVICE_ADMIN_ENABLED", "public static final String"],
],
},
"FACTORY_TEST": {
"android.content.pm.ApplicationInfo": [
["C", "FLAG_FACTORY_TEST", "public static final int"],
["C", "flags", "public int"],
],
"android.content.Intent": [
["C", "IntentResolution", "public static final String"],
["C", "ACTION_FACTORY_TEST", "public static final String"],
],
},
"BIND_INPUT_METHOD": {
"android.view.inputmethod.InputMethod": [
["C", "SERVICE_INTERFACE", "public static final String"],
],
},
"AUTHENTICATE_ACCOUNTS": {
"android.accounts.AccountManager": [
["F",
"addAccountExplicitly(android.accounts.Account, java.lang.String, android.os.Bundle)",
"public boolean"],
["F", "getPassword(android.accounts.Account)", "public String"],
["F", "getUserData(android.accounts.Account, java.lang.String)",
"public String"],
["F", "peekAuthToken(android.accounts.Account, java.lang.String)",
"public String"],
["F",
"setAuthToken(android.accounts.Account, java.lang.String, java.lang.String)",
"public void"],
["F", "setPassword(android.accounts.Account, java.lang.String)",
"public void"],
["F",
"setUserData(android.accounts.Account, java.lang.String, java.lang.String)",
"public void"],
],
},
"INTERNET": {
"android.drm.DrmErrorEvent": [
["C", "TYPE_NO_INTERNET_CONNECTION", "public static final int"],
],
},
"RECORD_AUDIO": {
"android.net.sip.SipAudioCall": [
["F", "startAudio()", "public void"],
],
},
"ACCESS_MOCK_LOCATION": {
"android.location.LocationManager": [
["F",
"addTestProvider(java.lang.String, boolean, boolean, boolean, boolean, boolean, boolean, boolean, int, int)",
"public void"],
["F", "clearTestProviderEnabled(java.lang.String)", "public void"],
["F", "clearTestProviderLocation(java.lang.String)", "public void"],
["F", "clearTestProviderStatus(java.lang.String)", "public void"],
["F", "removeTestProvider(java.lang.String)", "public void"],
["F", "setTestProviderEnabled(java.lang.String, boolean)",
"public void"],
["F",
"setTestProviderLocation(java.lang.String, android.location.Location)",
"public void"],
["F",
"setTestProviderStatus(java.lang.String, int, android.os.Bundle, long)",
"public void"],
],
},
"VIBRATE": {
"android.provider.Settings.System": [
["C", "VIBRATE_ON", "public static final String"],
],
"android.app.Notification": [
["C", "DEFAULT_VIBRATE", "public static final int"],
["C", "defaults", "public int"],
],
"android.app.Notification.Builder": [
["F", "setDefaults(int)", "public Notification.Builder"],
],
"android.media.AudioManager": [
["C", "EXTRA_RINGER_MODE", "public static final String"],
["C", "EXTRA_VIBRATE_SETTING", "public static final String"],
["C", "EXTRA_VIBRATE_TYPE", "public static final String"],
["C", "FLAG_REMOVE_SOUND_AND_VIBRATE", "public static final int"],
["C", "FLAG_VIBRATE", "public static final int"],
["C", "RINGER_MODE_VIBRATE", "public static final int"],
["C", "VIBRATE_SETTING_CHANGED_ACTION", "public static final String"
],
["C", "VIBRATE_SETTING_OFF", "public static final int"],
["C", "VIBRATE_SETTING_ON", "public static final int"],
["C", "VIBRATE_SETTING_ONLY_SILENT", "public static final int"],
["C", "VIBRATE_TYPE_NOTIFICATION", "public static final int"],
["C", "VIBRATE_TYPE_RINGER", "public static final int"],
["F", "getRingerMode()", "public int"],
["F", "getVibrateSetting(int)", "public int"],
["F", "setRingerMode(int)", "public void"],
["F", "setVibrateSetting(int, int)", "public void"],
["F", "shouldVibrate(int)", "public boolean"],
],
},
"GLOBAL_SEARCH": {
"android.app.SearchManager": [
["C", "EXTRA_SELECT_QUERY", "public static final String"],
["C", "INTENT_ACTION_GLOBAL_SEARCH", "public static final String"],
],
},
"BROADCAST_STICKY": {
"android.content.Context": [
["F", "removeStickyBroadcast(android.content.Intent)",
"public abstract void"],
["F", "sendStickyBroadcast(android.content.Intent)",
"public abstract void"],
],
"android.content.ContextWrapper": [
["F", "removeStickyBroadcast(android.content.Intent)", "public void"
],
["F", "sendStickyBroadcast(android.content.Intent)", "public void"],
],
},
"KILL_BACKGROUND_PROCESSES": {
"android.app.ActivityManager": [
["F", "killBackgroundProcesses(java.lang.String)", "public void"],
],
},
"SET_TIME_ZONE": {
"android.app.AlarmManager": [
["F", "setTimeZone(java.lang.String)", "public void"],
],
},
"BLUETOOTH_ADMIN": {
"android.bluetooth.BluetoothAdapter": [
["F", "cancelDiscovery()", "public boolean"],
["F", "disable()", "public boolean"],
["F", "enable()", "public boolean"],
["F", "setName(java.lang.String)", "public boolean"],
["F", "startDiscovery()", "public boolean"],
],
},
"CAMERA": {
"android.hardware.Camera.ErrorCallback": [
["F", "onError(int, android.hardware.Camera)",
"public abstract void"],
],
"android.view.KeyEvent": [
["C", "KEYCODE_CAMERA", "public static final int"],
],
"android.bluetooth.BluetoothClass.Device": [
["C", "AUDIO_VIDEO_VIDEO_CAMERA", "public static final int"],
],
"android.provider.MediaStore": [
["C", "INTENT_ACTION_STILL_IMAGE_CAMERA",
"public static final String"],
["C", "INTENT_ACTION_VIDEO_CAMERA", "public static final String"],
],
"android.hardware.Camera.CameraInfo": [
["C", "CAMERA_FACING_BACK", "public static final int"],
["C", "CAMERA_FACING_FRONT", "public static final int"],
["C", "facing", "public int"],
],
"android.provider.ContactsContract.StatusColumns": [
["C", "CAPABILITY_HAS_CAMERA", "public static final int"],
],
"android.hardware.Camera.Parameters": [
["F", "setRotation(int)", "public void"],
],
"android.media.MediaRecorder.VideoSource": [
["C", "CAMERA", "public static final int"],
],
"android.content.Intent": [
["C", "IntentResolution", "public static final String"],
["C", "ACTION_CAMERA_BUTTON", "public static final String"],
],
"android.content.pm.PackageManager": [
["C", "FEATURE_CAMERA", "public static final String"],
["C", "FEATURE_CAMERA_AUTOFOCUS", "public static final String"],
["C", "FEATURE_CAMERA_FLASH", "public static final String"],
["C", "FEATURE_CAMERA_FRONT", "public static final String"],
],
"android.hardware.Camera": [
["C", "CAMERA_ERROR_SERVER_DIED", "public static final int"],
["C", "CAMERA_ERROR_UNKNOWN", "public static final int"],
["F", "setDisplayOrientation(int)", "public final void"],
],
},
"SET_WALLPAPER": {
"android.content.Intent": [
["C", "IntentResolution", "public static final String"],
["C", "ACTION_SET_WALLPAPER", "public static final String"],
],
"android.app.WallpaperManager": [
["C", "WALLPAPER_PREVIEW_META_DATA", "public static final String"],
],
},
"WAKE_LOCK": {
"android.net.sip.SipAudioCall": [
["F", "startAudio()", "public void"],
],
"android.media.MediaPlayer": [
["F", "setWakeMode(android.content.Context, int)", "public void"],
],
"android.os.PowerManager": [
["C", "ACQUIRE_CAUSES_WAKEUP", "public static final int"],
["C", "FULL_WAKE_LOCK", "public static final int"],
["C", "ON_AFTER_RELEASE", "public static final int"],
["C", "PARTIAL_WAKE_LOCK", "public static final int"],
["C", "SCREEN_BRIGHT_WAKE_LOCK", "public static final int"],
["C", "SCREEN_DIM_WAKE_LOCK", "public static final int"],
["F", "newWakeLock(int, java.lang.String)",
"public PowerManager.WakeLock"],
],
},
"MANAGE_ACCOUNTS": {
"android.accounts.AccountManager": [
["F",
"addAccount(java.lang.String, java.lang.String, java.lang.String[], android.os.Bundle, android.app.Activity, android.accounts.AccountManagerCallback<android.os.Bundle>, android.os.Handler)",
"public AccountManagerFuture"],
["F", "clearPassword(android.accounts.Account)", "public void"],
["F",
"confirmCredentials(android.accounts.Account, android.os.Bundle, android.app.Activity, android.accounts.AccountManagerCallback<android.os.Bundle>, android.os.Handler)",
"public AccountManagerFuture"],
["F",
"editProperties(java.lang.String, android.app.Activity, android.accounts.AccountManagerCallback<android.os.Bundle>, android.os.Handler)",
"public AccountManagerFuture"],
["F",
"getAuthTokenByFeatures(java.lang.String, java.lang.String, java.lang.String[], android.app.Activity, android.os.Bundle, android.os.Bundle, android.accounts.AccountManagerCallback<android.os.Bundle>, android.os.Handler)",
"public AccountManagerFuture"],
["F", "invalidateAuthToken(java.lang.String, java.lang.String)",
"public void"],
["F",
"removeAccount(android.accounts.Account, android.accounts.AccountManagerCallback<java.lang.Boolean>, android.os.Handler)",
"public AccountManagerFuture"],
["F",
"updateCredentials(android.accounts.Account, java.lang.String, android.os.Bundle, android.app.Activity, android.accounts.AccountManagerCallback<android.os.Bundle>, android.os.Handler)",
"public AccountManagerFuture"],
],
},
"NFC": {
"android.inputmethodservice.InputMethodService": [
["C", "SoftInputView", "public static final int"],
["C", "CandidatesView", "public static final int"],
["C", "FullscreenMode", "public static final int"],
["C", "GeneratingText", "public static final int"],
],
"android.nfc.tech.NfcA": [
["F", "close()", "public void"],
["F", "connect()", "public void"],
["F", "get(android.nfc.Tag)", "public static NfcA"],
["F", "transceive(byte[])", "public byte[]"],
],
"android.nfc.tech.NfcB": [
["F", "close()", "public void"],
["F", "connect()", "public void"],
["F", "get(android.nfc.Tag)", "public static NfcB"],
["F", "transceive(byte[])", "public byte[]"],
],
"android.nfc.NfcAdapter": [
["C", "ACTION_TECH_DISCOVERED", "public static final String"],
["F", "disableForegroundDispatch(android.app.Activity)",
"public void"],
["F", "disableForegroundNdefPush(android.app.Activity)",
"public void"],
["F",
"enableForegroundDispatch(android.app.Activity, android.app.PendingIntent, android.content.IntentFilter[], java.lang.String[][])",
"public void"],
["F",
"enableForegroundNdefPush(android.app.Activity, android.nfc.NdefMessage)",
"public void"],
["F", "getDefaultAdapter()", "public static NfcAdapter"],
["F", "getDefaultAdapter(android.content.Context)",
"public static NfcAdapter"],
["F", "isEnabled()", "public boolean"],
],
"android.nfc.tech.NfcF": [
["F", "close()", "public void"],
["F", "connect()", "public void"],
["F", "get(android.nfc.Tag)", "public static NfcF"],
["F", "transceive(byte[])", "public byte[]"],
],
"android.nfc.tech.NdefFormatable": [
["F", "close()", "public void"],
["F", "connect()", "public void"],
["F", "format(android.nfc.NdefMessage)", "public void"],
["F", "formatReadOnly(android.nfc.NdefMessage)", "public void"],
],
"android.app.Activity": [
["C", "Fragments", "public static final int"],
["C", "ActivityLifecycle", "public static final int"],
["C", "ConfigurationChanges", "public static final int"],
["C", "StartingActivities", "public static final int"],
["C", "SavingPersistentState", "public static final int"],
["C", "Permissions", "public static final int"],
["C", "ProcessLifecycle", "public static final int"],
],
"android.nfc.tech.MifareClassic": [
["C", "KEY_NFC_FORUM", "public static final byte[]"],
["F", "authenticateSectorWithKeyA(int, byte[])", "public boolean"],
["F", "authenticateSectorWithKeyB(int, byte[])", "public boolean"],
["F", "close()", "public void"],
["F", "connect()", "public void"],
["F", "decrement(int, int)", "public void"],
["F", "increment(int, int)", "public void"],
["F", "readBlock(int)", "public byte[]"],
["F", "restore(int)", "public void"],
["F", "transceive(byte[])", "public byte[]"],
["F", "transfer(int)", "public void"],
["F", "writeBlock(int, byte[])", "public void"],
],
"android.nfc.Tag": [
["F", "getTechList()", "public String[]"],
],
"android.app.Service": [
["C", "WhatIsAService", "public static final int"],
["C", "ServiceLifecycle", "public static final int"],
["C", "Permissions", "public static final int"],
["C", "ProcessLifecycle", "public static final int"],
["C", "LocalServiceSample", "public static final int"],
["C", "RemoteMessengerServiceSample", "public static final int"],
],
"android.nfc.NfcManager": [
["F", "getDefaultAdapter()", "public NfcAdapter"],
],
"android.nfc.tech.MifareUltralight": [
["F", "close()", "public void"],
["F", "connect()", "public void"],
["F", "readPages(int)", "public byte[]"],
["F", "transceive(byte[])", "public byte[]"],
["F", "writePage(int, byte[])", "public void"],
],
"android.nfc.tech.NfcV": [
["F", "close()", "public void"],
["F", "connect()", "public void"],
["F", "get(android.nfc.Tag)", "public static NfcV"],
["F", "transceive(byte[])", "public byte[]"],
],
"android.nfc.tech.TagTechnology": [
["F", "close()", "public abstract void"],
["F", "connect()", "public abstract void"],
],
"android.preference.PreferenceActivity": [
["C", "SampleCode", "public static final String"],
],
"android.content.pm.PackageManager": [
["C", "FEATURE_NFC", "public static final String"],
],
"android.content.Context": [
["C", "NFC_SERVICE", "public static final String"],
],
"android.nfc.tech.Ndef": [
["C", "NFC_FORUM_TYPE_1", "public static final String"],
["C", "NFC_FORUM_TYPE_2", "public static final String"],
["C", "NFC_FORUM_TYPE_3", "public static final String"],
["C", "NFC_FORUM_TYPE_4", "public static final String"],
["F", "close()", "public void"],
["F", "connect()", "public void"],
["F", "getType()", "public String"],
["F", "isWritable()", "public boolean"],
["F", "makeReadOnly()", "public boolean"],
["F", "writeNdefMessage(android.nfc.NdefMessage)", "public void"],
],
"android.nfc.tech.IsoDep": [
["F", "close()", "public void"],
["F", "connect()", "public void"],
["F", "setTimeout(int)", "public void"],
["F", "transceive(byte[])", "public byte[]"],
],
},
"ACCESS_FINE_LOCATION": {
"android.telephony.TelephonyManager": [
["F", "getCellLocation()", "public CellLocation"],
],
"android.location.LocationManager": [
["C", "GPS_PROVIDER", "public static final String"],
["C", "NETWORK_PROVIDER", "public static final String"],
["C", "PASSIVE_PROVIDER", "public static final String"],
["F", "addGpsStatusListener(android.location.GpsStatus.Listener)",
"public boolean"],
["F", "addNmeaListener(android.location.GpsStatus.NmeaListener)",
"public boolean"],
],
},
"REORDER_TASKS": {
"android.app.ActivityManager": [
["F", "moveTaskToFront(int, int)", "public void"],
],
},
"MODIFY_AUDIO_SETTINGS": {
"android.net.sip.SipAudioCall": [
["F", "setSpeakerMode(boolean)", "public void"],
],
"android.media.AudioManager": [
["F", "startBluetoothSco()", "public void"],
["F", "stopBluetoothSco()", "public void"],
],
},
"READ_PHONE_STATE": {
"android.telephony.TelephonyManager": [
["C", "ACTION_PHONE_STATE_CHANGED", "public static final String"],
["F", "getDeviceId()", "public String"],
["F", "getDeviceSoftwareVersion()", "public String"],
["F", "getLine1Number()", "public String"],
["F", "getSimSerialNumber()", "public String"],
["F", "getSubscriberId()", "public String"],
["F", "getVoiceMailAlphaTag()", "public String"],
["F", "getVoiceMailNumber()", "public String"],
],
"android.telephony.PhoneStateListener": [
["C", "LISTEN_CALL_FORWARDING_INDICATOR", "public static final int"
],
["C", "LISTEN_CALL_STATE", "public static final int"],
["C", "LISTEN_DATA_ACTIVITY", "public static final int"],
["C", "LISTEN_MESSAGE_WAITING_INDICATOR", "public static final int"
],
["C", "LISTEN_SIGNAL_STRENGTH", "public static final int"],
],
"android.os.Build.VERSION_CODES": [
["C", "DONUT", "public static final int"],
],
},
"BIND_WALLPAPER": {
"android.service.wallpaper.WallpaperService": [
["C", "SERVICE_INTERFACE", "public static final String"],
],
},
"DUMP": {
"android.os.Debug": [
["F",
"dumpService(java.lang.String, java.io.FileDescriptor, java.lang.String[])",
"public static boolean"],
],
"android.os.IBinder": [
["C", "DUMP_TRANSACTION", "public static final int"],
],
},
"USE_CREDENTIALS": {
"android.accounts.AccountManager": [
["F",
"blockingGetAuthToken(android.accounts.Account, java.lang.String, boolean)",
"public String"],
["F",
"getAuthToken(android.accounts.Account, java.lang.String, android.os.Bundle, android.app.Activity, android.accounts.AccountManagerCallback<android.os.Bundle>, android.os.Handler)",
"public AccountManagerFuture"],
["F",
"getAuthToken(android.accounts.Account, java.lang.String, boolean, android.accounts.AccountManagerCallback<android.os.Bundle>, android.os.Handler)",
"public AccountManagerFuture"],
["F", "invalidateAuthToken(java.lang.String, java.lang.String)",
"public void"],
],
},
"ACCESS_COARSE_LOCATION": {
"android.telephony.TelephonyManager": [
["F", "getCellLocation()", "public CellLocation"],
],
"android.telephony.PhoneStateListener": [
["C", "LISTEN_CELL_LOCATION", "public static final int"],
],
"android.location.LocationManager": [
["C", "NETWORK_PROVIDER", "public static final String"],
],
},
"RECEIVE_BOOT_COMPLETED": {
"android.content.Intent": [
["C", "ACTION_BOOT_COMPLETED", "public static final String"],
],
},
"SET_ALARM": {
"android.provider.AlarmClock": [
["C", "ACTION_SET_ALARM", "public static final String"],
["C", "EXTRA_HOUR", "public static final String"],
["C", "EXTRA_MESSAGE", "public static final String"],
["C", "EXTRA_MINUTES", "public static final String"],
["C", "EXTRA_SKIP_UI", "public static final String"],
],
},
"PROCESS_OUTGOING_CALLS": {
"android.content.Intent": [
["C", "ACTION_NEW_OUTGOING_CALL", "public static final String"],
],
},
"GET_TASKS": {
"android.app.ActivityManager": [
["F", "getRecentTasks(int, int)", "public List"],
["F", "getRunningTasks(int)", "public List"],
],
},
"SET_TIME": {
"android.app.AlarmManager": [
["F", "setTime(long)", "public void"],
["F", "setTimeZone(java.lang.String)", "public void"],
],
},
"ACCESS_WIFI_STATE": {
"android.net.sip.SipAudioCall": [
["F", "startAudio()", "public void"],
],
},
"READ_HISTORY_BOOKMARKS": {
"android.provider.Browser": [
["C", "BOOKMARKS_URI", "public static final Uri"],
["C", "SEARCHES_URI", "public static final Uri"],
["F",
"addSearchUrl(android.content.ContentResolver, java.lang.String)",
"public static final void"],
["F", "canClearHistory(android.content.ContentResolver)",
"public static final boolean"],
["F", "getAllBookmarks(android.content.ContentResolver)",
"public static final Cursor"],
["F", "getAllVisitedUrls(android.content.ContentResolver)",
"public static final Cursor"],
["F",
"requestAllIcons(android.content.ContentResolver, java.lang.String, android.webkit.WebIconDatabase.IconListener)",
"public static final void"],
["F", "truncateHistory(android.content.ContentResolver)",
"public static final void"],
["F",
"updateVisitedHistory(android.content.ContentResolver, java.lang.String, boolean)",
"public static final void"],
],
},
"STATUS_BAR": {
"android.view.View.OnSystemUiVisibilityChangeListener": [
["F", "onSystemUiVisibilityChange(int)", "public abstract void"],
],
"android.view.View": [
["C", "STATUS_BAR_HIDDEN", "public static final int"],
["C", "STATUS_BAR_VISIBLE", "public static final int"],
],
"android.view.WindowManager.LayoutParams": [
["C", "TYPE_STATUS_BAR", "public static final int"],
["C", "TYPE_STATUS_BAR_PANEL", "public static final int"],
["C", "systemUiVisibility", "public int"],
["C", "type", "public int"],
],
},
"READ_LOGS": {
"android.os.DropBoxManager": [
["C", "ACTION_DROPBOX_ENTRY_ADDED", "public static final String"],
["F", "getNextEntry(java.lang.String, long)",
"public DropBoxManager.Entry"],
],
},
"BLUETOOTH": {
"android.os.Process": [
["C", "BLUETOOTH_GID", "public static final int"],
],
"android.content.pm.PackageManager": [
["C", "FEATURE_BLUETOOTH", "public static final String"],
],
"android.media.AudioManager": [
["C", "ROUTE_BLUETOOTH", "public static final int"],
["C", "ROUTE_BLUETOOTH_A2DP", "public static final int"],
["C", "ROUTE_BLUETOOTH_SCO", "public static final int"],
],
"android.provider.Settings.System": [
["C", "AIRPLANE_MODE_RADIOS", "public static final String"],
["C", "BLUETOOTH_DISCOVERABILITY", "public static final String"],
["C", "BLUETOOTH_DISCOVERABILITY_TIMEOUT",
"public static final String"],
["C", "BLUETOOTH_ON", "public static final String"],
["C", "RADIO_BLUETOOTH", "public static final String"],
["C", "VOLUME_BLUETOOTH_SCO", "public static final String"],
],
"android.provider.Settings": [
["C", "ACTION_BLUETOOTH_SETTINGS", "public static final String"],
],
"android.bluetooth.BluetoothAdapter": [
["C", "ACTION_CONNECTION_STATE_CHANGED",
"public static final String"],
["C", "ACTION_DISCOVERY_FINISHED", "public static final String"],
["C", "ACTION_DISCOVERY_STARTED", "public static final String"],
["C", "ACTION_LOCAL_NAME_CHANGED", "public static final String"],
["C", "ACTION_REQUEST_DISCOVERABLE", "public static final String"],
["C", "ACTION_REQUEST_ENABLE", "public static final String"],
["C", "ACTION_SCAN_MODE_CHANGED", "public static final String"],
["C", "ACTION_STATE_CHANGED", "public static final String"],
["F", "cancelDiscovery()", "public boolean"],
["F", "disable()", "public boolean"],
["F", "enable()", "public boolean"],
["F", "getAddress()", "public String"],
["F", "getBondedDevices()", "public Set"],
["F", "getName()", "public String"],
["F", "getScanMode()", "public int"],
["F", "getState()", "public int"],
["F", "isDiscovering()", "public boolean"],
["F", "isEnabled()", "public boolean"],
["F",
"listenUsingInsecureRfcommWithServiceRecord(java.lang.String, java.util.UUID)",
"public BluetoothServerSocket"],
["F",
"listenUsingRfcommWithServiceRecord(java.lang.String, java.util.UUID)",
"public BluetoothServerSocket"],
["F", "setName(java.lang.String)", "public boolean"],
["F", "startDiscovery()", "public boolean"],
],
"android.bluetooth.BluetoothProfile": [
["F", "getConnectedDevices()", "public abstract List"],
["F", "getConnectionState(android.bluetooth.BluetoothDevice)",
"public abstract int"],
["F", "getDevicesMatchingConnectionStates(int[])",
"public abstract List"],
],
"android.bluetooth.BluetoothHeadset": [
["C", "ACTION_AUDIO_STATE_CHANGED", "public static final String"],
["C", "ACTION_CONNECTION_STATE_CHANGED",
"public static final String"],
["C", "ACTION_VENDOR_SPECIFIC_HEADSET_EVENT",
"public static final String"],
["F", "getConnectedDevices()", "public List"],
["F", "getConnectionState(android.bluetooth.BluetoothDevice)",
"public int"],
["F", "getDevicesMatchingConnectionStates(int[])", "public List"],
["F", "isAudioConnected(android.bluetooth.BluetoothDevice)",
"public boolean"],
["F", "startVoiceRecognition(android.bluetooth.BluetoothDevice)",
"public boolean"],
["F", "stopVoiceRecognition(android.bluetooth.BluetoothDevice)",
"public boolean"],
],
"android.bluetooth.BluetoothDevice": [
["C", "ACTION_ACL_CONNECTED", "public static final String"],
["C", "ACTION_ACL_DISCONNECTED", "public static final String"],
["C", "ACTION_ACL_DISCONNECT_REQUESTED",
"public static final String"],
["C", "ACTION_BOND_STATE_CHANGED", "public static final String"],
["C", "ACTION_CLASS_CHANGED", "public static final String"],
["C", "ACTION_FOUND", "public static final String"],
["C", "ACTION_NAME_CHANGED", "public static final String"],
["F", "createInsecureRfcommSocketToServiceRecord(java.util.UUID)",
"public BluetoothSocket"],
["F", "createRfcommSocketToServiceRecord(java.util.UUID)",
"public BluetoothSocket"],
["F", "getBluetoothClass()", "public BluetoothClass"],
["F", "getBondState()", "public int"],
["F", "getName()", "public String"],
],
"android.provider.Settings.Secure": [
["C", "BLUETOOTH_ON", "public static final String"],
],
"android.bluetooth.BluetoothA2dp": [
["C", "ACTION_CONNECTION_STATE_CHANGED",
"public static final String"],
["C", "ACTION_PLAYING_STATE_CHANGED", "public static final String"],
["F", "getConnectedDevices()", "public List"],
["F", "getConnectionState(android.bluetooth.BluetoothDevice)",
"public int"],
["F", "getDevicesMatchingConnectionStates(int[])", "public List"],
["F", "isA2dpPlaying(android.bluetooth.BluetoothDevice)",
"public boolean"],
],
"android.bluetooth.BluetoothAssignedNumbers": [
["C", "BLUETOOTH_SIG", "public static final int"],
],
},
"WRITE_HISTORY_BOOKMARKS": {
"android.provider.Browser": [
["C", "BOOKMARKS_URI", "public static final Uri"],
["C", "SEARCHES_URI", "public static final Uri"],
["F",
"addSearchUrl(android.content.ContentResolver, java.lang.String)",
"public static final void"],
["F", "clearHistory(android.content.ContentResolver)",
"public static final void"],
["F", "clearSearches(android.content.ContentResolver)",
"public static final void"],
["F",
"deleteFromHistory(android.content.ContentResolver, java.lang.String)",
"public static final void"],
["F",
"deleteHistoryTimeFrame(android.content.ContentResolver, long, long)",
"public static final void"],
["F", "truncateHistory(android.content.ContentResolver)",
"public static final void"],
["F",
"updateVisitedHistory(android.content.ContentResolver, java.lang.String, boolean)",
"public static final void"],
],
},
"ACCOUNT_MANAGER": {
"android.accounts.AccountManager": [
["C", "KEY_ACCOUNT_MANAGER_RESPONSE", "public static final String"],
],
},
"GET_ACCOUNTS": {
"android.accounts.AccountManager": [
["F", "getAccounts()", "public Account[]"],
["F", "getAccountsByType(java.lang.String)", "public Account[]"],
["F",
"getAccountsByTypeAndFeatures(java.lang.String, java.lang.String[], android.accounts.AccountManagerCallback<android.accounts.Account[]>, android.os.Handler)",
"public AccountManagerFuture"],
["F",
"hasFeatures(android.accounts.Account, java.lang.String[], android.accounts.AccountManagerCallback<java.lang.Boolean>, android.os.Handler)",
"public AccountManagerFuture"],
],
},
"WRITE_EXTERNAL_STORAGE": {
"android.os.Build.VERSION_CODES": [
["C", "DONUT", "public static final int"],
],
"android.app.DownloadManager.Request": [
["F", "setDestinationUri(android.net.Uri)",
"public DownloadManager.Request"],
],
},
"REBOOT": {
"android.os.RecoverySystem": [
["F", "installPackage(android.content.Context, java.io.File)",
"public static void"],
["F", "rebootWipeUserData(android.content.Context)",
"public static void"],
],
"android.content.Intent": [
["C", "IntentResolution", "public static final String"],
["C", "ACTION_REBOOT", "public static final String"],
],
"android.os.PowerManager": [
["F", "reboot(java.lang.String)", "public void"],
],
},
}

View File

@ -1,33 +0,0 @@
PERMISSIONS_BY_HAND = {
"SEND_SMS": {
"android.telephony.SmsManager": [
["F", "getDefault()", "static SmsManager"],
["F",
"sendDataMessage(java.lang.String, java.lang.String, short, byte[], PendingIntent, PendingIntent)",
"void"],
# [ "F", "sendMultipartTextMessage(String destinationAddress, String scAddress, ArrayList<String> parts, ArrayList<PendingIntent> sentIntents, ArrayList<PendingIntent> deliveryIntents", "void" ],
["F",
"sendTextMessage(java.lang.String, java.lang.String, java.lang.String, PendingIntent, PendingIntent)",
"void"],
],
"android.telephony.gsm.SmsManager": [
["F", "getDefault()", "static android.telephony.gsm.SmsManager"],
["F",
"sendDataMessage(java.lang.String, java.lang.String, short, byte[], PendingIntent, PendingIntent)",
"void"],
# [ "F", "sendMultipartTextMessage(String destinationAddress, String scAddress, ArrayList<String> parts, ArrayList<PendingIntent> sentIntents, ArrayList<PendingIntent> deliveryIntents", "void" ],
["F",
"sendTextMessage(java.lang.String, java.lang.String, java.lang.String, PendingIntent, PendingIntent)",
"void"],
],
},
"SET_WALLPAPER":
{"android.app.WallpaperManager": [
["F", "setBitmap(Bitmap)", "void"],
], },
"READ_CONTACTS": {
"android.provider.ContactsContract$CommonDataKinds$Phone": [
["C", "CONTENT_URI", "Uri"]
],
},
}

View File

@ -1,230 +0,0 @@
#!/usr/bin/env python
# This file is part of Androguard.
#
# This is a tool to extract permissions and permission groups from Android Open Source Project.
# The information about the permissions and permission groups is appended to a file, which is
# later used in Androguard project.
#
# Author: Yury Zhauniarovich
#
#
# 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.
import os, re, codecs
from xml.dom import minidom
from xml.parsers.expat import ExpatError
PATH_TO_AOSP_ROOT = "" # path to AOSP folder
AOSP_PERMISSION_MODULE_NAME = "aosp_permissions"
AOSP_PERMISSION_MODULE_PATH = "../../androguard/core/api_specific_resources/aosp_permissions/" # where to append the results
SDK_VERSION_PATTERN = re.compile(
"\s*PLATFORM_SDK_VERSION\s*:=\s*(?P<sdk_version>\d{1,3})\s*") # hope Android will get 3digit version number :)
PLATFORM_VERSION_PATTERN = re.compile(
"\s*PLATFORM_VERSION\s*:=\s*(?P<platform_version>.+)\s*") # just to add as a comment from which version the parsing has happened
ANDROID_MANIFEST_NAME = "AndroidManifest.xml"
STRINGS_REL_PATH = "res/values/strings.xml"
PLATFORM_VERSIONS_FILE_REL_PATH = "build/core/version_defaults.mk"
NS_ANDROID_URI = "http://schemas.android.com/apk/res/android"
AOSP_PERMISSIONS_PARAM_NAME = "AOSP_PERMISSIONS"
AOSP_PERMISSION_GROUPS_PARAM_NAME = "AOSP_PERMISSION_GROUPS"
def getPlatformVersions(aosp_root_dir):
sdk_version = None
platform_version = None
version_file_path = os.path.join(aosp_root_dir,
PLATFORM_VERSIONS_FILE_REL_PATH)
if os.path.isfile(version_file_path):
with open(version_file_path, 'r') as ver_file:
lines = ver_file.readlines()
for line in lines:
sdk_version_match = SDK_VERSION_PATTERN.match(line)
if sdk_version_match:
sdk_version = sdk_version_match.group('sdk_version')
continue
platform_version_match = PLATFORM_VERSION_PATTERN.match(line)
if platform_version_match:
platform_version = platform_version_match.group(
'platform_version')
continue
return platform_version, sdk_version
def get_all_dirs_with_manifest(root_dir_path):
dir_list = list()
for root, dirs, files in os.walk(root_dir_path):
for name in files:
if name == ANDROID_MANIFEST_NAME:
dir_list.append(root)
return dir_list
def get_permission_details(manifest_dir):
perms = {}
perm_groups = {}
dstrings = {}
strings_document = None
strings_document_path = os.path.join(manifest_dir, STRINGS_REL_PATH)
if os.path.exists(strings_document_path):
print("Parsing file: %s" % strings_document_path)
strings_document = None
try:
strings_document = minidom.parse(strings_document_path)
except ExpatError:
with open(strings_document_path, 'r') as xml_file:
xml_string = xml_file.read()
xml_string = xml_string[xml_string.find(
'<?xml version="1.0" encoding="utf-8"?>'):]
strings_document = minidom.parseString(xml_string)
# loading strings into memory
dstrings = {}
for i in strings_document.getElementsByTagName("string"):
try:
dstrings[i.getAttribute("name")] = i.firstChild.data
except AttributeError:
pass
manifest_path = os.path.join(manifest_dir, ANDROID_MANIFEST_NAME)
print("Working with file: %s" % manifest_path)
# getting permissions
manifest_document = None
try:
manifest_document = minidom.parse(manifest_path)
except ExpatError:
with open(manifest_path, 'r') as xml_file:
xml_string = xml_file.read()
xml_string = xml_string[xml_string.find(
'<?xml version="1.0" encoding="utf-8"?>'):]
manifest_document = minidom.parseString(xml_string)
for i in manifest_document.getElementsByTagName("permission"):
name = i.getAttributeNS(NS_ANDROID_URI, "name")
protection_level = i.getAttributeNS(NS_ANDROID_URI, "protectionLevel")
permission_group = i.getAttributeNS(NS_ANDROID_URI, "permissionGroup")
label = ""
label_string_id = i.getAttributeNS(NS_ANDROID_URI, "label")[8:]
if label_string_id != "":
label = dstrings.get(label_string_id, "")
description = ""
description_string_id = i.getAttributeNS(NS_ANDROID_URI,
"description")[8:]
if description_string_id != "":
description = dstrings.get(description_string_id, "")
# removing auxiliary symbols
label = ' '.join(label.split())
description = ' '.join(description.split())
perms[name] = {
"label": label,
"description": description,
"protectionLevel": protection_level,
"permissionGroup": permission_group
}
# getting permission groups
for i in manifest_document.getElementsByTagName("permission-group"):
name = i.getAttributeNS(NS_ANDROID_URI, "name")
label = ""
label_string_id = i.getAttributeNS(NS_ANDROID_URI, "label")[8:]
if label_string_id != "":
label = dstrings.get(label_string_id, "")
description = ""
description_string_id = i.getAttributeNS(NS_ANDROID_URI,
"description")[8:]
if description_string_id != "":
description = dstrings.get(description_string_id, "")
# removing auxiliary symbols
label = ' '.join(label.split())
description = ' '.join(description.split())
perm_groups[name] = {"label": label, "description": description}
return perms, perm_groups
print("Starting analysis [%s] ..." % PATH_TO_AOSP_ROOT)
platform_version, sdk_version = getPlatformVersions(
aosp_root_dir=PATH_TO_AOSP_ROOT)
print("Detected sdk_version [%s], platform_version [%s]..." % (platform_version,
sdk_version))
if sdk_version is None:
print("Cannot detect SDK version. Exiting!")
exit(1)
print("Checking if we already have the file with the version...")
perms_module_name = "%s_api%s.py" % (AOSP_PERMISSION_MODULE_NAME, sdk_version)
perms_module_path = os.path.join(AOSP_PERMISSION_MODULE_PATH, perms_module_name)
if os.path.exists(perms_module_path):
print("API specific file for this version already exists!")
print("If you want create a file for newer version, please, delete file: %s" % perms_module_path)
exit(1)
permissions = {}
permission_groups = {}
print("Searching aosp for all manifest files...")
dirs_with_manifest = get_all_dirs_with_manifest(root_dir_path=PATH_TO_AOSP_ROOT)
for m_dir in dirs_with_manifest:
perms, perm_groups = get_permission_details(m_dir)
if perms:
permissions.update(perms)
if perm_groups:
permission_groups.update(perm_groups)
# print "Permission:\n", permissions
# print "Permission Groups:\n", permission_groups
print("Checking if folder exists...")
if not os.path.exists(AOSP_PERMISSION_MODULE_PATH):
os.makedirs(AOSP_PERMISSION_MODULE_PATH)
print("Appending found information to the permission file...")
with codecs.open(perms_module_path, 'w', 'utf-8') as perm_py_module:
perm_py_module.write("#!/usr/bin/python\n")
perm_py_module.write("# -*- coding: %s -*-\n" % "utf-8")
perm_py_module.write("#################################################\n")
perm_py_module.write("### Extracted from platform version: %s \n" %
platform_version)
perm_py_module.write("#################################################\n")
perm_py_module.write("%s = {\n" % AOSP_PERMISSIONS_PARAM_NAME)
for p_key in list(permissions.keys()):
properties = permissions.get(p_key)
props_string = ", ".join(["'%s' : '%s'" % (prop_key, properties.get(
prop_key)) for prop_key in list(properties.keys())])
perm_py_module.write("\t'%s' : {%s},\n" % (p_key, props_string))
perm_py_module.write("}\n\n")
perm_py_module.write("%s = {\n" % AOSP_PERMISSION_GROUPS_PARAM_NAME)
for pg_key in list(permission_groups.keys()):
properties = permission_groups.get(pg_key)
props_string = ", ".join(["'%s' : '%s'" % (prop_key, properties.get(
prop_key)) for prop_key in list(properties.keys())])
perm_py_module.write("\t'%s' : {%s},\n" % (pg_key, props_string))
perm_py_module.write("}\n")
perm_py_module.write("#################################################\n")
print("Done...")

View File

@ -1,257 +0,0 @@
#!/usr/bin/env python
# This file is part of Androguard.
#
# This is a tool to extract permissions and permission groups from Android Open Source Project.
# The information about the permissions and permission groups is appended to a file, which is
# later used in Androguard project.
#
# Author: Yury Zhauniarovich
#
#
# 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.
# CONSTANTS
PATH_TO_PSCOUT_FOLDER = "/home/yury/TMP/PScout/results/API_09"
API_VERSION = 9
MAPPINGS_MODULE_PATH = "../../androguard/core/api_specific_resources/api_permission_mappings/" # where to append the results
MAPPINGS_MODULE_NAME = "api_permission_mappings"
PSCOUT_METHOD_MAPPING_FILENAME = "allmappings"
PSCOUT_CONTENTPROVIDERFIELDS_MAPPING_FILENAME = "contentproviderfieldpermission"
METHODS_MAPPING_PARAM_NAME = "AOSP_PERMISSIONS_BY_METHODS"
FIELDS_MAPPING_PARAM_NAME = "AOSP_PERMISSIONS_BY_FIELDS"
# IMPORTS
import os, re, codecs
# auxiliary
TYPE_DESCRIPTOR = {
'V': 'void',
'Z': 'boolean',
'B': 'byte',
'S': 'short',
'C': 'char',
'I': 'int',
'J': 'long',
'F': 'float',
'D': 'double',
}
DESCRIPTOR_TYPE = {
'void': 'V',
'boolean': 'Z',
'byte': 'B',
'short': 'S',
'char': 'C',
'int': 'I',
'long': 'J',
'float': 'F',
'double': 'D',
}
def countBrackets(atype):
res = re.findall('\[\s*\]', atype)
return len(res)
def transformClassParam(atype):
res = ""
arrDim = countBrackets(atype)
if arrDim > 0:
pos = atype.find('[')
atype = atype[0:pos].strip()
res = '[' * arrDim
if atype in DESCRIPTOR_TYPE:
res += DESCRIPTOR_TYPE[atype]
else:
res += FormatClassToJava(atype)
return res
def FormatClassToJava(i):
"""
Transoform a typical xml format class into java format
:param i: the input class name
:rtype: string
"""
return "L" + i.replace(".", "/") + ";"
def parseMethod(methodString):
ms = methodString.strip()
mParamStartPos = ms.find('(')
mParamEndPos = ms.find(')')
paramString = ms[mParamStartPos + 1:mParamEndPos].strip()
params = [l.strip() for l in paramString.split(',')]
retValue_mName = ms[0:mParamStartPos].strip()
mNameStartPos = retValue_mName.rfind(' ')
returnValue = retValue_mName[0:mNameStartPos].strip()
methodName = retValue_mName[mNameStartPos + 1:].strip()
return methodName, params, returnValue
# end of auxiliary
print("Starting conversion of PScout data: [%s]" % PATH_TO_PSCOUT_FOLDER)
if not os.path.exists(MAPPINGS_MODULE_PATH):
os.makedirs(MAPPINGS_MODULE_PATH)
print("Checking if we already have the file with the version %d..." % API_VERSION)
api_specific_mappings_module_name = "%s_api%s.py" % (MAPPINGS_MODULE_NAME,
API_VERSION)
api_specific_mappings_module_path = os.path.join(
MAPPINGS_MODULE_PATH, api_specific_mappings_module_name)
if os.path.exists(api_specific_mappings_module_path):
print("API specific file for this version already exists!")
print("If you want create a file for newer version, please, delete file: %s" % api_specific_mappings_module_path)
exit(1)
print("Reading method mapping file...")
pscout_method_mapping_filepath = os.path.join(PATH_TO_PSCOUT_FOLDER,
PSCOUT_METHOD_MAPPING_FILENAME)
methods_mapping_file_lines = []
with open(pscout_method_mapping_filepath, 'r') as pscout_file:
methods_mapping_file_lines = pscout_file.readlines()
print("Starting to parse file: [%s]" % pscout_method_mapping_filepath)
perm_name = None
methods_mapping = {}
for line in methods_mapping_file_lines:
line = line.strip()
if line.startswith("Permission:"):
perm_name = line.split("Permission:")[1].strip()
print("PROCESSING PERMISSIONS: %s" % perm_name)
elif line.startswith("<"):
class_method = line[line.find('<') + 1:line.rfind('>')]
sepPos = class_method.find(':')
className = class_method[0:sepPos].strip()
methodStr = class_method[sepPos + 1:].strip()
methodName, params, returnValue = parseMethod(methodStr)
modParStr = ""
for par in params:
if par != "":
modParStr += transformClassParam(par) + ' '
modParStr = modParStr.strip()
method_identificator = "%s-%s-(%s)%s" % (
transformClassParam(className), methodName, modParStr,
transformClassParam(returnValue))
try:
methods_mapping[method_identificator].add(perm_name)
except KeyError:
methods_mapping[method_identificator] = set()
methods_mapping[method_identificator].add(perm_name)
print("Reading contentproviderfield mapping file...")
pscout_contentproviderfields_mapping_filepath = os.path.join(
PATH_TO_PSCOUT_FOLDER, PSCOUT_CONTENTPROVIDERFIELDS_MAPPING_FILENAME)
contentproviderfields_mapping_file_lines = []
with open(pscout_contentproviderfields_mapping_filepath, 'r') as pscout_file:
contentproviderfields_mapping_file_lines = pscout_file.readlines()
perm_name = None
fields_mapping = {}
for line in contentproviderfields_mapping_file_lines:
line = line.strip()
if line.startswith("PERMISSION:"):
perm_name = line.split("PERMISSION:")[1].strip()
print("PROCESSING PERMISSIONS: %s" % perm_name)
elif line.startswith("<"):
field_entry = line[line.find('<') + 1:line.rfind('>')]
classNameSepPos = field_entry.find(':')
className = field_entry[0:classNameSepPos].strip()
proto_name_str = field_entry[classNameSepPos + 1:].strip()
proto_name_parts = proto_name_str.split()
proto = proto_name_parts[0].strip()
name = proto_name_parts[1].strip()
field_identificator = "%s-%s-%s" % (transformClassParam(className),
name, transformClassParam(proto))
try:
fields_mapping[field_identificator].add(perm_name)
except KeyError:
fields_mapping[field_identificator] = set()
fields_mapping[field_identificator].add(perm_name)
print("Appending found information to the mappings file...")
with codecs.open(api_specific_mappings_module_path, 'w',
'utf-8') as perm_py_module:
perm_py_module.write('#!/usr/bin/python\n')
perm_py_module.write('# -*- coding: %s -*-\n\n' % 'utf-8')
perm_py_module.write('# This file is a part of Androguard.\n')
perm_py_module.write('#\n')
perm_py_module.write(
'# This file is generated automatically from the data\n')
perm_py_module.write(
'# provided by PScout tool [http://pscout.csl.toronto.edu/]\n')
perm_py_module.write('# using script: %s\n' % os.path.basename(__file__))
perm_py_module.write('#\n')
perm_py_module.write('# Author: Yury Zhauniarovich\n')
perm_py_module.write('#\n')
perm_py_module.write('#\n')
perm_py_module.write(
'# Licensed under the Apache License, Version 2.0 (the "License");\n')
perm_py_module.write(
'# you may not use this file except in compliance with the License.\n')
perm_py_module.write('# You may obtain a copy of the License at\n')
perm_py_module.write('#\n')
perm_py_module.write('# http://www.apache.org/licenses/LICENSE-2.0\n')
perm_py_module.write('#\n')
perm_py_module.write(
'# Unless required by applicable law or agreed to in writing, software\n')
perm_py_module.write(
'# distributed under the License is distributed on an "AS-IS" BASIS,\n')
perm_py_module.write(
'# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n')
perm_py_module.write(
'# See the License for the specific language governing permissions and\n')
perm_py_module.write('# limitations under the License"\n\n')
perm_py_module.write('#################################################\n')
perm_py_module.write('### API version: %d \n' % API_VERSION)
perm_py_module.write(
'#################################################\n\n\n')
perm_py_module.write("%s = {\n" % METHODS_MAPPING_PARAM_NAME)
for method in list(methods_mapping.keys()):
permissions = methods_mapping.get(method)
perms_string = ", ".join(["'%s'" % prm for prm in permissions])
perm_py_module.write("\t'%s' : [%s],\n" % (method, perms_string))
perm_py_module.write("}\n\n")
perm_py_module.write("%s = {\n" % FIELDS_MAPPING_PARAM_NAME)
for field in list(fields_mapping.keys()):
permissions = fields_mapping.get(field)
perms_string = ", ".join(["'%s'" % prm for prm in permissions])
perm_py_module.write("\t'%s' : [%s],\n" % (field, perms_string))
perm_py_module.write("}\n")
perm_py_module.write("#################################################\n")
print("Done...")