CSRF token generation in GWT RequestFactory based app - gwt

including a CSRF prevention token in POST requests and validating it on the server by overriding DefaultRequestTransport and RequestFactoryServlet seems to be simple enough.
However, I have one remaining issue: How can I generate the token and get it to the client the first place?
It is quite possible, ney likely, that I have missed something obvious. I am assuming that I need to create the token when the session is created on the server, store it in the session and pass it to the client.
The client then stores the token in a cookie and passes the token in request headers from that point onwards.
Is there a filter of some sort which I can use to provide the tokens?

If you were using RPC, you can read this document, it has example code for implementing it.
For RF, this question could be helpful.

The server generates a random token on the first request and typically includes it in the download of the script.

Related

JWT verification of signature on each page?

I am fairly new to JWT and I need to implement it. We use angular on client and PHP with composer on backend. I already know basics on verification and token forming. So I can form the token and sign it on server side, then send it to cient side for saving in a localStorage or somewhere similar. My question is, on subsequent requests of browser for some page, do I need to check the signature? Seems to be like I do, since merely checking the existence of token on client-side doesn't do much. Please advise? Thanks,
Once the Jwt is stored on the client side, on every request made to the server, it has to be checked and verified before serving the page requested.
If the token doesn't exists, the client needs to be authenticated. If the token exists but doesn't match the signature, the client needs to get a new one, so it needs to re-authenticate.
So token verification is mandatory each time you have to pass through the server.

Does using tokens break REST principles

Does using tokens for authentication break REST principles, which is supposed to be stateless.
I have an application which is required to be REST and I stored some tokens in a database. Each time a user wants to do an action, they should get a token (by sending a username and a password) and send it to the server with every request.
No they, don't.
A key aspect of something like the authentication header is the fact that it's orthogonal to the request itself. It's a property of the request in the same way that a Content-Type header is.
How Authentication is implemented on the back end is not germane to the discussion as long as results of the requests that submit the header are consistent. There's no reason the process of validating an authentication header can't be a stateless process in and of itself.
The presence and content of the Authentication can certainly impact what a client receives from a request, from a 403 Unauthorized response, to a limited amount of content based on whether the client is, perhaps, using an "admin" token vs. a non-privileged user.
It's also in contrast to a Cookie, which represent Session state (which is not RESTful). This is because the two headers serve different purposes and offer up different application semantics.
Authentication Tokens are a standard way of authenticating REST Clients.
Authentication token themselves do not beak REST principles as long as your API doesn't behave differently based on the Auth token passed to the API.
i.e. if 2 consumers place the same request with different auth token, and they are both allowed to perform that operation, the result should be the same.
You can find more info on REST API authentication here: https://dzone.com/articles/api-security-ways-to-authenticate-and-authorize
No it does not break the rule of being stateless.
Why?
Because the server is not maintaining any session w.r.t the client. It is just validating the token provided by client and returning results based on that.
If its client that has to maintain any data related to the session (which happens in case of tokens since they are sent with every request) then it is not breaking the REST principle, it is still stateless since the server is not maintaining the session or data related to the session.
Hope that helped.
It does break Rest principles because once the service generates a temporary token based on login credentials, the service is no longer stateless. The service has to check with itself if the token has expired yet (the token is part of the system state now), for each call made using that token.
One can't say the session at any point is independent of all the client's previous actions, because if they did not log in correctly, they could not even use the system.
But you should use logins and tokens, and break the Restfulness in this small way for security.

Doubt on prevention of CSRF

I had one doubt about CSRF prevention. A lot of sites say that CSRF can be prevented by using 'tokens' which are randomly generated per session.
Now my doubt is,
suppose i have a function like :
$.post("abcd.php",{'fbuid':userid,'code':'<?php echo md5($_SESSION['randcode']); ?>'}
now this md5 hash would obviously be visible to any hacker through the source code.He could simply open this page, generate a token, and keep the page open, so that the session doesn't get destroyed, and useanother tab or anything else , to start hacking,
No ?
Or is my idea of tokens incorrect ?
Thanks for your help :D
I think you are misunderstanding what needs to be done. To protect against CSRF you need to create a token and save it for that session. Then you need to append all your submits and AJAX calls with that token.
For another person to send you to a page on your website they would need to have access to the request with in the same session. It is true that one could parse the HTML and look for the token. But when they try to request a http call on your website they will have a new session created. The new session will have a new token which will not match the token that was passed.
Next you will ask what if you can copy the cookies and the session id as a result. This is not something that is protected. I can simply sit anybody's computer and copy all their cookies and I will then be logged in as them.
As kapep points out, you are confusing the two seperate issues of input validation and cross-site form posting. You must validate your inputs anyway, so the case of your malicious attacker using his own session token is already handled if you have sound input validation. CSRF protection is not there to protect the data, it is simply to ensure that only forms from your own application can post data back to that application. the CSRF protection is simply stopping other people being able to post data directly into your app from forms they put up on their own site.
One specific point to be aware of is that the token is visible to any javascript running on your page, so as soon as you have a cross-site scripting (XSS) vulnerability, your CSRF protection is defeated.
See Cross-site scripting and the prevention cheat sheet
You should use a per request token.
Generate a token and store it in the session.
Pass the token to the client.
Execute actions.
Destroy the token.
The token is safer and cannot be used more than one time.
I would define a stolen token as a token that is used by someone else, and not the one you have send the token to. If you send someone a token he can't really steal it from himself.
If you are concerned that a user can run a malicious script with his own token, your design seems to be broken. You can't prevent a user from sending data that you didn't indented to receive. It's your job to validate any data, the session token is just there to identify multiple requests by the same client.
It could be a security issue if you send that token over unsecured http. Then it could easily be stolen by monitoring the clients network.

How do I implement authentication the restful way?

I'm building a picture diary on web application google app engine using python. Users can sign up and post pictures to their diary.
Also, I'm trying to conform as much as I can to the REST architecture of doing things.
The authentication scheme is based like this for the web application:
1. Post username/password from the frontend
2. Backend sets up a cookie if authentication is successful
3. The rest of the AJAX calls made are authenticated using this cookie.
Is there any way to conform to REST without using cookies ?
Now, I'm also building an android application where users can sign in and post/view their picture diary. I need to expose the data from web application's datastore so I'll be building a webservice to fetch data from the datastore.
The authentication scheme for the android client:
OPTION a
1. Post username/password over https to the web service
2. Web service returns a unique authorization token (store the token in the username/pwd table on the datastore)
3. Request subsequent services by adding this token to the Request Header of the request
4. Server maps the token to the username/pwd table and returns data if token is found
5. Authorization token expires after a certain period of time
OPTION b
1. Set up a secret key on the client and server side
2. Use "username:hash of password and secret key" in the authorization header of every request
3. server generates the password by extracting the password from the hash value using the same hash algorithm ; if successful returns data
btw, I didn't wanna use basic authorization because of its security vulnerabilities.
Which is better ?
Are there other significantly better ways to accomplish what I'm trying to do ? Security is quite a concern for me btw.
I'd appreciate if anyone has any insight into this issue. thanks.
I've been doing some research myself as to what would be the best solution. I think the 2-legged oauth might work in my case as Leonm suggested.
In this case the server has to provide the client with a consumer key/secret which in my case is hardcoded in the app.
The steps now would be:
1. Generate a signature using the oauth_parameters(consumer_key, signature_method, timestamp), request url, request parameters, and the SECRET.
2. Include the signature, oauth parameters when making a request.
3. Server verifies the request by generating the signature again except in this case it uses the SECRET that corresponds to the key
I think this way I am pretty much confirming to the REST principles. The server is statless as I far I understand now.
What are the pros/cons on doing things this way?
If "security is a concern" then I would say that you'd be a lot better off using open standards and a library to achieve what you want. The main reason for this is that if you do it yourself, you're very likely to forget something; these standards have had a lot of eyes looking at them, looking for holes.
Your options include (in increasing level of complexity)
Basic authentication and HTTPS
Everything is encrypted, which makes it impossible to compress or look into, it increases the overhead somewhat, using more horsepower on the server, and more perhaps battery power on the client. Simple to implement, since it's well supported by libraries.
Digest authentication
Unencrypted messages pass the wire, but the authentication is securely managed in the Authorization headers. See the wikipedia entry for more information.
OAuth
See how Google is providing OAuth for installed applications. I believe it isn't what you're looking for, since you're not asking to share data between applications, just authenticating users.
Roll your own
If you want to roll your own, I suggest looking at e.g. how Google's (now deprecated ?) ClientLogin used to work.
Clients would GET a protected resource, and get a 401 with instructions to perform a GoogleLogin authentication, including a URI for where to perform the login itself
Clients (knowing how to do this) POST a request in a specific manner to that URI
The server responds with a specific response including a (long) token
The client can now perform GET requests to the protected resource with that token.
Statelessness
You cite REST, which dictates that requests should not specifically depend on prior interaction: "... each request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server." (fielding) This means that a server shouldn't store conversational context (like an authentication token) in a table.
One way of fixing this is by using any of the token based approaches (where the server tells the client about a token it should use for future requests) where the token is not a random number, but a message to the server itself. To protect yourself from client tampering, it can be signed, and if you're afraid of clients looking at it, you can encrypt it.
Edit: Although I'm not certain, it seems unlikely that Google has a table of all authentication tokens ever issued; The length of their tokens suggests that the token is some encrypted message proving that whoever holds this token actually provided real credentials in some realm at some time.
OAuth does exactly what you want to do in a standard way.
You could use a combination of HTTPS and HTTP Basic Auth. Both are existing standards and should be secure enough when used together.

Good approach for a web API token scheme?

I am working on a REST API for a web application that up until now we have developed internally for a couple of companion applications. Now that we are looking at opening up to outside developers we want to add tokens to the API in order to help identify who is making requests and in general to help manage it's use. At this point we are using https and basic authentication for user authentication on the API.
The token scheme we've been discussing would be very simple where each developer would be assigned 1 or more tokens and these tokens would be passed as a parameter with each request.
My question is if you've done something similar before how did you do it (did you do more or less, how did you handle security, etc) and do you have any recommendations?
First, you might want look at http://OAuth.net. Depending on your usecases, it might provide the security you need.
As to the token, it's a BLOB to most protocols, including OAuth. You can put any information you need in it in any format.
Here is what we do,
First we assign each developer a key with associated secret.
The token itself is an encrypted name-value pairs. We put things like username, expiry, session id, roles etc in there. It's encrypted with our own secret so no one else can make it.
For easy of use with web API, we use the URL-safe version of Base64 so the token is always URL-safe.
Hope that helps!
You might also want to think about maybe adding a time based token that would allow you to limit the amount of time a request is valid. this will help with someone trying to do a replay attack.
You would have a handshake call to get/assign a time valid token based off the above developerKey. This token would be stored locally and passed back to the caller.
The developer would then use this key in a request to validate the request and the developer.
For example that key can then be used for 5 mins or for 10 requests or whatever you define. after that point the generated time based token is removed from the valid list and can no longer be used. the developer will then have to ask for a new token.
UUID is very good for any temporary random key you fancy dishing out. Unpredictable and fast to generate, with collisions so unlikely they are effectively unique. Make nice session keys also.