Frida Tutorial

Samouczek Frida

Naucz się hakować AWS od zera do bohatera z htARTE (HackTricks AWS Red Team Expert)!

Inne sposoby wsparcia HackTricks:

Wskazówka dotycząca bug bounty: zarejestruj się na platformie Intigriti, premium platformie bug bounty stworzonej przez hakerów, dla hakerów! Dołącz do nas na https://go.intigriti.com/hacktricks już dziś i zacznij zarabiać nagrody do 100 000 USD!

Instalacja

Zainstaluj narzędzia Frida:

pip install frida-tools
pip install frida

Pobierz i zainstaluj na urządzeniu Android serwer Frida (Pobierz najnowsze wydanie). Jednolinijkowe polecenie do ponownego uruchomienia adb w trybie root, połączenia z nim, przesłania frida-server, nadania uprawnień do wykonania i uruchomienia go w tle:

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

Sprawdź, czy to działa:

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

Samouczki

Źródło: https://medium.com/infosec-adventures/introduction-to-frida-5a3f51595ca1 APK: https://github.com/t0thkr1s/frida-demo/releases Kod źródłowy: https://github.com/t0thkr1s/frida-demo

Kliknij link, aby przeczytać.

Źródło: https://11x256.github.io/Frida-hooking-android-part-2/ (Części 2, 3 i 4) APK i kod źródłowy: https://github.com/11x256/frida-android-examples

Kliknij link, aby przeczytać.

Źródło: https://joshspicer.com/android-frida-1 APK: https://github.com/OWASP/owasp-mstg/blob/master/Crackmes/Android/Level_01/UnCrackable-Level1.apk

Kliknij link, aby przeczytać.

Więcej niesamowitych skryptów Frida znajdziesz tutaj: https://codeshare.frida.re/

Szybkie przykłady

Wywoływanie Fridy z wiersza poleceń

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.

Podstawowy skrypt Pythona

import frida

# Connect to the USB device
device = frida.get_usb_device()

# Attach to the target process
pid = device.spawn(["com.example.app"])
session = device.attach(pid)

# Load the JavaScript code
with open("script.js", "r") as file:
    script_code = file.read()

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

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

# Resume the target process
device.resume(pid)

# Keep the script running
input("Press Enter to stop...")

# Clean up
session.detach()
device.kill(pid)

Podstawowy skrypt Pythona

import frida

# Połącz się z urządzeniem USB
device = frida.get_usb_device()

# Dołącz do procesu docelowego
pid = device.spawn(["com.example.app"])
session = device.attach(pid)

# Wczytaj kod JavaScript
with open("script.js", "r") as file:
    script_code = file.read()

# Utwórz skrypt
script = session.create_script(script_code)

# Wczytaj skrypt do procesu docelowego
script.load()

# Wznów działanie procesu docelowego
device.resume(pid)

# Utrzymuj działanie skryptu
input("Naciśnij Enter, aby zatrzymać...")

# Sprzątanie
session.detach()
device.kill(pid)
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()

Hookowanie funkcji bez parametrów

Zahacz funkcję a() z klasy 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 Java 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

Follow these steps to hook the exit() method:

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

  2. Open a terminal and start the Frida server by running the following command:

    frida-server
  3. Create a new JavaScript file, for example hook_exit.js, and add the following code:

    Java.perform(function() {
        var System = Java.use('java.lang.System');
        var Runtime = Java.use('java.lang.Runtime');
    
        // Hook the exit() method of System class
        System.exit.implementation = function(code) {
            console.log('System.exit() called with code: ' + code);
    
            // Perform additional actions here
    
            // Call the original exit() method
            this.exit(code);
        };
    
        // Hook the exit() method of Runtime class
        Runtime.getRuntime().exit.implementation = function(code) {
            console.log('Runtime.exit() called with code: ' + code);
    
            // Perform additional actions here
    
            // Call the original exit() method
            this.exit(code);
        };
    });
  4. Save the JavaScript file.

  5. In the terminal, navigate to the directory where the JavaScript file is saved.

  6. Use Frida to inject the JavaScript code into the target application by running the following command:

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

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

  7. You should see the output of the console.log() statements in the terminal whenever the exit() method is called.

  8. Customize the additional actions in the JavaScript code as per your requirements.

Conclusion

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

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

Frida Tutorial: Hook MainActivity .onStart() & .onCreate()

W tym samouczku dowiesz się, jak używać Fridy do przechwytywania wywołań metod .onStart() i .onCreate() w klasie MainActivity w aplikacji Androidowej.

Wymagania

Aby zacząć, musisz mieć zainstalowane następujące narzędzia:

Kroki

  1. Sklonuj repozytorium z przykładową aplikacją Androidową:

    git clone https://github.com/example/example-app.git
  2. Otwórz projekt w Android Studio i zbuduj go.

  3. Uruchom aplikację na urządzeniu lub emulatorze.

  4. Uruchom Fridę w trybie serwera na swoim komputerze:

    frida-server
  5. Uruchom skrypt Fridy, który przechwytuje wywołania metod .onStart() i .onCreate() w klasie MainActivity:

    Java.perform(function () {
        var MainActivity = Java.use('com.example.app.MainActivity');
    
        MainActivity.onStart.implementation = function () {
            console.log('Hooked MainActivity.onStart()');
            this.onStart();
        };
    
        MainActivity.onCreate.implementation = function (savedInstanceState) {
            console.log('Hooked MainActivity.onCreate()');
            this.onCreate(savedInstanceState);
        };
    });
  6. Podłącz się do urządzenia/emulatora za pomocą Fridy:

    frida -U com.example.app -l script.js
  7. Teraz, gdy aplikacja zostanie uruchomiona, zobaczysz w konsoli wiadomości potwierdzające, że metody .onStart() i .onCreate() zostały przechwycone.

Podsumowanie

Dzięki Fridzie możesz łatwo przechwytywać wywołania metod w aplikacjach Androidowych. W tym samouczku nauczyłeś się, jak przechwycić metody .onStart() i .onCreate() w klasie MainActivity.

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

Introduction

In this tutorial, we will learn how to hook the .onCreate() method in an Android application using Frida. By hooking this method, we can intercept and modify the behavior of the application during its initialization process.

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 Android development

Steps

  1. Start by launching the target application on your device or emulator.

  2. Open a terminal and run the following command to start the Frida server:

    frida-server
  3. Next, we need to find the process ID (PID) of the target application. Run the following command to list all running processes:

    frida-ps -U

    Look for the process corresponding to the target application and note down its PID.

  4. Now, create a new JavaScript file (e.g., hook.js) and add the following code:

    Java.perform(function() {
        var targetClass = Java.use('com.example.TargetClass');
        targetClass.onCreate.implementation = function() {
            console.log('onCreate() hooked');
            // Add your custom code here
            this.onCreate();
        };
    });

    Replace com.example.TargetClass with the actual class name of the target application.

  5. Save the hook.js file and run the following command to start the hooking process:

    frida -U -l hook.js -p <PID>

    Replace <PID> with the PID of the target application obtained in step 3.

  6. If everything is set up correctly, you should see the message onCreate() hooked in the Frida console.

  7. Now, whenever the target application's .onCreate() method is called, your custom code will be executed.

Conclusion

By hooking the .onCreate() method in an Android application using Frida, you can gain control over the application's initialization process and modify its behavior as desired. This technique can be useful for various purposes, such as bypassing security checks or analyzing the application's internal workings.

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

Hookowanie funkcji z parametrami i pobieranie wartości

Hookowanie funkcji deszyfrującej. Wyświetl wejście, wywołaj oryginalną funkcję, odszyfruj dane wejściowe i na koniec wyświetl odszyfrowane dane:

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

Hookowanie funkcji i wywoływanie ich z naszym wejściem

Zahacz funkcję, która przyjmuje ciąg znaków i wywołaj ją z innym ciągiem znaków (od tutaj).

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

Pobieranie już utworzonego obiektu klasy

Jeśli chcesz wyodrębnić pewną cechę utworzonego obiektu, możesz to zrobić za pomocą tego sposobu.

W tym przykładzie zobaczysz, jak pobrać obiekt klasy my_activity i jak wywołać funkcję .secret(), która wyświetli prywatną cechę obiektu:

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

Inne samouczki Frida

Wskazówka dotycząca nagrody za błąd: Zarejestruj się na platformie Intigriti, premium platformie nagród za błędy stworzonej przez hakerów, dla hakerów! Dołącz do nas na https://go.intigriti.com/hacktricks już dziś i zacznij zarabiać nagrody do 100 000 USD!

Naucz się hakować AWS od zera do bohatera z htARTE (HackTricks AWS Red Team Expert)!

Inne sposoby wsparcia HackTricks:

Last updated