js的hook方法和技巧

hook是什么

hook作用就是在你关键代码位置前或者后进行一些处理

如何定位

  • 搜索

  • 断点调试

    • xhr

    • dom

    • event

    • 自定义

  • 使用油猴插件脚本进行hook

    • json

    • cookie

    • window attr

    • eval/function

    • 等等

chrome调试的方法

无限debugger解决方案(操作chrome浏览器)

  • 禁止所有的断点

    • 在chrome的断点调试栏点击取消所有断点

    • 这样做虽然可以取消别人断点,但是自己也无法下断点分析了

  • 禁止某处的断点

    • 在sources的操作窗口点击想要取消断点的那一行号,右键点击取消断点
  • 条件断点

    • 和上述操作差不多,只是选择条件设置
  • 远程js映射到本地的文件

    • Windows 下可以使用 Fiddler

    • Mac 下可以使用 Charles

    • Chrome 开发工具自带的 Override

    • 需要特殊环境才能下载的Reres和 Resource Override插件

  • 中间工具替换字符串特征(fiddler,chales)

    • 使用工具把debugger这个关键字替换成字符串或者修改逻辑使得debugger不生效

    • 示例fiddler

      • 在fiddler界面点击Autoresponder选项

      • 下面rule
        editor选择上面选择请求的地址,下面选择替换的html,然后save

      • 重新打开

    • 示例chales

      • 抓包url,右键点击map local
  • 使用reres插件替换特征字符串

    • 通过reres插件,修改原来代码的,然后映射

    • 点开添加规则之后:

      • If URL match栏,填入的是匹配 URL
        的规则,这里填入的是一个正则表达式,比如我想配置github.com/login这个域名,可以使用*://github.com/login*这样的方式匹配,或者使用偷懒的方式直接匹配网站路径下的文件^[https://www.xxxAAA.cn/js/jquery.min.js]{.ul}

      • If URL
        match注意事项:不要填开头的/和结束的/x,如/./g请写成.

      • Response栏,填写的是映射的响应地址,比如在 Window
        下,我想要将 E 盘下的 index.js
        文件映射回去,使用本地地址的方式是file:///E:/index.js,使用线上地址的方式是http://localhost:3000/xxx/index.js

      • Response注意事项:线上地址以http://开头,本地地址以file:///开头,Mac
        推荐使用超级右键可以直接复制文件路径,同时上一点中提到的线上地址需要启动一个可以访问静态文件的服务,可以使用
        Flask 快速搭建一个。

      • 添加完成,点击保存,重新加载页面即可。

  • 利用油猴插件删除debugger特征

  • 重写关键函数

    • 分析代码的逻辑,把关键的debugger函数在console重写为空。
  • [https://qqe2.com/Video/default.html,出现debugger后,在console输入:Function.prototype.constructor]{.ul} =
    function(){},然后点击切换回sources,点击继续运行。前提是(function(){}).constructor
    === Function为True才可以。

  • 思路

    • 分过debugger的代码流程,重写逻辑

举个比方,打个例子

我们通过 JSON.stringify 的 hook 来了解具体的操作方式。JSON.stringify
的作用是将一个对象转换为字符串,常用于与服务端交换数据时。假设请求时需要将
{“name”: “sfhfpc”, “pwd”: “39ik-0ake-2jz3”, “client”: 1, “_sign”:
“298zudju27zyeh58zmgj293ozl48zjr829zmg92=”}
这样一个对象发送给服务端,那么很有可能需要在 JavaScript
代码里构造这样一个对象并将其转换为字符串的形式,最后发给服务端。既然知道有这样的过程,那么我们就编写一个
hook 函数,对 JSON.stringify 进行 hook。也就是比 JSON.stringify
先一步获得消息,在为所欲为后将原函数(JSON.stringify)返回。具体的 hook
代码如下:

JS


1 // ==UserScript==
2 // @name New Userscript
3 // @namespace http://tampermonkey.net/
4 // @version 0.1
5 // @description try to take over the world!
6 // @author You
7 // @match http:///
8 // @grant none
9 // ==/UserScript==
10
11 (function() {
12 ‘use strict’;
13 var stringifg = JSON.stringify;
14 JSON.stringify = function(input){
15
16 console.log(“stringify - > “, input);
17 debugger;
18 return stringify(input)
19 }
20 })();



这里用了 (function(){})(); 来确保函数自动执行,TamperMonkey
还允许我们设置执行的时间(run-at 参数正是这个作用)。也就是说系统在调用
JSON.stringify 之前,这个函数就被hook函数劫下了,调用 JSON.stringify
的时候调用的其实是我们设定的hook函数。

油猴脚本编写

官方文档:[https://www.tampermonkey.net/documentation.php]{.ul}

JS


1 // ==UserScript==
2 // @name New Userscript
3 // @namespace http://tampermonkey.net/
4 // @version 0.1
5 // @description try to take over the world!
6 // @author You
7 // @match http:///
8 // @grant none
9 // ==/UserScript==
10
11 (function() {
12 ‘use strict’;
13
14 // Your code here…
15 })();



  1. 首先来看看脚本的内容,上面是一大排注释,这些注释可以非常有用的,它表明了脚本的各个属性。下面来简单介绍一下。

    • 属性名 作用

    • name 油猴脚本的名字

    • namespace
      命名空间,类似于Java的包名,用来区分相同名称的脚本,一般写成作者名字或者网址就可以了

    • version 脚本版本,油猴脚本的更新会读取这个版本号

    • description 描述,用来告诉用户这个脚本是干什么用的

    • author 作者名字

    • match
      只有匹配的网址才会执行对应的脚本,例如*、http://*、[http://www.baidu.com/*等,参见谷歌开发者文档]{.ul}

    • grant
      指定脚本运行所需权限,如果脚本拥有相应的权限,就可以调用油猴扩展提供的API与浏览器进行交互。如果设置为none的话,则不使用沙箱环境,脚本会直接运行在网页的环境中,这时候无法使用大部分油猴扩展的API。如果不指定的话,油猴会默认添加几个最常用的API

    • require
      如果脚本依赖其他js库的话,可以使用require指令,在运行脚本之前先加载其他库,常见用法是加载jquery

    • connect
      当用户使用GM_xmlhttpRequest请求远程数据的时候,需要使用connect指定允许访问的域名,支持域名、子域名、IP地址以及*通配符

    • updateURL
      脚本更新网址,当油猴扩展检查更新的时候,会尝试从这个网址下载脚本,然后比对版本号确认是否更新

收集常用的js的hook脚本

document下的createElement()方法的hook,查看创建了什么元素

JS


1 (function() {
2 ‘use strict’
3 var _createElement = document.createElement.bind(document);
4 document.createElement = function(elm){
5 // 这里做判断 是否创建了script这个元素
6 if(elm == ‘body’){
7 debugger;
8 }
9 return _createElement(elm);
10 }
11 })();



headers hook 当header中包含Authorization时,则插入断点

JS


1 var code = function(){
2 var org = window.XMLHttpRequest.prototype.setRequestHeader;
3 window.XMLHttpRequest.prototype.setRequestHeader =
4 function(key,value){
5 if(key==’Authorization’){
6 debugger;
7 }
8 return org.apply(this,arguments);
9 }
10 }
11 var script = document.createElement(‘script’);
12 script.textContent = ‘(‘ + code + ‘)()’;
13 (document.head||document.documentElement).appendChild(script);
14 script.parentNode.removeChild(script);



请求hook 当请求的url里包含MmEwMD时,则插入断点

JS


1 var code = function(){
2 var open = window.XMLHttpRequest.prototype.open;
3 window.XMLHttpRequest.prototype.open = function (method, url,
4 async){
5 if (url.indexOf(“MmEwMD”)>-1){
6 debugger;
7 }
8 return open.apply(this, arguments);
9 };
10 }
11 var script = document.createElement(‘script’);
12 script.textContent = ‘(‘ + code + ‘)()’;
13 (document.head||document.documentElement).appendChild(script);
script.parentNode.removeChild(script);



docuemnt.getElementById 以及value属性的hook

JS


1 // docuemnt.getElementById
2 以及value属性的hook,可以参考完成innerHTML的hook
3 document.getElementById = function(id) {
4 var value = document.querySelector(‘#’ + id).value;
5 console.log(‘DOM操作 id: ‘, id)
6 try {
7
8 Object.defineProperty(document.querySelector(‘#’+ id), ‘value’,
9 {
10 get: function() {
11 console.log(‘getting -‘, id, ‘value -‘, value);
12 return value;
13 },
14 set: function(val) {
15 console.log(‘setting -‘, id, ‘value -‘, val)
16 value = val;
17 }
18 })
19 } catch (e) {
20 console.log(‘———华丽的分割线——–’)
21 }
return document.querySelector(‘#’ + id);
}



检测函数是否被hook

JS


1 if (window.eval == ‘native code’){
2 console.log(‘发现eval函数被hook了’);
3 }
4
5 function encry(){
6 return “ox0oo”
7
8 }
9 native_code = encry.toString();
10 hook_encry = encry;
11 var hook_encry = function(){
12 return “hook”
13 };
14
15 function detect(){
16 // console.log(encry.toString());
17 if (encry.toString() != native_code){
18 console.log(22131);
19 return “detect”
20 }
21 }
22 if (detect() == “detect”){
23 console.log(encry());
24 }else{
25 // console.log(encry())
26 console.log(“11”)
27 }
28



过debugger

JS


1 function Closure(injectFunction) {
2 return function () {
3 if (!arguments.length)
4 return injectFunction.apply(this, arguments)
5 arguments[arguments.length - 1] = arguments[arguments.length -
6 1].replace(/debugger/g, “”);
7 return injectFunction.apply(this, arguments)
8 }
9 }
10
11 var oldFunctionConstructor = window.Function.prototype.constructor;
12 window.Function.prototype.constructor = Closure(oldFunctionConstructor)
13 //fix native function
14 window.Function.prototype.constructor.toString =
15 oldFunctionConstructor.toString.bind(oldFunctionConstructor);
16
17 var oldFunction = Function;
18 window.Function = Closure(oldFunction)
19 //fix native function
20 window.Function.toString = oldFunction.toString.bind(oldFunction);
21
22 var oldEval = eval;
23 window.eval = Closure(oldEval)
24 //fix native function
25 window.eval.toString = oldEval.toString.bind(oldEval);
26
27 // hook GeneratorFunction
28 var oldGeneratorFunctionConstructor = Object.getPrototypeOf(function * ()
29 {}).constructor
30 var newGeneratorFunctionConstructor = Closure(oldGeneratorFunctionConstructor)
31 newGeneratorFunctionConstructor.toString =
32 oldGeneratorFunctionConstructor.toString.bind(oldGeneratorFunctionConstructor);
33 Object.defineProperty(oldGeneratorFunctionConstructor.prototype, “constructor”,
34 {
35 value: newGeneratorFunctionConstructor,
36 writable: false,
37 configurable: true
38 })
39
40 // hook Async Function
41 var oldAsyncFunctionConstructor = Object.getPrototypeOf(async function ()
42 {}).constructor
43 var newAsyncFunctionConstructor = Closure(oldAsyncFunctionConstructor)
44 newAsyncFunctionConstructor.toString =
45 oldAsyncFunctionConstructor.toString.bind(oldAsyncFunctionConstructor);
46 Object.defineProperty(oldAsyncFunctionConstructor.prototype, “constructor”, {
47 value: newAsyncFunctionConstructor,
48 writable: false,
49 configurable: true
50 })
51
52 // hook dom
53 var oldSetAttribute = window.Element.prototype.setAttribute;
54 window.Element.prototype.setAttribute = function (name, value) {
55 if (typeof value == “string”)
56 value = value.replace(/debugger/g, “”)
57 // 向上调用
58 oldSetAttribute.call(this, name, value)
59 };
60 var oldContentWindow =
61 Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype,
62 “contentWindow”).get
63 Object.defineProperty(window.HTMLIFrameElement.prototype, “contentWindow”, {
get() {
var newV = oldContentWindow.call(this)
if (!newV.inject) {
newV.inject = true;
core.call(newV, globalConfig, newV);
}
return newV
}
})



过debugger—1 constructor 构造器构造出来的

JS


1 var _constructor = constructor;
2 Function.prototype.constructor = function(s) {
3 if (s == “debugger”){
4 console.log(s);
5 return null;
6 }
7 return _constructor(s);
8 }



过debugger—2 eval

JS


1 (function() {
2 ‘use strict’;
3 var eval_ = window.eval;
4 window.eval = function(x){
5 eval_(x.replace(“debugger;”,” ; “));
6 };
7 window.eval.toString = eval_.toString;
8 })();



json hook

JS


1 var my_stringify = JSON.stringify;
2 JSON.stringify = function (params) {
3 //这里可以添加其他逻辑比如 debugger
4 console.log(“json_stringify params:”,params);
5 return my_stringify(params);
6 };
7
8 var my_parse = JSON.parse;
9 JSON.parse = function (params) {
10 //这里可以添加其他逻辑比如 debugger
11 console.log(“json_parse params:”,params);
12 return my_parse(params);
13 };



对象属性hook 属性自定义

JS


1 (function(){
2 // 严格模式,检查所有错误
3 ‘use strict’
4 // document 为要hook的对象 ,属性是cookie
5 Object.defineProperty(document,’cookie’,{
6 // hook set方法也就是赋值的方法,get就是获取的方法
7 set: function(val){
8 //
9 这样就可以快速给下面这个代码行下断点,从而快速定位设置cookie的代码
10 debugger; // 在此处自动断下
11 console.log(‘Hook捕获到set-cookie ->’,val);
12 return val;
13 }
14 })
})();



cookies hook(不是万能的 有些时候hook不到)

JS


1 var cookie_cache = document.cookie;
2
3 Object.defineProperty(document, ‘cookie’, {
4 get: function() {
5 console.log(‘Getting cookie’);
6 return cookie_cache;
7 },
8 set: function(val) {
9 console.log(“Seting cookie”,val);
10 var cookie = val.split(“;”)[0];
11 var ncookie = cookie.split(“=”);
12 var flag = false;
13 var cache = cookie_cache.split(“; “);
14 cache = cache.map(function(a){
15 if (a.split(“=”)[0] === ncookie[0]){
16 flag = true;
17 return cookie;
18 }
19 return a;
20 })
21 }
22 })



cookie

JS


1 var code = function(){
2 var org = document.cookie.lookupSetter(‘cookie’);
3 document.defineSetter(“cookie”,function(cookie){
4 if(cookie.indexOf(‘TSdc75a61a’)>-1){
5 debugger;
6 }
7 org = cookie;
8 });
9 document.defineGetter(“cookie”,function(){return org;});
10 }
11 var script = document.createElement(‘script’);
12 script.textContent = ‘(‘ + code + ‘)()’;
13 (document.head||document.documentElement).appendChild(script);
14 script.parentNode.removeChild(script);
15
16 // 当cookie中匹配到了 TSdc75a61a, 则插入断点。



window attr

JS


1 // 定义hook属性
2 var window_flag_1 = “_t”;
3 var window_flag_2 = “ccc”;
4
5 var key_value_map = {};
6 var window_value = window[window_flag_1];
7
8 // hook
9 Object.defineProperty(window, window_flag_1, {
10 get: function(){
11 console.log(“Getting”,window,window_flag_1,”=”,window_value);
12 //debugger
13 return window_value
14 },
15 set: function(val) {
16 console.log(“Setting”,window, window_flag_1, “=”,val);
17 //debugger
18 window_value = val;
19 key_value_map[window[window_flag_1]] = window_flag_1;
20 set_obj_attr(window[window_flag_1],window_flag_2);
21 },
22
23 });
24
25 function set_obj_attr(obj,attr){
26 var obj_attr_value = obj[attr];
27 Object.defineProperty(obj,attr, {
28 get: function() {
29 console.log(“Getting”, key_value_map[obj],attr, “=”,
30 obj_attr_value);
31 //debugger
32 return obj_attr_value;
33 },
34 set: function(val){
35 console.log(“Setting”, key_value_map[obj], attr, “=”, val);
36 //debugger
37 obj_attr_value = val;
38 },
39 });
}



eval/Function

JS


1 window.__cr_eval = window.eval;
2 var myeval = function(src) {
3 console.log(src);
4 console.log(“========= eval end ===========”);
5 return window.__cr_eval;
6 }
7
8 var _myeval = myeval.bind(null);
9 _myeval.toString = window.__cr_eval.toString;
10 Object.defineProperty(window, ‘eval’,{value: _myeval});
11
12 window._cr_fun = window.Function
13 var myfun = function(){
14 var args = Array.prototype.slice.call(arguments, 0, -1).join(“,”),
15 src = arguments[arguments.lenght -1];
16 console.log(src);
17 console.log(“======== Function end =============”);
18 return window._cr_fun.apply(this, arguments)
19 }
20
21 myfun.toString = function() {return window._cr_fun + “”}
//小花招,这里防止代码里检测原生函数
Object.defineProperty(window, “Function”,{value: myfun})



websocket hook

JS


1 // 1、webcoket
2 一般都是json数据格式传输,那么发生之前需要JSON.stringify
3 var my_stringify = JSON.stringify;
4 JSON.stringify = function (params) {
5 //这里可以添加其他逻辑比如 debugger
6 console.log(“json_stringify params:”,params);
7 return my_stringify(params);
8 };
9
10 var my_parse = JSON.parse;
11 JSON.parse = function (params) {
12 //这里可以添加其他逻辑比如 debugger
13 console.log(“json_parse params:”,params);
14 return my_parse(params);
15 };
16
17 // 2 webScoket
18 绑定在windows对象,上,根据浏览器的不同,websokcet名字可能不一样
19 //chrome window.WebSocket firfox window.MozWebSocket;
20 window._WebSocket = window.WebSocket;
21
22 // hook send
23 window._WebSocket.prototype.send = function (data) {
24 console.info(“Hook WebSocket”, data);
25 return this.send(data)
26 }

    Object.defineProperty(window, "WebSocket",{value: WebSocket})


hook 正则 —— 1

JS


1 (function () {
2 var _RegExp = RegExp;
3 RegExp = function (pattern, modifiers) {
4 console.log(“Some codes are setting regexp”);
5 debugger;
6 if (modifiers) {
7 return _RegExp(pattern, modifiers);
8 } else {
9 return _RegExp(pattern);
10 }
11 };
12 RegExp.toString = function () {
13 return “function setInterval() { [native code] }”
14 };
15 })();



hook 正则 2 加在sojson头部过字符串格式化检测

JS


1 (function () {
2 var _RegExp = RegExp;
3 RegExp = function (pattern, modifiers) {
4 if (pattern == decodeURIComponent(“%5Cw%2B%20*%5C(%5C)%20*%7B%5Cw%2B%20*%5B’%7C%22%5D.%2B%5B’%7C%22%5D%3B%3F%20*%7D”) || pattern ==
5 decodeURIComponent(“function%20*%5C(%20*%5C)”)
6 || pattern ==
7 decodeURIComponent(“%5C%2B%5C%2B%20*(%3F%3A_0x(%3F%3A%5Ba-f0-9%5D)%7B4%2C6%7D%7C(%3F%3A%5Cb%7C%5Cd)%5Ba-z0-9%5D%7B1%2C4%7D(%3F%3A%5Cb%7C%5Cd))”)
8 || pattern == decodeURIComponent(“(%5C%5C%5Bx%7Cu%5D(%5Cw)%7B2%2C4%7D)%2B”)) {
9 pattern = ‘.*?’;
10 console.log(“发现sojson检测特征,已帮您处理。”)
11 }
12 if (modifiers) {
13 console.log(“疑似最后一个检测…已帮您处理。”)
14 console.log(“已通过全部检测,请手动处理debugger后尽情调试吧!”)
15 return _RegExp(pattern, modifiers);
16 } else {
17 return _RegExp(pattern);
18 }
19 };
20 RegExp.toString = function () {
return _RegExp.toString();
};
})();



hook canvas (定位图片生成的地方)

JS


1 (function() {
2 ‘use strict’;
3 let create_element = document.createElement.bind(doument);
4
5 document.createElement = function (_element) {
6 console.log(“create_element:”,_element);
7 if (_element === “canvas”) {
8 debugger;
9 }
10 return create_element(_element);
11 }
12 })();



setInterval 定时器

JS


1 (function () {
2 setInterval_ = setInterval;
3 console.log(“原函数已被重命名为setInterval_”)
4 setInterval = function () {};
5 setInterval.toString = function () {
6 console.log(“有函数正在检测setInterval是否被hook”);
7 return setInterval_.toString();
8 };
9 })();



console.log 检测 (不让你输出调试)

JS


1 var oldConsole = [“debug”, “error”, “info”, “log”, “warn”,
2 “dir”, “dirxml”, “table”, “trace”, “group”,
3 “groupCollapsed”, “groupEnd”, “clear”, “count”,
4 “countReset”, “assert”, “profile”, “profileEnd”, “time”,
5 “timeLog”, “timeEnd”, “timeStamp”, “context”,
6 “memory”].map(key => {
var old = console[key];
console[key] = function () {};
console[key].toString = old.toString.bind(old)
return old;
})




本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!