Best practice for Prevent XSS hacking - asp.net-mvc

I am member of team with 25 developer.we use mvc.net application that security is a n important for us.we use #Html.AntiForgeryToken() and anything that related with security but We are concerned about Prevent XSS hacking.
we encode every where but some places we need html from user.
What is the best practice for Prevent XSS hacking?

The golden rule to prevent XSS is to HTML encode everything that you are outputting to a view.
Hopefully the # Razor function already does that automatically for you.
So when you write one of the following you are pretty safe:
#Model.SomeProperty
#Html.DisplayFor(x => x.SomeProperty)
You should be careful with the #Html.Raw helper:
#Html.Raw(Model.SomeProperty)
If you use that the output will not be HTML encoded. This doesn't mean that your site is vulnerable to XSS injection. For example if you have total control of the property and is not coming from an user input you should be pretty safe.
If you are using the WebForms view engine then you should be more careful because the <%= function doesn't HTML encode the output.
So the following is not safe:
<%= Model.SomeProperty %>
You should use one of the following:
<%= Html.DisplayFor(x => x.SomeProperty) %>
<%: Model.SomeProperty %>
If on the other hand you need to output some user input without HTML encoding it I would recommend you using the AntiXSS library from Microsoft. It will filter out all dangerous tags from the input and you are safe to output it. For example it will remove the <script> tags from the input. There's also an article on MSDN about this library that you might checkout.

Related

How to avoid html, iframe and cross site injection in rails?

I have stored the data in my database as html content.
Whenever user giving the input it will inject my html.
What should I do before storing into db I need to sanitize my data. Or I can store data whatever it. While displaying in view only I need to do something for injection.
I would recommend you to refer to the XSS Cross Site Scripting cheatsheet
and for Rails in particular, as stated:
The SanitizeHelper module provides a set of methods for scrubbing text of undesired HTML elements.
<%= sanitize #comment.body, tags: %w(strong em a), attributes: %w(href) %>

Rails translation performance impact <%= raw t( vs. <%= t(

I am building a multilingual application using rails-i18n Ruby on Rails.
Most of content (and DB entries) I have to translate is pure text, though part of it has some embedded html.
I was thinking of using <%= raw t('translation_key') %> instead of the straight <%= t('translation_key') %> to account for future changes that might include html.
If I adopt <%= raw t('translation_key') %> throughout the all website, am I going to get any (negative) impact when it comes to
website performance
website security
You just just append _html to your tag keys to handle HTML in translation tags:
en:
key_one: test text
key_one_html: <p>test text</p>
Then the standard code will work:
<%= t('key_one_html') %>
Performance aspect:
The performance impact should be negligible. Calling raw copies the parameter into a new string (an ActiveSupport::SafeBuffer to be precise) with its html_safe flag set to true. On the other hand there is no longer HTML escaping performed on that string.
Security aspect:
There are more substantial drawbacks to using raw everywhere.
You say your translations are read from the database. Can the user edit these translations? If so...
You risk HTML injections: A malicious user could just enter a <script> tag.
All your translations must to be HTML safe from now on. That means you have to manually escape all your translations, i.e. you have to replace <,>, and &.
Alternatives:
There are other options if you need to incorporate HTML into your translations:
Use the _html suffix judiciously to prevent automatic escaping
Use localized views and partials, i.e. index.en.html, _footer.de-DE.html to translate larger parts of your views.
To streamline translation of database entries, you try
Globalize
hstore_translate (PostgreSQL only)
Conclusion:
Using raw everywhere will lead to a lot of problems along the road. Save yourself a lot of trouble and just use it "as needed".
You could also use the globalize gem for bigger text / html sections of content.
https://github.com/globalize/globalize/blob/master/README.md
It also supports eager loading if you're worried about performance.

What are the benefits, if i use rails view form template?

Example, i made a form like this
<form name="register" method="post" enctype="multipart/form-data">
<p><h3>User check</h3></p>
<p>admin ID: <input type="text" name="userid"></p>
<p>admin Pass: <input type="password" name="password"></p>
<input type="submit" name="apply" value="Submit"></p>
<p> </p>
</form>
and my manager wants to change this form to rails form template like this,
<%= form_for(:model) do |form| %>
<p>
<%=form.label :input%>
<%=form.text_field :input, :placeholder => 'Enter text here...'%>
</p>
<%end%>
My question is, it works fine with html based front code. Why do i have to change this to rails code? I just want to keep my front-end code...I don't know why i have to change this :(. Also, I'm new on Ruby on Rails. That is the main reason. I dont' want to change the existing code, if it is working.
I really hate this job. I have to translate all the attributes to the rails code and that makes me really exhausted :(
Form builders are here to help
Form helpers are supposed to make your life simpler. They are quicker to write than their pure html alternative, provided you don't write pure html first.
They also provide a lot of easy implementations for difficult integration pieces, like :
displaying a date selection select group
mirroring the fact that a check box has been unchecked in POST params
automatically adding multipart param on form if you add a file input (not actually difficult to achieve, but easy to forget)
... and many more
Further development
All of this is about comfort, and you may think you could avoid it if you already have a perfectly working pure html implementation.
But what happen if someone later has to add a date select input in your form ? She will have to use the rails helper, since it saves a lot of time in controller part to set date in database. But she won't be able to leverage form builder, since you haven't used it.
Now, she has to choose between using a non builderdate_select tag mixed in pure html or ... to rewrite your form completely. As you may realize, mixing different styles is generally considered ugly, and we don't like ugly in ruby.
Security
Form tag helpers also provide an important security measure : CSRF protection. Every time you use a rails helper to create a <form> tag, it automatically adds an hidden input containing a secret key. That key has to be posted with form data to prove request originated from current website.
If you use plain html forms, you won't have this security. You could of course add the token manually using the correct method, but this would again be more time wasting than simply using form helpers.
Bottom line
The main problem is that you write pure html before using rails helpers - that is what is wasting time.
Some benefits of using Rails form helpers are:
Consistent naming of input elements names and ids
i18n support for labels
generated URL with form_for is less error prone
Better handling of checkboxes
Nice helpers like options_for_select
Less typing
That last ones might be my favourite: less typing.

Does Razor syntax provide a compelling advantage in UI markup?

I notice Scott Guthrie is starting to mention Razor a fair bit on his blog but I'm just not that sure that it's a good fit for my style.
Granted it's a fairly unfamiliar style for someone who's pretty used to a "standard" sort of ASP.Net markup (content place holders and inline code), but it just feels like a lot of additional pages to manage and less clear markup to me.
What are other peoples' feelings on it? Is it something that you believe should be seriously considered when scaffolding new MVC pages or is it just trying to solve a problem that doesn't exist?
[Disclaimer: I'm one of the Microsoft developers on MVC and Razor, so I might be a bit biased :)]
We designed Razor to be a concise templating language that uses only the minimal necessary amount of control characters. I would say that large parts of your views can be expressed with fewer characters than the same code using the "traditional" WebForms syntax.
For example the following code snippet in ASPX syntax:
<% if(someCondition) { %>
<ol>
<% foreach(var item in Model) { %>
<li><%: item.ToString() %></li>
<% } %>
</ol>
<% } %>
Can be expressed as follows in Razor:
#if(someCondition) {
<ol>
#foreach(var item in Model) {
<li>#item.ToString()</li>
}
</ol>
}
While the ASPX version has 21 transition characters (the <% and %>), the Razor version has only three (#)
I would say that the advantages of Razor are as follows:
Concise syntax, which is very similar to the way you write regular C# code (check out the following recent blog post by Phil Haack comparing Asxp with Razor syntax: http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx)
Automatic HTML encoding of output (which helps protect you from html injection attacks)
Built in (though not 100%) validation of your markup which helps you avoid unbalanced tags
The page-related concepts also map easily from what you have in ASPX
As you can see inline code is still allowed
Sections (which can be optional) are equivalent to content placeholders
Layout pages instead of Master pages
The concepts of full and partial views are the same
#functions { ... } blocks instead of <script runat="server"> ... </script>
In addition Razor has a number of useful concepts that I would say are better than what is available in ASPX:
#helper functions for really easy creation of functions that emit markup
#model keyword for specifying your view's model type without having to write a <%# Page ... directive with the full class name
I would like to think that we have tackled a real problem, which is to allow you to more easily write concise and standards-compliant views while at the same time providing you with ways to refactor common code.
Of course, not everyone will prefer the syntax which is why we are also fully supporting the ASPX view engine. In addition you can check out Spark and NHaml, which are two 3rd-party view engines that enjoy significant community following. The following blog post has a good comparison of the different offerings: Link
Personally I really appreciate the reduction in how many escape characters are used. Using <% %> gets very tedious when compared to #{} and is not nearly as syntactically appealing.
Moreover, writing a whole definition for the codebehind and page is simplified to a single #model model.
As also noted by marcind, not having to always include runat=server is very nice also.
Overall, I really appreciate using the Razor engine and find it not only makes things easier on me to develop but also makes code easier to read.

Escaping HTML in Rails

What is the recommended way to escape HTML to prevent XSS vulnerabilities in Rails apps?
Should you allow the user to put any text into the database but escape it when displaying it? Should you add before_save filters to escape the input?
There are three basic approaches to this problem.
use h() in your views. The downside here is that if you forget, you get pwnd.
Use a plugin that escapes content when it is saved. My plugin xss_terminate does this. Then you don't have to use h() in your views (mostly). There are others that work on the controller level. The downsides here are (a) if there's a bug in the escaping code, you could get XSS in your database; and (b) There are corner cases where you'll still want to use h().
Use a plugin that escapes content when it is displayed. CrossSiteSniper is probably the best known of these. This aliases your attributes so that when you call foo.name it escapes the content. There's a way around it if you need the content unescaped. I like this plugin but I'm not wild about letting XSS into my database in the first place...
Then there are some hybrid approaches.
There's no reason why you can't use xss_terminate and CrossSiteSniper at the same time.
There's also a ERb implementation called Erubis that can be configured so that any call like <%= foo.name %> is escaped -- the equivalent of <%= h(foo.name) %>. Unfortunately, Erubis always seems to lag behind Rails and so using it can slow you down.
If you want to read more, I wrote a blog post (which Xavor kindly linked to) about using xss_terminate.
The h is an alias for html_escape, which is a utility method for escaping all HTML tag characters:
html_escape('<script src=http://ha.ckers.org/xss.js></script>')
# => <script src=http://ha.ckers.org/xss.js></script>
If you need more control, go with the sanitize method, which can be used as a white-list of tags and attributes to allow:
sanitize(#article.body, :tags => %w(table tr td), :attributes => %w(id class style))
I would allow the user to input anything, store it as-is in the database, and escape when displaying it. That way you don't lose any information entered. You can always tweak the escaping logic later...
Use the h method in your view template. Say you have a post object with a comment property:
<div class="comment">
<%= h post.comment %>
</div>
Or with this plugin - no need for h 8)
http://railspikes.com/2008/1/28/auto-escaping-html-with-rails
I've just released a plugin called ActsAsSanitiled using the Sanitize gem which can guarantee well-formedness as well being very configurable to what kind of HTML is allowed, all without munging user input or requiring anything to be remembered at the template level.

Resources