Browse files

combined instrumentation with stub methods generation

  • Loading branch information...
1 parent ebc3285 commit 7183ba0b4f61fe6b8170ea9b8e36d9b9cc5e6680 @kelwin committed Jul 13, 2012
View
26 apkil/monitor.py
@@ -20,7 +20,6 @@
# }
# }
-
BASIC_TYPES = {
'V': "void",
'Z': "boolean",
@@ -33,8 +32,8 @@
'D': "double"
}
-
CLASS_NAME = "org/honeynet/apimonitor/APIMonitor"
+
PKG_PREFIX = "droidbox"
LOG_TAG = "DroidBox"
@@ -54,14 +53,25 @@ class APIMonitor(object):
def __init__(self, method_descs):
self.method_descs = method_descs
self.stub_classes = {}
+ self.method_map = {}
+ self.class_map = {}
for m in method_descs:
segs = m.rsplit("->", 1)
if self.stub_classes.has_key(segs[0]):
stub_class = self.stub_classes[segs[0]]
else:
stub_class = StubClass(segs[0])
self.stub_classes[segs[0]] = stub_class
+ self.class_map[segs[0]] = "L" + PKG_PREFIX + "/" + segs[0][1:]
stub_class.add(segs[1])
+ i = m.find('(')
+ self.method_map[m] = "L" + PKG_PREFIX + "/" + m[1:i + 1] + \
+ segs[0] + m[i + 1:]
+# Landroid/widget/TextView;->setText(Ljava/lang/CharSequence;)V
+# Ldroidbox/android/widget/TextView;->setText(Landroid/widget/TextView;Ljava/lang/CharSequence;)V"
+
+ def get_class_descs(self):
+ return self.class_map.values()
def __repr__(self):
return "%s" % \
@@ -89,7 +99,7 @@ def add(self, method_short_desc):
def gen(self):
self.buf = []
- self.buf.append("package %s;" % self.package)
+ self.buf.append("package %s;" % self.package.replace('/', '.'))
self.buf.append("import android.util.Log;")
# self.buf.append("import %s;" % self.class_desc[1:-1])
self.buf.append("public class %s {" % self.class_name)
@@ -153,7 +163,17 @@ def gen(self):
', '.join( \
["%s p%d" % \
(self.paras[i], i) for i in range(len(self.paras))])))
+ self.buf.append("try {")
self.buf.append("p0.%s(%s);" % (self.name, ', '.join(["p%d" % i for i in
range(1, len(self.paras))])))
+
+ for i in range(1, len(self.paras)):
+ if self.paras[i] == "java.lang.String":
+ self.buf.append("Log.v(TAG, p%d);" % i)
+
+
+ self.buf.append("} catch (Exception e) {")
+ self.buf.append("e.printStackTrace();")
+ self.buf.append("}")
self.buf.append("}")
View
11 apkil/smali.py
@@ -250,14 +250,16 @@ def __parse(self, lines):
self.descriptor = segs[-1]
self.name = self.descriptor.split('(', 1)[0]
+ start = 1
# .registers <register-num>
segs = self.buf[1].split()
- # segs[0] == ".registers"
- self.registers = int(segs[1])
+ if segs[0] == ".registers":
+ self.registers = int(segs[1])
+ start = 2
index = 0
try_node_cache = []
- for line in self.buf[2:-1]:
+ for line in self.buf[start:-1]:
segs = line.split()
# :<label-name>
if segs[0][0] == ":":
@@ -297,7 +299,8 @@ def reload(self):
if l.try_node:
self.buf.insert(l.index + count, l.try_node.buf)
count += 1
- self.buf.insert(0, ".registers %d" % self.registers)
+ if self.registers > 0:
+ self.buf.insert(0, ".registers %d" % self.registers)
self.buf.insert(0, ".method %s %s" % \
(' '.join(self.access), self.descriptor))
self.buf.append(".end method")
View
8 template/APIMonitor/.classpath
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="src" path="gen"/>
+ <classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
+ <classpathentry kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
+ <classpathentry kind="output" path="bin/classes"/>
+</classpath>
View
33 template/APIMonitor/.project
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>APIMonitor</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>com.android.ide.eclipse.adt.ApkBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>com.android.ide.eclipse.adt.AndroidNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
View
23 template/APIMonitor/AndroidManifest.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="droidbox.tests"
+ android:versionCode="1"
+ android:versionName="1.0" >
+
+ <uses-sdk android:minSdkVersion="7" />
+
+ <application
+ android:icon="@drawable/ic_launcher"
+ android:label="@string/app_name" >
+ <activity
+ android:name=".APIMonitorActivity"
+ android:label="@string/app_name" >
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+
+ <category android:name="android.intent.category.LAUNCHER" />
+ </intent-filter>
+ </activity>
+ </application>
+
+</manifest>
View
85 template/APIMonitor/build.xml
@@ -0,0 +1,85 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project name="APIMonitorActivity" default="help">
+
+ <!-- The local.properties file is created and updated by the 'android' tool.
+ It contains the path to the SDK. It should *NOT* be checked into
+ Version Control Systems. -->
+ <property file="local.properties" />
+
+ <!-- The ant.properties file can be created by you. It is only edited by the
+ 'android' tool to add properties to it.
+ This is the place to change some Ant specific build properties.
+ Here are some properties you may want to change/update:
+
+ source.dir
+ The name of the source directory. Default is 'src'.
+ out.dir
+ The name of the output directory. Default is 'bin'.
+
+ For other overridable properties, look at the beginning of the rules
+ files in the SDK, at tools/ant/build.xml
+
+ Properties related to the SDK location or the project target should
+ be updated using the 'android' tool with the 'update' action.
+
+ This file is an integral part of the build system for your
+ application and should be checked into Version Control Systems.
+
+ -->
+ <property file="ant.properties" />
+
+ <!-- The project.properties file is created and updated by the 'android'
+ tool, as well as ADT.
+
+ This contains project specific properties such as project target, and library
+ dependencies. Lower level build properties are stored in ant.properties
+ (or in .classpath for Eclipse projects).
+
+ This file is an integral part of the build system for your
+ application and should be checked into Version Control Systems. -->
+ <loadproperties srcFile="project.properties" />
+
+ <!-- quick check on sdk.dir -->
+ <fail
+ message="sdk.dir is missing. Make sure to generate local.properties using 'android update project' or to inject it through an env var"
+ unless="sdk.dir"
+ />
+
+
+<!-- extension targets. Uncomment the ones where you want to do custom work
+ in between standard targets -->
+<!--
+ <target name="-pre-build">
+ </target>
+ <target name="-pre-compile">
+ </target>
+
+ /* This is typically used for code obfuscation.
+ Compiled code location: ${out.classes.absolute.dir}
+ If this is not done in place, override ${out.dex.input.absolute.dir} */
+ <target name="-post-compile">
+ </target>
+-->
+
+ <!-- Import the actual build file.
+
+ To customize existing targets, there are two options:
+ - Customize only one target:
+ - copy/paste the target into this file, *before* the
+ <import> task.
+ - customize it to your needs.
+ - Customize the whole content of build.xml
+ - copy/paste the content of the rules files (minus the top node)
+ into this file, replacing the <import> task.
+ - customize to your needs.
+
+ ***********************
+ ****** IMPORTANT ******
+ ***********************
+ In all cases you must update the value of version-tag below to read 'custom' instead of an integer,
+ in order to avoid having your file be overridden by tools such as "android update project"
+ -->
+ <!-- version-tag: 1 -->
+ <import file="${sdk.dir}/tools/ant/build.xml" />
+
+</project>
View
10 template/APIMonitor/local.properties
@@ -0,0 +1,10 @@
+# This file is automatically generated by Android Tools.
+# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
+#
+# This file must *NOT* be checked in Version Control Systems,
+# as it contains information specific to your local configuration.
+
+# location of the SDK. This is only used by Ant
+# For customization when using a Version Control System, please read the
+# header note.
+sdk.dir=/Users/kelwin/SDK/android-sdk-macosx
View
40 template/APIMonitor/proguard.cfg
@@ -0,0 +1,40 @@
+-optimizationpasses 5
+-dontusemixedcaseclassnames
+-dontskipnonpubliclibraryclasses
+-dontpreverify
+-verbose
+-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*
+
+-keep public class * extends android.app.Activity
+-keep public class * extends android.app.Application
+-keep public class * extends android.app.Service
+-keep public class * extends android.content.BroadcastReceiver
+-keep public class * extends android.content.ContentProvider
+-keep public class * extends android.app.backup.BackupAgentHelper
+-keep public class * extends android.preference.Preference
+-keep public class com.android.vending.licensing.ILicensingService
+
+-keepclasseswithmembernames class * {
+ native <methods>;
+}
+
+-keepclasseswithmembers class * {
+ public <init>(android.content.Context, android.util.AttributeSet);
+}
+
+-keepclasseswithmembers class * {
+ public <init>(android.content.Context, android.util.AttributeSet, int);
+}
+
+-keepclassmembers class * extends android.app.Activity {
+ public void *(android.view.View);
+}
+
+-keepclassmembers enum * {
+ public static **[] values();
+ public static ** valueOf(java.lang.String);
+}
+
+-keep class * implements android.os.Parcelable {
+ public static final android.os.Parcelable$Creator *;
+}
View
11 template/APIMonitor/project.properties
@@ -0,0 +1,11 @@
+# This file is automatically generated by Android Tools.
+# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
+#
+# This file must be checked in Version Control Systems.
+#
+# To customize properties used by the Ant build system use,
+# "ant.properties", and override values to adapt the script to your
+# project structure.
+
+# Project target.
+target=android-7
View
BIN template/APIMonitor/res/drawable-hdpi/ic_launcher.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
BIN template/APIMonitor/res/drawable-ldpi/ic_launcher.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
BIN template/APIMonitor/res/drawable-mdpi/ic_launcher.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
12 template/APIMonitor/res/layout/main.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="fill_parent"
+ android:layout_height="fill_parent"
+ android:orientation="vertical" >
+
+ <TextView
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:text="@string/hello" />
+
+</LinearLayout>
View
7 template/APIMonitor/res/values/strings.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+
+ <string name="hello">Hello World, APIMonitorActivity!</string>
+ <string name="app_name">APIMonitor</string>
+
+</resources>
View
13 template/APIMonitor/src/droidbox/tests/APIMonitorActivity.java
@@ -0,0 +1,13 @@
+package droidbox.tests;
+
+import android.app.Activity;
+import android.os.Bundle;
+
+public class APIMonitorActivity extends Activity {
+ /** Called when the activity is first created. */
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.main);
+ }
+}
View
76 testMonitor.py
@@ -17,17 +17,71 @@
# }
import sys
import time
+import shutil
+import os
+from androguard.core.bytecodes import apk
from apkil import smali, monitor, logger
from subprocess import call
-EXPORT_FOLDER = "examples/java"
-# print(monitor.smali2java_type('Landroid/widget/TextView;'))
-m = monitor.APIMonitor([ \
- "Landroid/widget/TextView;->setText(Ljava/lang/CharSequence;)V", \
- "Landroid/widget/TextView;->setNBText(Ljava/lang/CharSequence;I[[IZ)V", \
- "Landroid/test/TextView;->setNBText(Ljava/lang/CharSequence;I[[IZ)V", \
- ])
-m.export(EXPORT_FOLDER)
-for c in m.stub_classes.values():
- c.gen()
- print '\n'.join(c.buf)
+APK = "examples/DroidBoxTests.apk"
+DEX = "examples/DroidBoxTests.dex"
+SMALI_DIR = "examples/DroidBoxTests_smali"
+
+a = apk.APK(APK)
+dex_file = open(DEX, 'w')
+dex_file.write(a.get_dex())
+dex_file.close()
+
+call(args=['baksmali', '-b', '-o', SMALI_DIR, DEX])
+s = smali.SmaliTree(SMALI_DIR)
+
+NEW_OUT = "examples/new"
+NEW_DEX = "examples/classes.dex"
+NEW_APK = "examples/new.apk"
+
+# sys.exit(0)
+
+API_LIST = [ "Landroid/widget/TextView;->setText(Ljava/lang/CharSequence;)V", \
+ "Ljava/io/OutputStreamWriter;->write(Ljava/lang/String;)V"
+ ]
+
+TEMPLATE = "template/APIMonitor"
+EXPORT_FOLDER = "examples/APIMonitor/java"
+
+if os.path.exists(EXPORT_FOLDER):
+ shutil.rmtree(EXPORT_FOLDER)
+shutil.copytree(TEMPLATE, EXPORT_FOLDER)
+m = monitor.APIMonitor(API_LIST)
+m.export(os.path.join(EXPORT_FOLDER, "src"))
+call(args=["android", "update", "project", "--path", EXPORT_FOLDER])
+call(args=["ant", "debug", "-buildfile", \
+ os.path.join(EXPORT_FOLDER, "build.xml")])
+
+# sys.exit(0)
+
+dex_file_path = os.path.join(EXPORT_FOLDER, "bin", "classes.dex")
+MONITOR_SMALI = "examples/APIMonitor/smali"
+
+call(args=['baksmali', '-b', '-o', MONITOR_SMALI, dex_file_path])
+m_s = smali.SmaliTree(MONITOR_SMALI)
+
+# print repr(m.method_map)
+
+for api in API_LIST:
+ insns = s.get_insn35c("invoke-virtual", api)
+ for i in insns:
+ i.obj.replace("invoke-static", m.method_map[api])
+
+for c in m.get_class_descs():
+ print c
+ s.add_class(m_s.get_class(c))
+s.save(NEW_OUT)
+call(args=['smali', '-a', '6', '-o', NEW_DEX, NEW_OUT])
+
+new_dex = open(NEW_DEX).read();
+a.new_zip(filename=NEW_APK,
+ deleted_files="(META-INF/.)", new_files = {
+ "classes.dex" : new_dex } )
+apk.sign_apk( NEW_APK, \
+"/Users/kelwin/Dropbox/Backup/androguard", "androguard", "haimen!!" )
+

0 comments on commit 7183ba0

Please sign in to comment.