javascript 评估用户提交的简单数学node.js
我需要评估一些简单的用户提交的数学。例如,2 个数字的乘法。
这让我很容易受到注入攻击。
我的计划是将一堆值 [^|(|)|\d+|\*|\/|\+|-]
列入白名单,并在评估之前用正则表达式替换其他所有内容。
这有什么问题吗?
示例字符串:
324*32
(5+4-17) / 3
I need to evaluate some simple user submitted math. Multiplication of 2 numbers for example.
This opens me up to injection attacks.
My plan is to whitelist a bunch of values [^|(|)|\d+|\*|\/|\+|-]
and replace everything else with regex before evaluation.
Any problems with this?
Example strings:
324*32
(5+4-17) / 3
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想不出任何特别令人讨厌的方法来仅使用数字和少数运算符来过多地搞乱您的服务器,但是,您需要注意一些事情:
鉴于
[^... ]
是一个字符类,您不需要用|
分隔每个值。这可能是您真正想要的:[^^()\d*\/+-]
。这将匹配您不想要允许的一切。此外,重要的是要记住,在 JavaScript 中,
^
并不代表幂,而是代表“异或”。例如,这意味着2 ^ 3 == 1
。因此,您可能不想将^
列入白名单:[^()\d*\/+-]
。您可能会遇到像
(1 * (2 + 3)
这样的无效语法,因此您也应该注意这一点。您可能只需要一个 try catch 块并有意义地处理类似的事情(报告将问题返回给用户或其他)。I can't think of any particularly nasty way to mess up your server too much using just numbers and a handful of operators, however, there are some things you need to look out for:
Given that the
[^...]
is a character class, you do not need to separate every value with|
. This is probably what you really want:[^^()\d*\/+-]
. This will match everything you do not want to allow.Additionally, it is important to remember that, in JavaScript,
^
does not represent powers but rather "exclusive or". This means, for example, that2 ^ 3 == 1
. So you probably do not want to whitelist^
:[^()\d*\/+-]
.You might encounter invalid syntax like
(1 * (2 + 3)
, so you should watch out for that as well. You can probably just have a try catch block and meaningfully deal with things like that (report the problem back to the user or something).