首页
论坛
课程
招聘
[原创]XCTF黑客精神—Frida RPC爆破
2021-4-9 21:00 9135

[原创]XCTF黑客精神—Frida RPC爆破

2021-4-9 21:00
9135

1. 背景

此题比较简单,网上也有各种各样的wp。wp可以分为两类,一类分析算法,另一类是爆破。此题采用的是异或算法,所以分析算法求flag是最快的。而爆破的话,可以重写成等价的代码,如C++、python,或者直接采用主动调用的方式进行爆破,如Frida的主动调用。采用主动调用的好处是不用重写,而我采用Frida RPC进行主动调用的目的是想利用python丰富的库,方便爆破,缺点相对于直接用JS代码进行爆破是太慢了,慢了200多倍。

  • 用到的工具:
    • pixel 3 android 9.0(不能用模拟器,因为被hook的libmyjni.so只有arm架构的)
    • jadx
    • IDA
    • Frida12.8
    • Pycharm
    • VSCode

2. 分析过程

输入注册码,显示如下:

 

 

在代码中搜索"您的注册码已保存",相关代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class RegActivity extends Activity {
    private Button btn_reg;
    private EditText edit_sn;
 
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reg);
        this.btn_reg = (Button) findViewById(R.id.button1);
        this.edit_sn = (EditText) findViewById(R.id.editText1);
        this.btn_reg.setOnClickListener(new View.OnClickListener() {
            /* class com.gdufs.xman.RegActivity.AnonymousClass1 */
 
            public void onClick(View v) {
                String sn = RegActivity.this.edit_sn.getText().toString().trim();
                if (sn == null || sn.length() == 0) {
                    Toast.makeText(RegActivity.this, "您的输入为空", 0).show();
                    return;
                }
                ((MyApp) RegActivity.this.getApplication()).saveSN(sn);
                new AlertDialog.Builder(RegActivity.this).setTitle("回复").setMessage("您的注册码已保存").setPositiveButton("好吧", new DialogInterface.OnClickListener() {
                    /* class com.gdufs.xman.RegActivity.AnonymousClass1.AnonymousClass1 */
 
                    public void onClick(DialogInterface dialog, int which) {
                        Process.killProcess(Process.myPid());
                    }
                }).show();
            }
        });
    }
}

然后跳转到saveSN函数所在的类MyApp,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class MyApp extends Application {
    public static int m = 0;
 
    public native void initSN();
 
    public native void saveSN(String str);
 
    public native void work();
 
    static {
        System.loadLibrary("myjni");
    }
 
    public void onCreate() {
        initSN();
        Log.d("com.gdufs.xman m=", String.valueOf(m));
        super.onCreate();
    }
}

接着分析libmyjni.so文件,在JNI_OnLoad函数中注册了initSNsaveSNwork函数,代码如下:

 

 

2.1 分析initSN函数

首先分析initSN函数,其中setValue函数的作用是设置com/gdufs/xman/MyApp类的静态字段m的值,

 

 

 

initSN函数只做了一件事,即如果/sdcard/reg.dat文件的内容是"EoPAoY62@ElRD",com/gdufs/xman/MyApp类的静态字段m的值则设置为1,否则设置为0

 

通过对com/gdufs/xman/MyApp类的静态字段m交叉引用发现,如果m的值为1,则显示已注册,所以我们怀疑输入的注册码通过一系列的计算后得到的值会保存到/sdcard/reg.dat文件中,如果得到的值为"EoPAoY62@ElRD",则输入的注册码即为flag

 

2.2 分析 saveSN函数

saveSN也只干了一件事,把输入的注册码经过异或运算之后存到了/sdcard/reg.dat文件中

 

 

 

我们可以试试,直接把/sdcard/reg.dat文件的内容替换成"EoPAoY62@ElRD",会是什么效果,如下:

 

 

则我们的flag格式为xman{注册码}

3. 编写脚本

通过上面的分析过程可知,我们可以通过Frida主动调用的方式爆破出flag,首先给出直接用JS代码进行爆破的脚本,再给出RPC爆破的脚本。

3.1 JS代码爆破

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
var fputs_str = null;
 
function Hook() {
    Java.perform(function () {
        const imports = Module.enumerateImportsSync("libmyjni.so");
        const imports_len = imports.length;
        var fputs_addr = null;
        for (var i = 0; i < imports_len; i++) {
            if (imports[i].name == "fputs") {
                fputs_addr = imports[i].address;
                break;
            }
        }
        if (fputs_addr != null) {
            Interceptor.attach(fputs_addr, {
                onEnter: function (args) {
                    fputs_str = args[0].readCString();
                },
                onLeave: function (retval) {
                }
            })
        }
    })
}
 
function Invoke(try_str) {
    Java.perform(function () {
        Java.choose("com.gdufs.xman.MyApp", {
            onMatch: function (instance) {
                instance.saveSN(try_str);
            },
            onComplete: function () {
            }
        })
    })
}
 
function Main() {
    Hook();
    Java.perform(function () {
        const three_character_array = new Array("EoP", "AoY", "62@", "ElR");
        const last_character = "D";
        const my_dict = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?_"
        const myapp_class_obj = Java.use("com.gdufs.xman.MyApp");
        const three_character_array_len = three_character_array.length;
        const my_dict_len = my_dict.length
        const myapp = Java.use("com.gdufs.xman.MyApp").$new();
        var flag = "";
        for (var i = 0; i < three_character_array_len; i++) {
            var found = false;
            for (var j = 0; j < my_dict_len; j++) {
                if (found == true) {
                    break;
                }
                for (var k = 0; k < my_dict_len; k++) {
                    if (found == true) {
                        break;
                    }
                    for (var m = 0; m < my_dict_len; m++) {
                        const try_str = my_dict[j] + my_dict[k] + my_dict[m];
                        console.log(`try_str: ${try_str}`);
                        myapp.saveSN(try_str);
                        if (three_character_array[i] == fputs_str) {
                            flag += try_str;
                            console.log(`found: ${try_str}`);
                            found = true;
                            break;
                        }
                    }
                }
            }
        }
 
        for (var i = 0; i < my_dict_len; i++) {
            const try_str = my_dict[i];
            console.log(`try_str: ${try_str}`);
            Invoke(try_str);
            if (last_character == fputs_str) {
                flag += try_str;
                console.log(`found: ${try_str}`);
                break;
            }
        }
        console.log(`flag: xman{${flag}}`);
    })
}
 
//不能用setImmediate(Main),会出现Process crashed: SIGSYS SYS_SECCOMP
//需要延迟一下再爆破
setTimeout(Main, 500);

 

花了大概两分钟爆破出了flag

3.2 RPC爆破

JavaScript代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
var myapp = null;
 
function Hook() {
    Java.perform(function () {
        myapp = Java.use("com.gdufs.xman.MyApp").$new();
        const imports = Module.enumerateImportsSync("libmyjni.so");
        const imports_len = imports.length;
        var fputs_addr = null;
        for (var i = 0; i < imports_len; i++) {
            if (imports[i].name == "fputs") {
                fputs_addr = imports[i].address;
                break;
            }
        }
        if (fputs_addr != null) {
            Interceptor.attach(fputs_addr, {
                onEnter: function (args) {
                    send(args[0].readCString());
                },
                onLeave: function (retval) {
                }
            })
        }
    })
}
 
function Invoke(try_str) {
    Java.perform(function () {
        myapp.saveSN(try_str);
    })
}
 
rpc.exports = {
    hook: Hook,
    invoke: Invoke
}

Python代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
from itertools import permutations
import sys
import time
import frida
 
result = ""
received = False
 
 
def MessageHandler(message, data):
    if message["type"] == "send":
        global result
        global received
        result = message["payload"]
        received = True
    else:
        print(message)
 
 
def GeneratePossibilities(dict, count, repetitive=False):
    """
 
    :param dict: Dictionary
    :param count: Number of characters per group
    :param repetitive: Whether there are duplicate characters in each group
    :return: return permutations(dict, count)
    """
    if repetitive and (count > 1):
        src_dict = dict
        for i in range(count - 1):
            dict += src_dict
    return permutations(dict, count)
 
 
device = frida.get_device_manager().add_remote_device("192.168.1.5:8888")
pid = device.spawn("com.gdufs.xman")
session = device.attach(pid)
with open("index.js") as file_descriptor:
    script = session.create_script(file_descriptor.read(), runtime="v8")
    script.on("message", MessageHandler)
    script.load()
    time.sleep(1)
    device.resume(pid)
 
goal_three_character_array = ["EoP", "AoY", "62@", "ElR"]
goal_three_character_array_length = len(goal_three_character_array)
goal_last_character = "D"
my_dict = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?_"
flag = ['*'] * 13
possibilities = GeneratePossibilities(my_dict, 3, True)
time.sleep(1)
time_begin = time.time()
script.exports.hook()
first_part_times = 0
try_count = 0
for p in possibilities:
    character1, character2, character3 = p
    try_str = character1 + character2 + character3
    try_count += 1
    sys.stdout.write("[{}]Try_str: {}\r".format(try_count, "".join(try_str)))
    sys.stdout.flush()
    received = False
    script.exports.invoke(try_str)
    while not received:
        pass
    for i in range(goal_three_character_array_length):
        if result == goal_three_character_array[i]:
            if flag[i * 3] == "*":
                first_part_times += 1
            flag[i * 3: i * 3 + 3] = character1, character2, character3
            break
    sys.stdout.write("[*] Flag: xman{{{}}} ".format("".join(flag)))
    sys.stdout.flush()
    if first_part_times == 4:
        break
# 清屏
print("\033c")
try_count = 0
for try_str in my_dict:
    sys.stdout.write("[{}]Try_str: {}\r".format(try_count, "".join(try_str)))
    script.exports.invoke(try_str)
    if result == goal_last_character:
        flag[12] = try_str
        break
    sys.stdout.write("[*] Flag: xman{{{}}} ".format("".join(flag)))
    sys.stdout.flush()
# 清屏
print("\033c")
print("[*] Flag: xman{{{}}}".format("".join(flag)))
time_end = time.time()
cost_time = time_end - time_begin
print(" cost time: " + str(cost_time // 60) + "min")

 

采用RPC爆破的方式花了429分钟才爆破出了flag,花的时间是直接使用JS代码进行爆破的214倍

4. 问题答疑

4.1 设备问题

如果出现各种无法解决的问题,尝试换成跟我一样的设备和系统——pixel 3、android 9.0

4.2 出现global reference table overflow

错误是全局引用表溢出了,具体意思是Java对象的全局引用表溢出了,你在循环里new Java对象就可能会溢出,因为frida对Java对象的引用就是用的全局引用,不知道什么时候才释放,反正循环的时候没有释放

4.3 爆破卡住了

多次调用Java.choose程序就会卡住,好像跟frida版本无关,不知道为什么,所以我直接new一个对象进行主动调用

4.4 为什么233字符没有被爆破出来?

排列使用的字典是没有重复字符的,所以3个字符中不可能同时出现两个相同的字符,下面的代码就会出现这种问题

1
2
my_dict = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?_"
permutations(dict, 3)

解决办法是把字典自加多次,代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def GeneratePossibilities(dict, count, repetitive=False):
    """
 
    :param dict: Dictionary
    :param count: Number of characters per group
    :param repetitive: Whether there are duplicate characters in each group
    :return: return permutations(dict, count)
    """
    if repetitive and (count > 1):
        src_dict = dict
        for i in range(count - 1):
            dict += src_dict
    return permutations(dict, count)
 
my_dict = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?_"
possibilities = GeneratePossibilities(my_dict, 3, True)

5. 附件

链接:https://pan.baidu.com/s/1NRPGU_j6CK7bgB363FN33w
提取码:09wb


2022 KCTF春季赛【最佳人气奖】火热评选中!快来投票吧~

最后于 2021-4-21 11:17 被genliese编辑 ,原因:
收藏
点赞2
打赏
分享
最新回复 (6)
雪    币: 74
活跃值: 活跃值 (651)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
saloyun 活跃值 2021-4-14 08:46
2
0
good job
雪    币: 1245
活跃值: 活跃值 (567)
能力值: ( LV4,RANK:50 )
在线值:
发帖
回帖
粉丝
hackdaliu 活跃值 1 2021-4-24 10:43
3
0
好奇,我用这个Frida调试的时候,为什么找不到这个进程呢?直接ps能看到,frida-ps -U就找不到这个com.gdufs.xman进程了?
雪    币: 1245
活跃值: 活跃值 (567)
能力值: ( LV4,RANK:50 )
在线值:
发帖
回帖
粉丝
hackdaliu 活跃值 1 2021-4-24 11:44
4
0
hackdaliu 好奇,我用这个Frida调试的时候,为什么找不到这个进程呢?直接ps能看到,frida-ps -U就找不到这个com.gdufs.xman进程了?
找到原因了,之前装的frida,这次升级只升级了frida,没有连frida-tools一起升级导致的。。
雪    币: 2370
活跃值: 活跃值 (2086)
能力值: ( LV6,RANK:90 )
在线值:
发帖
回帖
粉丝
genliese 活跃值 1 2021-4-24 11:49
5
0
hackdaliu 找到原因了,之前装的frida,这次升级只升级了frida,没有连frida-tools一起升级导致的。。
好的
雪    币: 22
能力值: ( LV1,RANK:0 )
在线值:
发帖
回帖
粉丝
万里星河 活跃值 2021-4-25 08:44
6
0
这不是非虫大佬提供的crackMe吗
雪    币: 210
活跃值: 活跃值 (154)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
szukodf 活跃值 2022-4-27 09:30
7
0
今天我终于能看懂这脚本了,还是积累不够
游客
登录 | 注册 方可回帖
返回