通过frida hook ssl函数获取APP流量

通常通过安装证书和设置代理可以mitm并解密所有的流量[1]。但是有些时候不适宜使用代理,所以还可以通过直接hook ssl的函数来解密流量[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
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
/**
* define global objects.
*/
var SSL_get_fd, SSL_get_session, SSL_SESSION_get_id, getpeername, getsockname, ntohs, ntohl, addresses;
var necessary_functions = [
"SSL_get_fd",
"SSL_get_session",
"SSL_SESSION_get_id",
"getpeername",
"getsockname",
"ntohs",
"ntohl"
];
console.log("[*] Start the Script.");

/**
* Initializes 'addresses' dictionary and NativeFunctions.
*/
function initializeGlobals() {
addresses = {};
var resolver = new ApiResolver("module");
var exps = [
["*libssl*",
["SSL_read", "SSL_write", "SSL_get_fd", "SSL_get_session",
"SSL_SESSION_get_id"]],
["*libc*",
["getpeername", "getsockname", "ntohs", "ntohl"]]
];
for (var i = 0; i < exps.length; i++) {
var lib = exps[i][0];
var names = exps[i][1];

for (var j = 0; j < names.length; j++) {
var name = names[j];
var matches = resolver.enumerateMatchesSync("exports:" + lib + "!" +
name);
if (matches.length == 0) {
throw "Could not find " + lib + "!" + name;
}
else if (matches.length != 1) {
// Sometimes Frida returns duplicates.
var address = 0;
var s = "";
var duplicates_only = true;
for (var k = 0; k < matches.length; k++) {
if (s.length != 0) {
s += ", ";
}
s += matches[k].name + "@" + matches[k].address;
if (address == 0) {
address = matches[k].address;
}
else if (!address.equals(matches[k].address)) {
duplicates_only = false;
}
}
if (!duplicates_only) {
throw "More than one match found for " + lib + "!" + name + ": " +
s;
}
}
addresses[name] = matches[0].address;
}
}
for (var index in necessary_functions) {
var key = necessary_functions[index];
console.log(" * Function: " + key + ", value: " + addresses[key]);
}
SSL_get_fd = new NativeFunction(addresses["SSL_get_fd"], "int", ["pointer"]);
SSL_get_session = new NativeFunction(addresses["SSL_get_session"], "pointer", ["pointer"]);
SSL_SESSION_get_id = new NativeFunction(addresses["SSL_SESSION_get_id"], "pointer", ["pointer", "pointer"]);
getpeername = new NativeFunction(addresses["getpeername"], "int", ["int", "pointer", "pointer"]);
getsockname = new NativeFunction(addresses["getsockname"], "int", ["int", "pointer", "pointer"]);
ntohs = new NativeFunction(addresses["ntohs"], "uint16", ["uint16"]);
ntohl = new NativeFunction(addresses["ntohl"], "uint32", ["uint32"]);
}
initializeGlobals();

/**
* Returns a dictionary of a sockfd's "src_addr", "src_port", "dst_addr", and
* "dst_port".
* @param {int} sockfd The file descriptor of the socket to inspect.
* @param {boolean} isRead If true, the context is an SSL_read call. If
* false, the context is an SSL_write call.
* @return {dict} Dictionary of sockfd's "src_addr", "src_port", "dst_addr",
* and "dst_port".
*/
function getPortsAndAddresses(sockfd, isRead) {
var message = {};

var addrlen = Memory.alloc(4);
var addr = Memory.alloc(16);

var src_dst = ["src", "dst"];
for (var i = 0; i < src_dst.length; i++) {
Memory.writeU32(addrlen, 16);
if ((src_dst[i] == "src") ^ isRead) {
getsockname(sockfd, addr, addrlen);
}
else {
getpeername(sockfd, addr, addrlen);
}
message[src_dst[i] + "_port"] = ntohs(Memory.readU16(addr.add(2)));
message[src_dst[i] + "_addr"] = ntohl(Memory.readU32(addr.add(4)));
}

return message;
}

/**
* Get the session_id of SSL object and return it as a hex string.
* @param {!NativePointer} ssl A pointer to an SSL object.
* @return {dict} A string representing the session_id of the SSL object's
* SSL_SESSION. For example,
* "59FD71B7B90202F359D89E66AE4E61247954E28431F6C6AC46625D472FF76336".
*/
function getSslSessionId(ssl) {
var session = SSL_get_session(ssl);
if (session == 0) {
return 0;
}
var len = Memory.alloc(4);
var p = SSL_SESSION_get_id(session, len);
len = Memory.readU32(len);

var session_id = "";
for (var i = 0; i < len; i++) {
// Read a byte, convert it to a hex string (0xAB ==> "AB"), and append
// it to session_id.
session_id +=
("0" + Memory.readU8(p.add(i)).toString(16).toUpperCase()).substr(-2);
}

return session_id;
}

Interceptor.attach(addresses["SSL_read"],
{
onEnter: function (args) {
var message = getPortsAndAddresses(SSL_get_fd(args[0]), true);
message["ssl_session_id"] = getSslSessionId(args[0]);
message["function"] = "SSL_read";
this.message = message;
this.buf = args[1];
},
onLeave: function (retval) {
retval |= 0; // Cast retval to 32-bit integer.
if (retval <= 0) {
return;
}
send(this.message, Memory.readByteArray(this.buf, retval));
}
});

Interceptor.attach(addresses["SSL_write"],
{
onEnter: function (args) {
//var message = "Requests."
var message = getPortsAndAddresses(SSL_get_fd(args[0]), false);
message["ssl_session_id"] = getSslSessionId(args[0]);
message["function"] = "SSL_write";
send(message, Memory.readByteArray(args[1], parseInt(args[2])));
},
onLeave: function (retval) { }
});
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
import frida
import sys
import time
import random
import datetime


ROOT_DIR = ""
SCRIPT = ""
APP = "com.xxx"


device = frida.get_usb_device()
# pid = device.spawn(APP) # I don't know why this does not work well.
pid = None
for a in device.enumerate_applications():
if a.identifier == APP:
pid = a.pid # find the process by its' package name and get its' pid
break

time.sleep(1) # waitting for something (I don't know for what THING, but let's wait)
session = device.attach(pid)
print("[*] Press Ctrl+C to stop logging.")
fw = open(f"{ROOT_DIR}/log/{APP}-{datetime.datetime.now().strftime('%Y-%m-%d_%H_%M_%S')}.log",'w+', encoding='utf-8') # file object to write log

with open(f"{ROOT_DIR}/js_scripts/ssl_hook.js", "r") as f:
SCRIPT = str(f.read())
# print(SCRIPT)

def on_msg(message, data):
if message["type"] == "send":
print(message["payload"], data)
fw.write("payload: " + str(message["payload"]) + "\n")
fw.write("data: " + str(data) + "\n")
fw.flush()
else:
print("Send type error!")
print(message, data)

script = session.create_script(SCRIPT)
script.on('message', on_msg)

script.load()

sys.stdin.read()

以上代码来自fanxs-t/Android-SSL_read-write-Hook[3](有一些修改)

通过ApiResolver获取libssl中的几个关键函数的地址,并hook相应的函数来获取解密后的流量。

References


通过frida hook ssl函数获取APP流量
http://zr4in.github.io/2024/09/04/通过frida-hook-ssl函数获取APP流量/
作者
zr4in
发布于
2024年9月4日
许可协议