PHP preg_replace security

2019-08-13 20:04发布

问题:

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]);

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.

回答1:

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

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);
}

Testing

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);

EDIT: 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.

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.