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 = "";

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

&lt;script type=&quot;text/javascript&quot;&gt;
window.location = &quot;;;


What we have done:

PHP Code:
$comment =
<script type="text/javascript">
      window.location = "";

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 !