How to secure URL parameters in java - java

Sample URL http://dineshlingam.appspot.com/guestbook?name=xxx&skills=zzz
Sample Code
public class GuestbookServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException
{
String userName = req.getParameter("name");
String userSkills = req.getParameter("skills");
if(userName != null && userSkills != null)
{
res.setContentType("text/plain");
res.getWriter().println("Name : " + userName + ", Skills : " + userSkills);
}
else
res.sendRedirect(req.getRequestURI());
}
}
I am manually enter this URL to web browser.
How to secure parameters value.
Give me any one suitable example. Because I don't know the java concept and google-app-engine concept.
Really I don't know the SSL. So please I need detailed explanation of SSL with Example.
I am using eclipse to develop my application. Please help me. Thanks.

Your code is a classic example of a page vunerable to a CSS (Cross-Site-Scripting) attack. Using HTTPS wont mitigate that. Instead you need to escape any input before adding it to the page.
For example by using StringEscapeUtils.escapeHtml() and StringEscapeUtils.escapeJavaScript() from the Apache Commons Lang library.

Using https does not secure url parameter by any mean. You have to put parameters either in header or body if you want to make it secure. However if you are making a call directly from browser for this you cant put it in header neither in body because it is a a GET request. +1 to nfechner for highlighting XSS issue in your code.
For your problem here are the possible workaround with https:
Instead of GEt call use a POST call by putting this search in separate form in your page and use HTTPS on top of that.
If you want to use GET request you have to put the parameters in Headers, make a search page, When user hits the search button, make ajax call to above resource by passing it into header using https call.

Related

How to change the URL that contains "#!" to "d/" in Java?

Ok, here is my problem. I am building the Ajax Web app & to make my webapp to be seen by Google spider, I need to use the url that contain hashbang "#!". For example, my url could be like this:
mydomain.com/#!getCustomer
mydomain.com/#!getOrder
....
These url look pretty ugly & beside Google adword does not allow # in the url so I can't advertise my url in Goolge.
Thus, I want that everytime user go to the above link, the system will change "#!" to "d/", so that users will see these:
mydomain.com/d/getCustomer
mydomain.com/d/getOrder
....
Note: even the url doesn't contain "#!", but the system still be able to let Google spider to index my website.
So, I use FilterServlet to do that:
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String fullURLQueryString = getFullURL(httpRequest);
System.out.println(fullURLQueryString); // test url
if ((fullURLQueryString != null) && (fullURLQueryString.contains("#!"))) {
fullURLQueryString=fullURLQueryString.replace("#!", "d/");
request.getRequestDispatcher(fullURLQueryString).forward(request, response);
}
}
However, the system does not recognize the part "#!" when capturing the fullURLQueryString
So the System.out.println(fullURLQueryString); only print out the mydomain.com & it ignores completely the part #!getCustomer or #!getOrder.
Did i do anything wrongly here?
Can you fix it?
You do not have to use #!, if your web application doesn't use client-side generated content. If your URLs do not currently contain #, this functionality is of no interest for your.
In typical scenario in which this is useful user goes to page: http://example.com/#page1.
The browser requests http://example.com/ (notice #page1 is not in the request). After the page is loaded, client side JavaScript examines the part after # and downloads additional content.
Google bots do not support JavaScript and cannot download any additional content. For them, every page http://example.com/#page1, http://example.com/#page2 ... looks the same.
To fix this, #! syntax was introduced. You can learn more about it here.
You cannot do this server-side because browsers never send the URL fragment (the # and everything after it) to the server. You can do this replacement only with client-side JavaScript:
if (location.href.match(/\/#!/)) {
location.replace(location.href.replace(/\/#!/, '/d/'));
}
You should be constructing your URLs with the URL class (not a String).
Here is the official Java 8 Documentation:
http://docs.oracle.com/javase/8/docs/api/java/net/URL.html
The problem is with your getFullURL() method. Instead you should use getRequestURL().

How to download file from web site having liferay portlet using java code

i'm trying to download a file from a site , this site has a life ray server
i have been reading to much about but all describe how to configure a server not how to read from , all examples i saw has HTTPServletRequest which needs a request input how can i transfer a URL to a request ,from where to start at least .
in other words :i have the URL , in the webpage i select a date and a download like is generated , how can i make it down in java ????
i tried this:
HttpServletRequest request = PortalUtil.getHttpServletRequest(PortletRequest);
so how to link my URL to PortletRequest
If you have the URL of the download the only thing you need is to perform a client request against that URL.
First thing you should try to be sure that the URL you have is the one that will give you the expected results is try to paste it in a new browser window and verify that the download starts.
Then, if you want to perform that download through Java you can do very easily using the URL and URLConnection (HttpURLConnection in this case) classes:
String urlString = "..."; // Your URL
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (conn.getResponseCode() == 200) {
InputStream stream = conn.getInputStream();
// Read the data from the stream
}
You could also do the same using Apache HTTP Client.
Note: PortalUtil.getHttpServletRequest(...) is used internally by Liferay and you won't have any access to that API if you are doing a client request.
If you're writing a portlet, by design you don't get access to the HttpServletRequest.
What you can do is to utilize the "resource-serving" lifecycle phase of a portlet. There you get access to a ResourceRequest and ResourceResponse object. Those objects behave almost like a HttpServletRequest/-Response object
As you don't name the framework that you're using: javax.portlet.GenericPortlet.serveResource() is the method that you want to override in the pure JSR-286 API.
On the UI side, <portlet:resourceURL/> will provide the URL to your portlet's resource handling method.
This should provide you with enough google-food to find tutorials on how to implement different lifecycle phases - I can't judge the required level of detail you need. Note that Liferay has quite a few sample portlets that you can utilize as a source for sample code.
Edit: Following your comment below, let me give you some pseudo code (just typed here, never compiled/run):
on a jsp frontend, e.g. view.jsp:
Download File
Then, in your portlet, assuming you're implementing javax.portlet.GenericPortlet in one way or another (e.g. indirectly through Liferay's MVCPortlet or any other superclass):
public class MyPortlet extends GenericPortlet {
....
#Override
public void serveResource(ResourceRequest request, ResourceResponse response) {
// implement the file streaming here,
// use ResourceResponse the way you find illustrated
// in samples for HttpServletResponse
}

Django and Java Applet authorization failed

I'm building a Django App with allauth.
I have a page, with authentication required, where I put a Java applet. This applet do GET requests to other pages (of the same django project) which return Json objects.
The applet gets the CSRF token from the parent web page, using JSObject.
The problem is that I want to set ALL the pages with authentication control, but I cannot get the sessionid cookie from the parent web page of the applet, so it cannot do GET (and neither POST) to obtain (or save) data.
Maybe it is a simple way to obtain this, but I'm a newby, and I haven't found anything.
Ask freely if you need something.
Thank you.
EDIT:
Has I wrote downstairs, I found out that the sessionid cookie is marked as HTTPOnly, so the problem now is which is the most safe way to allow the applet to do POST and GET request.
For example it is possible to create a JS method in the page, which GET the data and pass it down to the applet?
Maybe in the same way I can do the POST?
EDIT:
I successfully get the data, using a jquery call from the page. The problem now is that the code throws an InvocationTargetException. I found out the position of the problem, but I don't know how to solve it.
Here is the Jquery code:
function getFloor() {
$.get(
"{% url ... %}",
function(data) {
var output = JSON.stringify(data);
document.mapGenerator.setFloor(output)
}
);}
And here there are the two functions of the applet.
The ** part is the origin of the problem.
public void setFloor(String input) {
Floor[] f = Floor.parse(input);
}
public static Floor[] parse(String input) {
**Gson gson = new Gson();**
Floor[] floors = gson.fromJson(input, Floor[].class);
return floors;
}
And HERE is the log that come out on my server, where you can see that the applet try to load the Gson's library from the server (instead from the applet)
"GET /buildings/generate/com/google/gson/Gson.class HTTP/1.1" 404 4126
Somebady can help me?
You can do something like this in your applet:
String cookies = JSObject.getWindow(this).eval("document.cookie").toString();
This will give you all the cookies for that page delimited by semicolons.

How to pass the session cookie to Play via Uploadify?

I'm trying to use Uploadify, an Ajax file uploader, with Play Framework.
Uploadify uses a Flash object to talk to the server ... so by default it will not use the Play cookies. I want to authenticate my user correctly, so I need to get uploadify to send some cookies over itself.
Does anyone has a working example of the two working together, or, failing that, some pointers?
uploadify has an option called scriptData which you could used to send your authentityToken:
#{authenticityToken /}
<script>
var token = $('#input[name=authenticityToken]').val();
$('#file_upload').uploadify({
'uploader' : '/uploadify/uploadify.swf',
'script' : '/uploadify/uploadify.php',
'cancelImg' : '/uploadify/cancel.png',
'folder' : '/uploads',
'scriptData' : {'authenticyToken': token}
});
</script>
Well, if you're using httpOnly configuration (and you should!), then it's impossible to pass Play's native auth cookie to uploadify.
What I did was:
1. Not secure the Images controller with #With(Secure.class), but instead use a before method:
#Before(unless = "uploadPost")
public static void before() throws Throwable {
Secure.checkAccess();
}
2. Pass along two parameters from the controller that renders the page hosting the uploadify plugin: userId, and signedUserId
String userIdSignature = Crypto.sign(Long.toString(user.id));
render(..., user.id, userIdSignature);
3. Pass these two parameters to uploadify, and to the uploadPost method
public static void uploadPost(Upload upload, long userId, String userIdSignature) {
assertEquals(userIdSignature, Crypto.sign(Long.toString(userId)),
"Failed to authenticate user ID " + userId);
If for some reason you don't want the client to know its user ID, an alternative to signing is encrypting the user id.
Note that you are still exposed to replay attacks using this method, but I believe this is a general problem with Play (I could be mistaken about this). You can add an expiration date to the signature to limit the damage.

redirecting between java servlets from url containing #

Hey,
Maybe the title is not the best choice, but I really don't know how to better describe the problem.
The thing is when you point your browser to url that contains #
http://anydomain.com/test/elsem/1234#dogeatdog
and for some reason (ie. there is a business logic) you want to redirect to other page
http://anydomain.com/test/els/1234
the #dogeatdog will be added to new url.
I found this behavior while developing wicket app, but just now I tested it with simple pure java servlet. Can someone explain it to me?
Here is the code just in case I'm doing something wrong:
private void process(HttpServletRequest req, HttpServletResponse res)
{
res.setContentType("text/plain");
try
{
HttpSession session = req.getSession();
Object as = session.getAttribute("as");
if (as == null)
{
log.info("redirecting");
session.setAttribute("as", 1);
res.sendRedirect("/test/");
}
else
{
log.info("writing");
PrintWriter out = res.getWriter();
out.write("after redirect "+as);
out.flush();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
Hash fragments (#a_hash_fragment) never leave the browser, they are not part of HTTP request.
What the web server gets in this case is GET /test/elsem/1234, and it responds with redirect 3xx code and the new url /test/els/1234, which your browser picks and appends #dogeatdog. Makes sense now?
UPDATE: Thanks to Zack, here's a W3C document that exactly explains how this (should) work:
http://www.w3.org/Protocols/HTTP/Fragment/draft-bos-http-redirect-00.txt
From the sendRedirect Javadoc:
Sends a temporary redirect response to the client using the specified
redirect location URL. This method can accept relative URLs; the
servlet container must convert the relative URL to an absolute URL
before sending the response to the client. If the location is relative
without a leading '/' the container interprets it as relative to the
current request URI. If the location is relative with a leading '/'
the container interprets it as relative to the servlet container root.
Because of repetitive use of "relative" in the Javadoc, I suspect the new URL is using what it can from the old URL and then building from there...
In the brief amount of what I've read, forwarding should be used if possible instead of redirect.
See this for a good explanation of forward verses redirect.
See this for straight-forward examples of forwarding requests to Servlets or JSPs.
Of course, with forwarding, the original URL will remain intact so that may not be what you're looking for...
EDIT
With information from milan, I found some more information regarding URL fragments (the stuff after "#" - I didn't know that was their official name until corresponding with milan).
There's another SOF post that has some good information concerning this and possibly the best answer: URL Fragment and 302 redirects
I have "+1'd" milan for giving good direction on this...

Categories

Resources