# Frida Tutorial

<details>

<summary><strong>从零开始学习 AWS 黑客技术，成为专家</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE（HackTricks AWS 红队专家）</strong></a><strong>！</strong></summary>

支持 HackTricks 的其他方式：

* 如果您想在 HackTricks 中看到您的**公司广告**或**下载 PDF 版本的 HackTricks**，请查看[**订阅计划**](https://github.com/sponsors/carlospolop)!
* 获取[**官方 PEASS & HackTricks 商品**](https://peass.creator-spring.com)
* 探索[**PEASS 家族**](https://opensea.io/collection/the-peass-family)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord 群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或在 **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks_live) 上 **关注**我们\*\*。\*\*
* 通过向 [**HackTricks**](https://github.com/carlospolop/hacktricks) 和 [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github 仓库提交 PR 来**分享您的黑客技巧**。

</details>

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-ce4fbfd491ab398bd58639023728b416b0758bc1%2Fi3.png?alt=media" alt=""><figcaption></figcaption></figure>

**漏洞赏金提示**：**注册** Intigriti，这是一家由黑客创建的高级**漏洞赏金平台**！立即加入我们，访问 [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks)，开始赚取高达\*\*$100,000\*\*的赏金！

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

## 安装

安装 **frida 工具**：

```bash
pip install frida-tools
pip install frida
```

**下载并安装**安卓设备上的**frida server**（[下载最新版本](https://github.com/frida/frida/releases)）。 一行命令以root模式重新启动adb，连接到adb，上传frida-server，赋予执行权限并在后台运行：

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

**检查**是否**有效**：

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

## 教程

### [教程 1](https://hacktricks.xsx.tw/mobile-pentesting/android-app-pentesting/frida-tutorial/frida-tutorial-1)

**来源**: <https://medium.com/infosec-adventures/introduction-to-frida-5a3f51595ca1>\
**APK**: <https://github.com/t0thkr1s/frida-demo/releases>\
**源代码**: <https://github.com/t0thkr1s/frida-demo>

**点击**[**链接阅读**](https://hacktricks.xsx.tw/mobile-pentesting/android-app-pentesting/frida-tutorial/frida-tutorial-1)**.**

### [教程 2](https://hacktricks.xsx.tw/mobile-pentesting/android-app-pentesting/frida-tutorial/frida-tutorial-2)

**来源**: <https://11x256.github.io/Frida-hooking-android-part-2/> (第2、3和4部分)\
**APK和源代码**: <https://github.com/11x256/frida-android-examples>

**点击**[**链接阅读**](https://hacktricks.xsx.tw/mobile-pentesting/android-app-pentesting/frida-tutorial/frida-tutorial-2)**.**

### [教程 3](https://hacktricks.xsx.tw/mobile-pentesting/android-app-pentesting/frida-tutorial/owaspuncrackable-1)

**来源**: <https://joshspicer.com/android-frida-1>\
**APK**: <https://github.com/OWASP/owasp-mstg/blob/master/Crackmes/Android/Level_01/UnCrackable-Level1.apk>

**点击**[**链接阅读**](https://hacktricks.xsx.tw/mobile-pentesting/android-app-pentesting/frida-tutorial/owaspuncrackable-1)**.**

**您可以在这里找到更多令人敬畏的Frida脚本:** [**https://codeshare.frida.re/**](https://codeshare.frida.re)

## 快速示例

### 从命令行调用Frida

```bash
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脚本

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

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

### Translate:

### Hook java `exit()`

### 翻译：

### 钩住java `exit()`

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

#### English

````markdown
1. Open the `hook_main_activity.js` file.
2. Add the following code to hook the `onStart()` and `onCreate()` methods of the MainActivity class:

```javascript
Java.perform(function() {
    var MainActivity = Java.use('com.example.app.MainActivity');
    
    MainActivity.onStart.implementation = function() {
        console.log('onStart() is called');
        this.onStart();
    };
    
    MainActivity.onCreate.implementation = function() {
        console.log('onCreate() is called');
        this.onCreate();
    };
});
````

````

#### Chinese
```markdown
1. 打开`hook_main_activity.js`文件。
2. 添加以下代码以钩住MainActivity类的`onStart()`和`onCreate()`方法：

```javascript
Java.perform(function() {
    var MainActivity = Java.use('com.example.app.MainActivity');
    
    MainActivity.onStart.implementation = function() {
        console.log('onStart()被调用');
        this.onStart();
    };
    
    MainActivity.onCreate.implementation = function() {
        console.log('onCreate()被调用');
        this.onCreate();
    };
});
````

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

### English

```markdown
To hook the `.onCreate()` method of an Android application, you can use Frida to intercept the method call and execute your custom code. This can be useful for various purposes such as dynamic analysis, debugging, or modifying the behavior of the application.

Here is an example of how you can hook the `.onCreate()` method using Frida:

1. Write a Frida script to intercept the `.onCreate()` method.
2. Load the script into the target Android application using Frida.
3. Run the application and observe the custom code execution when `.onCreate()` is called.

By hooking the `.onCreate()` method, you can gain insights into the application's initialization process and potentially modify its behavior in real-time.
```

### Chinese

````markdown
要钩住Android应用程序的`.onCreate()`方法，您可以使用Frida拦截方法调用并执行自定义代码。这对于动态分析、调试或修改应用程序行为等各种目的都很有用。

以下是使用Frida钩住`.onCreate()`方法的示例：

1. 编写一个Frida脚本来拦截`.onCreate()`方法。
2. 使用Frida将脚本加载到目标Android应用程序中。
3. 运行应用程序，并观察在调用`.onCreate()`时自定义代码的执行情况。

通过钩住`.onCreate()`方法，您可以深入了解应用程序的初始化过程，并在实时中潜在地修改其行为。
```javascript
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);
};
````

### 使用参数挂钩函数并检索值

挂钩解密函数。打印输入，调用原始函数解密输入，最后打印明文数据：

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

### 钩住函数并使用我们的输入调用它

钩住一个接收字符串的函数，并用另一个字符串调用它（来自[这里](https://11x256.github.io/Frida-hooking-android-part-2/)）

```javascript
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()来打印对象的私有属性：

```javascript
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教程

* <https://github.com/DERE-ad2001/Frida-Labs>
* [高级Frida用法博客系列第1部分：IOS加密库](https://8ksec.io/advanced-frida-usage-part-1-ios-encryption-libraries-8ksec-blogs/)

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-ce4fbfd491ab398bd58639023728b416b0758bc1%2Fi3.png?alt=media" alt=""><figcaption></figcaption></figure>

**漏洞赏金提示**：**注册**Intigriti，一个由黑客创建的高级**漏洞赏金平台**！立即加入我们，访问[**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks)，开始赚取高达\*\*$100,000\*\*的赏金！

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

<details>

<summary><strong>从零开始学习AWS黑客技术，成为专家</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE（HackTricks AWS Red Team Expert）</strong></a><strong>！</strong></summary>

支持HackTricks的其他方式：

* 如果您想在HackTricks中看到您的**公司广告**或**下载PDF格式的HackTricks**，请查看[**订阅计划**](https://github.com/sponsors/carlospolop)!
* 获取[**官方PEASS & HackTricks周边产品**](https://peass.creator-spring.com)
* 探索[**PEASS家族**](https://opensea.io/collection/the-peass-family)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>
