I have plenty of controllers and I want to validate all of parameters submitted in forms against XSS attacks. Instead securing each controller separately I would like to have one component that works as interceptor for all submitted forms and checks the parameters submitted.
I wrote a Filter that uses antisamy for correcting values of parameters but it works too good. I mean it escapes everything, even rich content that should not be escaped.
Sanitizing user inputs with Spring MVC framework
https://jeevanpatil.wordpress.com/2011/07/22/prevention_of_xss/
Therefre I need some solution to escape concrete parameters in controlers, do u know any solution ? I plan to create annotation next to parameters in every method in controller, for example #XSSEscaped, then only those parameters would be escaped.
HTML encoding at the time of input can corrupt the data. It may still not be secure because data inserted into an attribute, stylesheet, or script could still execute code even with HTML encoding. It may not cover all the data on the page as some values might not have come through the controller, or could have been modified since then.
There are many ways to bypass input filters (see XSS Filter evasion cheatsheet). The RequestWrapper in the linked answer for example filters out eval(), but pass in e<script></script>val() instead and you get eval() as output again. Fix that, then they'll be something else.
HTML encoding is the the responsibility of the view layer. This is where you can make sure all the data used on the page is encoded appropriately for the context where it's used. XSS is prevented by following the rules at the Cross Site Scripting Prevention Cheatsheet. Templating systems like Thymeleaf will do HTML encoding by default of its values.
Related
I Know, we can use encodeForHTML for HTMl and encodeForJavascript for javaScript.
There is a Cross-Site Scripting: "Reflected fortify scan problem" in my code
String errorDesc = HttpServletRequest.getParameter("error_description");
I have to validate this using Encoder but I am confused to use which one should i use between them. As we do not know the return type of HttpServletRequest.getParameter.
1. org.owasp.esapi.Encoder.encodeForHTML
2. org.owasp.esapi.Encoder.encodeForJavaScript
What we have here dear asker is a rather common misunderstanding about the differences between output encoding--which is what you're working with when you look at the Encoder calls, and input validation, which is a completely separate operation that has little to do with the Encoder class.
The Encoder methods you're dealing with here are to be used only when you're presenting data to a user, and only for the correct context. For example, if the application is a "Single Page Application" (SPA) then very likely you're just going to want to ensure that the output is encoded for JavaScript as the client-facing framework will almost certainly be JavaScript.
If you were using an older style of application, then you would encode for HTML anytime you were going to place data between <some_tag> data </some_tag>.
XSS requires you to understand one thing for every variable in your application: Its data flow, from when the value is generated (Server, User, DB, etc.) and understand all of the transformations it might undergo as it traverses to the user and back to the system. If the value starts in the browser, it will enter into some kind of Controller on the backend, and before you process the value you'll whitelist validate it--ESAPI has a validator class--and then if it passes validation you'll ensure that the database will only treat it as data (PreparedStatement, or through use of an ORM framework's utilities.) Best practice is to
Canonicalize the data
Validate against the canonicalized value
If valid, discard the canonicalized value and store the original data
If used properly, the Validator class is defaulted to help you do this.
The methods you're asking about in this question are for instances where user input is being sent back to the browser, either from the database or from a previous request in your session that hasn't yet been persisted.
The main difference is how the output encoding is done. Encoder.encodeForHTML() does HTML entity encoding via the org.owasp.esapi.codecs.HTMLEntityCodec class, whereas Encoder.encodeForJavaScript() uses JavaScript's backslash encoding via org.owasp.esapi.codecs.JavaScriptCodec.
Which one you choose depends on the context of how your "error_description" parameter will be rendered in your application. If it is rendered between HTML tags, use encodeForHTML(), if you are rendering it in purely a JavaScript context, use encodeForJavaScript(). Refer to https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html for a more thorough explanation of all this.
I am currently learning JSF and was rather amazed and puzzled when I realized that whenever we use <h:form>, the standard behavior of JSF is to always show me the URL of the previous page in the browser, as opposed to the URL of the current page.
I understand that this has to do with the way JSF always posts a form to the same page and then just renders whatever page the controller gives it back to the browser which doesn't know the page location has changed.
It seems like JSF has been around for long enough that there must be a clean, solid way to deal with this. If so, would you mind sharing?
I have found various workarounds, but sadly nothing that seems like a real solid solution.
Simply accept that the URL is misleading.
Append "?faces-redirect=true" to the return value of every bean's action and then
figure out how to replace #RequestScoped with something else (Flash Scopes, CDI conversation, #SessionScoped, ...).
accept to have two HTTP round trips for every user action.
Use some method (e.g. 3rd party library or custom code) to hide the page name in the URL, always using the same generic URL for every page.
If "?faces-redirect=true" is as good as it gets, is there a way do configure an entire application to treat all requests this way?
Indeed, JSF as being a form based application targeted MVC framework submits the POST form to the very same URL as where the page with the <h:form> is been requested form. You can confirm it by looking at the <form action> URL of the generated HTML output. This is in web development terms characterized as postback. A navigation on a postback does by default not cause a new request to the new URL, but instead loads the target page as content of the response. This is indeed confusing when you merely want page-to-page navigation.
Generally, the right approach as to navigation/redirection depends on the business requirements and the idempotence (read: "bookmarkability") of the request (note: for concrete code examples, see the "See also" links below).
If the request is idempotent, just use a GET form/link instead of POST form (i.e. use <a>, <form>, <h:link> or <h:button> instead of <h:form> and <h:commandXxx>).
For example, page-to-page navigation, Google-like search form, etc.
If the request is non-idempotent, just show results conditionally in the same view (i.e. return null or void from action method and make use of e.g. <h:message(s)> and/or rendered).
For example, in-page data entry/edit, multi-step wizard, modal dialog, confirmation form, etc.
If the request is non-idempotent, but the target page is idempotent, just send a redirect after POST (i.e. return outcome with ?faces-redirect=true from action method, or manually invoke ExternalContext#redirect(), or put <redirect/> in legacy XML navigation case).
For example, showing list of all data after successful editing, redirect after login, etc.
Note that pure page-to-page navigation is usually idempotent and this is where many JSF starters fail by abusing command links/buttons for that and then complain afterwards that URLs don't change. Also note that navigation cases are very rarely used in real world applications which are developed with respect to SEO/UX and this is where many JSF tutorials fail by letting the readers believe otherwise.
Also note that using POST is absolutely not "more secure" than GET because the request parameters aren't immediately visible in URL. They are still visible in HTTP request body and still manipulatable. So there's absolutely no reason to prefer POST for idempotent requests for the sake of "security". The real security is in using HTTPS instead of HTTP and checking in business service methods if currently logged-in user is allowed to query entity X, or to manipulate entity X, etc. A decent security framework offers annotations for this.
See also:
What is the difference between redirect and navigation/forward and when to use what?
JSF implicit vs. explicit navigation
What URL to use to link / navigate to other JSF pages
Bookmarkability via View Parameters feature
What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?
When should I use h:outputLink instead of h:commandLink?
Creating master-detail pages for entities, how to link them and which bean scope to choose
Retaining GET request query string parameters on JSF form submit
Pass an object between #ViewScoped beans without using GET params
I'd like to accomplish the following:
I have a form represented in a JSP – let's call this input.jsp. This form submits to a servlet which will create objects in a DB – lets call this CreateServlet. When the form is successfully submitted, the servlet should direct the user back to input.jsp and display a success message. When validation fails, it should redirect back to input.jsp, display an error message, retain the input values.
I can think of a few options:
On validation failure I can use a RequestDispatcher to perform a forward to input.jsp. This would allow me to easily display the validation errors and input parameters from the form. However, I know that a forward should not be used in the case of performing an edit operation, so when the request is successful I should not do a forward and should do a redirect instead. The problem with a redirect is that I can't set attributes as easily unless I pass it in the URL, e.g. input.jsp?success=true.
I can store validation messages, success messages, and input values in the session, and always perform a redirect. After the JSP has displayed the page then it can remove these attributes from the session.
I am using plain servlets and JSP and not any framework like Struts. What is the recommended practice in this case?
i will choose second option if i were you. My reason :
Make it an object to encapsulate all input in that form. it will
easier to maintain if i need to add attribute to the form.
It more secure because your url will clean from attributes.
It will very easy if you used framework like struts. Everything will be handled by them.
I want to implement web services in Java EE whose response is going to be a JSON. This is my first attempt for doing so but before that I just want to know are there any security issues with JSON because everywhere in many blogs I read it is mentioned Like "JSON is not secured in comparison to XML". JSON has several advantages like easy to use, greater speed.
So anyone can explain me the truth whether JSON is really unsecured or not. If so why it is. Please explain with an example.
There are couple old articles on the topic:
JSON vs XML - 2006
concerns about eval
JSON is not as safe as people think it is
Claims only protection for non-public data available via JSON is to use unique urls.
CSRF (Cross Site Request Fogery) - 2007
Array hack highjacking parsing of JavaScript by browser.
This is nonsense. Both, json and xml are just methods for representation of structured data. None of them could be considered as "more secured" or "less secured".
There is no difference security wise between JSON and XML. The "insecurities" referred to by people regarding JSON have to do with the way JSON can (but should never be) parsed in Javascript.
JSON is based on the syntax for coding objects in javascript, so evaluating a JSON result in javascript returns a valid object.
This may open JSON to a variety of javascript injection exploits.
The way to resolve this: don't use eval() to parse JSON in javascript, use a JSON parser and fix any security issues in your server that allow unescaped user generated content in the response.
There is no more secure version. There are other features to consider though:
Example 1
Example 2
It doesn't matter whether you work with java, php or perl. They can all parse json and xml. json is lightweight, though xml can handle more. I would say, start with json unless you really need features of xml.
There is no security benefit to go with one or the other. Both formats are meant to provide a simple protocol for sending data, and neither use encryption by default (you could add something yourself). JSON is generally considered faster, since it takes less characters to assemble. It is also easy to use in JavaScript, since JSON is simply JavaScript Object Notation, and all JavaScript Objects can be converted to or from JSON representation.
Many (especially newer) developers prefer using XML because of its readability. It is structured in such a way that it is much easier for a human to read through it. This of course is what makes it bulkier than JSON, but it is by no means less secure.
Vulnerabilities that can occur as a result of these transfer protocols are a result of bad parsing. Parsers for services on an open network cannot simply assume that the data is valid, since that may lead to attacks such as code injection - but that has nothing to do with JSON or XML.
Both of the formats are representing data therefore there is no difference in security, i have been using JSON for years and never had any security issues.
JSON and XML both serves as a medium for server client communication. So, why are security concerns with one and not other?
The fundamental difference is that JSON(JavaScript Object Notation) as name suggests is very near and dear to JavaScript and hence in design of some JavaScript methods and functionalities, JavaScript treats JSON strings as it's cup of tea and tries to interpret it directly, which give workarounds to attackers to fool JavaScript interpreter to run malicious JavaScript embedded in the string causing vulnerabilities, while XML has to go through a parsing stage to be parsed into an object making it harder to attack with.
2 such JavaScript functionalities are eval() method and tag.
How does these create a security vulnerabilities?
Although web follows the same-origin policy, historically there have been loopholes found to bypass it and malicious sites use them to send cross site request to authenticated user website, breaking the intent of same-origin policy.
Example :
In spite of same-origin policy being in place, web has allowed some tags like <img> <script> to make cross origin GET requests.
let us say you are on a website www.authenticatedwebsite.com, but lured to open a www.malicious.com which has a tag in its html
<script src="www.authenticatedwebsite.com/get-user-order-history" />
Attacker from www.malicious.com use this script tag behavior to access your private data from www.authenticatedwebsite.com.
Now, how does a script tag which is calling a src url, store the url response to a javascript object[to perform operations like POSTing it to malicious site server]?
Here comes the role of JSON and XML proves out to be safer here. As JavaScript understands JSON pretty well, some JavaScript interpreters interprets naked JSON string as a valid JavaScript and run it.
What can running a JSON string potentially do, as it is still not assigned to a variable?
This can be achieved by another fancy hack.
If the returned JSON string represents an array. JavaScript will try to run the constructor of Array class. Now it is possible to override the constructor of Array in JavaScript. You can do something like :
Array = function(){ yourObject = this };
This is basically overriding JavaScript Array constructor, such that whenever JavaScript calls constructor, the current interpreted array is assigned to yourObject, thus giving malicious website access to your private data.
Now, this attack can be used with variants of JSON strings, with more sophisticated hacks.
Although above represents a valid scenario, where JSON can be dangerous as a return format of your GET APIs. This is actually possible in only some versions of some browsers, and as far as I know, all modern versions of famous browsers have mitigated it, but as your user base can be divided across versions of browsers, you need to be careful with GET APIs giving out private information in naked JSON format.
One of the technique used to circumvent this is adding a while(true) in front of your JSON response strings, which will never allow JavaScript interpreter to reach to the actual string. But it creates parsing overhead on your client side.
Another possible mishaps that JSON can cause is use of eval() method on browser client side to parse JSON. As eval() has capability to run script, if your JSON string contains some hidden script which eval() runs and perform dangerous actions what attacker injected script asks it to do, can prove out to be security issues for your system. But as others have mentioned, this attack can be easily prevented by strictly abandoning eval() method as your JSON parser everywhere in client code. This vulnerability plug in is highly important for websites which stores user generated content.
This post does a good job comparing the security issues found in the two data sharing formats. It even has code snippets with explanations of how attacks can be pulled off on the common vulnerabilities like XXE and DTD validation. Then it shows how to remediate/harden against these security issues so that both XML and JSON can be used safely.
https://blog.securityevaluators.com/xml-vs-json-security-risks-22e5320cf529
In terms of security, XML parsers in their default configuration are open to XXE injection attacks and DTD validation attacks, so XML data exchanges need to be hardened if used.
JSON, on the other hand, is in itself secure in its default state, but as soon as JSONP is utilized to bypass Same-Origin Policy restrictions (CSRF attacks), it becomes vulnerable because:
it allows cross-origin exchanges of data.
The author summarizes the comparison here:
In regard to security, processing untrusted Internet-facing requests is one of the most basic functions of an XML or JSON parser. Unfortunately, common XML parsers are not suitable for this purpose in their default configuration; only with hardening to disable external entity expansion and external DTD validation are they safe. Conversely, JSON parsing is almost always safe, so long as the programmer uses modern techniques rather than JSONP. As long as web developers are aware of these security risks and take the steps to defend against them, either option is completely viable in the current web environment.
i want to protect my website form xss, and i want to assure that all my data are correct and consistent, so i don't want to allow to add any scripts to my db, that's because my data may be used by other web services , so i want to be sure that my data is correct and will not cause any problems to others.
I want to make validation only in the input of the data , not at the output, hence i will make the validation only once, and also i will be sure that no scripts exist in my db .
EDIT: please check the last comment I added.
Use some Filter to sanitize HTTP request data.
You may go for jsoup, it is very handy:
String unsafe = "<p><a href='http://example.com/' onclick='stealCookies()'>Link</a></p>";
String safe = Jsoup.clean(unsafe, Whitelist.basic());
// now: <p>Link</p>
Ref: http://jsoup.org/cookbook/cleaning-html/whitelist-sanitizer
In short, you can write filter which does proper escaping of User input(map to relevant URL mapping). There could be readily available plugin to do this but I am not aware.
You can refer to this thread XSS prevention in JSP/Servlet web application