spring security native xss filter - spring-security

Why Spring Security doesn't provide any XSS filter to clean the form input values?
Accordingly to this ticket, such XSS filter is a low priority:
https://jira.spring.io/browse/SEC-2167?jql=text%20~%20%22xss%22
(although the ticket speaks only about URL querystring. Sanitizing POST params would be also required)
In my opinion it would be really useful that spring would provide such a filter instead of building your own. This filter it's a recurrent problem.

XSS is best handled at output stage via the use of encoding. That is, store everything in your database as is, and yes storing <script> is fine, however once output, encode correctly for the context it is output in. For HTML this would be <script>, however if your output context was plain text you would just output as is <script> (assuming the same character set encoding is used). Side note: Use parameterised queries or equivalent for storing in your database to avoid SQL injection, however the text stored should exactly match what was entered.
Microsoft attempts to block inputs that look like XSS via their request validation feature in ASP.NET. However, this isn't very effective and flaws are found quite often. Similar approaches from other frameworks are doomed to fail.
The reason that this is much better is that it makes things much more simple. Imagine if StackOverflow didn't allow HTML or script tags - the site would not be functional as a place for people to post code snippets.
You can use input validation as second line of defence. For example, if you are asking the user to enter their car registration you would only want to allow alphanumerics and space to be entered. However, for more complex fields it is often difficult to restrict input to a safe set as output context is unknown at this stage.
Say your language filtered < and > characters. However you were outputting user input into the following context.
<img src="foo.jpg" alt="USER-INPUT" />
An XSS attack is possible by entering " onmouseover="alert('xss') because it would be rendered as
<img src="foo.jpg" alt="" onmouseover="alert('xss')" />
Similar problems would ensue if you were outputting to JavaScript server-side. This is why it should be up to the developer to select the correct encoding type when using user controlled values.

Related

When do I need to encode with multiple codecs in Grails?

I'm not clear of when (or if) I should use multiple Grails encodeAsXXX calls.
This reference says you need to encodeAsURL and then encodeAsJavaScript: http://grailsrocks.com/blog/2013/4/19/can-i-pwn-your-grails-application
It also says you need to encodeAsURL and then encodeAsHTML, I don't understand why this is necessary in the case shown but not all the time?
Are there other cases I should me using multiple chained encoders?
If I'm rendering a URL to a HTML attribute should I encodeAsURL then encodeAsHTML?
If I'm rendering a URL to a JavaScript variable sent as part of a HTML document (via a SCRIPT element) should I encodeAsURL, encodeAsJavaScript then encodeAsHTML?
If I'm rendering a string to a JavaScript variable sent as part of a HTML document should I encodeAsJavaScript then encodeAsHTML?
The official docs - https://docs.grails.org/latest/guide/security.html - don't show any examples of multiple chained encoders.
I can't see how I can understand what to do here except by finding the source for all the encoders and looking at what they encode and what's valid on the receiving end - but I figure it shouldn't be that hard for a developer and there is probably something simple I'm missing or some instructions I haven't found.
FWIW, I think the encoders I'm talking about are these ones:
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/util/JavaScriptUtils.html#javaScriptEscape-java.lang.String-
https://docs.oracle.com/javase/7/docs/api/java/net/URLEncoder.html#encode(java.lang.String,%20java.lang.String)
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/util/HtmlUtils.html#htmlEscape-java.lang.String-
.
It is certainly important to always consider XSS but in reading your question I think you are overestimating what you need to do. As long as you're using Grails 2.3 or higher and your grails.views.default.codec is set to html which it will be by default, everything rendered in your GSP with ${} will be escaped properly for you.
It is only when you are intentionally bypassing the escaping, such as if you need to get sanitized user input back into valid JavaScript within your GSP for some reason, that you would need to use the encodeAsXXX methods or similar.
I would argue (and the article makes a mention of this as well) that this should raise a smell anyway, as you probably should have that JavaScript encapsulated in a different file or TagLib where the escaping is handled.
Bottom line, use the encoding methods only if you are overriding the default HTML encoding, otherwise ${} handles it for you.

is it good practice to encode user input to database?

I am wondering if it is consider good practice to encode user input to database.
Or is it ok to not encode to user input instead.
Currently my way of doing it is to encode it when entering database and use Html.DisplayFor to display it.
No. You want to keep the input in its original form until you need it and know what the output type is. It might be HTML for now, but later if you want to change it to json, text file, xml, etc the encoding might make it look different then you want.
So, first you want to make sure you are securely validating your input. It is a good idea to know what are the requirements for each of your inputs and validate that they are withing the correct length, range, character set, etc. It will be to your interest to limit the type of characters that are allowed as valid characters of an input type. (If using Regular Expressions to validate input ensure you do not use a regular expressions that is susceptible to a Regular Expression Denial of Service.
When moving the data around in your code ensure that you are properly handling the data in a manner that it will not turn into an Injection Attack.
Since you are talking about a database, the best practice is to use paramaterized statements. Check out the prevention methods in the above link.
Then when it comes outputting using MVC, if you are not using RAW or MvcHtmlString functions/calls, then the output is automatically encoded. With the automatic encoding, you want to make sure you are using the AntiXss encoder and not the default (whitelist approach vs. blacklist). Link
If you are using Raw or MvcHtmlString, you want to make sure you COMPLETE TRUST the values (you hard coded them in) or you manually encode them using the AntiXss Encoder class.
No it is not necessary to encode all the user inputs, rather if you want to avoid the script injection either you my try to validate the fields for special characters like '<', '>', '/', etc. else your Html helper method itself will do the needful.

Struts 2 - is there any way to escape HTML in input fields?

When I allow a user to enter text using s:textfield, he can enter something like <b>Name</b> or something like \Me/. I want that these should be escaped before I am saving them to the database. When we retrieve them, the escaping is done automatically, but I want it to happen also when we are saving it.
I was trying to return a json output from my action class, but due to a name \a/ stored in my database, wrong json was being formed. This would have been avoided if the name had been escaped before being saved into the database.
You can use StringEscapeUtils. You can call escapeJavascript(textfield) in your action and then store it into the database.
#Daud, The problem you explained is called Cross site scripting or XSS.
And I think you should use Filters to clean the request parameters. This is the most sophisticated way. You can call these filters for the actions which are posting some parameters via request.
Visit my blog to see how to avoid XSS threat using Filter approach.
I also faced this issue when our project was tested by well known firm specializing in security testing and they suggested this filter approach.
You can give it a try.

Validating Input in ASP.NET MVC

Any suggestions for best practice on validating/cleaning user input in ASP.NET MVC. It seems ValidateInput will almost always need to be set to False since it cant be handled from within the MVC framework (the error is thrown even before the Action Method is fired).
So how should the input be validated for malicious input. Do we have to manually screen each input and check it for characters such as <, >, " etc
How about if we only wish to allow some types of input such as tags but forbid and other inputs? This must be a pretty common requirement of a web app now, but I can't see much in ASP.NET MVC to automate this.
So how should the input be validated for malicious input. \
It depends on what your application is doing with this input. If you are storing it in a relational database for example, well, as long as you use parametrized queries and properly encode the user request, relational database don't care about storing for example alert('foo'); in a given column. When you might get into trouble is when you try to fetch the result stored in this database and show it on some view. It is at that moment that you must ensure that the result is properly HTML encoded.
So for example let's suppose that you have stored some hyper dangerous string in your data store and you want to display it on your view. If you were using the Razor view engine you would simply:
#Html.DisplayFor(x => x.SomeProperty)
which will take care of properly HTML encoding the value of SomeProperty so that you don;t have to worry about.
And if you were using the WebForms view engine:
<%= Html.DisplayFor(x => x.SomeProperty) %>
So, as you can see there are two critical moments where you should be careful with the user input:
always use parametrized queries if you are storing this user input into a relational database
always HTML encode the value you have stored when time comes to render it on some view

How good is the Rails sanitize() method?

Can I use ActionView::Helpers::SanitizeHelper#sanitize on user-entered text that I plan on showing to other users? E.g., will it properly handle all cases described on this site?
Also, the documentation mentions:
Please note that sanitizing
user-provided text does not guarantee
that the resulting markup is valid
(conforming to a document type) or
even well-formed. The output may still
contain e.g. unescaped ’<’, ’>’, ’&’
characters and confuse browsers.
What's the best way to handle this? Pass the sanitized text through Hpricot before displaying?
Ryan Grove's Sanitize goes a lot farther than Rails 3 sanitize. It ensures the output HTML is well-formed and has three built-in whitelists:
Sanitize::Config::RESTRICTED
Allows only very simple inline formatting markup. No links, images, or block elements.
Sanitize::Config::BASIC
Allows a variety of markup including formatting tags, links, and lists. Images and tables are not allowed, links are limited to FTP, HTTP, HTTPS, and mailto protocols, and a attribute is added to all links to mitigate SEO spam.
Sanitize::Config::RELAXED Allows an even wider variety of markup than BASIC, including images and tables. Links are still limited to FTP, HTTP, HTTPS, and mailto protocols, while images are limited to HTTP and HTTPS. In this mode, is not added to links.
Sanitize is certainly better than the "h" helper. Instead of escaping everything, it actually allows the html tags that you specify. And yes, it does prevent cross-site scripting because it removes javascript from the mix entirely.
In short, both will get the job done. Use "h" when you don't expect anything other than plaintext, and use sanitize when you want to allow some, or you believe people may try to enter it. Even if you disallow all tags with sanitize, it'll "pretty up" the code by removing them instead of escaping them as "h" does.
As for incomplete tags: You could run a validation on the model that passes html-containing fields through hpricot, but I think this is overkill in most applications.
The best course of action depends on two things:
Your rails version (2.x or 3.x)
Whether your users are supposed to enter any html at all on the input or not.
As a general rule, I don't allow my users to input html - instead I let them input textile.
On rails 3.x:
User input is sanitized by default. You don't have to do anything, unless you want your users to be able to send some html. In that case, keep reading.
This railscast deals with XSS attacks on rails 3.
On rails 2.x:
If you don't allow any html from your users, just protect your output with the h method, like this:
<%= h post.text %>
If you want your users to send some html: you can use rails' sanitize method or HTML::StathamSanitizer

Resources