注入eval, Function等系统函数,截获动态代码

27次阅读

共计 1878 个字符,预计需要花费 5 分钟才能阅读完成。

现在很多网站都上了各种前端反爬手段,无论手段如何,最重要的是要把包含反爬手段的前端 javascript 代码加密隐藏起来,然后在运行时实时解密动态执行。动态执行 js 代码无非两种方法,即 eval 和 Function。那么,不管网站加密代码写的多牛,我们只要将这两个方法 hook 住,即可获取到解密后的可执行 js 代码。注意,有些网站会检测 eval 和 Function 这两个方法是否原生,因此需要一些小花招来忽悠过去。
首先是 eval 的挂钩代码:
(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 是个变长参数的构造方法,需要处理 this
另外,有些网站还会用类似的机制加密页面内容,然后通过 document.write 输出动态解密的内容,因此同样可以挂钩 document.write,挂钩方法类似 eval,这里就不重复了。
另外,还有个问题需要关注,就是挂钩代码的注入方法。最简单的就是 F12 调出控制台,直接执行上面的代码,但这样只能 hook 住之后的调用,如果希望从页面刚加载时就注入,那么可以用以下几种方式:

油猴注入,油猴可以监听文档加载的几种不同状态,并在特定时刻执行 js 代码。我没有太多研究,具体请参见油猴手册
代理注入,修改应答数据,在 <head> 标签内的第一个位置插入 <script> 节点,确保在其它 js 加载执行前注入;Fiddler, anyproxy 等都可以编写外部规则,具体请参见代理工具的手册
使用 chrome-devtools-protocol, 通过 Page.addScriptToEvaluateOnNewDocument 注入外部 js 代码

正文完
 0