下载使用vm2(有安全漏洞,酌情使用)
如果我们直接使用Node环境来运行js代码的话,有些东西是无法规避环境检测的,所以我们需要一个纯净的V8环境来进行补环境的操作。vm2可以理解为一个纯净的脱离Node的V8环境,相当于重新启动了一个进程,然后在进程中不允许加载Node中的一些东西,禁止了一些Node中的特性,相当于V8的沙箱环境。PS:一些node环境中无法删除的node特征可以在vm2中删除,而不是说vm2=v8环境。
npm install vm2 //下载vm2
const fs = require('fs')
const {
VM,VMScript} = require('vm2') //VMScript是用来调试VM环境中的代码的
const file = `${
__dirname}/code.js`
const windowfile = `${
__dirname}/window.js`
const vm = new VM()
const script = new VMScript(fs.readFileSync(file),'VM2') //第二个参数是指调试名,可以自己任意指定
vm.run(script)
检测环境的例子
- 如node环境中有process,而V8环境或者浏览器环境中没有process。
- 任何canvas指纹都存在一定误杀率,所以厂商不会去对canvas指纹做强校验,因为不同浏览器canvas底层实现代码不同;其次即便是相同浏览器,它的内核版本不同则取出来的canvas指纹也是不同的:
document.createElement('canvas').toDataURL()。 - toString()
- 基于原型链的检测
- DOM环境的检测
手动补环境的例子
主要可以参考官方文档来:
https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLCanvasElement/getContext
- 补
document.createElement:
// 补 document.createElement('canvas').toDataURL()
document = {
createElement: function(tagName){
var tag = (tagName + '').toLowerCase;
if (tag == 'canvas')
{
return {
toDataURL:function(){
return 'data:image/png;base64,iVBORw0KG...略...RU5ErkJggg==' //可以手动在浏览器中运行生成获取
}
}
}
return {
}
}
}
- 下面的代码中:
//在node环境中运行下面代码
var window = this;
navigator = {
userAgent:'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36'
}
const descriptor1 = Object.getOwnPropertyDescriptor(navigator,'userAgent');
此时会返回这样的一个对象:

但如果是在浏览器中,是拿不到descriptor1的(返回undefined)。
此时我们可以这样补环境:
Object.getOwnPropertyDescriptor_ = Object.getOwnPropertyDescriptor;
Object.getOwnPropertyDescriptor = function(o,p){
if (o.toLocaleString() == '[object Navigator]'){
return undefined;
}
Object.getOwnPropertyDescriptor_.apply(this,arguments);
}
此时再次运行const descriptor1 = Object.getOwnPropertyDescriptor(navigator,'userAgent');,得到的返回值便是undefined了。
- 补原型链环境例
var Window_my = function Window_my() {
}
window_my = new Window_my;
Object.defineProperties(window_my.__proto__,{
[Symbol.toStringTag]:{
value:'Window_my',
configurable:true
}
});
var WindowProperties_my = function

本文介绍了如何在JavaScript中使用vm2创建纯净的V8环境,以及如何手动补全在不同环境下缺失的功能,如process、canvas指纹检测、Proxy代理等,还涉及了WebRTC、console重写等问题的处理方法。
1万+

被折叠的 条评论
为什么被折叠?



