hacktricks/mobile-pentesting/android-app-pentesting/frida-tutorial
2023-12-16 14:33:49 +00:00
..
frida-tutorial-1.md Translated ['README.md', 'backdoors/salseo.md', 'forensics/basic-forensi 2023-12-16 14:33:49 +00:00
frida-tutorial-2.md Translated to French 2023-06-03 13:10:46 +00:00
objection-tutorial.md Translated ['backdoors/salseo.md', 'forensics/basic-forensic-methodology 2023-08-22 10:39:53 +00:00
owaspuncrackable-1.md Translated ['README.md', 'backdoors/salseo.md', 'forensics/basic-forensi 2023-12-16 14:33:49 +00:00
README.md Translated ['generic-methodologies-and-resources/external-recon-methodol 2023-12-11 09:52:39 +00:00

Tutoriel Frida

☁️ HackTricks Cloud ☁️ -🐦 Twitter 🐦 - 🎙️ Twitch 🎙️ - 🎥 Youtube 🎥

Astuce de bug bounty : inscrivez-vous sur Intigriti, une plateforme premium de bug bounty créée par des hackers, pour des hackers ! Rejoignez-nous sur https://go.intigriti.com/hacktricks dès aujourd'hui et commencez à gagner des primes allant jusqu'à 100 000 $ !

{% embed url="https://go.intigriti.com/hacktricks" %}

Installation

Installez les outils frida :

pip install frida-tools
pip install frida

Téléchargez et installez sur l'Android le serveur frida (Téléchargez la dernière version).
Une ligne de commande pour redémarrer adb en mode root, se connecter à celui-ci, télécharger frida-server, donner les permissions d'exécution et l'exécuter en arrière-plan :

{% code overflow="wrap" %}

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 &"

{% endcode %}

Vérifiez si cela fonctionne :

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

Tutoriels

Tutoriel 1

Depuis: https://medium.com/infosec-adventures/introduction-to-frida-5a3f51595ca1
APK: https://github.com/t0thkr1s/frida-demo/releases
Code source: https://github.com/t0thkr1s/frida-demo

Suivez le lien pour le lire.

Tutoriel 2

Depuis: https://11x256.github.io/Frida-hooking-android-part-2/ (Parties 2, 3 et 4)
APKs et code source: https://github.com/11x256/frida-android-examples

Suivez le lien pour le lire.

Tutoriel 3

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

Suivez le lien pour le lire.
Vous pouvez trouver des scripts Frida impressionnants ici: https://codeshare.frida.re/

Exemples rapides

Ici, vous pouvez trouver les fonctionnalités les plus basiques et intéressantes de Frida pour créer rapidement un script :

Appeler Frida depuis la ligne de commande

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 de 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 () {
    // Find the target method
    var targetMethod = Java.use("com.example.app.TargetClass.targetMethod");

    // Hook the target method
    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
        result += 100;

        // 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 de base

import frida

# Se connecter au processus cible
session = frida.attach("com.example.app")

# Définir le code JavaScript à injecter
js_code = """
Java.perform(function () {
    // Trouver la méthode cible
    var targetMethod = Java.use("com.example.app.TargetClass.targetMethod");

    // Accrocher la méthode cible
    targetMethod.implementation = function () {
        // Afficher les arguments passés à la méthode
        console.log("Arguments : " + Array.prototype.slice.call(arguments));

        // Appeler la méthode originale
        var result = this.targetMethod.apply(this, arguments);

        // Afficher le résultat
        console.log("Résultat : " + result);

        // Modifier le résultat
        result += 100;

        // Retourner le résultat modifié
        return result;
    };
});
"""

# Créer le script
script = session.create_script(js_code)

# Charger le script dans le processus cible
script.load()

# Se détacher du processus cible
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()

Accrocher des fonctions sans paramètres

Accrochez la fonction a() de la 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()

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 getting started, make sure you have the following:

  • A rooted Android device or an emulator
  • Frida Server installed on the device/emulator
  • Frida Python bindings installed on your computer

Steps

  1. Launch the target application on your device/emulator.

  2. Open a terminal and start the Frida server:

    frida-server -D
    
  3. Create a new Python script, for example, exit_hook.py, and import the necessary Frida modules:

    import frida
    import sys
    
  4. Define a function that will be called when the exit() method is invoked:

    def on_exit_called(message, data):
        print("[*] exit() called")
        # Perform additional actions here
    
  5. Connect to the target application using Frida:

    try:
        session = frida.get_usb_device().attach('com.example.app')
    except Exception as e:
        print("Failed to attach to the target process:", e)
        sys.exit(1)
    
  6. Retrieve the exit() method from the Java Virtual Machine (JVM) and hook it:

    try:
        script = session.create_script("""
            Java.perform(function () {
                var System = Java.use('java.lang.System');
                System.exit.implementation = function () {
                    send("[*] exit() called");
                    // Perform additional actions here
                    this.exit();
                };
            });
        """)
        script.on('message', on_exit_called)
        script.load()
        sys.stdin.read()
    except Exception as e:
        print("Failed to create script:", e)
        sys.exit(1)
    
  7. Save and run the Python script:

    python exit_hook.py
    
  8. Trigger the exit() method in the target application, either by closing the application or by calling System.exit() explicitly.

  9. Check the terminal output to see if the hook was successful. You should see the message [*] exit() called printed.

By hooking the exit() method, we can intercept and modify the behavior of the target application before it exits. This technique can be useful for various purposes, such as debugging, analyzing application flow, or implementing custom cleanup logic.

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, we can use the Frida framework. Frida allows us 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.app.MainActivity');

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

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

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

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

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

By hooking these methods, we can perform various actions such as logging method calls, modifying method behavior, or even bypassing certain checks. This can be useful for analyzing the app's behavior, identifying vulnerabilities, or testing security controls.

Remember to run this code using Frida on a rooted or jailbroken device, or with the appropriate permissions if running on a non-rooted device.

Happy hacking!

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()

To hook the .onCreate() method in an Android application, we can use the Frida framework. Frida allows us to dynamically inject JavaScript code into the target application and modify its behavior.

Here's an example of how to hook the .onCreate() method using Frida:

Java.perform(function() {
    var targetClass = Java.use('com.example.MyActivity');
    targetClass.onCreate.implementation = function(savedInstanceState) {
        // Your custom code here
        console.log('Hooked .onCreate()');
        
        // Call the original method
        this.onCreate(savedInstanceState);
    };
});

In the above code, we first use Java.use() to get a reference to the target class (com.example.MyActivity). Then, we override the .onCreate() method by assigning our custom implementation to targetClass.onCreate.implementation. Inside the custom implementation, we can add our own code to be executed when the .onCreate() method is called. Finally, we call the original method using this.onCreate(savedInstanceState).

Remember to replace com.example.MyActivity with the actual class name you want to hook.

By hooking the .onCreate() method, we can intercept and modify the initialization logic of an Android application, allowing us to perform various actions such as logging, debugging, or even modifying the application's behavior.

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

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);
};

Accrocher des fonctions avec des paramètres et récupérer la valeur

Accrocher une fonction de décryptage. Imprimer l'entrée, appeler la fonction originale pour décrypter l'entrée et enfin, imprimer les données en clair :

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
};

Accrocher des fonctions et les appeler avec notre entrée

Accrochez une fonction qui reçoit une chaîne de caractères et appelez-la avec une autre chaîne de caractères (à partir de ici)

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;
};

Obtenir un objet déjà créé d'une classe

Si vous souhaitez extraire un attribut d'un objet créé, vous pouvez utiliser ceci.

Dans cet exemple, vous allez voir comment obtenir l'objet de la classe my_activity et comment appeler la fonction .secret() qui affichera un attribut privé de l'objet :

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(){}
});

Autres tutoriels sur Frida

Astuce pour les primes de bug: inscrivez-vous sur Intigriti, une plateforme premium de prime de bug créée par des hackers, pour des hackers! Rejoignez-nous sur https://go.intigriti.com/hacktricks dès aujourd'hui et commencez à gagner des primes allant jusqu'à 100 000 $!

{% embed url="https://go.intigriti.com/hacktricks" %}

☁️ HackTricks Cloud ☁️ -🐦 Twitter 🐦 - 🎙️ Twitch 🎙️ - 🎥 Youtube 🎥