使用用户的RegEx是否安全?

时间:2022-11-28 22:06:12

I want to add a feature to my website to let users search the texts with RegEx. But, is it safe to let the users do something like that ?

我想在我的网站上添加一项功能,让用户使用RegEx搜索文本。但是,让用户做这样的事情是否安全?

preg_match('/' . $user_input_regex . '/', $subject);

2 个解决方案

#1


12  

There is a possible attack on this code called a ReDoS attack (Regular expression Denial of Service).

此代码可能存在攻击,称为ReDoS攻击(正则表达式拒绝服务)。

The Regular expression Denial of Service (ReDoS) is a Denial of Service attack, that exploits the fact that most Regular Expression implementations may reach extreme situations that cause them to work very slowly (exponentially related to input size). An attacker can then cause a program using a Regular Expression to enter these extreme situations and then hang for a very long time.

正则表达式拒绝服务(ReDoS)是一种拒绝服务攻击,它利用了大多数正则表达式实现可能达到导致它们工作非常缓慢(与输入大小呈指数关联)的极端情况的事实。然后,攻击者可以使用正则表达式使程序进入这些极端情况,然后挂起很长时间。

Specifically with preg_match there is a known issue that can cause a PHP Segmentation Fault.

特别是在preg_match中,存在一个已知的问题,可能导致PHP分段错误。

So the answer is no, it is not safe because of issues such as these.

所以答案是否定的,因为这些问题不安全。

#2


4  

Security wise you should never trust user input, so it depends what you do with the input. In your given case you should at least escape the used delimiter (backslash) in the user input to ensure the regex works.

安全方面,您永远不应该信任用户输入,因此这取决于您对输入的处理方式。在您给定的情况下,您应该至少转义用户输入中使用的分隔符(反斜杠)以确保正则表达式正常工作。

#1


12  

There is a possible attack on this code called a ReDoS attack (Regular expression Denial of Service).

此代码可能存在攻击,称为ReDoS攻击(正则表达式拒绝服务)。

The Regular expression Denial of Service (ReDoS) is a Denial of Service attack, that exploits the fact that most Regular Expression implementations may reach extreme situations that cause them to work very slowly (exponentially related to input size). An attacker can then cause a program using a Regular Expression to enter these extreme situations and then hang for a very long time.

正则表达式拒绝服务(ReDoS)是一种拒绝服务攻击,它利用了大多数正则表达式实现可能达到导致它们工作非常缓慢(与输入大小呈指数关联)的极端情况的事实。然后,攻击者可以使用正则表达式使程序进入这些极端情况,然后挂起很长时间。

Specifically with preg_match there is a known issue that can cause a PHP Segmentation Fault.

特别是在preg_match中,存在一个已知的问题,可能导致PHP分段错误。

So the answer is no, it is not safe because of issues such as these.

所以答案是否定的,因为这些问题不安全。

#2


4  

Security wise you should never trust user input, so it depends what you do with the input. In your given case you should at least escape the used delimiter (backslash) in the user input to ensure the regex works.

安全方面,您永远不应该信任用户输入,因此这取决于您对输入的处理方式。在您给定的情况下,您应该至少转义用户输入中使用的分隔符(反斜杠)以确保正则表达式正常工作。