Saturday, August 27, 2011

Javascript Injection in MVC

ASP.net MVC (model view controller) by default open to javascript injections. It depends upon the developer how to protect their website from javascript injections. MVC provide options for the same but due to lazy coding or incomplete knowledge some of us avoid to use these.
Firs of all let us understand what is javascipt injection and how these injections affect our websites? There is a website in which we have two controllers named as "Insert" , "Details". Insert controller inserts input informatin of user (say user name) in database. Details controller used to dispaly information (that is saved by "Insert" controller) from database.
In view suppose i am using following code to display the user names:

<% foreach ( string userName in Model.UserNames) {%>
    <%# userName %>
<%}%>

In this case if a user ( not a normal user say intruder or hacker) inserts a script in datbase say: he inserts <script> alert('hiiii'); </script>. Our "Insert" controller doesn't detect this javascript code, It will consider it as a normal data. It will save it into the database. During display it will show an alert box on the screen. A smart or clever developer can also do this alerts in loop so that it will affect the functionality of website. This is a simple and small example of such javascript injection. Such type of injections can also be very dangerious.
Now let us discuss how we can protect our websites from such type of injections. A simple usage of "Html.Encode" function during displaying the user names. If  we use following code in view to display data then such scripting injections will not work.


<% foreach ( string userName in Model.UserNames) {%>
    <%# Html.Encode(userName) %>
<%}%>

We can also apply during insertion of data in "Insert" controller. By using "Html.Encode" it will convert the "<" into "&lt; and ">" to "&gt;". By doing this inserted javascript code will not work and website will work normally :)