Frida Tutorial

Frida 튜토리얼

htARTE (HackTricks AWS Red Team Expert)를 통해 AWS 해킹을 처음부터 전문가까지 배워보세요!

HackTricks를 지원하는 다른 방법:

버그 바운티 팁: 해커들에 의해 만들어진 프리미엄 버그 바운티 플랫폼인 Intigriti에 가입하세요! 오늘 https://go.intigriti.com/hacktricks에서 참여하여 최대 $100,000의 바운티를 받으세요!

설치

frida 도구를 설치하세요:

pip install frida-tools
pip install frida

frida 서버를 안드로이드에 다운로드하고 설치하세요 (최신 릴리스 다운로드). 루트 모드에서 adb를 재시작하고 연결한 후, frida-server를 업로드하고 실행 권한을 부여하여 백그라운드에서 실행하는 원라이너입니다:

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

작동하는지 확인하세요:

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

튜토리얼

출처: https://medium.com/infosec-adventures/introduction-to-frida-5a3f51595ca1 APK: https://github.com/t0thkr1s/frida-demo/releases 소스 코드: https://github.com/t0thkr1s/frida-demo

링크를 클릭하여 읽어보세요.

출처: https://11x256.github.io/Frida-hooking-android-part-2/ (파트 2, 3 및 4) APK 및 소스 코드: https://github.com/11x256/frida-android-examples

링크를 클릭하여 읽어보세요.

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

링크를 클릭하여 읽어보세요.

더 많은 멋진 Frida 스크립트를 찾을 수 있습니다: https://codeshare.frida.re/

빠른 예제

명령 줄에서 Frida 호출하기

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.

기본 Python 스크립트

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 () {
    // Hook the target method
    var targetClass = Java.use("com.example.app.TargetClass");
    targetClass.targetMethod.implementation = function () {
        // Modify the behavior of the target method
        console.log("Target method hooked!");
        // Call the original method
        this.targetMethod();
    };
});
"""

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

위의 Python 스크립트는 Frida를 사용하여 타겟 프로세스에 주입할 JavaScript 코드를 정의하고 실행하는 기본적인 예제입니다.

import frida

# 타겟 프로세스에 연결
session = frida.attach("com.example.app")

# 주입할 JavaScript 코드 정의
js_code = """
Java.perform(function () {
    // 타겟 메소드 후킹
    var targetClass = Java.use("com.example.app.TargetClass");
    targetClass.targetMethod.implementation = function () {
        // 타겟 메소드의 동작 수정
        console.log("타겟 메소드 후킹됨!");
        // 원본 메소드 호출
        this.targetMethod();
    };
});
"""

# 스크립트 생성
script = session.create_script(js_code)

# 스크립트를 타겟 프로세스에 로드
script.load()

# 타겟 프로세스와 연결 해제
session.detach()

이 스크립트는 com.example.app이라는 타겟 앱에 대해 Frida를 사용하여 JavaScript 코드를 주입하고 실행하는 방법을 보여줍니다. 타겟 앱의 TargetClass라는 클래스의 targetMethod 메소드를 후킹하여 동작을 수정하고, 원본 메소드를 호출하는 예제입니다.

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

매개변수가 없는 함수 후킹

sg.vantagepoint.a.c 클래스의 a() 함수를 후킹하세요.

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

Frida Tutorial: Hooking Java exit()

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

  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 at the beginning of the file:

const { Java } = require('frida');
  1. Attach Frida to the target application using the package name or process ID:

const processName = 'com.example.app';
const session = Java.openSession();
const target = Java.choose(processName, {
  onMatch: function (instance) {
    return instance;
  },
  onComplete: function () {
    console.log('Target not found');
    session.detach();
  }
});
  1. Define the hook function that will be executed when exit() is called:

function onExit() {
  console.log('Exit called');
  // Additional actions can be performed here
}
  1. Hook the exit() method using the Java.use() function:

const System = Java.use('java.lang.System');
System.exit.implementation = function () {
  onExit();
  this.exit();
};
  1. Save the JavaScript file and start the Frida server on your Android device or emulator.

  2. Launch the target application on the device or emulator.

  3. Use Frida to inject the JavaScript code into the target application:

frida -U -l hook_exit.js -f com.example.app

Replace com.example.app with the package name of the target application.

  1. You should see the message "Exit called" printed in the console whenever the exit() method is called in the target application.

Conclusion

By hooking the exit() method in Java using Frida, we can intercept the application's exit calls and perform additional actions. This technique can be useful for debugging, analyzing, or modifying the behavior of Android applications during penetration testing.

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

이 튜토리얼에서는 Frida를 사용하여 Android 앱의 MainActivity 클래스의 .onStart().onCreate() 메서드를 후킹하는 방법을 배우게 됩니다.

Frida란?

Frida는 동적 분석 도구로서, 앱의 실행 중에 코드를 수정하고 감시할 수 있도록 해주는 오픈 소스 프레임워크입니다. Frida를 사용하면 앱의 동작을 실시간으로 조작하고 분석할 수 있습니다.

필요한 도구

이 튜토리얼을 완료하기 위해 다음 도구들이 필요합니다:

  • Frida CLI (Command Line Interface)

  • 안드로이드 디바이스 또는 에뮬레이터

단계별 지침

  1. Frida를 설치하고 환경을 설정합니다. Frida CLI를 사용하여 Frida를 설치하고 안드로이드 디바이스 또는 에뮬레이터와 연결합니다.

  2. Frida 스크립트를 작성합니다. 다음과 같은 내용으로 hook.js 파일을 생성합니다:

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

    MainActivity.onStart.implementation = function() {
        console.log('MainActivity.onStart() hooked');
        this.onStart();
    };

    MainActivity.onCreate.implementation = function() {
        console.log('MainActivity.onCreate() hooked');
        this.onCreate();
    };
});
  1. Frida 스크립트를 실행합니다. 다음 명령어를 사용하여 Frida 스크립트를 실행합니다:

frida -U -l hook.js -f com.example.app
  1. 앱을 실행합니다. Frida 스크립트가 실행 중인 동안 앱을 실행합니다.

  2. 결과 확인. 앱이 .onStart() 또는 .onCreate() 메서드를 호출할 때마다 Frida 스크립트에서 정의한 후킹 함수가 실행되고 로그가 출력됩니다.

결론

이 튜토리얼에서는 Frida를 사용하여 Android 앱의 MainActivity 클래스의 .onStart().onCreate() 메서드를 후킹하는 방법을 배웠습니다. Frida를 사용하면 앱의 동작을 실시간으로 조작하고 분석할 수 있으므로, 앱의 동작을 이해하고 보안 취약점을 발견하는 데 도움이 됩니다.

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

안드로이드 .onCreate() 후킹

안드로이드 앱을 펜테스팅할 때, .onCreate() 메서드를 후킹하는 것은 매우 유용합니다. .onCreate() 메서드는 액티비티가 생성될 때 호출되는 메서드로, 앱의 초기화 및 설정을 담당합니다. 이 메서드를 후킹하여 앱의 동작을 조작하거나 중요한 정보를 수집할 수 있습니다.

Frida를 사용하여 안드로이드 앱의 .onCreate() 메서드를 후킹하는 방법은 다음과 같습니다:

  1. Frida를 설치하고 타겟 디바이스에 Frida 서버를 설치합니다.

  2. Frida 스크립트를 작성하여 .onCreate() 메서드를 후킹합니다.

  3. Frida 스크립트를 실행하여 후킹을 적용합니다.

다음은 Frida 스크립트의 예시입니다:

Java.perform(function() {
  var targetClass = Java.use('com.example.app.MainActivity');
  targetClass.onCreate.implementation = function() {
    console.log('Hooked .onCreate()');
    // 원하는 동작을 수행합니다.
    // 예: 중요한 정보를 수집하거나 조작합니다.
    this.onCreate();
  };
});

위 스크립트는 com.example.app.MainActivity 클래스의 .onCreate() 메서드를 후킹하고, 후킹이 적용되었음을 로그로 출력합니다. 원하는 동작을 수행한 후, this.onCreate()을 호출하여 원래의 .onCreate() 메서드를 실행합니다.

Frida 스크립트를 작성한 후, 다음 명령을 사용하여 Frida 스크립트를 실행합니다:

frida -U -f com.example.app -l script.js --no-pause

위 명령에서 com.example.app은 타겟 앱의 패키지 이름이며, script.js는 작성한 Frida 스크립트 파일입니다.

.onCreate() 메서드를 후킹하여 안드로이드 앱을 조작하거나 중요한 정보를 수집하는 것은 펜테스팅 과정에서 매우 유용한 기술입니다. Frida를 사용하여 이를 실현할 수 있습니다.

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

매개변수와 값을 검색하여 함수 후킹하기

복호화 함수 후킹하기. 입력값을 출력하고, 원래 함수를 호출하여 입력값을 복호화하고, 마지막으로 평문 데이터를 출력합니다:

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

함수 후킹 및 입력값으로 호출하기

문자열을 받는 함수를 후킹하고, 다른 문자열로 호출합니다 (여기에서 가져옴).

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

클래스의 이미 생성된 객체 가져오기

만약 생성된 객체의 어트리뷰트를 추출하고 싶다면, 다음을 사용할 수 있습니다.

이 예제에서는 클래스 my_activity의 객체를 가져오고, 객체의 비공개 어트리뷰트를 출력하는 함수 .secret()를 호출하는 방법을 볼 수 있습니다.

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

다른 Frida 튜토리얼

버그 바운티 팁: 해커들이 만든 프리미엄 버그 바운티 플랫폼인 Intigriti에 가입하세요! 오늘 https://go.intigriti.com/hacktricks에서 가입하고 최대 $100,000의 바운티를 받으세요!

htARTE (HackTricks AWS Red Team Expert)를 통해 AWS 해킹을 처음부터 전문가까지 배워보세요!

HackTricks를 지원하는 다른 방법:

Last updated