Security flaws : How to avert them? - java

I am in a bit of a pickle :
I have a lot of values which i am setting in a bean in java and then i am getting them in javascript and jsp using scriplets like this :
In My Bean.java :
public void setListValue(String s) { listValue = s; }
public String getListValue() { return listValue; }
Now in my jsp(inside a javascript function) :
input = $input({type:'hidden',id:'ListVal',name:'ListVal',
value: '<%= results.getListValue() %>'});
Sometimes i am using the scriplet code to retrieve parametres in jsp as well.
Normally if a parameter is passed from java file to java file or from jsp file to jsp file , then i use native java encoder and decoder like this :
EncodedHere = URLEncoder.encode(encodedStr,"UTF-8");
DecodedHere = URLDecoder.decode(EncodedHere,"UTF-8");
This works flawlessly for those scenarios but if i have set my variables in java and then i try to retrieve them in javascript or jsp like the afore mentioned way , it fails. I have tried the JSTL way as well , but could not make it work, seems JSTL is not suitable to get values in javascript. Now this scriplet has been flagged as security concern by many. Since it's a huge code base it's very difficult to change that as well.
Does some one have any ideas as to avert this security flaw somehow. In other words, is there a way i can encode the variable in java and get the encoded string in jsp and javascript and then decode it ?

It sounds like your security guys are worried about XSS (cross site scripting) attacks, which means data entered by the user that is re-displayed on a page could have malicious code in it. If that is the case you actually don't want to URL encode the data, you want to XML escape it, i.e replace potentially dangerous characters like < with their corresponding character entity like <. To do this in JSP you can use the <c:out> tag or the fn:escapeXML EL function. This works perfectly fine in javascript code, even if it is a little ugly. In your case it would look something like this:
First escape the javascript before you put it on the request using an escaping library the ESAPI reference implementation:
String jsEscapedValue = ESAPI.encoder().encodeForJavaScript(results.getListValue());
request.setAttribute("listValue", jsEscapedValue);
Then on the page use the <c:out> tag to HTML/XML escape it:
var myJsValue = '<c:out value="${listValue}"/>';
Make sure jstl.jar is on the classpath and be sure to include the correct tag lib at the top of your page.
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

Related

Fetchinng JSON data from servlet to display on JSP [duplicate]

I have a form in JSP. I have to populate it based on the request object (from the servlet). How do I use Java Script for accessing request object attributes or if you can suggest me any other better way to populate form dynamically?
You need to realize that Java/JSP is merely a HTML/CSS/JS code producer. So all you need to do is to just let JSP print the Java variable as if it is a JavaScript variable and that the generated HTML/JS code output is syntactically valid.
Provided that the Java variable is available in the EL scope by ${foo}, here are several examples how to print it:
<script>var foo = '${foo}';</script>
<script>someFunction('${foo}');</script>
<div onclick="someFunction('${foo}')">...</div>
Imagine that the Java variable has the value "bar", then JSP will ultimately generate this HTML which you can verify by rightclick, View Source in the webbrowser:
<script>var foo = 'bar';</script>
<script>someFunction('bar');</script>
<div onclick="someFunction('bar')">...</div>
Do note that those singlequotes are thus mandatory in order to represent a string typed variable in JS. If you have used var foo = ${foo}; instead, then it would print var foo = bar;, which may end up in "bar is undefined" errors in when you attempt to access it further down in JS code (you can see JS errors in JS console of browser's web developer toolset which you can open by pressing F12 in Chrome/FireFox23+/IE9+). Also note that if the variable represents a number or a boolean, which doesn't need to be quoted, then it will just work fine.
If the variable happens to originate from user-controlled input, then keep in mind to take into account XSS attack holes and JS escaping. Near the bottom of our EL wiki page you can find an example how to create a custom EL function which escapes a Java variable for safe usage in JS.
If the variable is a bit more complex, e.g. a Java bean, or a list thereof, or a map, then you can use one of the many available JSON libraries to convert the Java object to a JSON string. Here's an example assuming Gson.
String someObjectAsJson = new Gson().toJson(someObject);
Note that this way you don't need to print it as a quoted string anymore.
<script>var foo = ${someObjectAsJson};</script>
See also:
Our JSP wiki page - see the chapter "JavaScript".
How to escape JavaScript in JSP?
Call Servlet and invoke Java code from JavaScript along with parameters
How to use Servlets and Ajax?
If you're pre-populating the form fields based on parameters in the HTTP request, then why not simply do this on the server side in your JSP... rather than on the client side with JavaScript? In the JSP it would look vaguely like this:
<input type="text" name="myFormField1" value="<%= request.getParameter("value1"); %>"/>
On the client side, JavaScript doesn't really have the concept of a "request object". You pretty much have to parse the query string yourself manually to get at the CGI parameters. I suspect that isn't what you're actually wanting to do.
Passing JSON from JSP to Javascript.
I came here looking for this, #BalusC's answer helped to an extent but didn't solve the problem to the core. After digging deep into <script> tag, I came across this solution.
<script id="jsonData" type="application/json">${jsonFromJava}</script>
and in the JS:
var fetchedJson = JSON.parse(document.getElementById('jsonData').textContent);
In JSP file:
<head>
...
<%# page import="com.common.Constants" %>
...
</head>
<script type="text/javascript">
var constant = "<%=Constants.CONSTANT%>"
</script>
This constant variable will be then available to .js files that are declared after the above code.
Constants.java is a java file containing a static constant named CONSTANT.
The scenario that I had was, I needed one constant from a property file, so instead of constructing a property file for javascript, I did this.
In JSP page :
<c:set var="list_size" value="${list1.size() }"></c:set>
Access this value in Javascipt page using :
var list_size = parseInt($('#list_size').val());
I added javascript page in my project externally.

Java Custom tag containing generated JSTL : not interpreted

I have a custom tag that has no body at all. I'm trying to programmatically replace the empty body with, for simplicity's sake,
[<c:out value="SUCCESS!"/>]
The goal is to see "[SUCCESS!]" displayed by the JSP which uses the tag, but all I see is "[]" and if I look at the generated source code, I can see that the c:out statement is written on the page between the brackets, but not interpreted.
Is there a common way to achieve this ? The final goal will be to use other custom tags instead of the "c:out" tag. The tags/content will come from a database.
I tried different techniques with SimpleTagSupport and BodyTagSupport but none of those were successfull. In fact I'm not sure if it is technically possible to do it, since, the tag has already been interpreted at that time.. But then how should this be done ?
Server tags (like your custom tag or JSTL tags) get transformed to Java code when the JSP is translated into a servlet. For example, the following JSP code:
<c:out value="FooBar" />
gets translated to something like this inside the servlet:
....
OutTag outTag = (OutTag) tagHandlerPool.get(OutTag.class);
outTag.setPageContext(pageContext);
outTag.setParent(null);
outTag.setValue(new String("FooBar"));
int evalOut = outTag.doStartTag();
....
In your custom tags you can call other Java classes/methods and can write HTML code (not JSP code) to the response.
The [<c:out value="SUCCESS!"/>] is not interpreted because at this level it's just a string that gets written directly to the response.

Jquery html() encoding error in chrome

I'm developing an Java Web Application, I used some jQuery and a REST web services that output an JSON object with a list of Javascript objects using AJAX. All is ok but when I try to fill a table created with Javascript using jQuery.html() to a valid div, all hell broke loose in Chrome, including this
Error: INVALID_STATE_ERR: DOM Exception 11
in the Javascript console.
The problem is like this, try this in chrome Javascript console:
$('#ValidadorWrapper').html("<div>AMOXICILIN 100 C&psulapsula</div>");
But if we delete the ampersand, it works
$('#ValidadorWrapper').html("<div>AMOXICILIN 100 Camp;psulapsula</div>");
This problem happens only in Chrome, I suspect it has something to do with the encoding characters but I cant' find any way of doing it. Obviously I need to input an & ( i mean the & entity) in this document.
Some steps I have tried and didn't work:
I'm using the gson library to output a String to an JSP page. My JSP page have this header <%#page pageEncoding= "UTF-8" contentType="text/html; charset=UTF-8" %> . This was my first attempt and didn't work when an ampersand appeared in my JSON object (well any special char).
My second attempt was using the HTMLEntities Java library to encode all special chars. This is the actual version and it still doesn't work
Using unicode chars like \u0026 doesnt work either
There is something more strange. Apparently if I use $('#ValidadorWrapper').html("AMOXICILIN 100 \u0026"); it works!, but this is just an example. I'm trying to fill an HTML table with my object so I really need to put that data inside html (table) tags
Try this:
$('<div></div>').appendTo('#ValidadorWrapper').text('AMOXICILIN 100 Cápsulapsula');

Why is Eclipse/JSP parsing my JavaScript?

I have a JSP page which doesn't actually have any server tags in it so its basically an HTML page. But, my work is in love with JSP so I set it as a .jsp file. Anyhow, Tomcat is under the belief that my JavaScript is in fact Java code and tries to parse it. I get a nice big error on the screen saying its not a real function, etc. Could anyone tell me why its doing this? Code below...
...
<script>
$(function() {
$.dragAndDrop({
dom: {
fileList: '#fileList tbody',
contextMenu: '#fileContextMenu',
dropzone: '#dropzone'
},
templates: {
file: '<tr><td>${fileName}</td><td>${$.dragAndDrop.getDate()}</td><td>${$.dragAndDrop.parseSize(size)}</td></tr>'
}
});
});
</script>
...
The error:
org.apache.jasper.JasperException: /index.jsp(22,42) The function getDate must be used with a prefix when a default namespace is not specified
org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:40)
org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:407)
org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:148)
${} marks expressions for evaluating via JSP. As you say you don't use any JSP, you can disable the expressions language by adding
<%# page isELIgnored="true" %>
to your page.
It is likely the ${ notation
Try replacing this code ${$
with something like this $' + '{$
or $<%='{'%>$
I don't know if there is a proper way to escape that,, but what I just gave you should work.
See Google for more information. The top result looks good but I could not find how to do a proper escape: http://www.google.com/search?q=jsp+dollar+sign

How Do I make dynamic-attributes Work in JSP Tag Files?

So according to my JSP reference book, as well as every other reference I can find on the web, I'm supposed to be able to do something like:
<%# tag dynamic-attributes="dynamicAttributesVar" %>
and then when someone uses an attribute that I didn't define in an attribute directive, I should be able to access that attribute from the "dynamicAttributesVar" map:
<%= dynamicAttributesVar.get("someUnexpectedAttribute") %>
However, that doesn't work, at all; I just get a "dynamicAttributesVar cannot be resolved" error when I try.
Now, I did discover (by looking at the generated Java class for the tag) that I can "hack" a working dynamic attributes variable by doing:
<% Map dynamicAttributesVar = _jspx_dynamic_attrs; %>
Now, that hack doesn't work unless I also use the dynamic-attributes parameter on my tag directive, so it seems that the parameter is doing something.
But what I want to know is, how can I make it do what it does for every other JSP user out there?
Just trying to get a badge for answering a four year old question.
I have this problem as well and came across some help at O'Reilly to use JSTL instead of scriptlets.
The original poster could have used this code to get all keys/values:
<c:forEach items="${dynamicAttributesVar}" var="a">
${a.key}="${a.value}"
</c:forEach>
This would get a specific value:
<c:out value="${dynamicAttributesVar['someUnexpectedAttribute']}"/>
Isn't "dynamicAttributesVar" the name of the key in the page context that the dynamic attributes are put into? So you could do
<c:out value="${dynamicAttributesVar.someUnexpectedAttributes}"/>
or if you must use scriptlets:
Map dynamicAttributes = (Map) pageContext.getAttribute("dynamicAttributesVar")
(Disclaimer: I haven't tried it, I've just used dynamic attributes in tags with direct Java implementations... but it seems reasonable)

Categories

Resources