Wednesday, October 16, 2013

Protecting your website from Vulnerable Script Tags and Codes



It's really important for you to protect your website from hackers, but without removing any features from your website.
In this post we are going to understand how to solve the problem of XSS - Cross Site Scripting problems.

What is XSS:
Cross-site scripting (XSS) is a type of computer security vulnerability typically found in Web applications. XSS enables attackers to inject client-side script into Web pages viewed by other users. A cross-site scripting vulnerability may be used by attackers to bypass access controls such as the same origin policy.
                                                                                                                                -Source Wikipedia

Now to prevent our website from XSS attack, we are going to use a PHP function called: htmlentities()
This function of PHP will help your website to parse all harmful tags safely.

For example, if you have a website which displays comments submitted by the user and that comment system is XSS vulnerable, then if a user will enter some comment like this:

Javascript Code:
<script type="text/javascript">
     window.location = "http://www.google.com";
</script>

and now this comment is stored in your website's comment database. So whenever any user will meet the page where this comment is loaded from your database. Then the user will re-directed to the specified website.

So to prevent this problem we are going to use PHP function: htmlentities()
This function will replace all the < > / " ' = & and other symbols to a non-vulnerable signs. Like to display and in your website we use HTML Entities: &amp;
So in the similar way we are going to covert the vulnerable symbols in to non vulnerable HTML Entities.

You'll just need to wrap htmlentities() to the variable from which you POST the comment to the database.

PHP Code:
<?php
   $comment = htmlentities($_POST['comment_area']);
?> 

So that's how you can protect your website from XSS. In the next post we'll be discussing about how to prevent our website from getting hacked using SQL-injections.

About the javascript code, if we parse it using the htmlentities() function then this is the safe result and this can be added in our database.

Result:
&lt;script type=&quot;text/javascript&quot;&gt;
window.location = &quot;http://www.google.com&quot;;

&lt;/script&gt;

What we have done:

PHP Code:
<?php
$comment =
<<<comment
<script type="text/javascript">
      window.location = "http://www.google.com";
</script>
comment;

echo htmlentities($comment);
?>

Liked the post ? subscribe us with your email to get upcoming tutorials directly in your inbox:

No comments:

Post a Comment

Your Comment Will Be Visible After Approval, Thanks !