Prevent cross-site scripting in ASP.NET MVC - using jQuery or standard HtmlHelpers
I am creating an ASP.NET MVC application that is AJAX driven. For some reason I need to add some DOM elements on the fly by clicking the submit button. This is accomplished with jQuery.append ().
One inserted element is a text area, the data of which must be parsed before being sent to ensure that cross-site scripting cannot be performed.
We know that Html.Encode () works great, but must be declared outside the script tag. Everything I've done with jQuery is embedded in the script tag.
1) Is there a way to use Html.Encode () in a script tag?
2) How can I accomplish this using jQuery?
In the worst case, I can use HttpUtility.HtmlEncode () which is called on the server side.
Thanks for your help.
Roland
a source to share
As I understand it, the data you enter is received using some kind of client call, and not during server side page creation. In this case, you can replace $(dest).append(data);
to $(dest).append($('<div>').text(data));
use .text vs .html will have to disinfect the line.
Whatever you do, I REALLY recommend watching this video by Phil Haack and Scott Hanselman http://live.visitmix.com/MIX10/Sessions/FT05 . They show you different ways to hack a site using XSS and CSRS, as well as ways to protect yourself - exactly what you need :)
a source to share
What version of MVC are you using? Not sure if I understand the full context, so I will try to cover it from many points of view (for scenarios I can think of, I'm sure there are more). As of MVC 2, you have new support for this: <%: Model.FirstName%> to encode data, which is equivalent to <% = Html.Encode (Model.FirstName)%> as in MVC 1.
You should be able to do this in JS on a view, as in:
<script type="text/javascript">
$(document).ready(function() { $("#this").html('<%= "Some HTML to write" %>');
</script>
I thought I did it ... if there weren't a few alternatives left. There is client side code with runaway JS and unescape, but it encodes / decodes it differently than the server does ... try it for yourself, replace% 20 spaces and other changes.
Finally, JQuery can make a call to the server action method using $ .get ("/ controller / action", function (data) {/ * data here * /}, which you can code with this, but this is very importantly inefficient.
NTN.
a source to share