CSRF Filtering using GWT RequestFactoryServlet - gwt

I am implementing a token based system to prevent CSRF attacks in my Request Factory based GWT App.
To implement my filter on the server side I have overridden the doPost method on RequestFactoryServlet, thus:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String sessionToken = CsrfTokenManager.getToken(request.getSession());
String requestToken = request.getHeader(CsrfTokenManager.CSRF_TOKEN_NAME);
if (sessionToken.equals(requestToken)) {
super.doPost(request, response);
} else {
logger.error(String.format("Received unsafe http request [%s]", getFullRequest(request)));
response.sendError(401,"Unsafe HTTP Request");
}
}
This works in that it does not allow requests without a valid token to be processed, and my logs contain a suitable message, but the error I get back is a 500-Internal Server Error rather than a 401.
Can anyone shed light on why this is and what I should be doing differently?

There is very little information provided by you on the reason for 500 internal server error. Please share the exception stack trace ( 500 internal server error would have thrown one).
Also avoid implementing a custom one if it is not based on GWT recommendation. Read this stackoverflow query on CSRF with RequestFactory.

Related

Throw SOAP exception when there are pending Entity Framework database migrations for any SOAP request

I want to throw a SOAP exception when there are pending Entity Framework migrations and someone sends any SOAP request. If I throw a FaultException within my Global.asax, I get a html response from the IIS. This works but it is rather ugly. So I tried to throw it within the IServiceBehavior.Validate() method of my ServiceBehavior class.
public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
var isDatabaseUpdateRequired = new MyDb().GetPendingMigrations().Any();
if (isDatabaseUpdateRequired) throw new FaultException("There are pending migrations.");
}
But I do not get any XML response with the error message on my SoapUI client. Where should I throw this exception?
You can throw this exception in a class that implements the interface IDispatchMessageInspector. Implement IDispatchMessageInspector to inspect or modify inbound or outbound application messages either prior to dispatching a request message to an operation or before returning a reply message to a caller.
When the server receives the client request, the DispatchMessageInspector intercepts all the client requests.
The picture above is the implementation of IDispatchMessageInspector, Throw an exception in the BeforeSendReply method.
The client sends a request to the server and gets an exception message.
Here is a link about the IDispatchMessageInspector interface.

Which status to return for request to invalid URL for different http methods?

When a REST application receives a request for a non-existent resource, should it always return a 404 Not Found?
Should it return a different status for any of the HTTP methods GET, HEAD, POST, PUT, DELETE, OPTIONS or TRACE?
Spring returns a 404 for GET and HEAD, a 200 OK for OPTIONS, and a 405 Method Not Supported for the others. Is that wrong?
e.g. This Spring Boot application shows the different responses for requests to a mis-typed URL (greetings instead of greeting).
#RestController
#SpringBootApplication
public class Application {
private static Logger log = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
RestTemplate restTemplate = new RestTemplate();
String badUrl = "http://localhost:8080/greetings";
for (HttpMethod httpMethod : HttpMethod.values()) {
try {
restTemplate.execute(badUrl, httpMethod, null, null);
} catch (Exception e) {
log.error("Failed to " + httpMethod + " -- " + e.getMessage());
}
}
}
#RequestMapping("/greeting")
public String greeting() {
return "hello";
}
}
The logged output is:
Failed to GET -- 404 Not Found
Failed to HEAD -- 404 Not Found
Failed to POST -- 405 Method Not Allowed
Failed to PUT -- 405 Method Not Allowed
Failed to PATCH -- I/O error on PATCH request for "http://localhost:8080/greetings": Invalid HTTP method: PATCH; nested exception is java.net.ProtocolException: Invalid HTTP method: PATCH
Failed to DELETE -- 405 Method Not Allowed
OPTIONS request for "http://localhost:8080/greetings" resulted in 200 (OK)
Failed to TRACE -- 405 Method Not Allowed
Short answer: It does not have to always return 404. Longer answer: The specification seems to provide some options regarding which status codes to use. The specification at https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.5 says:
10.4.5 404 Not Found
The server has not found anything matching the Request-URI. No indication is given of whether the condition is temporary or permanent. The 410 (Gone) status code SHOULD be used if the server knows, through some internally configurable mechanism, that an old resource is permanently unavailable and has no forwarding address. This status code is commonly used when the server does not wish to reveal exactly why the request has been refused, or when no other response is applicable.
10.4.6 405 Method Not Allowed
The method specified in the Request-Line is not allowed for the resource identified by the Request-URI. The response MUST include an Allow header containing a list of valid methods for the requested resource.
There is some room for interpretation when to use those two codes. My interpretation would be: If some resource does not exist, yet some operation conceivably could still be applied to the URI, then a 405 would be more appropriate.
For example:
GET /reservation/1
405 Method not allowed
Allow: PUT
Could mean, that although GET is not allowed on that particular resource (because it does not actually exist), you could still make PUT work, thereby creating said resource in the process.
Arguably, a 404, although allowed by the specification, would be less usable.
Regarding OPTIONS. Specification is here: https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.2 . According to specification is does not imply an interaction with the resource itself. It is more of a query to the server specifically, to determine what methods would be "theoretically" supported on the given URI. It supports for example a wildcard ("*") query, which also probably does not exist at all.

GWT-RPC: hacked attempt on request payload

My test team try to hack on the system, they found out that GWT-RPC call returned a sensitive information (file name as emphasis as below) in response format "//EX" message. I'm amazed that I can't find any postings on this issue.
HTTP Request (Request payload):
7|0|5|http:/localhost:8080/Test_Web/|14B8AB60CF9C73722670313BAE18D294|abc|abc|abc|1|2|3|4|1|5|0|
HTTP Response:
//EX[2,1,["com.google.gwt.user.client.rpc.IncompatibleRemoteServiceException/3936916533","This application is out of date, please click the refresh button on your browser. ( Blocked attempt to access
interface 'abc', which is not implemented by 'com.testProject.client.customerClassService'; this is either misconfiguration or a hack attempt)"],0,7]
Specially the part that says "either misconfiguration or a hack attempt". In my case is hack attempt as HTTP Response, because the exception states that 'abc' is not implemented by 'com.testProject.client.customerClassService'.
Any ideas to hide the sensitive information (class name as emphasis) in the error message as above? I try with all browsers available it is not from the browser.
Name of your gwt-rpc service interface should not be considered sensitive information. That and all method names and parameters are sent using ajax on every gwt-rpc call... Its similar to rest service API resource names and crud operations you can perform on them.
The exception you got was caused by invalid name of gwt-rpc service interface/method/signature - the call was blocked. In this case its important to remember about server side validation of input parameters. You never know if the call was made by your app or was forged...
The 'sensitive' information gathered here is pretty minimal, so we have to assume that you have all other obfuscation turned on (removing class metadata, obfuscating rpc type names, and have otherwise gone over your own generated JS to ensure that no toString() ever returns its own classname).
With that being the case, it turns out that this is the standard RPC error that is sent out from com.google.gwt.user.server.rpc.RPC#decodeRequest(String, Class<?>, SerializationPolicyProvider) if the interface requested (apparently abc) is not implemented by this class. I'd be very surprised if there even was such an interface! It could be argued that this check shouldn't even happen if such an interface doesn't exist, but even doing that check would betray information about what classes don't exist on your server, which could also be considered 'sensitive'.
If this is a concern, my suggestion would be to prevent any IncompatibleRemoteServiceException from reaching the client. This would effectively prevent any debugging of the client, but just feed it a blank "Something went wrong from your bad request". There are a few legitimate cases where a client possibly should get info from exceptions like this, but from your perspective, that might still be sensitive. Without more detail in your question about exactly what sensitive means, this is hard to say.
With that said, here is how I would go about overriding this behavior: First, look at RemoveServiceServlet.processCall, which is where that failure would normally be handled by logging it to the user:
/**
* Process a call originating from the given request. This method calls
* {#link RemoteServiceServlet#checkPermutationStrongName()} to prevent
* possible XSRF attacks and then decodes the <code>payload</code> using
* {#link RPC#decodeRequest(String, Class, SerializationPolicyProvider)}
* to do the actual work.
* Once the request is decoded {#link RemoteServiceServlet#processCall(RPCRequest)}
* will be called.
* <p>
* Subclasses may optionally override this method to handle the payload in any
* way they desire (by routing the request to a framework component, for
* instance). The {#link HttpServletRequest} and {#link HttpServletResponse}
* can be accessed via the {#link #getThreadLocalRequest()} and
* {#link #getThreadLocalResponse()} methods.
* </p>
* This is public so that it can be unit tested easily without HTTP.
*
* #param payload the UTF-8 request payload
* #return a string which encodes either the method's return, a checked
* exception thrown by the method, or an
* {#link IncompatibleRemoteServiceException}
* #throws SerializationException if we cannot serialize the response
* #throws UnexpectedException if the invocation throws a checked exception
* that is not declared in the service method's signature
* #throws RuntimeException if the service method throws an unchecked
* exception (the exception will be the one thrown by the service)
*/
public String processCall(String payload) throws SerializationException {
// First, check for possible XSRF situation
checkPermutationStrongName();
RPCRequest rpcRequest;
try {
rpcRequest = RPC.decodeRequest(payload, delegate.getClass(), this);
} catch (IncompatibleRemoteServiceException ex) {
log(
"An IncompatibleRemoteServiceException was thrown while processing this call.",
ex);
return RPC.encodeResponseForFailedRequest(null, ex);
}
return processCall(rpcRequest);
}
Instead of catching the IncompatibleRemoteServiceException and just logging it out as-is, we want to write a nondescript "Something was wrong with your request, please submit to tech support" sort of answer. Do use the RPC.encodeResponseForFailedRequest or RPC.encodeResponseForFailure methods to make sure it is written as an exception that you client code and read and understand to be deliberately ambiguous.

Jetty custom status message ??

I am writing a service in clojure (using ring and compojure) which should change the status message. It is running on embedded Jetty 8. For example I have
200 OK
and I would like to have something like
200 <custome message>
In the EJB world there was possibility to set up header "X-Http-Status-Message" which does some magic behind the scene and changed message in response.
Is there any header in Jetty which allow me to do the same thing??
or Is there any other way in clojure to do it??
Not with a magic header like that.
The status reason has to be set along with the status code in the same call in Jetty.
You can use either javax.servlet.http.HttpServletResponse.setStatus(int, String) or org.eclipse.jetty.server.Response.setStatus(int, String).
Example:
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setStatus(HttpServletResponse.SC_OK, "Alrighty");
}
Note that some error conditions this status reason cannot be overridden. But generally, use of HttpServletResponse.sendError(int, String) will behave as you expect.
According to Ring documentation, you can only set the status code, not message:
https://github.com/mmcgrana/ring/wiki/Concepts
Also, the ring.util.servlet/set-status function invokes javax.servlet.http.HttpServletResponse .setStatus(int):
(defn set-status
"Update a HttpServletResponse with a status code."
[^HttpServletResponse response, status]
(.setStatus response status))
Whole implementation is here: https://github.com/ring-clojure/ring/blob/master/ring-servlet/src/ring/util/servlet.clj#L64
It should be fairly trivial to change Ring to add optional support for status message.
I suppose that the change could be introduced to the ring.util.servlet/update-servlet-response function:
(defn update-servlet-response
"Update the HttpServletResponse using a response map."
[^HttpServletResponse response, {:keys [status headers body]}]
(when-not response
(throw (Exception. "Null response given.")))
(when status
(set-status response status))
(doto response
(set-headers headers)
(set-body body)))
For example by adding status-message key to the response map.
https://github.com/ring-clojure/ring/blob/master/ring-servlet/src/ring/util/servlet.clj#L105

How to make use of GWT Serialization in RequestBuilder and Servlets

I'm using GWT RPC Calls for Server Side Request so far and it's pretty good. I'm planning on separating my Code into Servlets and GWT Client Side. Since i'm using RPC calls, it seems impossible. The Reason i want to do like this is , i'm planning to provide white labeling option for my App. So if i could separate the code to client code and servlets, i can simply provide the White Labeled client code to my Partners to host on their server. I have checked with GWT RequestBuilder and Access-Control Allow-Origin : Origin from Client Header and it works fine.
However i need to implement gwt-serialization over RequestBuilder request and Servlet Responses. How can i do this ..?
Scenario I like to make:
RequestBuilder sending Serializable String(Which is a IsSerialiazible object) to Servlet.
Servlet deserializes the String to Java Object,Processes and Returns the String Response of a 'IsSerialiazable' Object.
The Response String recieved in GWT RequestBuilder deserialzes it back to a Java Object(JS after Compiling).
I have checked on RemoteServiceServlet class which seems to have some info on serializing and deserializing request and response. But i couldn't get it right to get it to work with RequestBuilder. Any ideas , Hope it will be helpful for everyone.
public final void processPost(HttpServletRequest request,HttpServletResponse response)
throws IOException, ServletException,SerializationException
{
// Read the request fully.
//
String requestPayload = readContent(request);
// Let subclasses see the serialized request.
//
onBeforeRequestDeserialized(requestPayload);
// Invoke the core dispatching logic, which returns the serialized
// result.
//
String responsePayload = processCall(requestPayload);
// Let subclasses see the serialized response.
//
onAfterResponseSerialized(responsePayload);
// Write the response.
//
writeResponse(request, response, responsePayload);
}
GWT RPC and RequestBuilder serve different purposes. We cannot mix/match them.
GWT RPC - Services which fetch Data
GWT Request Builder - fire requests for static resources like js,css, json objects, querying soap services etc
The only feasible solution at the top of my mind for your approach of servicing requests is by using JSON - https://developers.google.com/web-toolkit/doc/latest/tutorial/JSON
You can keep your servlets code as is and then use RequestBuilder to query URL mapped to these servlets for JSON objects. Process the JSON objects using JSNI or Overlay concepts.
I'm trying to get the GWT Serialization & Deserialization source.Unfortunately, i have been stuck with other works and couldn't look on this right now. When i get the GWT Serialization Classes , i will update.