浏览器安全执行编译后 JS 字符串,替代 new Function()
数据小陈
结论:优先使用 iframe sandbox="allow-scripts"(不要加 allow-same-origin)加载一个只包含编译产物的 Blob 脚本,父页面通过 postMessage 传入可结构化克隆的 env 数据;同时在 iframe 内用 CSP 禁止网络和额外资源。Worker 可以作为无 DOM 场景的备选,但它不是完整安全边界。
为什么不能继续用 new Function()
new Function(...) 创建的函数仍然运行在页面全局作用域里,能访问 window、document、fetch 等对象。即使把变量当参数传进去,也挡不住代码通过全局对象访问页面资源。
推荐方案:sandboxed iframe + Blob script + postMessage
具体做法:
- iframe 只开
allow-scripts,不要开allow-same-origin; - 编译后的字符串作为 Blob 的文本内容,用
<script src="blob:...">加载,不使用eval/new Function; - 通过 CSP 断掉网络和额外资源;
env只能传可序列化数据,函数、DOM 节点、闭包不能直接传。原代码里的ifadeHesapla等函数需要在沙箱内重新提供安全实现,或者改成异步 RPC。
示例:
function runCompiledInSandbox(compiledCode, envData) {
const iframe = document.createElement('iframe');
iframe.sandbox = 'allow-scripts';
iframe.style.display = 'none';
const wrapper = [
'self.onmessage = function (event) {',
' const env = event.data;',
' function ifadeHesapla() { /* 安全实现 */ }',
' function matematikHesapla() { /* 安全实现 */ }',
' function kosulDegerlendir() { /* 安全实现 */ }',
' function cozArg() { /* 安全实现 */ }',
' function hmbh() { /* 安全实现 */ }',
' try {',
' (function (dgsknlr, fonksiyonlar, ifadeHesapla, matematikHesapla, kosulDegerlendir, cozArg, hmbh) {',
compiledCode,
' })(env.dgsknlr, env.fonksiyonlar, ifadeHesapla, matematikHesapla, kosulDegerlendir, cozArg, hmbh);',
" self.parent.postMessage({ type: 'result', ok: true }, '*');",
' } catch (e) {',
" self.parent.postMessage({ type: 'result', ok: false, error: String(e && e.message || e) }, '*');",
' }',
'};'
].join('\n');
const blob = new Blob([wrapper], { type: 'text/javascript' });
const url = URL.createObjectURL(blob);
iframe.srcdoc =
'<!doctype html>' +
`<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src ${url}; connect-src 'none'; img-src 'none'; style-src 'none'">` +
'<script src="' + url + '"></script>';
const onMessage = (event) => {
if (event.source === iframe.contentWindow) {
console.log('sandbox result:', event.data);
}
};
window.addEventListener('message', onMessage);
document.body.appendChild(iframe);
iframe.onload = () => {
iframe.contentWindow.postMessage(envData, '*');
};
return () => {
window.removeEventListener('message', onMessage);
URL.revokeObjectURL(url);
iframe.remove();
};
}
调用:
runCompiledInSandbox(jskod, {
dgsknlr: {},
fonksiyonlar: {}
// 只放数据;不要把函数、DOM 节点放进来
});
关于传函数和 env 对象
postMessage 走的是结构化克隆,不能把父页面函数、闭包、DOM 节点直接传进沙箱。原代码里 ifadeHesapla、matematikHesapla、kosulDegerlendir 这些如果是辅助函数,建议在 wrapper 里提供沙箱内版本;如果它们必须依赖父页面数据,需要把编译产物改成异步调用,用 postMessage 做 RPC,不能保留同步函数签名。否则就只能把父页面能力暴露给沙箱,安全边界会被打开。
CSP 和 sandbox 要注意的点
sandbox="allow-scripts"不要加allow-same-origin,否则同源能力会回来。- CSP 里至少限制
connect-src 'none'、img-src 'none'、default-src 'none',按需只放行脚本。 - 不要给 iframe 传真实
window、document、fetch、存储对象。 - 结果消息要自己校验,不要直接
innerHTML或eval父页面数据。 - 沙箱不是绝对安全。如果执行的是完全不可信代码,服务端隔离或独立 VM/容器更强。
Worker 能不能用?
可以,但它不是完整沙箱。Worker 没有 window/document,能减少 DOM 攻击面;不过 Worker 里仍有 fetch、WebSocket、importScripts 等网络能力,需要额外限制。传 env 同样只能用可结构化克隆数据,函数不能直接传。若代码不需要 DOM,Worker 是轻量选择;若需要严格限制网络和页面能力,sandboxed iframe + CSP 更可控。
备注:内容仅供参考。
