RPC 技術及其框架 Sekiro 在爬蟲逆向中的應用,加密數據一把梭!

什么是 RPC

RPC,英文 RangPaCong,中文讓爬蟲,旨在為爬蟲開路,秒殺一切,讓爬蟲暢通無阻!

成都創新互聯公司專注于企業成都全網營銷推廣、網站重做改版、克什克騰網站定制設計、自適應品牌網站建設、H5開發商城開發、集團公司官網建設、外貿網站建設、高端網站制作、響應式網頁設計等建站業務,價格優惠性價比高,為克什克騰等各大城市提供網站開發制作服務。

開個玩笑,實際上 RPC 為遠程過程調用,全稱 Remote Procedure Call,是一種技術思想而非一種規范或協議。RPC 的誕生事實上離不開分布式的發展,RPC 主要解決了兩個問題:

  1. 解決了分布式系統中,服務之間的互相調用問題;
  2. RPC 使得在遠程調用時,像本地調用一樣方便,讓調用者感知不到遠程調用的邏輯。

RPC 的存在讓構建分布式系統更加容易,相比于 HTTP 協議,RPC 采用二進制字節碼傳輸,因此也更加高效、安全。在一個典型 RPC 的使用場景中,包含了服務發現、負載、容錯、網絡傳輸、序列化等組件,完整 RPC 架構圖如下圖所示:

JSRPC

RPC 技術是非常復雜的,對于我們搞爬蟲、逆向的來說,不需要完全了解,只需要知道這項技術如何在逆向中應用就行了。

RPC 在逆向中,簡單來說就是將本地和瀏覽器,看做是服務端和客戶端,二者之間通過 WebSocket 協議進行 RPC 通信,在瀏覽器中將加密函數暴露出來,在本地直接調用瀏覽器中對應的加密函數,從而得到加密結果,不必去在意函數具體的執行邏輯,也省去了扣代碼、補環境等操作,可以省去大量的逆向調試時間。我們以某團網頁端的登錄為例來演示 RPC 在逆向中的具體使用方法。(假設你已經有一定逆向基礎,了解 WebSocket 協議,純小白可以先看看K哥以前的文章)

  • 主頁(base64):aHR0cHM6Ly9wYXNzcG9ydC5tZWl0dWFuLmNvbS9hY2NvdW50L3VuaXRpdmVsb2dpbg==
  • 參數:h5Fingerprint

首先抓一下包,登錄接口有一個超級長的參數 h5Fingerprint,如下圖所示:

直接搜一下就能找到加密函數:

其中 utility.getH5fingerprint() 傳入的參數 window.location.origin + url 格式化后,參數如下:

url = "https://passport.脫敏處理.com/account/unitivelogin"
params = {
    "risk_partner": "0",
    "risk_platform": "1",
    "risk_app": "-1",
    "uuid": "b5f00ba4143b920..1.0.0",
    "token_id": "DNCmLoBpSbBD6leXFdqIxA",
    "service": "www",
    "continue": "https://www.脫敏處理.com/account/settoken?continue=https%3A%2F%2Fwww.脫敏處理.com%2F"
}

uuid 和 token_id 都可以直接搜到,不是本次研究重點,這里不再細說,接下來我們使用 RPC 技術,直接調用瀏覽器里的 utility.getH5fingerprint() 方法,首先在本地編寫服務端代碼,使其能夠一直輸入待加密字符串,接收并打印加密后的字符串:

# ==================================
# --*-- 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加密結果:", 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() 得到加密參數并發送給服務端:

/* ==================================
# @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))
    }
};

然后我們需要把客戶端代碼注入到網頁中,這里方法有很多,比如抓包軟件 Fiddler 替換響應、瀏覽器插件 ReRes 替換 JS、瀏覽器開發者工具 Overrides 重寫功能等,也可以通過插件、油猴等注入 Hook 的方式插入,反正方法很多,對這些方法不太了解的朋友可以去看看K哥以前的文章,都有介紹。

這里我們使用瀏覽器開發者工具 Overrides 重寫功能,將 WebSocket 客戶端代碼加到加密的這個 JS 文件里并 Ctrl+S 保存,這里將其寫成了 IIFE 自執行方式,這樣做的原因是防止污染全局變量,不用自執行方式當然也是可以的。

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

Sekiro

通過前面的示例,可以發現自己寫服務端太麻煩了,不易擴展,那這方面有沒有現成的輪子呢?答案是有的,這里介紹兩個項目:

  • JsRPC-hliang:https://github.com/jxhczhl/JsRpc
  • Sekiro:https://github.com/virjar/sekiro

JsRPC-hliang 是用 go 語言寫的,是專門為 JS 逆向做的項目,而 Sekiro 功能更加強大,Sekiro 是由鄧維佳大佬,俗稱渣總,寫的一個基于長鏈接和代碼注入的 Android Private API 暴露框架,可以用在 APP 逆向、APP 數據抓取、Android 群控等場景,同時 Sekiro 也是目前公開方案唯一穩定的 JSRPC 框架,兩者在 JS 逆向方面的使用方法其實都差不多,本文主要介紹一下 Sekiro 在 Web JS 逆向中的應用。

參考 Sekiro 文檔,首先在本地編譯項目:

  • Linux & Mac:執行腳本 build_demo_server.sh,之后得到產出發布壓縮包:sekiro-service-demo/target/sekiro-release-demo.zip

  • Windows:可以直接下載:https://oss.virjar.com/sekiro/sekiro-demo

然后在本地運行(需要有 Java 環境,自行配置):

  • 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) 注入到瀏覽器環境,然后通過 SekiroClient 和 Sekiro 服務器通信,即可直接 RPC 調用瀏覽器內部方法,官方提供的 SekiroClient 代碼樣例如下:

function guid() {
    function S4() {
        return (((1+Math.random())*0x)|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 鏈接里,如果是免費版,要將 business 改成 business-demo,解釋一下涉及到的名詞:

  • group:業務類型(接口組),每個業務一個 group,group 下面可以注冊多個終端(SekiroClient),同時 group 可以掛載多個 Action;
  • clientId:指代設備,多個設備使用多個機器提供 API 服務,提供群控能力和負載均衡能力;
  • SekiroClient:服務提供者客戶端,主要場景為手機/瀏覽器等。最終的 Sekiro 調用會轉發到 SekiroClient。每個 client 需要有一個惟一的 clientId;
  • registerAction:接口,同一個 group 下面可以有多個接口,分別做不同的功能;
  • resolve:將內容傳回給客戶端的方法;
  • request:客戶端傳過來的請求,如果請求里有多個參數,可以以鍵值對的方式從里面提取參數然后再做處理。

說了這么多可能也不好理解,直接實戰,還是以某團網頁端登錄為例,我們將 sekiro_web_client.js 與 SekiroClient 通信代碼寫在一起,然后根據需求,改寫一下通信部分代碼:

  1. ws 鏈接改為:ws://127.0.0.1:5620/business-demo/register?group=rpc-test&clientId=,自定義 grouprpc-test
  2. 注冊一個事件 registerActiongetH5fingerprint
  3. resolve 返回的結果為 utility.getH5fingerprint(request["url"]),即加密并返回客戶端傳過來的 url 參數。

完整代碼如下(留意末尾 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環境的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()) * 0x) | 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"]));
    })

})();

與前面的方法一樣,使用瀏覽器開發者工具 Overrides 重寫功能,將上面的代碼注入到網頁 JS 里:

然后 Sekiro 為我們提供了一些 API:

  • 查看分組列表:http://127.0.0.1:5620/business-demo/groupList
  • 查看隊列狀態:http://127.0.0.1:5620/business-demo/clientQueue?group=test
  • 調用轉發:http://127.0.0.1:5620/business-demo/invoke?group=test&action=test&param=testparm

比如我們現在要調用 utility.getH5fingerprint() 加密方法該怎么辦呢?很簡單,代碼注入到瀏覽器里后,首先還是要手動登錄一遍,手動登錄一遍,手動登錄一遍,重要的事情說三遍!然后參考上面的調用轉發 API 進行改寫:

  • 我們自定義的分組 grouprpc-test
  • 事件 actiongetH5fingerprint
  • 待加密參數名稱為 url, 其值例如為:https://www.baidu.com/

那么我們的調用鏈接就應該是:http://127.0.0.1:5620/business-demo/invoke?group=rpc-test&action=getH5fingerprint&url=https://www.baidu.com/,直接瀏覽器打開,返回的字典,data 里面就是加密結果:

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

我們前面是把 sekiro_web_client.js 復制下來和通信代碼一起注入到瀏覽器的,這里我們還可以有更加優雅的方法,直接給 document 新創建一個 script,通過鏈接的形式插入 sekiro_web_client.js,這里需要注意一下幾點問題:

  1. 第一個是時機的問題,需要等待 document 這些元素加載完成才能建立 SekiroClient 通信,不然調用 SekiroClient 是會報錯的,這里可以用 setTimeout 方法,該方法用于在指定的毫秒數后調用函數或計算表達式,將 SekiroClient 通信代碼單獨封裝成一個函數,比如 function startSekiro(),然后等待 1-2 秒后再執行 SekiroClient 通信代碼;
  2. 由于 SekiroClient 通信代碼被封裝成了函數,此時直接調用 utility.getH5fingerprint 是會提示未定義的,所以我們要先將其導為全局變量,比如 window.getH5fingerprint = utility.getH5fingerprint,后續直接調用 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()) * 0x) | 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)
})();

優缺點

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

當前名稱:RPC 技術及其框架 Sekiro 在爬蟲逆向中的應用,加密數據一把梭!
當前網址:http://m.kartarina.com/article8/dsojoip.html

成都網站建設公司_創新互聯,為您提供建站公司網站設計公司服務器托管網站排名關鍵詞優化域名注冊

廣告

聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯

成都定制網站網頁設計
主站蜘蛛池模板: 内射无码专区久久亚洲| 中文字幕久久精品无码| 国产精品久久久久无码av | 秋霞鲁丝片无码av| 亚洲熟妇少妇任你躁在线观看无码| 性色av无码免费一区二区三区| 特级做A爰片毛片免费看无码| 中文字幕人成无码人妻| 亚洲乱亚洲乱妇无码麻豆| 亚洲国产成人无码AV在线影院| 亚洲中文字幕久久精品无码喷水| 无码八A片人妻少妇久久| 国精品无码一区二区三区在线蜜臀| 欧洲成人午夜精品无码区久久| 西西4444www大胆无码| 人妻无码αv中文字幕久久琪琪布 人妻无码第一区二区三区 | 亚洲AV成人无码久久WWW| 自拍中文精品无码| 西西4444www大胆无码| 欧美性生交xxxxx无码影院∵| 久久青青草原亚洲AV无码麻豆| 性色av无码免费一区二区三区| 69久久精品无码一区二区| 国产爆乳无码一区二区麻豆| 一区二区三区无码高清| 色综合久久久无码网中文| 久久亚洲精品AB无码播放| 中文无码熟妇人妻AV在线| 人妻少妇乱子伦无码专区| 精品无码专区亚洲| 99热门精品一区二区三区无码| 久久久久亚洲av无码专区导航| 中文字幕无码第1页| 日韩精品无码免费专区网站| 一道久在线无码加勒比| 国产成人无码aa精品一区| 日韩AV无码不卡网站| 国产精品无码一二区免费| 亚洲另类无码专区丝袜| 亚洲爆乳精品无码一区二区| 中文字幕av无码无卡免费|