Here it is the concept of this article

1. Get JSON from server.
2. The JSON data can have tags like <script>, <div>, <td>...etc.
3. Show the data in a table by preventing XSS attack

Here attacker entered address as "<script>alert('This is XSS attack');</script>". Whenever you showed this in HTML page you will see an alert "This is XSS attack"
But we should not execute the code in the address field. We have to show it as text.


The hackers will give markup text as input to :
      destroy your website User Interface.
      steal your data.
      steal user's cookies ( Stealing authentication ).

JSON :
{
"firstName":"John" , 
"lastName":"Doe",
"address":"<script>alert('This is XSS attack');</script>"
}

JavaScript :

String.prototype.encodeHtml = function() {
var tagsToReplace = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;'
};
return this.replace(/[&<>]/g, function(tag) {
return tagsToReplace[tag] || tag;
});
};

String.prototype.decodeHtml = function() {
var tagsToReplace = {
'&amp;': '&',
'&lt;': '<',
'&gt;': '>'};
return this.replace(/[&<>]/g, function(tag) {
return tagsToReplace[tag] || tag;
});
};

jQuery Code to display JSON as content :

$(document).ready(function(){
  $.get("json.json",function(data,status){
  var json = data;
  $("#jsonText").val(JSON.stringify(data));
  var eHtml="<table><tr><td>First Name</td><td>"+
                json.firstName.encodeHtml()+
       "</td></tr><tr><td>Last Name</td><td>"+
                json.lastName.encodeHtml()+
       "</td></tr><tr><td>Address</td><td>"+
                json.address.encodeHtml()+
       "</td></tr></table>";
  $("#encodeDiv").html(eHtml);
  });
});

Demo without Encoding :
In this demo you can see the alert box. It means it is executing the script in the address field. 

Demo with Encoding :
In this demo you wont see any alert box. It means it is showing the script as text.
DEMO - Without Encoding DEMO - With Encoding

0 comments:

Blogroll

Popular Posts