How does Xposed Framework hook methods in Android - android

I am going through Xposed framework in Android. Specifically reading blog - http://d3adend.org/blog/?p=589 for potential countermeasures and have couple of question on those line.
So when we hook a method using Xposed , framework makes that method as native and executes the code it wants to hook. So how is that in stacktrace original method is called?
com.example.hookdetection.DoStuff->getSecret //This one
de.robv.android.xposed.XposedBridge->invokeOriginalMethodNative
de.robv.android.xposed.XposedBridge->handleHookedMethod
com.example.hookdetection.DoStuff->getSecret //This one again
com.example.hookdetection.MainActivity->onCreate
android.app.Activity->performCreate
android.app.Instrumentation->callActivityOnCreate
android.app.ActivityThread->performLaunchActivity
android.app.ActivityThread->handleLaunchActivity
android.app.ActivityThread->access$800
android.app.ActivityThread$H->handleMessage
android.os.Handler->dispatchMessage
android.os.Looper->loop
android.app.ActivityThread->main
java.lang.reflect.Method->invokeNative
java.lang.reflect.Method->invoke
com.android.internal.os.ZygoteInit$MethodAndArgsCaller->run
com.android.internal.os.ZygoteInit->main
de.robv.android.xposed.XposedBridge->main
dalvik.system.NativeStart->main
Also why does it come twice in the stacktrace. I want to understand the order in which they are executed.
Is the actual method even run? Since the hooked method code executes it would not ideally execute the original method code. So how can we possible add a stracktrace detection mechanism in the same method knowing it would be replaced.

Xposed inner workings aren't easy to understand if you aren't comfortable with low level code and android kernel. To make it short, when you open an app on your Android device, there is a master process called Zygote that will spawn it as its child process.
The purpose of Xposed is to be able to control Zygote and detect whenever a process is about to be spawned, so that someone is able to hook methods by replacing their definitions before any calls are made to them.
You have a lot of control by using Xposed, you can replace the entire method body, so the original code never get called or you can use beforeCall and afterCall hooks which is basically an usage of the trampoline technique (A C++ example below)
As you can see when a method is called it doesn't directly go to the original code but to an injected code block where someone can do anything he wants (Dump, Change parameters, etc) then it will jump back to the genuine code. You can also do this after the genuine code, so you get the method output. Xposed implements this by using beforeHookedMethod and afterHookedMethod.
Adding a stacktrace detection mechanism won't help at all. You will call Java methods to get the actual stacktrace. It can be defeated easily by hooking the getStacktrace method, saving a valid genuine stacktrace, then when ever getStackTrace is called and contains Xposed methods, return the previously saved genuine stacktrace.
Your best bet is to rely on Native code to detect it, but even then any determined and experimented hacker with full device control can manage to defeat it eventually.

To add to above points when you call XposedHelpers.findAndHookMethod the callback can either be -
XC_MethodHook : Callback class for method hooks. Usually, anonymous subclasses of this class are created which override beforeHookedMethod(XC_MethodHook.MethodHookParam) and/or afterHookedMethod(XC_MethodHook.MethodHookParam).
XC_MethodReplacement : A special case of XC_MethodHook which completely replaces the original method.
1st one just provides you the hooks to execute methods before and after original method where as 2nd one replaces it completely. Eg - Xposed example on github
Couple of posts I have written -
Creating a new Xposed module in Android
Installing Xposed Framework on Android devices

Related

Share single instance between classes in Kotlin

I'm working with a 3rd party SDK in a Flutter plugin (Kotlin), and need to instantiate a particular class once, so I can share the state with various different instances of Method- and Event Channels.
I have several classes that expose 'features' as event channels, and they all use the same instance of a callback from the SDK.
For visual reference:
com.company.example
-- Feature1StreamHandler
-- Feature2StreamHandler
-- Feature3MethodHandler
-- Featuer4MethodHandler
Each one of these handler implementations, require a scan instance, which needs to be configured once, when the application starts up and then dispose of it, when the application closes.
Coming from C#, I'd implement a contract, create a concrete implementation and initialise the class during the application bootstrap stage, startup, however, a similar 'pattern' in Android does not seem to work, as I kind of expect the bootstrap to be the MainActivity, however, data is then not passed on to the Flutter plugin portion.
I'm hoping my explanation makes sense...
Something like this:
In MainActivity, construct SDKScan object.
In the Flutter plugin, for argument sake, MyPlugin, I want that instance of SDKScan created in MainActivity.

Modifying Dalvik Virtual Machine to intercept methods of Application code

In my current implementation, I can only intercept the Method_Entry event of the some Class initialization methods, including:
*.<init> or *.<cinit>
* stands for any Class
All the methods written in Java applications are missing.
Currently, I have inserted "fprintf()" in the following places:
stack.cpp: dvmCallMethod()
stack.cpp: dvmCallMethodV()
stack.cpp: dvmCallMethodA()
stack.cpp: dvmInvokeMethod()
Interp.cpp: dvmInterpret()
Mterp.cpp: dvmMterpStd()
When these places of DVM are executed, I will print a message in my log file. However, only the Class initialization functions has triggered my println() code. In other words, it looks like that the execution of application methods does not go through the above places of DVM. I don't know which part of DVM is responsible for method execution of applications. Can anyone give me a clue?
The easiest way to figure out how things work is to look at how the method profiling works. Profiling adds an entry to a log file every time a method is called. The key file is dalvik/vm/Profile.h, which defines macros like TRACE_METHOD_ENTER. (In gingerbread, this was all you needed to look for. The situation changed quite a bit in ICS, when the interaction between debugging, profiling, and JIT compilation got reworked. And KitKat added the "sampling" profiler into the mix. So it's a bit more twisty now, and there are some other functions to be aware of, like dvmFastMethodTraceEnter().)
The entry points you've identified in your question are for reflection and calls in and out of native code. Calls between interpreted code are handled by updating the stack and program counter, and just continuing to loop through the interpreter. You can see this at line 3928 in the portable interpreter.
The non-obvious part is the FINISH() macro, defined on line 415. This calls into dvmCheckBefore(), line 1692 in Interp.cpp. This function checks the subMode field to see if there is anything interesting to do; you can find the various meanings in the definition, line 50 in InterpState.h. In short, flags are used for various profiling, debugging, and JIT compilation features.
You can see a subMode check on line 3916 in the portable interpreter, in the method invocation handling. It calls into dvmReportInvoke(), over in Interp.cpp, which invokes the TRACE_METHOD_ENTER macro.
If you're just trying to have something happen every time any method is invoked, you should probably just wire it into the profiling system, as that's already doing what you want. If you don't need the method profiling features, just replace them with your code.

Android : Logging all API calls

I'm working on a collage project about security in Android. One part of the project attempts to capture and log all API function called by the selected APK. This can't be done with a external programs so in the project we are working with the Android source code to modify the ROM.
At the present time we only have two possible solutions:
DVM JNI Bridge
The API is Java code so, obviously, the Dalvik Virtual Machine needs a bridge to execute JNI code. The function which handle all cases is dvmCallJNIMethod(const u4* args, JValue* pResult, const Method* method, Thread* self). In this function we can get the name and the class of the called function.
This function can log all the JNI code executed, which includes API calls. But there is no easy way to distinct between private calls and API calls. And, if we wanted to execute some code depending on the risk of the API call executed, we would have to create a huge and inefficient switch.
API Framework
another solution To log all API calls is creating a new interface for the framework. With a new logging class and a simple inheritance should be easy to log all calls and add a risk parameter. But it would mean changing a lot of code. Also, Java code has worst performance than C, so it might not be the most efficient way.
More over, we would like to ask you a few questions about Android DVM and the API.
1.Which is exactly the call flow between DVM and the API?
2.Could be the DVM monitor a good idea to log the calls?
3.Which role have the shared libraries in all of this?
4.Are all API calls really Java code?
Thanks for your time.

How can Android source code not have a main method and still run?

I've seen this in a few tutorials now... but how in the world can Android source code not have a main method and still run.
For example (from http://developer.android.com/guide/tutorials/hello-world.html):
public class HelloAndroid extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
That runs but there is no main!!!
I've also thought that using things like onCreate (or formLoad, etc.) was bad becuase a constructor should do that work and such built-in methods can be smelly sometimes. But onCreate is an entry point? Even without a main?
What if there is more than one activity... is there a hierarchy to these built in event handlers? OnCreate trumps everything else? Otherwise, how would the app know what to run or where to enter the program?
Thanks!
Each application will be having it's own Virtual Machine. To run an app, within it's space (VM), must have a main method.
Activities are not the actual classes to be invoked for start of application. There is a class called Application, which will be the root class for an application to be launched.
If there is no main method, how can a VM recognize how to start an app?
Framework has classes called Process, VMRuntime which are responsible for starting an application. Which indeed deal with main method.
For better understanding, study the Zygote service of Android. deals with Applicationmanager Service, ActivityStack Activity Threadds etc.
That runs but there is no main!!!
Of course. Many things that you might think of as a Java "application" do not have their own main() method. For example, IIRC, servlets, WARs, and the like do not have main() methods -- the main() method, if there is one, is in the container.
But onCreate is an entry point?
onCreate() is a method.
What if there is more than one activity... is there a hierarchy to these built in event handlers?
Not really.
OnCreate trumps everything else?
Not really.
Otherwise, how would the app know what to run or where to enter the program?
An app does not "know what to run or where to enter the program".
An Android application is a basket of components. Some components may be tied to icons in a home screen launcher. Some components may be tied to scheduled timers, like cron jobs or Windows scheduled tasks. Some components may be tied to system events, such as when the device is placed into or removed from a car dock. Those components will be automatically created and used when appropriate (e.g., when a user taps the icon in the home screen launcher). Yet other components are only created and used when your code specifically asks for them.
Thinking of an Android application as if it were a monolithic console-mode Java program will cause you no end of trouble.
You tell it which one to run on startup in the manifest file. There isn't a main() because there doesn't have to be, main may be a convention used for "regular" java apps, but it isn't for things like browser applets. The system creates the activity object and calls methods within it, which may or may not be called main. In this case, it's not.
onCreate is different from a main, and from a constructor, in that it can be called twice on a single activity, such as if the process is killed and the user navigates back to the activity. See http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
Actually, this type of pattern is not peculiar of Android, but happens whenever you have some framework in the middle. Some basic examples are java Applets and Servlets. Some of the answers already provide give the correct response, but I will try to elaborate a bit.
When you launch a Java app, you start a JVM and then you need to load something into it: so you need a static method (the main) because there are no objects (yet) living in the JVM that you can refer to.
If you have some sort of framework in the middle, it is the framework that will start the JVM and will start populating it with its own service objects: writing your code then means writing your own objects (which will be subclasses of given "template"). Your objects can then be injected (loaded) by the framework. The framework service objects manage the lifecycle of the injected objects by calling the lifecycle methods defined in the "template" superclass.
So for instance when you provide an applet to a browser, you do not launch a static main method: you rather only provide a subclass of java.applet.Applet that implements some instance methods which act as callback to manage the lifecycle (init, paint, stop...). It is the browser that will launch the JVM, instantiate what's needed for the launching an applet, load your applet and call it.
Similarly, with servlets you subclass the javax.servlet.http.HttpServlet class and implement some instance (non static) methods (doGet, doPost...). The Web container (e.g. Tomcat) will be in charge to launch the JVM, instantiate what's needed for launching a servlet, load your servlet and call it.
The pattern in Android is pretty much the same: what do you do is to create a subclass of android.app.Activity. When you launch an app, the system looks in the manifest to find out which activity should be started, then the "framework" loads it and calls its instance methods (onCreate, onPause, onResume...).
In Java programs we need a main() method, because while executing the byte code the JVM will search for the main() method in the class and start executing there.
In Android, the Dalvik Virtual Machine is designed to find a class which is a subclass of Activity and which is set to start the execution of the application from its onCreate() method, so there is no need of a main() method.
The order in which Dalvik Virtual Machine calls methods is based on order of priorities called android life cycle for more information on android life cycle check the link below
Android Life Cycle: https://developer.android.com/guide/components/activities/activity-lifecycle.html
While there is no specific main entry point, intent filters describe which activity is started when the application is launched.
They are controlled in AndroidManifest.xml as described here:
http://developer.android.com/guide/topics/intents/intents-filters.html
where a note pad application example is described:
This filter declares the main entry point into the Note Pad application. The standard MAIN action is an entry point that does not require any other information in the Intent (no data specification, for example), and the LAUNCHER category says that this entry point should be listed in the application launcher.
An android programmer should learn this like the back of their hands it simply explains everything and would help in the future when creating activities.
http://developer.android.com/reference/android/app/Activity.html
There is a main of sorts, it just happens to be out of your hands. After all, there's nothing special about a main function in any language. It's just the entry point where your code starts executing. The Android operating system expects applications to have a certain structure and it calls your code based on the conventions you follow.
I found this particularly useful...
http://developer.android.com/guide/topics/fundamentals.html#appcomp
Applets don't have main() methods either. It just depends on how your code is packaged.
The Android UI frame encapsulate some Java common details, you can study the source code of the android UI framework
I think that Jonathon's answer is going in the right direction. He says the OS expects a certain structure. There's a name for that structure which is a "state machine". In this case Android calls it the "activity lifecycle". Rob gives a link to the documentation which contains an important diagram of that state machine though the text is a bit dry. A quick search also found me the following link that explains it fairly clearly: http://www.android-app-market.com/android-activity-lifecycle.html
In Java, there is a main even if it isn't listed as main(). The page you get after the icon click, whatever its name, is the main().

What is the preferred way to communicate between applications on Android (service vs. intents)

What is the difference between these two ways of interaction between applications on Android:
Implementing service in app #1 and using it in app #2
Handling intents and posting answers to the intents.
Interactions are supposed to be asynchronous.
What are pros and contras for each?
It really depends upon what it is you're trying to achieve. In the case where - as you ask - interactions should be asynchronous, there's no reason why you couldn't use Intents. This way has two advantages:
If it's a "general" request (something like "pick a photo" or such...) then it gives the user (and the operating system) a chance to choose the most suitable application. It's quite feasible that App #2 as you named it doesn't actually exist on the target user's device (unless App #1 specifically depends upon it).
App #2 can really take its time over whatever it is you've asked. If it's a user-centred task, then maybe it wants to launch an Activity and get user input, or such.
If you're looking for more technical advantages to this method: you don't have to worry about App #1 depending on generated class code every time you change the interface. When you write an interface using AIDL (this is how you implement the service model you named "1") the ADT will go away and generate a bunch of classes for you which you use to expose your remote service. Problems arise when App #1 has a different version of these generated classes to App #2. (And believe you me, the error messages associated with these problems are less than informative).
On the other hand, that's not to say that you should avoid the Remote Service model altogether; it has many useful applications. This is where my explanation becomes a little "hand wavy" but hopefully you will understand the gist of what I'm saying. AIDL interfaces give you much more direct control over the services you're calling. Instead of launching an intent, bundling in a bunch of data, and dispatching it in the hope that it will reach the correct Service (or activity, or other handler), then be handled in the right way, and eventually a result will get back to you, you directly call methods within a Remote class. The methods you call in that remote class are the ones specified by the AIDL interface written within App #2 (which functions like a server) - but you will quickly start to have to think about things like threads. You're directly calling code that lives in another process - which means that a thread belonging to App #1 is being given access to objects and methods in App #2.
How you deal with the fact that App #1 is calling code in App #2 is pretty much up to you, but the way I use (and I believe the recommended way, although if someone knows different I hope they will correct me here) is to use a Handler within App #2. When App #1 calls the AIDL interface, the code it calls sends a message to a Handler living in App #2, which then gets called by a thread belonging to App #2 - meaning you know which part of your app is accessing which members etc.
There are obvious advantages to this control flow, and to me it feels more "API-ish" - but that's not to say it's going to fit everyone's purposes. My experience is also that programming via an AIDL interface is much more error-fraught and fragile. Although technically it's always just doing what you told it to do, it's quite easy to tell it to do something wrong - or worse, misunderstand what you've told it altogether. I would say: exhaust other routes before thinking about writing an AIDL service.
On the note of asynchronous calls:
If you simply call code in App #2 directly, it's entirely synchronous.
If you use a message-handling interface, things are a little different. You can then provide a second AIDL interface living inside App #1 that allows App #2 to give you callbacks (this is what happens in the example on the official AIDL documentation for Android).
So you've got there two very flexable interfaces to interact between two processes. Both are good for different purposes.

Categories

Resources