如今不少网站都上了各类前端反爬手段,不管手段如何,最重要的是要把包含反爬手段的前端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