Products
EXPLIoT CloudFuzz
Home  ›  All Blogs  ›  amit  › 

Getting started with Frida on Android Apps

    amit
    10-May-2021

Getting started with Frida on Android Apps

Getting started with Frida on Android Apps

In this blog, we will demonstrate the Use of Frida for dynamic instrumentation of Android Application while doing android Application Pentesting. also explain the Frida Android Apis. We will show you some examples that highlight what Frida can do. In our Previous Blog, you already set up the lab, if you didn’t set up the lab please go through the previous blog and set up the lab first. Android Pentesting Lab Setup

Prerequisites

Before starting with Frida, it is assumed that the reader has prior knowledge of Javascript. It would help to better Understanding of API calls and build your own custom tools

What Is Frida

Frida is a dynamic code instrumentation toolkit. It lets you inject your script into black-box processes(No source code needed). It allows you to inject your own code and to programmatically and interactively inspect and change running processes.

Frida, on the other hand, allows you to interact with the Android APK so you can inject code to bypass many of the techniques developers use to secure the apps. Some examples include bypassing the login screen to authenticate without a password or disabling SSL pinning to allow the hacker to see all the network traffic between your app and any backend servers.

Many of the method calls you make in your Android app can be hijacked or overridden by Frida for purposes that were never intended. By injecting JavaScript code, Frida can disable or enable a switch or pass fake parameters to gain access to information that would not otherwise be available.

How Frida Works?

  • First User have to create an file in which patching method written like Accessing any method value, or changing return value .
  • The patched method is sent from the computer of the User to the agent frida (installed on android device),
  • The agent being inserted in the application on the mobile.
  • And there, the patch (in js) is compiled and used to patch application

imgae-2 imgae-3

While the application is running (the user of the phone starts the app)

  • The ART loads the app’s .oat file to run it and the .so containing FridaDroid + patch is started.
  • In the .so, FridaDroid hook ART functions
  • Get the references of the target method using the hooks obtained in (1).
  • Compile the patch and modify the reference to the target method with the binaries obtained at the end of the compilation.
  • The application continues to run

imgae-4

Frida Tools

  • Frida Cli : REPL interface, a tool aimed at rapid prototyping and easy debugging, for more Use Frida -h

  • frida-ps : This is a command-line tool for listing processes, which is very useful when interacting with a remote system. imgae-3

  • frida-trace : frida-trace is a tool for dynamically Monitoring/tracing Method calls. It is useful for debugging method calls on every event in mobile application. imgae-3 imgae-3

  • frida-discover: frida-discover is a tool for discovering internal functions in a program, which can then be traced by using frida-trace.

  • frida-ls-devices: This is a command-line tool for listing attached devices, which is very useful when interacting with multiple devices. imgae-3

  • frida-kill: This is a command-line tool for killing processes.

Building your own tools

While the CLI tools like frida, frida-trace, etc., are quite useful, there might be times when you’d like to build your own tools harnessing the powerful Frida APIs.

Frida Api

  • Java.available: This api is used to check Frida running on android or not. It is to check if you are actually running on Android. For example, you could create 1 SSL bypassing script that first checks if you’re on Android or iOS, and act accordingly .It specify whether the current process has the a Java VM loaded, i.e. Dalvik or ART return boolean (true or false)
  • Java.androidVersion: This Api return the android version of device that we are using.
  • Java.enumerateLoadedClasses(callback): This API enumerates classes where object specifying onMatch(name, handle): called for each loaded class with a name that may be passed to use() to get a JavaScript wrapper. onComplete(): called when all classes have been enumerated
 
 Java.enumerateLoadedClasses({    
              //Callback function, the parameter name  is the class loading information

       "onMatch": function(name) { 
           if(name.includes("com.example.demotest"))  ## matching class class name like-com.example.demotest
           {   
           	console.log(name)  ## print to the console
           }
           else
           {
           	return
           }
       },
       "onComplete": function() {  ## after completion this method is called
           console.log('Done!');   
       }
   });
  

imgae-4

  • Java.enumerateClassLoaders(callbacks) : This api enumerates the class loaders in Java VM, which have a callback function, which are onMatch: function (loader) and onComplete: function ()
 Java.enumerateClassLoaders({
                //Callback function, the parameter loader is the class loading information
                "onMatch": function (loader)
                {
               :       console.log("",loader);
                },
                //The callback function after enumerating all class loaders
                "onComplete": function ()
                {
                    console.log("end");
                }
            });
 
 
  • Java.enumerateMethods(query) : This APi enumerate methods matching query, specified as “class!method”
 Java.enumerateMethods('*com.example.demotest*!*')** ## In this example it will enumerates the class matching with com.example.demotest and its all methods.
 

imgae-4

  • Java.scheduleOnMainThread(fn) : The callback function is executed on the VM main thread (UI thread). Operating UI elements in Android requires code execution in the main thread, and scheduleOnMainThreadits role is to execute functions in the main thread

  • Java.perform(fn): ensure that the current thread is attached to the VM and call fn. and the fnfunction is called . This function calls VM::AttachCurrentThread internally, then executes the Javascript script in the fn callback function to operate the Java runtime, and finally uses VM::DetachCurrentThread to release resources

  • Java.use(className) : It dynamically get a JavaScript wrapper for className. Wrapper is basically a function that is intended to call one or more other functions.

Java.perform(function() { 
        var Test = Java.use("com.example.demotest.xyz");
        console.log( Test.AClassVariable.value );
     
});

imgae-4

  • Java.openClassFile(filePath) : This Api used for hook dynamic loaded dex.
  • Java.choose(className, callbacks) : Scan Java heap in memory and enumerate Java object (className) instances. For example, you can use java.lang.String Scan strings in memory. callbacks provide two parameters: onMatch(instance) and onComplete, which are to find the matching object and scan to complete the call.
Java.perform(function () {
    Java.choose("com.example.frida_1demo.abcd", {
        
        onMatch:function(instance){
            
            console.log(instance);
        },
        onComplete:function() {
            console.log("end")
        }});
});


  • Java.retain(obj) : duplicates the JavaScript wrapper obj for later use outside replacement method
  • Java.cast(handle, klass) : Create a JavaScript wrapper given the existing instance at the handle of given class klass as returned from Java.use()
  • Java.array(type, elements) : Used to creates a Java array with elements of the specified type, from a JavaScript array elements
  • Java.isMainThread() :This Api check the Programme executing in main thread or not. When a Java program starts up, one thread begins running immediately. This is usually called the main thread of our program, because it is the one that is executed when our program begins.
  • Java.registerClass(spec): Create a new Javaclass and return a wrapper, where the specification is
    • namestring containing :: Specify the name of the class.
    • superClass: (Optional) Parent class. java.lang.ObjecOmission to be inherited from t.
    • implements: (Optional) An array of interfaces implemented by this class.
    • fields: (Optional) Object, which specifies the name and type of each field to be exposed.
    • methods: (Optional) Object, which specifies the method to be implemented.
Java.perform(function () {
 
          var hellojni = Java.registerClass({
            name: 'com.example.frida_1demo.abcd'
          });
          console.log(hellojni.hello.value);
});
  • Java.deoptimizeEverything() : forces the VM to execute everything with its interpreter.

Some Points to Remember !!

  • You can’t access the local variable, you should use the site of the variable. If the variable is used in another function call in decryptChar, you should hook that function

  • Some Classes have Handler objects =>A Handler allows you to send and process Message and Runnable objects associated with a thread’s MessageQueue. Each Handler instance is associated with a single thread and that thread’s message queue. When you create a new Handler, it is bound to a Looper. It will deliver messages and runnables to that Looper’s message queue and execute them on Looper’s thread. they must be executed in the main thread, otherwise, an error will be reported

    Frida provides such a facility, that is scheduleOnMainThread

send(Java.available); 


Java.perform(function () { 
    send(Java.androidVersion); 
    send(Java.isMainThread());
//console.log(Java.isMainThread())
    Java.scheduleOnMainThread(function () { 
        send(Java.isMainThread());
        
        var Mgr = Java.use("com.example.frida_1demo.MainActivity2");
       // console.log(Mgr.hello.value)  
        var c3 = Mgr.$new();    
        //c3.call.overload("java.lang.String").implementation = function(x){


        //        console.log(x)
        //        return x
        //}


        c3.intabc()
    });


});

  • When a field and method having the same name to each other, you can access the field by prefixing _

Sample frida snippet for Classes and Their Methods Enumeration:

   Java.perform(() => {


  var obj = Java.enumerateMethods('*com.example.demotest*!*') // replace com.example.demotest with your android application package
///var methods= JSON.stringify(groups, null," ")
///console.log(methods)


///var common =JSON.stringify(obj[0].classes[0],null," ")
///console.log("\x1b[32m","class-name "+" "+JSON.parse(common).name,"\n"+"\x1b[35m","Methods name"+" "+JSON.parse(common).methods)
///console.log("\x1b[32m", common);
var i =0;
//console.log(obj.length)
for (i=0;i<obj.length;i++){
  console.log("obj" +"::"+i)
var common =JSON.stringify(obj[i].classes[i],null," ")
console.log("\x1b[32m","class-name "+" "+JSON.parse(common).name)
var x;
for (x=0;x<JSON.parse(common).methods.length;x++)
{
  //console.log("methods"+ "::>"+x)
  //console.log("df")
console.log("\x1b[34m",JSON.parse(common).methods[x])

}

}
}); 

imgae-1

References:

About Payatu

Payatu is a Research Focused, CERT-In impaneled Cybersecurity Consulting company specializing in security assessments of IoT product ecosystem, Web application & Network with a proven track record of securing applications and infrastructure for customers across 20+ countries.


Get in touch with us. Click on the get started button below.

Get to know more about our process, methodology & team!

Close the overlay

I am looking for
Please click one!