Frida Tutorial

Tutorial su Frida

Impara l'hacking di AWS da zero a esperto con htARTE (HackTricks AWS Red Team Expert)!

Altri modi per supportare HackTricks:

Consiglio per bug bounty: iscriviti a Intigriti, una piattaforma premium per bug bounty creata da hacker, per hacker! Unisciti a noi su https://go.intigriti.com/hacktricks oggi stesso e inizia a guadagnare ricompense fino a $100,000!

Installazione

Installa gli strumenti di Frida:

pip install frida-tools
pip install frida

Scarica e installa nel dispositivo Android il server frida (Scarica l'ultima versione). One-liner per riavviare adb in modalità root, connettersi ad esso, caricare frida-server, concedere i permessi di esecuzione e avviarlo in background:

adb root; adb connect localhost:6000; sleep 1; adb push frida-server /data/local/tmp/; adb shell "chmod 755 /data/local/tmp/frida-server"; adb shell "/data/local/tmp/frida-server &"

Verifica se funziona:

frida-ps -U #List packages and processes
frida-ps -U | grep -i <part_of_the_package_name> #Get all the package name

Tutorial

Da: https://medium.com/infosec-adventures/introduction-to-frida-5a3f51595ca1 APK: https://github.com/t0thkr1s/frida-demo/releases Codice sorgente: https://github.com/t0thkr1s/frida-demo

Segui il link per leggerlo.

Da: https://11x256.github.io/Frida-hooking-android-part-2/ (Parti 2, 3 e 4) APK e codice sorgente: https://github.com/11x256/frida-android-examples

Segui il link per leggerlo.

Da: https://joshspicer.com/android-frida-1 APK: https://github.com/OWASP/owasp-mstg/blob/master/Crackmes/Android/Level_01/UnCrackable-Level1.apk

Segui il link per leggerlo.

Puoi trovare altri script Frida fantastici qui: https://codeshare.frida.re/

Esempi rapidi

Chiamare Frida dalla riga di comando

frida-ps -U

#Basic frida hooking
frida -l disableRoot.js -f owasp.mstg.uncrackable1

#Hooking before starting the app
frida -U --no-pause -l disableRoot.js -f owasp.mstg.uncrackable1
#The --no-pause and -f options allow the app to be spawned automatically,
#frozen so that the instrumentation can occur, and the automatically
#continue execution with our modified code.

Script Python di base

import frida

# Attach to the target process
session = frida.attach("com.example.app")

# Define the JavaScript code to be injected
js_code = """
Java.perform(function () {
    // Intercept the target method
    var targetClass = Java.use("com.example.app.TargetClass");
    targetClass.targetMethod.implementation = function () {
        // Print the arguments passed to the method
        console.log("Arguments: " + Array.prototype.slice.call(arguments));
        
        // Call the original method
        var result = this.targetMethod.apply(this, arguments);
        
        // Print the result
        console.log("Result: " + result);
        
        // Modify the result if needed
        result += 1;
        
        // Return the modified result
        return result;
    };
});
"""

# Create the script
script = session.create_script(js_code)

# Load the script into the target process
script.load()

# Detach from the target process
session.detach()

Script Python di base

import frida

# Collegarsi al processo di destinazione
session = frida.attach("com.example.app")

# Definire il codice JavaScript da iniettare
js_code = """
Java.perform(function () {
    // Interrompere il metodo di destinazione
    var targetClass = Java.use("com.example.app.TargetClass");
    targetClass.targetMethod.implementation = function () {
        // Stampare gli argomenti passati al metodo
        console.log("Argomenti: " + Array.prototype.slice.call(arguments));
        
        // Chiamare il metodo originale
        var result = this.targetMethod.apply(this, arguments);
        
        // Stampare il risultato
        console.log("Risultato: " + result);
        
        // Modificare il risultato se necessario
        result += 1;
        
        // Restituire il risultato modificato
        return result;
    };
});
"""

# Creare lo script
script = session.create_script(js_code)

# Caricare lo script nel processo di destinazione
script.load()

# Scollegarsi dal processo di destinazione
session.detach()
import frida, sys

jscode = open(sys.argv[0]).read()
process = frida.get_usb_device().attach('infosecadventures.fridademo')
script = process.create_script(jscode)
print('[ * ] Running Frida Demo application')
script.load()
sys.stdin.read()

Hooking delle funzioni senza parametri

Hook la funzione a() della classe sg.vantagepoint.a.c

Java.perform(function () {
;  rootcheck1.a.overload().implementation = function() {
rootcheck1.a.overload().implementation = function() {
send("sg.vantagepoint.a.c.a()Z   Root check 1 HIT!  su.exists()");
return false;
};
});

Hook java exit()

Introduction

In this tutorial, we will learn how to hook the exit() method in a Java application using Frida. By hooking this method, we can intercept the application's exit calls and perform additional actions before the application terminates.

Prerequisites

Before we begin, make sure you have the following:

  • A rooted Android device or an emulator

  • Frida installed on your machine

  • Basic knowledge of JavaScript and Java

Steps

  1. Start by creating a new JavaScript file, for example hook_exit.js, and open it in a text editor.

  2. Import the necessary Frida modules:

    const { Java } = require('frida');
  3. Attach to the target process:

    const process = Java.use('java.lang.Runtime').getRuntime().exec.overload('java.lang.String').implementation;
  4. Define the hook function:

    function hookExit() {
      console.log('Exit method called');
      // Perform additional actions here
    }
  5. Hook the exit() method:

    Java.use('java.lang.Runtime').exit.implementation = function() {
      hookExit();
      this.exit();
    };
  6. Save the JavaScript file.

  7. Launch the target application on your Android device or emulator.

  8. Open a terminal and navigate to the directory where the JavaScript file is located.

  9. Use Frida to inject the JavaScript code into the target process:

    frida -U -l hook_exit.js -f <package_name>

    Replace <package_name> with the package name of the target application.

  10. You should see the message "Exit method called" in the terminal whenever the exit() method is invoked in the target application.

Conclusion

By hooking the exit() method in a Java application using Frida, we can intercept the application's exit calls and perform additional actions. This technique can be useful for various purposes, such as debugging or analyzing the behavior of an application before it terminates.

var sysexit = Java.use("java.lang.System");
sysexit.exit.overload("int").implementation = function(var_0) {
send("java.lang.System.exit(I)V  // We avoid exiting the application  :)");
};

Hook MainActivity .onStart() & .onCreate()

To hook the .onStart() and .onCreate() methods of the MainActivity class in an Android app, you can use the Frida framework. Frida allows you to dynamically inject JavaScript code into the app's runtime and intercept method calls.

Here's an example of how to hook these methods using Frida:

Java.perform(function() {
  var MainActivity = Java.use('com.example.MainActivity');

  MainActivity.onStart.implementation = function() {
    console.log('Hooked MainActivity.onStart()');
    // Your custom code here

    // Call the original method
    this.onStart();
  };

  MainActivity.onCreate.implementation = function() {
    console.log('Hooked MainActivity.onCreate()');
    // Your custom code here

    // Call the original method
    this.onCreate();
  };
});

In the above code, we first use Java.use() to get a reference to the MainActivity class. Then, we override the .onStart() and .onCreate() methods using .implementation. Inside the overridden methods, you can add your custom code to be executed when these methods are called. Finally, we call the original methods using this.onStart() and this.onCreate().

Remember to replace 'com.example.MainActivity' with the actual package and class name of the MainActivity in the app you are testing.

By hooking these methods, you can intercept their execution and perform actions such as logging, modifying parameters, or even bypassing certain checks. This can be useful for analyzing the behavior of the app and identifying potential vulnerabilities.

Note: Make sure you have the necessary permissions and legal authorization before performing any app penetration testing.

var mainactivity = Java.use("sg.vantagepoint.uncrackable1.MainActivity");
mainactivity.onStart.overload().implementation = function() {
send("MainActivity.onStart() HIT!!!");
var ret = this.onStart.overload().call(this);
};
mainactivity.onCreate.overload("android.os.Bundle").implementation = function(var_0) {
send("MainActivity.onCreate() HIT!!!");
var ret = this.onCreate.overload("android.os.Bundle").call(this,var_0);
};

Hook android .onCreate()

Per intercettare il metodo .onCreate() di un'applicazione Android, possiamo utilizzare Frida. Questo ci permette di eseguire del codice personalizzato prima o dopo l'esecuzione del metodo .onCreate() dell'app.

Ecco un esempio di come fare ciò utilizzando Frida:

Java.perform(function() {
    var MainActivity = Java.use('com.example.MainActivity');
    
    MainActivity.onCreate.implementation = function() {
        // Codice personalizzato da eseguire prima dell'esecuzione di .onCreate()
        console.log('Metodo .onCreate() intercettato!');
        
        // Chiamata al metodo originale .onCreate()
        this.onCreate();
        
        // Codice personalizzato da eseguire dopo l'esecuzione di .onCreate()
        console.log('Metodo .onCreate() completato!');
    };
});

In questo esempio, stiamo intercettando il metodo .onCreate() della classe MainActivity dell'applicazione Android. Prima dell'esecuzione del metodo originale, stiamo stampando un messaggio di log. Successivamente, chiamiamo il metodo originale .onCreate() e, infine, stampiamo un altro messaggio di log dopo l'esecuzione del metodo.

Ricorda che per utilizzare Frida, devi avere un dispositivo Android rootato o un emulatore con Frida Server installato.

var activity = Java.use("android.app.Activity");
activity.onCreate.overload("android.os.Bundle").implementation = function(var_0) {
send("Activity HIT!!!");
var ret = this.onCreate.overload("android.os.Bundle").call(this,var_0);
};

Hooking delle funzioni con parametri e recupero del valore

Hooking di una funzione di decrittografia. Stampa l'input, chiama la funzione originale per decrittare l'input e infine, stampa i dati in chiaro:

function getString(data){
var ret = "";
for (var i=0; i < data.length; i++){
ret += data[i].toString();
}
return ret
}
var aes_decrypt = Java.use("sg.vantagepoint.a.a");
aes_decrypt.a.overload("[B","[B").implementation = function(var_0,var_1) {
send("sg.vantagepoint.a.a.a([B[B)[B   doFinal(enc)  // AES/ECB/PKCS7Padding");
send("Key       : " + getString(var_0));
send("Encrypted : " + getString(var_1));
var ret = this.a.overload("[B","[B").call(this,var_0,var_1);
send("Decrypted : " + ret);

var flag = "";
for (var i=0; i < ret.length; i++){
flag += String.fromCharCode(ret[i]);
}
send("Decrypted flag: " + flag);
return ret; //[B
};

Hooking delle funzioni e chiamarle con il nostro input

Hook una funzione che riceve una stringa e chiamala con un'altra stringa (da qui)

var string_class = Java.use("java.lang.String"); // get a JS wrapper for java's String class

my_class.fun.overload("java.lang.String").implementation = function(x){ //hooking the new function
var my_string = string_class.$new("My TeSt String#####"); //creating a new String by using `new` operator
console.log("Original arg: " +x );
var ret =  this.fun(my_string); // calling the original function with the new String, and putting its return value in ret variable
console.log("Return value: "+ret);
return ret;
};

Ottenere un oggetto già creato di una classe

Se si desidera estrarre un attributo di un oggetto creato, è possibile utilizzare questo metodo.

In questo esempio vedrai come ottenere l'oggetto della classe my_activity e come chiamare la funzione .secret() che stamperà un attributo privato dell'oggetto:

Java.choose("com.example.a11x256.frida_test.my_activity" , {
onMatch : function(instance){ //This function will be called for every instance found by frida
console.log("Found instance: "+instance);
console.log("Result of secret func: " + instance.secret());
},
onComplete:function(){}
});

Altri tutorial su Frida

Suggerimento per bug bounty: iscriviti a Intigriti, una piattaforma premium per bug bounty creata da hacker, per hacker! Unisciti a noi su https://go.intigriti.com/hacktricks oggi stesso e inizia a guadagnare ricompense fino a $100,000!

Impara l'hacking di AWS da zero a eroe con htARTE (HackTricks AWS Red Team Expert)!

Altri modi per supportare HackTricks:

Last updated