如今不少網站都上了各類前端反爬手段,不管手段如何,最重要的是要把包含反爬手段的前端javascript代碼加密隱藏起來,而後在運行時實時解密動態執行。
動態執行js代碼無非兩種方法,即eval和Function。那麼,無論網站加密代碼寫的多牛,咱們只要將這兩個方法hook住,便可獲取到解密後的可執行js代碼。
注意,有些網站會檢測eval和Function這兩個方法是否原生,所以須要一些小花招來忽悠過去。javascript
首先是eval的掛鉤代碼:html
(function() { if (window.__cr_eval) return window.__cr_eval = window.eval var myeval = function (src) { console.log("================ eval begin: length=" + src.length + ",caller=" + (myeval.caller && myeval.caller.name) + " ===============") console.log(src); console.log("================ eval end ================") return window.__cr_eval(src) } var _myeval = myeval.bind(null) // 注意:這句和下一句就是小花招本招了! _myeval.toString = window.__cr_eval.toString Object.defineProperty(window, 'eval', { value: _myeval }) console.log(">>>>>>>>>>>>>> eval injected: " + document.location + " <<<<<<<<<<<<<<<<<<<") })();
這段代碼執行後,以後全部的eval操做都會在控制檯打印輸出將要執行的js源碼。
同理能夠寫出Function的掛鉤代碼:前端
(function() { if (window.__cr_fun) return window.__cr_fun = window.Function var myfun = function () { var args = Array.prototype.slice.call(arguments, 0, -1).join(","), src = arguments[arguments.length - 1] console.log("================ Function begin: args=" + args + ", length=" + src.length + ",caller=" + (myfun.caller && myfun.caller.name) + " ===============") console.log(src); console.log("================ Function end ================") return window.__cr_fun.apply(this, arguments) } myfun.toString = function() { return window.__cr_fun + "" } // 小花招 Object.defineProperty(window, 'Function', { value: myfun }) console.log(">>>>>>>>>>>>>> Function injected: " + document.location + " <<<<<<<<<<<<<<<<<<<") })();
注意:和eval不一樣,Function是個有變長參數的構造方法,須要處理thisjava
另外,有些網站還會用相似的機制加密頁面內容,而後經過document.write輸出動態解密的內容,所以一樣能夠掛鉤document.write,掛鉤方法相似eval,這裏就不重複了。git
另外,還有個問題須要關注,就是掛鉤代碼的注入方法。
最簡單的就是F12調出控制檯,直接執行上面的代碼,但這樣只能hook住執行以後的eval調用,若是但願從頁面剛加載時就注入,那麼能夠用如下幾種方式:github
很多人沒用過代理規則,這裏寫一下Fiddler和anyproxy的規則編寫方法:chrome
在腳本編輯器裏找OnBeforeResponse方法,方法內添加下面C#代碼:c#
if (oSession.oResponse.headers.ExistsAndContains("Content-Type", "html")){ oSession.utilDecodeResponse(); // Remove any compression or chunking var b = System.Text.Encoding.UTF8.GetString(oSession.responseBodyBytes); var r = /<head[^>]*>/i; var js = "..."; // 要注入的js源碼,見正文 b = b.replace(r, "$0<script>" + js + "</script>"); oSession.utilSetResponseBody(b); // Set the response body back }
編輯一個rule.js保存在anyproxy根目錄下,內容以下:app
function injectEval() { if (window.__cr_eval) return ... // 見正文,此處略 console.log(">>>>>>>>>>>>>> eval injected: " + document.location + " <<<<<<<<<<<<<<<<<<<") } module.exports = { summary: 'a rule to hook all eval', *beforeSendResponse(requestDetail, {response}) { if (response.header["Content-Type"].indexOf("text/html") >= 0) { response.body = (response.body + "").replace(/<head[^>]*>/i, `$&<script>(${injectEval})();</script>`) return {response} } }, };
anyproxy -r rule.js