Thursday 1 September 2016

code injection - PHP preg_replace security




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('$2
');

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.


Answer



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 = 'XSS';

// this link is attacked
echo $content . "
";
// 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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...