Cross Site Scripting Example

Posted by in Questions & Answers

In this post I’ll show you cross site scripting example , what is cross site scripting and how to protect your website from cross site scripting attack.

What Is Cross Site Scripting

Cross Site Scripting is a type of computer security vulnerability where malicious users can add carefully-constructed comments to webpages with the intention of fooling web browsers.
Cross site scripting flaws occur whenever an application takes untrusted¸data and sends it to a web browser without proper validation and escaping. Cross site scripting allows attackers to execute script in the victim’s browser which can hijack user sessions, deface web sites, or redirect the user to malicious sites.

Cross Site Scripting Example

I’ve created web application XSS_App that is vulnerable to cross site scripting attack.
XSS_App contains :

  • index.php – form that allows visitors to post comments
  • hackspccomments.php – PHP script that stores comments in the database table_comments.sql
  • viewcomments.php – PHP script that allows visitors to view all comments

The visitor can see all comments on viewcomments.php . viewcomments.php retrieves comments from the database table_comments.sql .

PHP script 1.1 that retrieves comments :

So, let’s assume that visitor 1 “John” publish the comment “Your website is the best!” ; visitor 2 “Jake” publish the comment “I don’t like your website ” ; visitor 3 “Max” publish the comment “Good!” .

In the database table_comments.sql will be stored :

table_comments cross site scripting example

When the visitor clicks the link : “View all comments!” , it will run PHP script 1.1 that retrieves all data from table_comments and show all comments !

Let’s say some hacker comes along and submits a comment with javascript code :

html form

Javascript code will be stored in database and it will become part of the page viewcomments.php .

Source code from viewcomments.php :

Whenever visitors visits the page viewcomments.php, the javascript code will be executed and it will pop up a window that will redirect visitors to certain website.

That is simple cross site scripting example , you can type what ever javascript code you want.
You can try XSS_App on this LINK !

How To Protect Your Website From Cross Site Scripting Attack

To protect your website from cross site scripting , you should filter out users input. PHP has a couple of different functions you can use to filter user input. For example using the function htmlspecialchars() in viewcomments.php would escape all HTML inputs and javascript code will not be executed .

viewcomments.php protected with htmlspecialchars() function :

Below is page source from viewcomments.php , you can see that javascript code is escaped .

To learn more about internet security buy Beginner’s Guide to Ethical Hacking .
I f you want to learn how to protect your website against SQL Injection visit my previous article -CLICK HERE-