How to fix the below XSS vulnerability issue?
How to secure my website from XSS vulnerability?
By adding a javascript in the URL of the website all the cookies values are being displayed.
below is a similar example of the URL which consists of a java script:
https://www.example.com/>< script>alert(document.cookie)< / script >&UserTarget=https://www.example.com/homepageredirect.jsp
To overcome this I added the below filer in obj.conf file in webserver 7.0:
Input fn="insert-filter"
method="POST"
filter="sed-request"
sed="s/(<|%3c)/\\< / gi"
sed="s/(>|%3e)/\\>/gi"
Ever after making these changes in the obj.conf , still the issue is not fixed. Please suggest something.
When you print your HTML just escape the special chars in the client side (or server-side, it depends for what you are going to print it) then you will be allowed to pass any input through without the need to use awkward regex or other kind of filter.
Example:
Let's say I have a variable that can receive a <script>alert( document.cookie )</script>, when I print I would do something like <div> <%= escapeHTML( dangerousVariable ) %> </div>.
In this URL XSS Prevention Rules mention you can apply rules according to your requirement
Related
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.
How can we implement ESAPI output encoding in an application using java and spring-mvc.
Read many posts and saw this:
<%# page import="org.owasp.esapi.*" %>
<input type="hidden" name="hidden" value="<%out.print(ESAPI.encoder().encodeForHTML(content));%>"/>
But, in my application all the jsps use spring form tags like the following,
<td>Number:
<form:input path="someNo" size="20" maxlength="18" id="firstfield" onkeypress="return PressAButton('submithidden');"/></td>
How can I have ESAPI implementation for above code? is there any other way of implementing output encoding like creating a filter or something? Any suggestions are greatly appreciated!
After researching spring tags a bit, it appears that the data-binding happens in framework code thus preventing you from applying any escaping in the jsp.
One, semi-quick win could be defaulting all output to escape HTML. Add this entry in web.xml:
<context-param>
<param-name>defaultHtmlEscape</param-name>
<param-value>true</param-value>
</context-param>
The only problem here is that output-escaping is a BIG pain... the rules for html escaping are different when your value is going to be passed as data to an HTML attribute or a Javascript function. And there could be some parts of your application where you DO NOT want to html escape, but you should be able to override those with the form tag attribute htmlEscape="false" when you need to.
What you need is to be able to hook the part of Spring tags where it is binding the HTML to the form, but you need to be able to do it so you can escape based on where its being placed. Escaping rules are different for an HTMLAttribute as opposed to plain HTML and if the value is going to be passed as data to a javascript function. So Spring's solution only defends one category of attack.
These are the only ways out I see, all of them will require work:
Use JSTL tags instead of Spring tags so you can write your variables with ${thisSyntax} and wrap them in esapi tags like this:
<c:out value="<esapi:encodeForHTML>${variable}</esapi:encodeForHTML>"/>
Follow a solution like what #A. Paul put forward, where you do your context escaping back on the controller side. I'm aware you feel that this isn't an option, but the next solution I'm putting forward is untested.
Implement your own tag library that subclasses [org.springframework.web.servlet.tags.form.InputTag][1], specifically the method writeValue. While esapi prevents alot, I would recommend looking at owasp's new Encoder project to show you exactly how tricky output encoding is. Ideally your tag library will allow you to utilize either esapi's Encoder or this new API.
Just a thought not sure if this is what you are looking for.
Can you use the below code in Java and change the data in the bean itself and then send in the user interface.
if ( ESAPI.securityConfiguration().getLogEncodingRequired() ) {
data = ESAPI.encoder().encodeForHTML(message);
}
You can check the below url.
http://www.jtmelton.com/tag/esapi/
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"%>
Due to some security constraints, there is requirement that the page visited should not be listed in browser's history.
So the pages need not to be shown in the history at all.
I have tried following ways but failed.
Solution 1:
1. <%
2. session.invalidate();
3. response.setHeader("Cache-Control","no-cache");
4. response.setHeader("Cache-Control","no-store");
5. response.setDateHeader("Expires", 0);
6. response.sendRedirect("home.jsp");
7. %>
Solution 2:
<%
Response.Cache.SetExpires(DateTime.Parse(DateTime.Now.ToString()))
Response.Cache.SetCacheability(HttpCacheability.Private)
Response.Cache.SetNoStore()
Response.AppendHeader("Pragma", "no-cache")
%>
Solution 3:
<body onload="history.forward()">
Solution 4:
<%
response.setDateHeader("Last-Modified", System.currentTimeMillis());
%>
Like in Firefox, there is functionality Tools -> Start Private Browsing which doesn't store any session data. Is there anything that can be done by JavaScript to achieve this.
You can't rely on client side when security matters. All browsers have different implementation for history. You should rely on a server side solution.
You cannot do it using all above four ways.
The only thing you can do it put your URL such that its unique and can't be revisited as per your requirement.
This behavior is under the control of the browser and not the server, so your options are very limited.
One way to achieve it is to create a page on site A which just contains an iframe that loads the content of the site which you don't want to see in the browser history.
But it will still be brittle. Users can use "Open Link in new window/tab" to break out of your shell.
If you have access to the clients, one solution is to install the browsers with history turned off in the settings plus restrict access to the browser preferences so users can't change this option.
You can't affect the browser's history mechanism. The best thing you can do is make sure the page has not been cached and possibly "disguise" it by making the URL random gibberish that has no meaning.
http://wiki.apache.org/struts/BrowserBackAndSecurity#Data_Caching_vs._Browser_Session_History
This smells of "security by obscurity". You should tackle the real problem (sensitive data in URLs) instead of obfuscating your way around it.
Just make it so that URLs don't contain any sensitive information (and please don't do it by wrapping the entire page in an iframe - this again is just a bit of obfuscation).
Morning all,
It early Monday morning and I'm struggling to understand why the followng line works in IE and not in FF.
<a class="button" href="#" onclick="setMaintenanceMode(false);">disable</a>
In both IE and FF the URL when you hover over the button is...
http://localhost:8080/mainapp/secure/gotoDevice.action?hardwareId=1&storeCode=2571#
When the button is clicked, the following method is called...
function setMaintenanceMode(enabled) {
var url = '<s:url action="secure/setMaintenanceMode"/>' + '&ModeEnabled=' + enabled;
document.location.href = url;
}
The URL that docuement is sent to is (in both browsers)...
/mainapp/secure/gotoDevice.action?hardwareId=1&storeCode=2571&ModeEnabled=false
The problem is that in IE the method on the struts action 'setSetCode()' is called, but from FF its not! If I remove the hash ahref above FF works, but IE doesn't (href="#").
I've tried changing the '&ModeEnabled=' to '&ModeEnabled=', but no success.
I've looked on google and the struts forum, but no success.
I'm tempted to rip out all the ahref's and replace them with Dojo buttons and see if that works, but before I do, I just wondered if anyone could shead some light on why.
My guess is that ahref is the wrong thing to use, but why?
If anyone could help me understand why though it would be appreciated.
Thanks
Jeff Porter
EDIT: The return false is part of the solution. The problem seems to be that the url..
/mainApp/secure/setMaintenanceMode.action?hardwareId=5&storeCode=2571&ModeEnabled=true
has the & inside it, if I go to this url as it is, then it works in IE, but not in FF.
if I change both to be & then it works in IE & FF.
if I change both to be & then it still works in IE but not FF.
Any ideas?
Note:
Seems that struts 2.0.9 does not support the property escapeAmp on the <s:url tag:
By default request parameters will be separated using escaped ampersands (i.e., &). This is necessary for XHTML compliance, however, when using the URL generated by this tag with the <s:property> tag, the escapeAmp attribute should be used to disable ampersand escaping.
soultion: return false on the onclick and upgrade to new struts + set escapeAmp param.
else, url = url.replace("&", "&");.
Try returning false from the javascript method
function setMaintenanceMode(enabled) {
var url = '<s:url action="secure/setMaintenanceMode"/>' + '&ModeEnabled=' + enabled;
document.location.href = url;
return false;
}
<a class="button" href="#" onclick="return setMaintenanceMode(false);">disable</a>
This should stop the javascript onclick event reaching the browser.
onclick="setMaintenanceMode(false); return false;"
The onclick is working, but then the href does immediately, as well. You need to return false from the click handler to signal that href should not be followed.
IE likely guesses at what you mean, and does the wrong thing.
the URL has the & inside it, if I go to this url as it is, then it works in IE, but not in FF.
I doubt it – it shouldn't work in either. It's not browser-dependent, but server-dependent.
The string a=b&c=d is split into parameters by the server framework. Servlet requires that only & be used to separate parameters, so it will return a=b and amp;c=d. The latter parameter obviously won't be recognised by the application which is expecting c.
The HTML specification for various reasons strongly recommends that ; also be allowed as a separator, in which case you'd get a=b, a stray amp which without an equals sign would be meaningless and discarded, and c=d. So despite the mis-encoding of the ampersand it would still work. Unfortunately, Servlet ignores this recommendation.
By default request parameters will be separated using escaped ampersands (i.e., &).
Oh dear! How unfortunate. You shouldn't escape ampersands at the point of joining parameters into a URL. You should simply join the parameters with a single ampersand, and then, if you need to put the finished URL into an attribute value of text content, HTML-encode the entire URL. Struts's default behaviour is simply wrong here.
In your case you are not outputting the URL to an attribute value or text content, you're writing it into a string literal in a script block:
var url = '<s:url action="secure/setMaintenanceMode"/>' + '&ModeEnabled=' + enabled;
In a script block in old-school HTML, HTML-escaping does not apply. (In XHTML in native XML it does, but let's not think about that yet.)
However, you still do need to think about JavaScript escapes. For example what if there were an apostrophe in the setMaintenanceMode link? It would break the string. Or if somehow you had a </ sequence in the string it'd break the entire script block.
What you really want to be doing is making the URL (without any ampersand-escaping), and then use a JavaScript string literal backslash-escape on it. Best would be to use an existing JSON encoder which will turn any Java value into a JavaScript literal, putting the surrounding quotes in for you too if it's a string. You can also on most JSON encoders tell it to JS-escape the < and & characters, which means not having to worry about XHTML parsing if you decided to serve the page as XML in the future.
I'm tempted to rip out all the ahref's and replace them with buttons
Well certainly if you have a thing you click on that isn't a link to another location, but simply does something to the page via script, then that's not a link really, and you'd be much better off marking it up as a <button> or <input type="button">, and using CSS to restyle it not to look like a button if you don't want it to.
However (again), this all seems rather pointless, as at the moment you are replacing the behaviour of a link with behaviour that just like a link only not as flexible. What's wrong with simply:?
disable