本文介绍了PHP preg_replace安全性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要防止跨站点脚本(XSS)。如何确认它不是跨站点脚本?问题出在我的 url BBCode上。

I need to prevent cross-site scripting (XSS). How can I validate that it isn't cross-site script? The issue is with my "url" BBCode.

function bbcode($input) {
    $search = array('/\[a url="(.+?)"\](.*?)\[\/a\]/is');

    $replace = array('<a href="$1" style="color: #337ab7;
                         text-decoration: none" target="_blank">$2
                      </a>');

    return preg_replace($search, $replace, $input);
}

bbcode([a url="javascript://hello.com/%0Aalert(%27s%27)"]XSS[/url]);

上面的代码是一个例子。当您单击链接时,将弹出一个JavaScript弹出窗口。另外,该数组中还有更多的BBCode,但我在发布此数组时将其删除以使其更容易。

The code above is an example of what happens. When you click the link, a JavaScript popup comes up. Also, there are more BBCode in that array, but I removed them when posting this to make it easier.

推荐答案

OP,好像OP网站已被XSS感染。

After chatting with OP, looks like OP site is XSS infected.

通常,XSS来自不良用户,他们通过提交表单,评论输入,发布,URL等来获取。因此,我们需要防止XSS,但是由于您已经受到伤害,您可以开始使用以下功能来阻止脚本执行,并分析并修复您的站点以防日后受到攻击。

Normally XSS comes from bad users through submit form, comments input, post, URL etc. So we need to prevent XSS, but since you are already harmed you could start using following function to stop scripts from execution, and analysis and fix your site against future attack.

function filterScript($content)
{
    $default = '';
    return preg_replace('/href="javascript:[^"]+"/', $default, $content);
}

测试

我们认为这是我们的攻击内容:

We imagine this is our attack content:

$content = '<a href="javascript://somedomain.com/%0Aalert(%27s%27)">XSS</a>';

// this link is attacked
echo $content . "<br>";
// this link is not attacked
echo filterScript($content);

编辑:除此答案外,值得一看。

in addition to this answer, it might be worth it to also take look at this answer.

注意:上述功能将提供帮助,但不是完整的解决方案,实际上是您制定策略所需要的

Note: The above functions will help, but is not a complete solution, what really you need to make a strategy of you site to find out weakness and and find out how you should protect it.

提供的有一些建议,介绍如何以及在何处查看。 OWASP列出了您应该的十大可能攻击方式,它们也有一个较新的推荐指南。

The provided link has some recommendation how and where to look at. OWASP has top 10 list of possible attack you should read, they have also a newer recommendation guide.

这篇关于PHP preg_replace安全性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 06:47
查看更多