How to prevent XSS vulnerability with Struts - java

We need to add anti-XSS support in our Struts application. Most specifically the architect requires that all user input must be "sanitized" before storing in DB. As I don't want to reinvent the square wheel, which Java library can I use for this ? And where to put it ? Ideally it should be configurable (which input fields to check, not all of them in request) and fast. My first thought is Struts Validator.
Thanks in advance
Lluis

I recommend you look into OWASP's ESAPI project. It has been under development for over a year, and is approaching its 2.0 release.
For escaping values stored in the database, check out the Encoder.encodeForSQL() method (reference implementation).
For input validation, check out the Validator (reference implementation).
Note: my understanding is that the functionality provided by older projects such as Stinger and CSRFGuard is being included in ESAPI.

If you seach google for XSS Java Filter, you'll come up with many open source solutions, such as this one.
You could also look at the OWASP validation project.

Related

Is OWASP Java Encoder Project enough to prevent reflected XSS?

I've been reading articles about reflected XSS prevention. From what I understand, output encoding is the primary way to deal with reflected XSS. Some tools available would be the OWASP Java Encoder project and OWASP ESAPI. I have a java/JSP web application. I'm not sure if input validation should be also performed on the .jsp file when there is already input validation in the corresponding .java file. So I have the following questions:
Is OWASP Java Encoder project sufficient to prevent reflected XSS?
Do I need to do input validation on the .jsp file?
If 2. is a yes, would creating my own input validation functions or using the ESAPI Validator class be better?
If I have to use ESAPI, it means that I need to add ESAPI.properties and validation.properties. Given my project is an Ant project, where do I add these files?
Thanks in advance.
I will address your individual questions in a moment, but first I want to suggest that you thoroughly read the OWASP Cross-Site Scripting Prevention Cheat Sheet. That will cover all the basics that you need to know, including discussions about defense-in-depth approaches. Now on to your specific questions.
Is OWASP Java Encoder project sufficient to prevent reflected XSS? Answer: If used correctly (that is you use the correct contextual encoder), for Java/JSPs, either the OWASP Java Encoder project or the ESAPI Encoder should be sufficient to prevent XSS in all but a few edge cases. Those edge cases are would including DOM-based XSS (so, technically, not 'reflected', I know) or cases where you have requirements that some HTML mark-up be allowed. (E.g., maybe in collecting user comments.) In those cases, you will want to also leverage HTML sanitizers such as the OWASP AntiSamy project or the OWASP Java HTML Sanitizer project.
Do I need to do input validation on the .jsp file? Answer: It is not absolutely necessary (assuming you use the output encoding correctly), but it wouldn't hurt. It is considered a part of the defense-in-depth strategy, especially in those tricky areas where mixed-encoding contexts are involved, such as rendering a URL in JavaScript. Along with input validation, Content-Security-Policy headers should are also strongly recommended, although CSPs are much easier to use in a green-field approach than in legacy applications.
If 2. is a yes, would creating my own input validation functions or using the ESAPI Validator class be better? Answer: In most cases you can probably do your own allow-list validation based on some simple regular expression matching. (Do not write the validation as block-lists though.) ESAPI Validation is probably more than you need and even as the ESAPI project co-lead, I personally wouldn't recommend it unless you are planning to use ESAPI for some other purpose (because it drags in a lot of transitive dependencies).
If I have to use ESAPI, it means that I need to add ESAPI.properties and validation.properties. Given my project is an Ant project, where do I add these files? Answer: You don''t have to use ESAPI, but if you do, where the ESAPI.properties and Validation.properties files go is not relevant to whether you use Ant or Maven or Gradle, etc. Look at class Javadoc for the ESAPI class org.owasp.esapi.reference.DefaultSecurityConfiguration for details of how the ESAPI.properties and Validation.properties files are located.
Hope that helps answer your questions.

Is there a validation in ESAPI library that can make sure the CWE-93 vulnerability does not come up in veracode SAST scan?

I did SAST scan of my code on Veracode platform and I got this vulnerability in Java mail functionality which I am using to send mails from my application. The following is the vulnerability that is coming - Improper Neutralization of CRLF Sequences('CRLF Injection') (CWE ID 93).
message.setSubject(subjectOfEmail);
I have heard that we can use ESAPI library but I cannot find an appropriate validation function for this. Someone please help me re-mediate this issue so that is does not come up in the scan again.
Check out this page on the Veracode Help Centre that lists out the validation libraries that will remediate certain flaw classes:
https://help.veracode.com/reader/DGHxSJy3Gn3gtuSIN2jkRQ/y52kZojXR27Y8XY51KtvvA
There are a whole slew of ESAPI libraries that will remediate CWSE 93 flaws, including
org.owasp.esapi.Encoder.encodeForHTML
If all you are looking to prevent in this case is header injection issue (which is what CWE ID 93 is related to), then look at ESAPI's org.owasp.esapi.StringUtilities class. In particular the static method stripControls() is probably exactly what you need. Using Encoder.encodeForHTML() will probably encode for more than what you want since it assumes an HTML context. (Of course, you may want that if you are concerned about preventing XSS on the Subject headers of certain web email clients. Generally those clients should already have that protection built into them though, so if you encode it, it could end up being encoded twice and not render correctly.)
Keep in mind that if you use StringUtilities.stripControls(), that you Veracode's SAST engine may still flag your code for the CWE though as I am not sure that it recognizes that class' method as removing the taint flag in this particular case. (But you can always mention it as a mitigation comment.)
Use ESAPI's decodeForHTML() method like below sample.
ESAPI.encoder().decodeForHTML(subjectOfEmail)

How to implement Java ESAPI for preventing XSS?

I've read a lot of posts that ESAPI for Java can be used to prevent XSS by using Validator & Encoder. By the way, I am using Eclipse. I'm not using Maven nor Spring.
My questions are:
How to implement Java ESAPI for preventing XSS?
Are there other configurations needed aside from adding the ESAPI jar in the Build Path?
Thanks in advance for your answers.
Preventing XSS has some trickery to it. Validator lets you define input characters to accept/reject. But there's also the concept of differing contexts, and that's where the Encoder class comes in. There will be instances in your career where you'll be forced to accept characters as input that can be used to attack a browser.
The basic ESAPI implementation is like this: reject input characters According to whitelists. Use the Encoder implementations according to the output contexts... the trick part comes in when making decisions in regards to "Do I encode for HTML first, or for Javascript first? Either of those can have impacts on your application, and they need to be decided upon based on your application's needs. I've had applications that required users to input valid Javascript for example... and in those contexts, you need to be very careful.
Answering your part 2: Yes. ESAPI as by now you probably know, requires two properties files to be defined... validation.properties, and esapi.properties. You can compile them into the jarfile yourself (which, would require you to learn maven, so probably not...) or to specify at runtime, java locations, using the standard -Dmy.property syntax. The loading exceptions actually guide you to the right path.

Validating input text in web forms with esapi

how could I use ESAPI to check for unsafe input texts in web forms ? My application is built using struts 1.X, so I assume the validations should be added to Actions classes. Any samples / tutorials you recommend ? Thanks.
For something as specific as that there is not usually going to be great tutorials out.
Hopefully I am wrong about this, but I would have to suggest their wiki due to lack of good resources.
I was looking to find input validation for you... seems they don't even have that up themselves. I coudn't find any information on it either. The videos below might have it or I would email them if it provides no real good answer. They should be able to put you in the right direction... and if you do that do us all a favor and demand they update their wiki!
Email: jeff.williams%owasp.org#gtempaccount.com (Leader, owner)
Since that email doesn't look right though I would also check this one.
Email: kevin.w.wall#gmail.com (Owner, coder of crypto libs)
Their are these youtube video's that might help. They even mention that their are not a lot of good resources to teach you how to use ESAPI, but said they hope to fix that in these four videos.
http://www.youtube.com/watch?v=suphwAsb-To
http://www.youtube.com/watch?v=13O9RyjuB3o
http://www.youtube.com/watch?v=_B2kv2mSJhE
http://www.youtube.com/watch?v=mMW4fiUI5kQ
Hope it helped!
Validation of form fields normally is done in the ActionForm class. There are all input values available and all validations can be done there. A tutorial (one of many available) cna be found here Struts form validation and error handling. More can be found using google (struts validation).
I have been working with the ESAPI library for a few months now. The library cannot do too much to validate your input, since it cannot know what the input could be or should be. That is especially true when you factor in all the international characters that could be in legitimate user input.
We use the ESAPI library mostly for encoding server output. The purpose is to send user (or possible attacker) input back to the browser in such a way that it cannot be executed. Instead HTML or JavaScript interprets it as text only.
That is why both my validation and ESAPI's encoding of user input are important for security.

Lib to protect SQL/javascript injection for java/jsp

Anyone know a good lib where i can run the strings before they are inserted, that can strip out sql/javascript code? To be run in jsp pages.
Idealy the lib would be:
Free
Lightweight
Easy to use
Thanks in advance to the SO community who will happily reply :)
Apache Commons lang StringEscapeUtils will get you some of the way. It escapes, doesnt strip.
http://commons.apache.org/lang/api/org/apache/commons/lang/StringEscapeUtils.html
Edit: Escaping can save you from injection attacks because it makes sure that the data the user has entered is not executed as code, but always presented as data to the user.
You need to rely on the your database api's mechanism for using parameterized queries. If you're first building an sql string dynamically and then want to sanitize the completed query string, you're doing it wrong. That's just asking for trouble.
Edit: after re-reading your question, it seems I mis-understood what you were asking. I stand by my initial comments as accurate for the sql injection part of your question. For that, you definitely want real query parameters.
As for filtering out javascript, I don't think there's a real standard way to do it yet. I know Jeff posted the code they use here at SO, but I don't have the link handy. If I can find it I'll post it.
Take a look at AntiSamy on OWASP. I think this might be what you are looking for. I do not currently work in Java so I cannot tell you about how it performs.
The what you're saying is that for every possible entry being added to the string I have to remove first the "malicious" data. Yeah it makes sense as I wouldn't be able to tell which was added as an input and what would be part of the query itself.
Ok ty i guess i need to restart changing some code :) still the question for the api still stands :)
The c:out tag by default escapes XML. This can be handy for storing user input, as the bound value will still be the user's input but the source generated by the browser will use escaped entries.
To prevent SQL injection utilize PreparedStatement objects. If you are using some persistence layer, ensure that it is utilizing PreparedStatement objects. With regard to malicious HTML and JavaScript, use . This escapes XML characters by default. You can also use the JSTL function escapeXml found in the fn tld.
Just rephrasing the suggestions given by others here:
The OP wants to prevent SQL and JavaScript injection attacks.
SQL Injection attacks can be prevented by ensuring that parameterized queries/bind variables are utilized to provide user input to the database. In the Java world, the use of PMD (and a PMD rule) and Findbugs (the rules are built into Findbugs by default) will help you determine locations in your code base that are susceptible to SQL injection attacks. OWASP has a good article on preventing SQL injection in Java.
As far as script injection is concerned, the safest way to prevent attacker-injected scripts from being executed is to ensure that user input, when it is used as output, is to be displayed using an encoded format - for web apps, this would be HTML encoding. This OWASP page shows you how to perform HTML encoding in Java.
If you want to protect your application from javascript injection, than you need to instrument or hook method which takes your javascript as argument, In case of mongodb, eval() method can execute javascript at mongo server.
You can follow below link to mitigate ssjs attack.
https://www.sciencedirect.com/science/article/pii/S1568494619305022

Categories