js逆向hook总结
document.cookie
常见做法
var oldCookie = document.cookie; Object.defineProperty(document, "cookie", { get(){ return oldCookie; }, set(val){
console.log("setting cookie", val); oldCookie += ";" +val; } })
这样做法有两个问题,其一是cookie并没有被设置上,只是js 获取与设置cookie的时候可以hook到。
其二是需要自己处理设置cookie的情况,比如更新,删除cookie。
较好的hook做法
// 代码来源 https://stackoverflow.com/questions/32410331/proxying-of-document-cookie var cookieDesc = Object.getOwnPropertyDescriptor(Document.prototype, 'cookie') || Object.getOwnPropertyDescriptor(HTMLDocument.prototype, 'cookie'); if (cookieDesc && cookieDesc.configurable) { Object.defineProperty(document, 'cookie', { get: function () { return cookieDesc.get.call(document); }, set: function (val) { console.log(val); cookieDesc.set.call(document, val); } }); }
hook函数
var oldEval = eval; eval = function(){ console.log("exec", arguments[0]); return oldEval.apply(this, arguments); }
hook方法
var obj = { a: { } }; var old = obj.a; Object.defineProperty(obj, "a", { get(){ return old; }, set(val){
console.log("obj.a set to be", val); old = val; return old } })
obj.a = 111;
new Proxy加with
const handlers = { get(target, p, rev) { const result = Reflect.get(target, p); console.log(`reading ${target.constructor.name}.${p}, value=${result}`) return result; }, set(tagret, p, value, rev) { const result = Reflect.set(tagret, p, value); console.log(`setting ${target}.${p} = ${value}`); return result; } }; (function setHook() { const withObject = { window: {} }; const mappedObject = { location, navigator, document }; Object.keys(mappedObject).forEach((key) => { var proxiedMethod = new Proxy(mappedObject[key], handlers); withObject[key] = proxiedMethod; }); withObject.window = withObject; window.withObject = withObject; })(); with (withObject) { console.log(window.a); console.log(navigator.userAgent); console.log(location.href); }
hook xhr请求
ast注入hook函数
利用ast给所有的赋值语句加上一层包装
var obj = { a: {} }; console.log(obj.a); // 读取 obj.a = 11; // 设置 // 包装成这样 console.log(wrapper(obj.a, obj, "a", {type: "property access"})); wrapper(obj.a, obj, "a", {type: "property assignment", value: 11});
做法借鉴了 js内存漫游那位大佬。