I am using Spring-MVC and AngularJS to create my web application, but I suppose that this question can apply for any technology, since it is more of a conceptual question rather than a specific technology question.
I am struggling with understanding a few things regarding CSRF attacks as well as authenticating users on my web application. Hence, I have the following questions:
For CSRF attacks, I read this website which stated the following:
Have the clients generate and send the same unique secret value in both a Cookie and a custom HTTP header. Considering a website is only allowed to read/write a Cookie for its own domain, only the real site can send the same value in both headers. Using this approach all your server has to do is check if both values are equal, on a stateless per request basis!
Now, I don't understand what the purpose is of generating these secret values. I mean, what is the purpose of having these 2 secret values and compare them on the server? Can't an attacker just put 2 identical values inside a fake cookie and http header and still submits the form?
From my understanding, REST is stateless, so the server does not keep track of any session on the server. In this case, I assume the user should again pass a secret value on every request to let the server now it is him? But what should the server do with this secret value? Should it be kept inside the database?
Now, I don't understand what the purpose is of generating these secret values. I mean, what is the purpose of having these 2 secret values and compare them on the server? Can't an attacker just put 2 identical values inside a fake cookie and http header and still submits the form?
You are right, an attacker could add a HTTP header, but he could only set a cookie for his own domain (origin). The browser will not send a cookie to another domain:
Considering a website is only allowed to read/write a Cookie for its own domain, only the real site can send the same value in both headers.
The server will receive only the HTTP request header from an attacker, not the cookie.
Related
I'm developing the restful web app that using some popular web framework on the backend, say (rails, sinatra, flask, express.js). Ideally, I want to develop client side with Backbone.js. How do I let only my javascript client side interact with those API calls? I don't want those API calls to be public and be called by curl or simply by entering the link on browser.
As a first principle, if your API is consumed by your JS client, you have to assume, that it is public: A simple JS debugger puts an attacker into a position, where he can send a byte-for-byte identical request from a tool of his choice.
That said, if I read your question correctly, this is not, what you want to avoid: What you really don't want to happen is, that your API is consumed (on a regular basis) without your JS client being involved. Here are some ideas on how to if not enforce, then at least encourage using your client:
I am sure, your API has some sort of authentication field (e.g. Hash computed on the client). If not, take a look at This SO question. Make sure you use a salt (or even API key) that is given to your JS client on a session basis (a.o.t. hardcoded). This way, an unauthorized consumer of your API is forced into much more work.
On loading the JS client, remember some HTTP headers (user agent comes to mind) and the IP address and ask for reauthentication if they change, employing blacklists for the usual suspects. This forces an attacker to do his homework more thoroughly again.
On the server side, remember the last few API calls, and before allowing another one, check if business logic allows for the new one right now: This denies an attacker the ability to concentrate many of his sessions into one session with your server: In combination with the other measures, this will make an abuser easy detectable.
I might not have said that with the necessary clarity: I consider it impossible to make it completely impossible for an abuser to consume your service, but you can make it so hard, it might not be worth the hassle.
You should implement some sort of authentication system. One good way to handle this is to define some expected header variables. For example, you can have an auth/login API call that returns a session token. Subsequent calls to your API will expect a session token to be set in an HTTP header variable with a specific name like 'your-api-token'.
Alternatively many systems create access tokens or keys that are expected (like youtube, facebook or twitter) using some sort of api account system. In those cases, your client would have to store these in some manner in the client.
Then it's simply a matter of adding a check for the session into your REST framework and throwing an exception. If at all possible the status code (to be restful) would be a 401 error.
There's an open standard now called "JSON Web Token",
see https://jwt.io/ & https://en.wikipedia.org/wiki/JSON_Web_Token
JSON Web Token (JWT) is a JSON-based open standard (RFC 7519) for
creating tokens that assert some number of claims. For example, a
server could generate a token that has the claim "logged in as admin"
and provide that to a client. The client could then use that token to
prove that they are logged in as admin. The tokens are signed by the
server's key, so the server is able to verify that the token is
legitimate. The tokens are designed to be compact, URL-safe and usable
especially in web browser single sign-on (SSO) context. JWT claims can
be typically used to pass identity of authenticated users between an
identity provider and a service provider, or any other type of claims
as required by business processes.[1][2] The tokens can also be
authenticated and encrypted.[3][4]
Set a SESSION var on the server when the client first loads your index.html (or backbone.js etc.)
Check this var on the server-side on every API call.
P.S. this is not a "security" solution!!! This is just to ease the load on your server so people don't abuse it or "hotlink" your API from other websites and apps.
Excuse me #MarkAmery and Eugene, but that is incorrect.
Your js+html (client) app running in the browser CAN be set up to exclude unauthorized direct calls to the API as follows:
First step: Set up the API to require authentication. The client must first authenticate itself via the server (or some other security server) for example asking the human user to provide the correct password.
Before authentication the calls to the API are not accepted.
During authentication a "token" is returned.
After authentication only API calls with the authentication "token" will be accepted.
Of course at this stage only authorized users who have the password can access the API, although if they are programmers debugging the app, they can access it directly for testing purposes.
Second step: Now set up an extra security API, that is to be called within a short limit of time after the client js+html app was initially requested from the server. This "callback" will tell the server that the client was downloaded successfully. Restrict your REST API calls to work only if the client was requested recently and successfully.
Now in order to use your API they must first download the client and actually run it in a browser. Only after successfully receiving the callback, and then user entry within a short frame of time, will the API accept calls.
So you do not have to worry that this may be an unauthorized user without credentials.
(The title of the question, 'How do I secure REST API calls', and from most of what you say, that is your major concern, and not the literal question of HOW your API is called, but rather BY WHOM, correct?)
Here's what I do:
Secure the API with an HTTP Header with calls such as X-APITOKEN:
Use session variables in PHP. Have a login system in place and save the user token in session variables.
Call JS code with Ajax to PHP and use the session variable with curl to call the API. That way, if the session variable is not set, it won't call and the PHP code contains the Access Token to the API.
I have developed a single page AngularJS application. For data retrieval/storage, it communicates with REST APIs over https. As per client requirement, i need to implement Client Authentication. i.e., As the application is based on REST APIs, how can we ensure that the request made to API is from a valid client and not from fiddler or a tempered client.
the current approach is:
1> configure a client secret and a key in the angular app.
2> authenticate the client by requesting a token from server using this client secret and key.
3> server checks this secret and key, if validates, responds with a newly generated token.
4> all further requests from angularjs app would carry this token in header, to ensure that the request is from a valid client.
But it is not good enough, as attacker can easily capture the requests using fiddler and also can easily read the client secret and key. or can debug using firebug.
Is there any secure way to authenticate the client app?
No security possible in the case if your REST API call is been shield by any User Authentication. I mean if User need to put Username/Password then they are able to call those API then you can implement some security.
But if your requirement like follows :
Any GUEST user with any browser open your application pages, which intern call your REST API.
Then there is no security. Since any attacker can intercept your Request/Response and call it further.
Note : From security prepective, Whatever a Browser can do, any good attacker can do the same.
But if you shield REST CALL Pages with username/password validation, then you can restrict the calls from server side with proper session validation.
JSON Web Tokens (JWT - pronounced jot) might be what you're looking for. Auth0 has a swell blog post that specifically addresses AngularJS + JWT.
You cannot trust the client to validate anything. If the user is using Firebug or Fiddler to "trick" your application then all you can do is verify the information server side to ensure it is valid.
You can trust the client to keep the user's session safe (to some extent), but if you can't trust the user then you can't trust anything the client sends to you.
If you need to ensure the integrity of a piece of data that is held client side you can use a MAC (Message Authentication Code) which is effectively a hash of the message appended to a server-side secret key that can be later verified. Sometimes this is (incorrectly) called signing. JWTs are the current standard to accomplish this.
It depends at the end of the day what threat you are trying to keep your application safe against - if it is a game with high scores that runs on the client, there's not much you can do to prevent the user from altering their score before it is sent to the server. If you need to trust such data, run it server side.
I've been struggling for 2 days now on how to secure a REST API without user authentification.
What does it mean ?
In my AngularJS application I identify an user by sending a GET request to an existing service (companydomain/userinfo) which I must use. I'm not sure how this work since I am not the author of this piece of code but the point is that I get the information about the user in the response as JSON (active directory name, phone in the company...).
This is all I have to identify an user.
What I did
Now, I found a lot of resources talking about OAuth, unique token, etc. but nothing seems to match with my issue. I implemented a token system but it's plain useless since I can't be sure of the authenticity of the requester.
User open the application. Application ask the service about the information related to the user. companydomain/userinfo
Application request a token to the server (nodejs & express), based on the information returned. /api/token/get/{user_info}
Server generates an unique token and store it in memory with expiration date and owner. The server also check in the table "authorized users" if the user exists (based on the active directory name), if not a new entry is added to it.
Application send the token along each request to the API. /api/entry/delete/{entry_id}
I think you see what is wrong here, an attacker could easily make a corrupted request to the API to get a legit token. So my question is :
How can I manage to secure my API since users don't use credentials to authentify ?
I hope my question is clear enough and at this point I am not even sure I can get around this issue without adding a credentials system.
You might want to look at Passport. It is a platform that allows you to easily add authentication to your application. There are many authentication strategies available. I am using Passport in a Node.js application implementing my own hmac strategy.
To authenticate, the client request includes an API ID to identify who the caller is and also includes an signature of a specified part of the message that includes things like the HTTP method, the API ID, a date value and some other header values, like maybe content-type. What data to include in the string to sign is up to you in your implementation, but the client and server must create and sign the same strings for the authentication to work. The signature is created by doing an hmac hash of the string using a shared secret.
On the server side, you use the API ID to retrieve the shared secret (possibly from a database or the filesystem) and perform the same hash on the request. If the hmac values match then you've authenticated the request. To prevent playback attacks, the date is included in the signed part of the request and must be within a certain window of the server's current time. For example, you might reject the request if the timestamp is more than 30 seconds old.
To enable a new user of your API, you generate a new API ID and shared secret. You give both of those to your API user and you store them for look up in your database or filesystem. The user must sign the requests with the shared secret and include the ID in the request.
The Hawk strategy provides much of this functionality, but we decided to roll our own hmac strategy.
Because you say that the user info endpoint returns active directory name, I assume you're on the Windows platform.
If so, why not use Windows integrated authentication (Kerberos) to authenticate your users without asking them for credentials? This will only work within your active directory domain, but is completely transparent to your service.
You can still call the user info endpoint and verify that the info it returns is for the same user that is calling your REST service.
If you need to call services that do not support Windows integrated auth, you could generate a security token (sign it to guarantee integrity) and make the other services trust this token.
I've read almost every answer on SO and some blog postings, but I can't figure out one simple thing. In a simple token authentication scheme where the server generates a token and sends it back to the user after verifying credentials, how does the client store and then resend that token in each request? I have seen both cookie examples and header examples. I would like to use the HTTP Headers if possible, but I can't figure out the mechanics of how to send the token to the client, where it will sit, and then have it sent back in the header upon requesting a REST resource.
I am using Jersey/Guice with AngularJS on the front end. Here are the resources I started with:
http://porterhead.blogspot.co.uk/2013/01/writing-rest-services-in-java-part-6.html
Session management : How to generate Authentication token for REST service ? (Jersey)
It depends on your needs. You can use HTTP basic or digest auth, if it is appropriate for you. If not, then if you don't need a permanent storage, you can store credentials in memory. If you need a permanent storage, then you can store them in localstorage, or any other client side storage, but aware, that they are considered not secure.
Anyways I think if your client or service is compromised somehow with xss, then you lost, and it does not matter what else you do about it. Otherwise you can send the credentials in plain text securely as long as you use HTTPS with proper settings. (But that's just an opinion, I am not a security expert, at least not in this topic.) So I think you should concentrate on not being xss vulnerable. For example you should use the proper headers and filter the input against js injection (and by firefox data URI injection). And use TextNode in your client instead of innerHTML wherever it is possible.
For example if you are using Javascript you can store the token in localstorage like window.localStorage["token_id"] on the client side.
The silverlight enabled WCF Service communication is secured using a USB token/smartcard. The first access has to be confirmed by entering a PIN. Once authenticated, a malicious website could start CSRF requests to the WCF service using IMG-Tags and/or JavaScript. According to the Security Guidance for Writing and
Deploying Silverlight Applications, a usual technique here is to use (session-)tokens or a so called "nonce", while checking the HTTP Referrer header has proven to be insecure.
I understand the idea behind this, to my understanding it works well if you have a single form (i.e. contact form) and a single service where you can ensure that a user has to see and fill out the form before sending. In a Silverlight application, I'm not able to predefine such kind of sequence, many requests (like requesting a price update for a product) can be started in an arbitrary order.
Do you have some advices how I should secure the Silverlight to WCF communication to prevent CSRF attacks, ensuring that an already authenticated caller requests from a trusted site?
One option could be:
Provide a service that when called, created a nonce and stores it on the users session on the server, and returns it to the calling application
On every request after this one, include the nonce as a URL parameter or in the POSTed body of the request (or within any other type of message you use)
Check for this nonce for every request to the server
An attacker could not trick this, because if he called the mentioned service he would get a different token for their own session. And as long as this nonce is not stored in a cookie, it will not be automatically submitted by the browser upon requests to the server. So as long as the attacker cannot guess the nonce (use a cryptographically secure random to generate it), this should work.