
什么是 RPC
RPC,英文 RangPaCong,中文讓爬蟲,旨在為爬蟲開路,秒殺一切,讓爬蟲暢通無阻!
開個玩笑,實(shí)際上 RPC 為遠(yuǎn)程過程調(diào)用,全稱 Remote Procedure Call,是一種技術(shù)思想而非一種規(guī)范或協(xié)議。RPC 的誕生事實(shí)上離不開分布式的發(fā)展,RPC 主要解決了兩個問題:
- 解決了分布式系統(tǒng)中,服務(wù)之間的互相調(diào)用問題;
- RPC 使得在遠(yuǎn)程調(diào)用時,像本地調(diào)用一樣方便,讓調(diào)用者感知不到遠(yuǎn)程調(diào)用的邏輯。
RPC 的存在讓構(gòu)建分布式系統(tǒng)更加容易,相比于 HTTP 協(xié)議,RPC 采用二進(jìn)制字節(jié)碼傳輸,因此也更加高效、安全。在一個典型 RPC 的使用場景中,包含了服務(wù)發(fā)現(xiàn)、負(fù)載、容錯、網(wǎng)絡(luò)傳輸、序列化等組件,完整 RPC 架構(gòu)圖如下圖所示:

JSRPC
RPC 技術(shù)是非常復(fù)雜的,對于我們搞爬蟲、逆向的來說,不需要完全了解,只需要知道這項(xiàng)技術(shù)如何在逆向中應(yīng)用就行了。
RPC 在逆向中,簡單來說就是將本地和瀏覽器,看做是服務(wù)端和客戶端,二者之間通過 WebSocket 協(xié)議進(jìn)行 RPC 通信,在瀏覽器中將加密函數(shù)暴露出來,在本地直接調(diào)用瀏覽器中對應(yīng)的加密函數(shù),從而得到加密結(jié)果,不必去在意函數(shù)具體的執(zhí)行邏輯,也省去了扣代碼、補(bǔ)環(huán)境等操作,可以省去大量的逆向調(diào)試時間。我們以某團(tuán)網(wǎng)頁端的登錄為例來演示 RPC 在逆向中的具體使用方法。(假設(shè)你已經(jīng)有一定逆向基礎(chǔ),了解 WebSocket 協(xié)議,純小白可以先看看K哥以前的文章)
- 主頁(base64):
aHR0cHM6Ly9wYXNzcG9ydC5tZWl0dWFuLmNvbS9hY2NvdW50L3VuaXRpdmVsb2dpbg== - 參數(shù):h5Fingerprint
首先抓一下包,登錄接口有一個超級長的參數(shù) h5Fingerprint,如下圖所示:

直接搜一下就能找到加密函數(shù):

其中 utility.getH5fingerprint() 傳入的參數(shù) window.location.origin + url 格式化后,參數(shù)如下:
url = "https://passport.脫敏處理.com/account/unitivelogin"
params = {
"risk_partner": "0",
"risk_platform": "1",
"risk_app": "-1",
"uuid": "96309b5f00ba4143b920.1644805104.1.0.0",
"token_id": "DNCmLoBpSbBD6leXFdqIxA",
"service": "www",
"continue": "https://www.脫敏處理.com/account/settoken?continue=https%3A%2F%2Fwww.脫敏處理.com%2F"
}
uuid 和 token_id 都可以直接搜到,不是本次研究重點(diǎn),這里不再細(xì)說,接下來我們使用 RPC 技術(shù),直接調(diào)用瀏覽器里的 utility.getH5fingerprint() 方法,首先在本地編寫服務(wù)端代碼,使其能夠一直輸入待加密字符串,接收并打印加密后的字符串:
# ==================================
# --*-- coding: utf-8 --*--
# @Time : 2022-02-14
# @Author : 微信公眾號:K哥爬蟲
# @FileName: ws_server.py
# @Software: PyCharm
# ==================================
import sys
import asyncio
import websockets
async def receive_massage(websocket):
while True:
send_text = input("請輸入要加密的字符串: ")
if send_text == "exit":
print("Exit, goodbye!")
await websocket.send(send_text)
await websocket.close()
sys.exit()
else:
await websocket.send(send_text)
response_text = await websocket.recv()
print("\n加密結(jié)果:", response_text)
start_server = websockets.serve(receive_massage, '127.0.0.1', 5678) # 自定義端口
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
編寫瀏覽器客戶端 JS 代碼,收到消息就直接 utility.getH5fingerprint() 得到加密參數(shù)并發(fā)送給服務(wù)端:
/* ==================================
# @Time : 2022-02-14
# @Author : 微信公眾號:K哥爬蟲
# @FileName: ws_client.js
# @Software: PyCharm
# ================================== */
var ws = new WebSocket("ws://127.0.0.1:5678"); // 自定義端口
ws.onmessage = function (evt) {
console.log("Received Message: " + evt.data);
if (evt.data == "exit") {
ws.close();
} else {
ws.send(utility.getH5fingerprint(evt.data))
}
};
然后我們需要把客戶端代碼注入到網(wǎng)頁中,這里方法有很多,比如抓包軟件 Fiddler 替換響應(yīng)、瀏覽器插件 ReRes 替換 JS、瀏覽器開發(fā)者工具 Overrides 重寫功能等,也可以通過插件、油猴等注入 Hook 的方式插入,反正方法很多,對這些方法不太了解的朋友可以去看看K哥以前的文章,都有介紹。
這里我們使用瀏覽器開發(fā)者工具 Overrides 重寫功能,將 WebSocket 客戶端代碼加到加密的這個 JS 文件里并 Ctrl+S 保存,這里將其寫成了 IIFE 自執(zhí)行方式,這樣做的原因是防止污染全局變量,不用自執(zhí)行方式當(dāng)然也是可以的。

然后先運(yùn)行本地服務(wù)端代碼,網(wǎng)頁上先登錄一遍,網(wǎng)頁上先登錄一遍,網(wǎng)頁上先登錄一遍,重要的步驟說三遍!然后就可以在本地傳入待加密字符串,獲取 utility.getH5fingerprint() 加密后的結(jié)果了:

Sekiro
通過前面的示例,可以發(fā)現(xiàn)自己寫服務(wù)端太麻煩了,不易擴(kuò)展,那這方面有沒有現(xiàn)成的輪子呢?答案是有的,這里介紹兩個項(xiàng)目:
- JsRPC-hliang:https://github.com/jxhczhl/JsRpc
- Sekiro:https://github.com/virjar/sekiro
JsRPC-hliang 是用 go 語言寫的,是專門為 JS 逆向做的項(xiàng)目,而 Sekiro 功能更加強(qiáng)大,Sekiro 是由鄧維佳大佬,俗稱渣總,寫的一個基于長鏈接和代碼注入的 Android Private API 暴露框架,可以用在 APP 逆向、APP 數(shù)據(jù)抓取、Android 群控等場景,同時 Sekiro 也是目前公開方案唯一穩(wěn)定的 JSRPC 框架,兩者在 JS 逆向方面的使用方法其實(shí)都差不多,本文主要介紹一下 Sekiro 在 Web JS 逆向中的應(yīng)用。
參考 Sekiro 文檔,首先在本地編譯項(xiàng)目:
Linux & Mac:執(zhí)行腳本
build_demo_server.sh,之后得到產(chǎn)出發(fā)布壓縮包:sekiro-service-demo/target/sekiro-release-demo.zipWindows:可以直接下載:https://oss.virjar.com/sekiro/sekiro-demo
然后在本地運(yùn)行(需要有 Java 環(huán)境,自行配置):
- Linux & Mac:
bin/sekiro.sh - Windows:
bin/sekiro.bat
以 Windows 為例,啟動后如下:

接下來就需要在瀏覽器里注入代碼了,需要將作者提供的 sekiro_web_client.js(下載地址:https://sekiro.virjar.com/sekiro-doc/assets/sekiro_web_client.js) 注入到瀏覽器環(huán)境,然后通過 SekiroClient 和 Sekiro 服務(wù)器通信,即可直接 RPC 調(diào)用瀏覽器內(nèi)部方法,官方提供的 SekiroClient 代碼樣例如下:
function guid() {
function S4() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}
var client = new SekiroClient("wss://sekiro.virjar.com/business/register?group=ws-group&clientId="+guid());
client.registerAction("clientTime",function(request, resolve, reject){
resolve(""+new Date());
})
wss 鏈接里,如果是免費(fèi)版,要將 business 改成 business-demo,解釋一下涉及到的名詞:
- group:業(yè)務(wù)類型(接口組),每個業(yè)務(wù)一個 group,group 下面可以注冊多個終端(SekiroClient),同時 group 可以掛載多個 Action;
- clientId:指代設(shè)備,多個設(shè)備使用多個機(jī)器提供 API 服務(wù),提供群控能力和負(fù)載均衡能力;
- SekiroClient:服務(wù)提供者客戶端,主要場景為手機(jī)/瀏覽器等。最終的 Sekiro 調(diào)用會轉(zhuǎn)發(fā)到 SekiroClient。每個 client 需要有一個惟一的 clientId;
- registerAction:接口,同一個 group 下面可以有多個接口,分別做不同的功能;
- resolve:將內(nèi)容傳回給客戶端的方法;
- request:客戶端傳過來的請求,如果請求里有多個參數(shù),可以以鍵值對的方式從里面提取參數(shù)然后再做處理。
說了這么多可能也不好理解,直接實(shí)戰(zhàn),還是以某團(tuán)網(wǎng)頁端登錄為例,我們將 sekiro_web_client.js 與 SekiroClient 通信代碼寫在一起,然后根據(jù)需求,改寫一下通信部分代碼:
- ws 鏈接改為:
ws://127.0.0.1:5620/business-demo/register?group=rpc-test&clientId=,自定義group為rpc-test; - 注冊一個事件
registerAction為getH5fingerprint; -
resolve返回的結(jié)果為utility.getH5fingerprint(request["url"]),即加密并返回客戶端傳過來的 url 參數(shù)。
完整代碼如下(留意末尾 SekiroClient 通信代碼部分的寫法):
/* ==================================
# @Time : 2022-02-14
# @Author : 微信公眾號:K哥爬蟲
# @FileName: sekiro.js
# @Software: PyCharm
# ================================== */
(function () {
'use strict';
function SekiroClient(wsURL) {
this.wsURL = wsURL;
this.handlers = {};
this.socket = {};
// check
if (!wsURL) {
throw new Error('wsURL can not be empty!!')
}
this.webSocketFactory = this.resolveWebSocketFactory();
this.connect()
}
SekiroClient.prototype.resolveWebSocketFactory = function () {
if (typeof window === 'object') {
var theWebSocket = window.WebSocket ? window.WebSocket : window.MozWebSocket;
return function (wsURL) {
function WindowWebSocketWrapper(wsURL) {
this.mSocket = new theWebSocket(wsURL);
}
WindowWebSocketWrapper.prototype.close = function () {
this.mSocket.close();
};
WindowWebSocketWrapper.prototype.onmessage = function (onMessageFunction) {
this.mSocket.onmessage = onMessageFunction;
};
WindowWebSocketWrapper.prototype.onopen = function (onOpenFunction) {
this.mSocket.onopen = onOpenFunction;
};
WindowWebSocketWrapper.prototype.onclose = function (onCloseFunction) {
this.mSocket.onclose = onCloseFunction;
};
WindowWebSocketWrapper.prototype.send = function (message) {
this.mSocket.send(message);
};
return new WindowWebSocketWrapper(wsURL);
}
}
if (typeof weex === 'object') {
// this is weex env : https://weex.apache.org/zh/docs/modules/websockets.html
try {
console.log("test webSocket for weex");
var ws = weex.requireModule('webSocket');
console.log("find webSocket for weex:" + ws);
return function (wsURL) {
try {
ws.close();
} catch (e) {
}
ws.WebSocket(wsURL, '');
return ws;
}
} catch (e) {
console.log(e);
//ignore
}
}
//TODO support ReactNative
if (typeof WebSocket === 'object') {
return function (wsURL) {
return new theWebSocket(wsURL);
}
}
// weex 和 PC環(huán)境的websocket API不完全一致,所以做了抽象兼容
throw new Error("the js environment do not support websocket");
};
SekiroClient.prototype.connect = function () {
console.log('sekiro: begin of connect to wsURL: ' + this.wsURL);
var _this = this;
// 不check close,讓
// if (this.socket && this.socket.readyState === 1) {
// this.socket.close();
// }
try {
this.socket = this.webSocketFactory(this.wsURL);
} catch (e) {
console.log("sekiro: create connection failed,reconnect after 2s");
setTimeout(function () {
_this.connect()
}, 2000)
}
this.socket.onmessage(function (event) {
_this.handleSekiroRequest(event.data)
});
this.socket.onopen(function (event) {
console.log('sekiro: open a sekiro client connection')
});
this.socket.onclose(function (event) {
console.log('sekiro: disconnected ,reconnection after 2s');
setTimeout(function () {
_this.connect()
}, 2000)
});
};
SekiroClient.prototype.handleSekiroRequest = function (requestJson) {
console.log("receive sekiro request: " + requestJson);
var request = JSON.parse(requestJson);
var seq = request['__sekiro_seq__'];
if (!request['action']) {
this.sendFailed(seq, 'need request param {action}');
return
}
var action = request['action'];
if (!this.handlers[action]) {
this.sendFailed(seq, 'no action handler: ' + action + ' defined');
return
}
var theHandler = this.handlers[action];
var _this = this;
try {
theHandler(request, function (response) {
try {
_this.sendSuccess(seq, response)
} catch (e) {
_this.sendFailed(seq, "e:" + e);
}
}, function (errorMessage) {
_this.sendFailed(seq, errorMessage)
})
} catch (e) {
console.log("error: " + e);
_this.sendFailed(seq, ":" + e);
}
};
SekiroClient.prototype.sendSuccess = function (seq, response) {
var responseJson;
if (typeof response == 'string') {
try {
responseJson = JSON.parse(response);
} catch (e) {
responseJson = {};
responseJson['data'] = response;
}
} else if (typeof response == 'object') {
responseJson = response;
} else {
responseJson = {};
responseJson['data'] = response;
}
if (Array.isArray(responseJson)) {
responseJson = {
data: responseJson,
code: 0
}
}
if (responseJson['code']) {
responseJson['code'] = 0;
} else if (responseJson['status']) {
responseJson['status'] = 0;
} else {
responseJson['status'] = 0;
}
responseJson['__sekiro_seq__'] = seq;
var responseText = JSON.stringify(responseJson);
console.log("response :" + responseText);
this.socket.send(responseText);
};
SekiroClient.prototype.sendFailed = function (seq, errorMessage) {
if (typeof errorMessage != 'string') {
errorMessage = JSON.stringify(errorMessage);
}
var responseJson = {};
responseJson['message'] = errorMessage;
responseJson['status'] = -1;
responseJson['__sekiro_seq__'] = seq;
var responseText = JSON.stringify(responseJson);
console.log("sekiro: response :" + responseText);
this.socket.send(responseText)
};
SekiroClient.prototype.registerAction = function (action, handler) {
if (typeof action !== 'string') {
throw new Error("an action must be string");
}
if (typeof handler !== 'function') {
throw new Error("a handler must be function");
}
console.log("sekiro: register action: " + action);
this.handlers[action] = handler;
return this;
};
function guid() {
function S4() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}
var client = new SekiroClient("ws://127.0.0.1:5620/business-demo/register?group=rpc-test&clientId=" + guid());
client.registerAction("getH5fingerprint", function (request, resolve, reject) {
resolve(utility.getH5fingerprint(request["url"]));
})
})();
與前面的方法一樣,使用瀏覽器開發(fā)者工具 Overrides 重寫功能,將上面的代碼注入到網(wǎng)頁 JS 里:

然后 Sekiro 為我們提供了一些 API:
- 查看分組列表:http://127.0.0.1:5620/business-demo/groupList
- 查看隊(duì)列狀態(tài):http://127.0.0.1:5620/business-demo/clientQueue?group=test
- 調(diào)用轉(zhuǎn)發(fā):http://127.0.0.1:5620/business-demo/invoke?group=test&action=test¶m=testparm
比如我們現(xiàn)在要調(diào)用 utility.getH5fingerprint() 加密方法該怎么辦呢?很簡單,代碼注入到瀏覽器里后,首先還是要手動登錄一遍,手動登錄一遍,手動登錄一遍,重要的事情說三遍!然后參考上面的調(diào)用轉(zhuǎn)發(fā) API 進(jìn)行改寫:
- 我們自定義的分組
group是rpc-test; - 事件
action是getH5fingerprint; - 待加密參數(shù)名稱為
url, 其值例如為:https://www.baidu.com/
那么我們的調(diào)用鏈接就應(yīng)該是:http://127.0.0.1:5620/business-demo/invoke?group=rpc-test&action=getH5fingerprint&url=https://www.baidu.com/,直接瀏覽器打開,返回的字典,data 里面就是加密結(jié)果:

同樣的,在本地用 Python 的話,直接 requests 就完事兒了:

我們前面是把 sekiro_web_client.js 復(fù)制下來和通信代碼一起注入到瀏覽器的,這里我們還可以有更加優(yōu)雅的方法,直接給 document 新創(chuàng)建一個 script,通過鏈接的形式插入 sekiro_web_client.js,這里需要注意一下幾點(diǎn)問題:
- 第一個是時機(jī)的問題,需要等待 document 這些元素加載完成才能建立 SekiroClient 通信,不然調(diào)用 SekiroClient 是會報錯的,這里可以用 setTimeout 方法,該方法用于在指定的毫秒數(shù)后調(diào)用函數(shù)或計算表達(dá)式,將 SekiroClient 通信代碼單獨(dú)封裝成一個函數(shù),比如
function startSekiro(),然后等待 1-2 秒后再執(zhí)行 SekiroClient 通信代碼; - 由于 SekiroClient 通信代碼被封裝成了函數(shù),此時直接調(diào)用
utility.getH5fingerprint是會提示未定義的,所以我們要先將其導(dǎo)為全局變量,比如window.getH5fingerprint = utility.getH5fingerprint,后續(xù)直接調(diào)用window.getH5fingerprint即可。
完整代碼如下所示:
/* ==================================
# @Time : 2022-02-14
# @Author : 微信公眾號:K哥爬蟲
# @FileName: sekiro.js
# @Software: PyCharm
# ================================== */
(function () {
var newElement = document.createElement("script");
newElement.setAttribute("type", "text/javascript");
newElement.setAttribute("src", "https://sekiro.virjar.com/sekiro-doc/assets/sekiro_web_client.js");
document.body.appendChild(newElement);
window.getH5fingerprint = utility.getH5fingerprint
function guid() {
function S4() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}
function startSekiro() {
var client = new SekiroClient("ws://127.0.0.1:5620/business-demo/register?group=rpc-test&clientId=" + guid());
client.registerAction("getH5fingerprint", function (request, resolve, reject) {
resolve(window.getH5fingerprint(request["url"]));
})
}
setTimeout(startSekiro, 2000)
})();

優(yōu)缺點(diǎn)
目前如果不去逆向 JS 來實(shí)現(xiàn)加密參數(shù)的話,用得最多的就是自動化工具了,比如 Selenium、Puppeteer 等,很顯然這些自動化工具配置繁瑣、運(yùn)行效率極低,而 RPC 技術(shù)不需要加載多余的資源,穩(wěn)定性和效率明顯都更高,RPC 不需要考慮瀏覽器指紋、各種環(huán)境,如果風(fēng)控不嚴(yán)的話,高并發(fā)也是能夠輕松實(shí)現(xiàn)的,相反,由于 RPC 是一直掛載在同一個瀏覽器上的,所以針對風(fēng)控較嚴(yán)格的站點(diǎn),比如檢測 UA、IP 與加密參數(shù)綁定之類的,那么 PRC 調(diào)用太頻繁就不太行了,當(dāng)然也可以研究研究瀏覽器群控技術(shù),操縱多個不同瀏覽器可以一定程度上緩解這個問題??傊?RPC 技術(shù)還是非常牛的,除了 JS 逆向,可以說是目前比較萬能、高效的方法了,一定程度上做到了加密參數(shù)一把梭!