当前位置:网站首页>JS reverse hook, eating hot pot and singing songs, was suddenly robbed by Ma bandits!

JS reverse hook, eating hot pot and singing songs, was suddenly robbed by Ma bandits!

2021-10-14 06:36:26 Brother K reptile

Pay attention to WeChat public number :K Brother reptile ,QQ Communication group :808574309, Continue to share advanced crawler 、JS/ Android reverse and other technology dry goods !

What is? Hook?

Hook Chinese translation is hook ,Hook It's actually Windows One provided in to replace DOS Next “ interrupt ” The system mechanism of ,Hook The concept of Windows Desktop software development is very common , In particular, the mechanisms that trigger events , When a specific system event is Hook after , Once it happens Hook event , The event was Hook Your program will be notified by the system , At this time, the program can respond to the event at the first time . In the program, it is understood as “ hijacked ” May better understand , We can go through Hook Technology to hijack an object , Pull out the program of an object and replace it with our own rewritten code fragment , Modify parameters or replace return values , So as to control its interaction with other objects .

Popular speaking ,Hook In fact, it's blocking the road and robbing , Marbond took his wife , Out of town , Eating hot pot , And singing , Suddenly he was robbed by the hemp bandits , Pockmarked Zhang robbed county magistrate Ma bond's train , Transformed into a county magistrate , Take his men to goose City to take office .Hook The process of , That's how pockmarked Zhang replaced marbond .

01.png

JS In reverse Hook

stay JavaScript In reverse , The process of replacing the original function can be called Hook, The following is a simple code to understand Hook The process of :

function a() {
  console.log("I'm a.");
}

a = function b() {
  console.log("I'm b.");
};

a()  // I'm b.

Covering the original function directly is the simplest way , The above code will a Function is rewritten , Call again a The function will output I'm b., If you still want to execute the original a The contents of the function , Intermediate variables can be used for storage :

function a() {
  console.log("I'm a.");
}

var c = a;

a = function b() {
  console.log("I'm b.");
};

a()  // I'm b.
c()  // I'm a.

here , call a The function will output I'm b., call c The function will output I'm a..

This method of direct coverage of original functions is usually only used for temporary debugging , Not very practical , But it can help us understand Hook The process of , In practice JS In the reverse process , We will use a more advanced method , such as Object.defineProperty().

Object.defineProperty()

Basic grammar :Object.defineProperty(obj, prop, descriptor), Its function is to define a new attribute directly on an object , Or modify the existing properties of an object , The meanings of the three parameters received are as follows :

obj: The current object that needs to define properties ;

prop: Property name to be defined at present ;

descriptor: property descriptor , The following values can be taken :

Property name The default value is meaning
get undefined Access descriptor , The method to get the value of the target attribute
set undefined Access descriptor , How to set the value of the target property
value undefined Data descriptor , Set the value of the property
writable false Data descriptor , Whether the value of the target property can be overridden
enumerable false Whether the target property can be enumerated
configurable false Whether the target attribute can be deleted or the attribute can be modified again

Usually , The definition and assignment of objects are as follows :

var people = {}
people.name = "Bob"
people["age"] = "18"

console.log(people)
// { name: 'Bob', age: '18' }

Use Object.defineProperty() Method :

var people = {}

Object.defineProperty(people, 'name', {
   value: 'Bob',
   writable: true  //  Can it be rewritten 
})

console.log(people.name)  // 'Bob'

people.name = "Tom"
console.log(people.name)  // 'Tom'

stay Hook in , The most used is the access descriptor , namely get and set.

get: Attribute getter function , without getter, Then for undefined, When accessing this property , This function will be called , No parameters are passed in during execution , But it will pass in this object ( By inheritance , there this It does not have to be the object that defines the property ), The return value of this function will be used as the value of the property .

set: Attribute setter function , without setter, Then for undefined, When the property value is modified , This function will be called , This method takes a parameter , That is, the new value given , The this object .

Use an example to demonstrate :

var people = {
  name: 'Bob',
};
var count = 18;

//  Define a  age  Return the defined variable when getting the value  count
Object.defineProperty(people, 'age', {
  get: function () {
    console.log(' Get value !');
    return count;
  },
  set: function (val) {
    console.log(' Set the value !');
    count = val + 1;
  },
});

console.log(people.age);
people.age = 20;
console.log(people.age);

Output :

 Get value !
18
 Set the value !
 Get value !
21

In this way , We can set a value , Add some code , such as debugger;, Let it break , Then use the call stack to debug , Parameter encryption found 、 Or where the parameters are generated , It should be noted that , When the website loads, we must first run our Hook Code , Then run the website's own code , To successfully disconnect , This process we can call it Hook Code injection , The following will introduce several mainstream injection methods .

Hook Several methods of Injection

The following is a strange art cookie Medium __dfp Value, for example , To demonstrate how to inject Hook.

1、Fiddler Plug in Injection

Come to the home page of a strange art , You can see it cookie There's a __dfp value :

02.png

If you search directly, you can't find it , We want to pass Hook The way , Let in generate __dfp Where the value is broken , You can write the following self executing function :

(function () {
  'use strict';
  var cookieTemp = '';
  Object.defineProperty(document, 'cookie', {
    set: function (val) {
      if (val.indexOf('__dfp') != -1) {
        debugger;
      }
      console.log('Hook Capture to cookie Set up ->', val);
      cookieTemp = val;
      return val;
    },
    get: function () {
      return cookieTemp;
    },
  });
})();

if (val.indexOf('__dfp') != -1) {debugger;} Search means to search __dfp The first occurrence in a string , be equal to -1 Indicates that the string value does not appear , On the contrary . If it does , then debugger Cut off , It should be noted here that it cannot be written as if (val == '__dfp') {debugger}, because val The value passed is similar to __dfp=xxxxxxxxxx, You can't break it like this .

How to use it with code ? That is, how to inject Hook What about code? ? It's recommended here Fiddler The bag capturing tool is used with the plug-in of the programming cat , Plugins can enter keywords in official account 【Fiddler plug-in unit 】 obtain , Its principle can be understood as intercepting —> machining —> A process of release , utilize Fiddler Replace response , stay Fiddler After intercepting the data , Insert... In the first line of the source code Hook Code , because Hook The code is a self executing function , Then once the web page is loaded , It must run first Hook Code . The installation is completed as shown in the figure below , Open the bag , Click to open the injection Hook:

03.png

Browser clear cookie Then re-enter the page of a strange art , You can see the successful disconnection , stay console The console can see some of the captured cookie value , At this time val Namely __dfp Value , Next on the right Call Stack You can see the calling process of some functions in the call stack , Follow up in turn to find the beginning __dfp Generated place .

04.png

2、TamperMonkey Inject

TamperMonkey Commonly known as oil monkey plug-in , Is a free browser extension and the most popular user script manager , Support many mainstream browsers , Include Chrome、Microsoft Edge、Safari、Opera、Firefox、UC browser 、360 browser 、QQ Browsers and so on , Basically, the script is written at one time , All platforms can run , It can be said that browser based applications are really cross platform . Users can go to GreasyFork、OpenUserJS And other platforms directly obtain scripts published by others , Numerous and powerful , Such as video analysis 、 Go to the advertisement, etc .

We still use some strange art cookie As an example to demonstrate how to write TamperMonkey Script , First go to the app store to install TamperMonkey, Installation process will not be repeated , Then click on the icon , Add new script , Or click the management panel , Then click the plus sign to create a new script , Write the following code :

// ==UserScript==
// @name Cookie Hook
// @namespace http://tampermonkey.net/
// @version 0.1
// @description Cookie Hook  Script example 
// @author K Brother reptile 
// @match *
// @icon https://www.kuaidaili.com/img/favicon.ico
// @grant none
// @run-at document-start
// ==/UserScript==

(function () {
  'use strict';
  var cookieTemp = '';
  Object.defineProperty(document, 'cookie', {
    set: function (val) {
      if (val.indexOf('__dfp') != -1) {
        debugger;
      }
      console.log('Hook Capture to cookie Set up ->', val);
      cookieTemp = val;
      return val;
    },
    get: function () {
      return cookieTemp;
    },
  });
})();

05.png

The main body JavaScript The self executing function is the same as before , Note here that the first comment , Each option makes sense , All options refer to TamperMonkey Official documents , The following is a list of commonly used 、 Some of the more important options ( Special attention needs to be paid to @match@include and @run-at Options ):

Options meaning
@name The name of the script
@namespace Namespace , To distinguish between scripts with the same name , Usually write the author's name or website
@version Script version , The update of oil monkey script will read this version number
@description Describe what this script is for
@author The name of the author who wrote this script
@match Match the regular expression from the beginning of the string , Only the matching URL will execute the corresponding script , for example * Match all ,https://www.baidu.com/* Match Baidu, etc , You can refer to Python re In the module re.match() Method , Allow multiple instances
@include and @match similar , Only the matching URL will execute the corresponding script , however @include Does not match from the beginning of the string , for example *://*baidu.com/* Match Baidu , Specific differences can be referred to TamperMonkey Official documents
@icon The script icon Icon
@grant Specify the permissions required for the script to run , If the script has the appropriate permissions , You can call the... Provided by the oil monkey extension API Interact with the browser . If set to none Words , Sandbox environment is not used , The script will run directly in the web page environment , Most of the oil monkey extensions cannot be used at this time API. If not specified , By default, the oil monkey will add several of the most commonly used API
@require If the script depends on other JS Ku's words , have access to require Command import , Load other libraries before running the script
@run-at Script injection timing , This option is whether or not hook The key to , There are five values to choose from :document-start: At the beginning of the page ;document-body:body When it appears ;document-end: Execute... On or after loading ;document-idle: Execute after loading , The default option ;context-menu: When you click the script in the browser context menu , It is usually set to document-start

eliminate cookie, Turn on TamperMonkey plug-in unit , Come to the home page of a strange art again , It can be seen that it has also been successfully disconnected , Similarly, you can follow up the call stack to further analyze __dfp Source of value .

06.png

3、 Browser plug-in injection

The official name of browser plug-in should be browser extension (Extension), Browser plug-ins can enhance browser functions , It can also help us Hook, The writing of browser plug-ins is not complicated , With Chrome Plug in as an example , Just make sure there is one under the project manifest.json File can , It is used to set all plug-in related configurations , Must be placed in the root . among manifest_versionnameversion 3 Two parameters are essential , If you want to study in depth , You can refer to Xiaoming Blog and Google Official documents . It should be noted that , Firefox plug-ins may not run on other browsers , and Chrome Plug ins can run in addition to Chrome Outside the browser , It can also run on all webkit The domestic browser of kernel , such as 360 Opera Portable 、360 Secure browser 、 Sogou browser 、QQ Browsers and so on . We still use some strange art cookie To demonstrate how to write a Chrome browser Hook plug-in unit .

newly build manifest.json file :

{
    "name": "Cookie Hook",          //  The plug-in name 
    "version": "1.0",               //  The plug-in version 
    "description": "Cookie Hook",   //  Plug-in description 
    "manifest_version": 2,          //  List version , Must be 2 perhaps 3
    "content_scripts": [{
        "matches": ["<all_urls>"],  //  Match all addresses 
        "js": ["cookie_hook.js"],   //  Injected code file name and path , If there are more than one , Then inject 
        "all_frames": true,         //  Allow content scripts to be embedded in all frames of the page 
        "permissions": ["tabs"],    //  Permission to apply for ,tabs  It means label 
        "run_at": "document_start"  //  Time of code injection 
    }]
}

newly build cookie_hook.js file :

var hook = function() {
    'use strict';
    var cookieTemp = '';
    Object.defineProperty(document, 'cookie', {
        set: function(val) {
            if (val.indexOf('__dfp') != -1) {
                debugger;
            }
            console.log('Hook Capture to cookie Set up ->', val);
            cookieTemp = val;
            return val;
        },
        get: function() {
            return cookieTemp;
        },
    });
}
var script = document.createElement('script');
script.textContent = '(' + hook + ')()';
(document.head || document.documentElement).appendChild(script);
script.parentNode.removeChild(script);

Put these two files in the same folder , open chrome Extension program , Open developer mode , Load the unzipped extender , Select the folder you want to create :

07.png

Come to a strange art page , eliminate cookie Then re-enter , You can see that it was also successfully disconnected , Trace the call stack to find where its value is generated :

08.png

Commonly used Hook Code summary

In addition to using the above Object.defineProperty() Method , You can also capture related interfaces directly , Then rewrite the interface , The following is a list of common Hook Code . Be careful : The following are just the key Hook Code , The specific injection methods are different , To make relevant changes .

Hook Cookie

Cookie Hook Used to locate Cookie Generation location of key parameters in , The following code demonstrates when Cookie There's a match in __dfp keyword , Insert breakpoint :

(function () {
  'use strict';
  var cookieTemp = '';
  Object.defineProperty(document, 'cookie', {
    set: function (val) {
      if (val.indexOf('__dfp') != -1) {
        debugger;
      }
      console.log('Hook Capture to cookie Set up ->', val);
      cookieTemp = val;
      return val;
    },
    get: function () {
      return cookieTemp;
    },
  });
})();
(function () {
    'use strict';
    var org = document.cookie.__lookupSetter__('cookie');
    document.__defineSetter__('cookie', function (cookie) {
        if (cookie.indexOf('__dfp') != -1) {
            debugger;
        }
        org = cookie;
    });
    document.__defineGetter__('cookie', function () {
        return org;
    });
})();

Hook Header

Header Hook Used to locate Header Generation location of key parameters in , The following code demonstrates when Header Contained in the Authorization When a keyword , Insert breakpoint :

(function () {
    var org = window.XMLHttpRequest.prototype.setRequestHeader;
    window.XMLHttpRequest.prototype.setRequestHeader = function (key, value) {
        if (key == 'Authorization') {
            debugger;
        }
        return org.apply(this, arguments);
    };
})();

Hook URL

URL Hook Used to locate the request URL Generation location of key parameters in , The following code demonstrates when requesting URL It contains login When a keyword , Insert breakpoint :

(function () {
    var open = window.XMLHttpRequest.prototype.open;
    window.XMLHttpRequest.prototype.open = function (method, url, async) {
        if (url.indexOf("login") != 1) {
            debugger;
        }
        return open.apply(this, arguments);
    };
})();

Hook JSON.stringify

JSON.stringify() Method is used to JavaScript Value to JSON character string , In the encryption process of some sites, you may encounter , The following code demonstrates the problem of JSON.stringify() when , Insert breakpoint :

(function() {
    var stringify = JSON.stringify;
    JSON.stringify = function(params) {
        console.log("Hook JSON.stringify ——> ", params);
        debugger;
        return stringify(params);
    }
})();

Hook JSON.parse

JSON.parse() Method is used to put a JSON String to object , In the encryption process of some sites, you may encounter , The following code demonstrates the problem of JSON.parse() when , Insert breakpoint :

(function() {
    var parse = JSON.parse;
    JSON.parse = function(params) {
        console.log("Hook JSON.parse ——> ", params);
        debugger;
        return parse(params);
    }
})();

Hook eval

JavaScript eval() The function is to calculate JavaScript character string , And execute it as script code . If the argument is an expression ,eval() The function will execute the expression . If the parameter is Javascript sentence ,eval() Will perform Javascript sentence , It is often used to dynamically execute JS. After the following code is executed , After that all eval() All operations will be printed out on the console JS Source code :

(function() {
    //  Save the original method 
    window.__cr_eval = window.eval;
    //  rewrite  eval
    var myeval = function(src) {
        console.log(src);
        console.log("=============== eval end ===============");
        debugger;
        return window.__cr_eval(src);
    }
    //  shielding  JS  For native functions in  native  Attribute detection 
    var _myeval = myeval.bind(null);
    _myeval.toString = window.__cr_eval.toString;
    Object.defineProperty(window, 'eval', {
        value: _myeval
    });
})();

Hook Function

After the following code is executed , All function operations will be printed out on the console JS Source code :

(function() {
    //  Save the original method 
    window.__cr_fun = window.Function;
    //  rewrite  function
    var myfun = function() {
        var args = Array.prototype.slice.call(arguments, 0, -1).join(","),
            src = arguments[arguments.length - 1];
        console.log(src);
        console.log("=============== Function end ===============");
        debugger;
        return window.__cr_fun.apply(this, arguments);
    }
    //  shielding js For native functions in native Attribute detection 
    myfun.toString = function() {
        return window.__cr_fun + ""
    }
    Object.defineProperty(window, 'Function', {
        value: myfun
    });
})();

版权声明
本文为[Brother K reptile]所创,转载请带上原文链接,感谢
https://chowdera.com/2021/10/20211002145418042L.html

随机推荐