XSS - encode - decode a href/url - java

I have a usecase where I have a text input field which takes URL and saves it.
That saved url is used in a jsp file
<script type="text/javascript">
var defaultSimulatorUrl = '<%= defaultSimulatorUrl %>';
</script>
Variable defaultSimulatorUrl is used to show in prefilled text input fields
Some attacker can attack defaultSimulatorUrl's value by sending http://abcxyz.com?a=b&c=d';alert(1);//
Script content will be converted to
<script type="text/javascript">
var defaultSimulatorUrl = 'http://abcxyz.com?a=b&c=d';alert(1);//';
</script>
My problem is if I encode this Url using com.adobe.granite.xss.XSSAPI.encodeForHTML(), how can i get orignal url to show in input field
Or Can I encode it by some other means to be used in prefilled text input fields
XSSAPI does not provides api to decode string back

I used XSSAPI's encodeForJS method which solved my problem

Related

How to ouput a json string in the js section of a html file using thymeleaf

I have a project with Java 8, bringing data to the frontend with Thymeleaf. The data entity I want to ouput in my frontend is calles logs and is a list of entities that have an attribute containig json data. I output it in the html file as follows:
<script type="text/javascript">
let logs = [[${logs}]];
</script>
The json has the following structure:
{
"oldest": 712367620,
"youngest": 712378606,
"measurements": []
}
But on the page it appears with the double quotes escaped which completely messes up the js:
<script type="text/javascript">
let logs = [LogEntity(id=52, success=true, runtimes={
"oldest" : 712367620,
"youngest" : 712378606,
"measurements" : []
})]
</script>
How can I prevent the escaping of the double quotes in the json string?
I work with php and twig in another project and there it is as simple as {{ logs|raw }}. Is there some kind of modifier in thymeleaf like |raw in php twig?
Security is not an issue since I have complete control over the data objects.
You have to enable JavaScript inlining with th:inline="javascript":
<script type="text/javascript" th:inline="javascript">
let logs = [[${logs}]];
</script>
(I'm not sure what you mean by "json data". Do you mean you have a String that contains JSON?)

How can you build an absolute URL in thymeleaf?

I would like to display an absolute url generated at run-time with a parameter. Not create a href to a page but display the URL using th:text. Any simple way to do this with Tymeleaf (without having to concatenate the URL pieces from #request object and without using some MVC utility class)?
Attempt 1
<p th:text="#{/myServlet(myParam=${dynamicParameter})}" /> - only displays part of the URL leaving out the protocol, port and host name. I am getting /myServlet?myParam=123. The same behavior as for th:href, if you inspect the <a> you will see the same href - in that case the browser helps by inferring the protocol, port and so on
Attempt 2
th:text="#{__${#httpServletRequest.requestURI}__}" - produces a relative URI of the current page that doesn't include the protocol and so on
Attempt 3
th:text="#{__${#httpServletRequest.requestURL}__}" - produces this time an absolute URL of the current page containing the protocol, host and servlet context. The problem now is when I display this text from a different page, my URL is ...myApp/myOtherServlet so I need to edit this string to replace myOtherServlet with the URI I want.
Non Tymeleaf Attempt 1
#Service("urlUtils")
public class UrlUtilsServiceImpl implements UrlUtilsService {
#Override
public String getAbsoluteUrlTo(final String aPath, final String param, final String value){
return ServletUriComponentsBuilder
.fromCurrentContextPath()
.path(aPath)
.queryParam(param, value)
.build().toString();
}
}
page.html:
th:text="${#urlUtils.getAbsoluteUrlTo('/myServlet', 'myParam', ${dynamicParameter})}"
The problem is the host name that can be aliased before it reaches my server (see this).
Thymeleaf+JS Sollution
Using some java script plus thymeleaf
<p id="myUrl" th:text="#{/myServlet(myParam=${dynamicParameter})}" />
<script type="text/javascript">
$(document).ready(function () {
var myUrl= $("#myUrl");
myUrl.text(window.location.origin + myUrl.text());
});
</script>
You can concatenate servlet request on the fly:
th:text="${#httpServletRequest.scheme}+'://'+${#httpServletRequest.serverName}+':'+${#httpServletRequest.serverPort}+#{/myServlet(myParam=${dynamicParameter})}"
Or for JavaScript:
<script type="text/javascript">
GLOBAL.serverURI = '[[${#httpServletRequest.scheme}+'://'+${#httpServletRequest.serverName}+':'+${#httpServletRequest.serverPort}+#{/myServlet(myParam=${dynamicParameter})}]]';
</script>

how to get html struts styleClass with javascript/jquery

I need to get the value of the styleClass element in javascript. Page is in jsp with struts/html tag elements. jsp code is
<input type="hidden" class="filename" name="filename" value="<%= filename %>" />
<html:file property="testfile" styleClass="testfile"/>
and onclick of button I invoke the javascript
function fields() {
var filename = jQuery('.filename');
alert(filename);
var testfile= jQuery('.testfile').val();
alert(testfile);
}
However in the firstcase(filename) I get [object object] returned and in second case I get "undefined". Can someone give some pointers on how to get the uploaded file name in jquery. Thanks
If you want to get a value from an input:
var filename = $('.filename').val();
or
var filename = jQuery('.filename').val(); (same as above)
read more here -> jquery selector can't read from hidden field
Try this
var testfile= jQuery('.testfile').attr('value');
It may be that your browser is preventing access to the value attribute for security reasons. Try both options in different browsers - Chrome, Firefox, IE, etc.

How I do get an image blob from JSP to JavaScript?

I retrieved a blob along with some other data from a table, say name and image:
name = varchar, image = blob
I set this to an object in my filter and pass it to the JSP file:
request.setAttribute("info", object);
In the JSP file I get that data:
request.getAttribute("info");
Now that I have the data from that object how do I go about passing that info to my JS file and render the image as a source for the JS file?
I'm trying:
<div>
<script type="text/javascript" src="jsFile.js></script>
</div>
var name = <%=info.name%>;
var image = <%=info.image%>
It just doesn't seem to be working. What is the correct method of doing this?
This isn't going to work. Leave the blob there in the server side. JavaScript on the client side can't do anything sensible with binary data. All it needs is an URL of the image so that it can reference it in the src attribute of a HTML <img> element, so that the webbrowser can in turn do its job of downloading and displaying the image. Best would be to include the image identifier in the URL. The name is unique for the image, right? Use that in the URL instead.
The first step is to let JS create a HTML <img> element with the proper src attribute which points to an URL which returns the image. Assuming that you're preparing the data like follows
String name = "foo.png";
String imageURL = "imageservlet/" + name;
request.setAttribute("imageURL", imageURL);
and are printing it in JSP(!) as if it are JS variables as follows
<script>
var imageURL = '${imageURL}';
// ...
</script>
(please note that those singlequotes are thus mandatory to represent them as a JS string variable)
so that they end up in the generated HTML source like follows (rightclick page in browser and do View Source to verify it)
<script>
var imageURL = 'imageservlet/foo.png';
// ...
</script>
then you can create the image as follows
var img = document.createElement("img"); // or getElementById("someId")?
img.src = imageURL;
// ... add to document?
(please note that this is just an example, I have no utter idea what the functional requirement is and what you would like to do with this image element, even more, perhaps JS code isn't needed at all for the concrete functional requirement)
so that it ends up like this in HTML:
<img src="imageservlet/foo.png" />
Now, the second step is to create a servlet which listens on an URL pattern of /imageservlet/*, retrieves the image as an InputStream from the database by the passed-in indentifier and writes it to the OutputStream of the response along a set of correct response headers. Long story short, I've posted several answers before as to how to do it, they contains kickoff code snippets:
How to retrieve and display images from a database in a JSP page?
Writing image to servlet response with best performance
You can access your data from the script if you set the variables in a script block before your jsFile.js. Ie:
<div>
<script type="text/javascript">
var name = <%=info.name%>;
var image = <%=info.image%>;
</script>
<script type="text/javascript" src="jsFile.js></script>
</div>
I'm not sure how you intend to handle the binary (BLOB) image data however? Typically this would be written to an image file on the server and referenced via an img tag:
<img src="/path/to/myimage.jpg" />
Instead of passing your blob data to the JSP file, I would suggest having the server (your servlet) pass a URL to the JSP which the browser can use to get the image via an img tag. You can either write the blob data to a URL or write a servlet that writes out Content-type: image/jpeg (or similar) data when passed an id, ie:
<img src="http://www.yourserver.com/GetImage?imageId=xxx" />

Passing an HTML string to jQuery function

I'm working on an application which retrieves some HTML code from a record in a database. That strings then gets taken and inserted inside of a specific div. Right now I'm accomplishing this by passing the variable from Java and printing it within the div in the JSP. Now I'm trying to use an external jQuery function to accomplish this task and I'm struggling with how to pass this String to the jQuery function.
I tried something like this:
<script>
var message = <%=message %>;
</script>
<script src="files/js.js" type="text/javascript"></script>
But it can't seem to interpret the var once it hits the external function (I tried using StringEscapeUtils but that didn't fix the issue).
try:
var message = '<%= message %>';
var message = '<%=message %>';
$(message); // we have a jQuery object with a property
// for each html element in the message string!
When you run into problems like this, view the source of your page. How does message render? My guess might be
var message = Passing an HTML string to jQuery function;
Which isn't valid. Enclosing the code in apostrophies will fix this case.
var message = '<%= message %>';
I also usually put global objects like this on the window object so it is easier to find
window.message = '<%= message %>';
var message= <%= message %>;
You not only need to put some quotes around the message text, you also need to escape it suitably for a JavaScript string literal. Otherwise a quote in the message will break it, and potentially open you up to cross-site scripting attacks.
var message= '<%= message.replaceAll("\\\\", "\\\\\\\\").replaceAll("'", "\\\\'") %>';
I think that's the right number of backslashes, but the interaction of Java String literal backslashes and regex backslashes balloons them out of all sanity. Also control codes like newlines would need escaping if you need to include those.
All in all it might be best to hand the task off to a JSON-encoding library which will output all kinds of JavaScript types properly, not just strings. eg. with json-simple:
var message= <%= JSONValue.toJSONString(message) %>;

Categories

Resources