crmulliner / ddi

ddi - Dynamic Dalvik Instrumentation Toolkit
http://www.mulliner.org/android/
395 stars 159 forks source link

Hooking Method Marked Native? #2

Closed TheBigS closed 10 years ago

TheBigS commented 10 years ago

I'm looking at a smali file and I want to hook this one method that is marked native:

.method public static native doLog(Ljava/lang/String;Ljava/lang/String);

DDI Hooked it fine, my callback method gets called, but as soon as I try to call the original method I get a segfault. Is this something that is even possible with DDI? Is there a way to get a handle to the native function that was orginally targeted by doLog() before the hook was installed and then just invoke that directly?

TheBigS commented 10 years ago

I realized that for the JNI to work on the native function that the function must be exported by its .so file and exported functions can be found and called. So the solution to this is to find the associated library location, find the exported function we need to call, then dynamically invoke it. This can be done directly from the callback function as follows:

static void* doLogCallback(JNIEnv *env, jclass clazz, jobject arg_1, jobject arg_2)
{
  // do logging or parameter inspection

  // get a handle to the application's library
  void* lib_handle = dlopen("/path/to/application/lib/libLogger.so", RTLD_LAZY);
  if ( lib_handle ) 
  {
    // declare function pointer signature
    void* (*fn)(JNIEnv *, jclass, jobject, jobject);
    // bind the function pointer to the exported libLogger.so function
    fn = dlsym(lib_handle, "Java_com_example_logger_doLog");
    if ( fn  ) 
    {
       // call the function
       (*fn)(env, clazz, arg_1, arg_2);  
    }
  }
}