在没有XSS威胁的情况下使用评估 [英] Use eval without threat of XSS

查看:61
本文介绍了在没有XSS威胁的情况下使用评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当时正在制作(不是现在,但仍然对此感到好奇)使用HTML5和JS的游戏,而我想要的是人们可以插入自定义脚本,但是很安全。

I was making(not now, but still I'm curious about this one) a game using HTML5 and JS, and one I wanted was that people can insert custom script, but secure.

function executeCustomJS(code){
 eval(code);//bad
}

当然,这段代码非常糟糕,因为如果代码类似于 document.location.href ='http:// meatspn .com',那么结果将变得非常...(...)

Of course this code is very bad, because if code is something like document.location.href='http://meatspn.com', then the result will become very...(...)

我发现一个解决方法是转义(例如 eval -> ___ eval ___ ),并在白名单中取消转义关键字,例如 while, for, if, var, true, false,...和 func0, func1,....,它们是游戏中的某些东西(如API),并且很安全。

One solution I found is escaping(like eval -> ___eval___) all keywords, and un-escape keywords in whitelist, such as 'while', 'for', 'if', 'var', 'true', 'false', ... and 'func0', 'func1', ...., which are something (like API) of the game and are secure.

例如,

function executeCustomJS(code){
 code = code.replace(/(Keyword RegEx)/g,'___$1___');
 /*unescape keywords in whitelist*/
 eval(code);
}

我还没有发表RegEx和评论的东西,但这不是问题

I haven't made RegEx and things in comment, but that's not the question.

我们假设代码中的字符串未转义,没有功能可以通过转义字符串和'eval','window','document', 警告,位置不在白名单中。仍然有些人可以执行 while(true){} 之类的代码,但不能执行 document.location.href ='http: //meatspn.com'

Let's assume strings in code are not escaped, there's no function which can be made by escaping a string, and 'eval', 'window', 'document', 'alert', 'location' are NOT in the whitelist. Still some people can execute code like while(true){}, they can't execute any code like document.location.href='http://meatspn.com'.

此方法安全吗?或者,是否存在更好的方法?

Is this method secure? Or, is better way exists or not?

推荐答案

我建议您通过JSON公开有限的脚本语言。因此,记录一个脚本引擎,该脚本引擎要求您创建一个JSON对象作为您的代码。

I recommend you expose a limited scripting language over JSON. So document a scripting engine that requires you to create a JSON object as your code.

这具有很大的优势,因为它只是数据,因此不可能将不良代码注入JSON

This has the large advantage that it's impossible to inject bad code into JSON because it's just data.

因此您可以为脚本代码创建某种声明性语法。例如

So you can create some kind of declarative syntax for your scripting code. For example

{
    "0": {
        "Action": "move",
        "X": 10,
        "Y": -5
    },
    "1": {
        "Action": "emote",
        "type": "dance"
    }
}

现在有什么好处设计一种小的声明性脚本语言是一个完全不同的问题。

Now what is a good design for a tiny declarative scripting language is a completely different question.

这篇关于在没有XSS威胁的情况下使用评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆