How to secure my API against "fictitious" payload? - security

I have developed an app for Android/iOS which calculates a value based on the users input. If an event occurs, this calculated value will be sent to my Backend as normal HTTPS payload. My question is now, how can I make sure, that this value is really only calculated by the source code of my app? Is there a way to handle such a problem?
To make it clear: I want to avoid, that somebody is rooting his phone, extract the Auth-Token from the private storage of my app and sends a valid HTTPS-Payload to my Backend with fictitious payload, manually or by manipulating the source code.
From the view of the backend, it's difficult to evaluate the payload based on its values if it is valid or not.
Any suggestions appreciated!
----------EDIT-----------
For the sake of completeness: apart from the answers here, the following are also very interesting:
Where to keep static information securely in Android app?
How to secure an API REST for mobile app? (if sniffing requests gives you the "key")

You can’t trust data coming from the client. Period.
You should consider moving the calculation logic to the server and just sending the raw values needed to perform the calculation. You can easily get sub-second response times sending the data to the server, so the user won’t notice a lag.
If you need offline connectivity, then you’ll need to duplicate the business logic on both the client and the server.

Short of doing everything on the backend, you can't very easily.
I'd recommend some reading around CSRF (Plenty of articles floating around) as that's at least a good mitigation against bots outside of your app domain hitting your backend. The upshot is that your application requests a unique, random, identifier from your backend (which ideally would be tied to the user's auth token) before submitting any data. This data is then submitted with your app's data to perform the calculation on the backend. The backend would then check this against the random identifier it sent for that user earlier and if it doesn't match, then reject it with a 400 (Bad Request), or 404 if you're paranoid about information leakage.

Related

Is this an acceptable approach to refreshing JWTs?

I'm in the process of rebuilding an existing web app, that uses JWTs to manage authentication. I'm still new to JWTs, so I'm learning about how they should work, while, at the same time, trying to understand why the web app's current implementation is the way it is.
The current version's flow is as follows:
When a user successfully logs in or registers, a user object is returned along with a JWT property. This JWT is included in subsequent API calls as an Authorization header.
Every ten minutes, a get request is made to API endpoint /refresh-token.
If successful, the response body contains a success message, and the response header contains an updated Authorization header.
All subsequent ten-minute timed get requests to /refresh-token use the original JWT that was returned in step 1, and so on.
From what I've read so far, this doesn't correlate with any recommended approaches.
Is it safe enough to replicate this flow in the newer version, or is this something I'm better off not replicating?
Edit: I'm working solely on the front-end - the API isn't being updated for a while, so I'm limited to what it currently returns.
I believe this article summarizes the current state of the art: https://auth0.com/blog/refresh-tokens-what-are-they-and-when-to-use-them/. You usually have two tokens. Access token which is short lived and an refresh token, which lives longer. This way you don't need to call the auth server every x minutes, but you can do it on demand.
I don't know if you need to deal with blacklisting too? I believe blacklisting is easier when you have a separation of access token and refresh token (only refresh token needs to be blacklisted). But I believe you could deal with this problem too, probably in a bit more sophisticated manner.
Having said that. What you have is not wrong. It's hard for me to point out any flaws in the way you are doing besides of what has been pointed out above.

Rest API real time Tricky Question- Need Answer

I was recently interviewed by a MNC technical panel and they asked me different questions related to RestAPI , i was able to answer all but below 2 questions though i answered but not sure if those are correct answers. Can somebody answer my queries with real time examples
1) How can i secure my Rest API when somebody send request from Postman.The user provides all the correct information in the header like session id, Token etc.
My answer was: The users token sent in the header of the request should be associated with the successfully authenticated user info then only the user will be granted access if the Request either comes from Postman or application calls these API.(The panel said no to my answer)
2) How can i handle concurrency in Rest API Means if multiple users are trying to access the API at the same given time (For e.g multiple post request are coming to update data in a table) how will you make sure one request is served at one time and accordingly the values are updated as requested by different user request.
2) My answer was: In Entitiy framework we have a class called DbUpdateConcurrencyException, This class takes of handling concurrency and serves one request is served at a time.
I am not sure about my both the above answers and i did not find any specific answer on Googling also.
Your expert help is appreciated.
Thanks
1) It is not possible, requests from Postman or any other client or proxy (Burp, ZAP, etc) are indistinguishable from browser requests, if the user has appropriate credentials (like for example can observe and copy normal requests). It is not possible to authenticate the client application, only the client user.
2) It would be really bad if a web application could only serve one client at a time. Think of large traffic like Facebook. :) In many (maybe most?) stacks, each request gets its own thread (or similar) to run, and that finishes when the request-response ends. These threads are not supposed to directly communicate with each other while running. Data consistency is a requirement of the persistence technology, ie. if you are using a database for example, it must guarantee that database queries are run one after the other. Note that if an application runs multiple queries, database transactions or locks need to be used on the database level to maintain consistency. But this is not at all about client requests, it's about how you use your persistence technology to achieve consistent data. With traditional RDBMS it's mostly easy, with other persistence technologies (like for example using plaintext files for storage) it's much harder, because file operations typically don't support a facility similar to transactions (but they do support locks, which you have to manage manually).

Is there a way to protect an API route from being hit by an authenticated user outside of an app making requests?

I'm making an angular app that has users log in, make progress, then they are awarded levels/experience points. I'm using a nodejs/express API and I want to be able to make a call from my app to award them exp. I'm using a JWT and server signing with a private key to auth requests, but realized that a user could just pull their token and give themselves experience. My question would be is there anyway to protect my route from that or is that a fundamental flaw in design?
I don't believe this is something you can do specifically with JWT. As commenters have already said, JWT just provides access rights for the given token. As you say yourself, it would be simple enough to just read the traffic and send their own requests to jack up their exp.
While your basic authentication/authorisation mechanism can't solve this, you can handle it in some other fashion within, for example, the request payload itself.
You could encrypt and/or sign your payloads - given that the app would need to know or receive key(s) to use, it's possible that with enough investigation that this is eventually found and duplicated as well. But it's another step someone would have to go through and replicate.
You could employ additional checks and measures - have your requests for [exp increase] be a two-step process; the server responds to the initial request with some minor task to be solved that is then attached to the follow-up request. Assuming the task is done properly, you can be reasonably sure that it came from your app as your app knows how to solve the problems issued (or someone with a serious lack of hobbies outside of deconstructing your entire application).
You could limit the amount of exp that should be reasonably achievable by your users. If you know that people should, at most, be able to gain xyz exp per minute/hour/day/etc, then by monitoring exp growth, you can flag and/or block additional gains past this point.

XSS Protection in Express Apps

I am developing an express app which serves as a REST api with web client and may be future mobile clients. I am using a Oauth 2.0 token authentication for both clients. This gives a good deal of security against CSRF. I want to know How to provide security against XSS.
*I made the tokens validity period very less, requiring the client to request with refresh_tokens and other client details for access_tokens. This makes it a bit safe but not entirely*.
I am concerned with the with client_id and client_secret being stolen since its present in the front-end javascript code and it being used by other client to validate. I am thinking of using a JWT for the client authentication, will this be helpful?
Data Sanitisation is another which I am confused about. There are modules like validator, express-validator which give regex validation. According to this blog post JSON Schema validations are fast. In the REST Api JSON will used for data exchange so I was wandering why can't I use modules like tv4 or any other JSON Schema validators for data validations?? I am not asking for suggestions to use what, I just want to know the basic difference in the kind of validations each provide and specially from a point of view of XSS protection and sanitisation.
So you have three separate questions here:
1) How to protect against XSS: As long as you use JSON to share data between the client & server and use standard libraries/methods for encoding/decoding JSON, you are mostly protected. After this, you only need to worry about DOM Based XSS, which is harder to be protected. But basically you need to be careful for not using any user supplied input that can be interpreted as anything other than "string" you intended. (please visit https://www.owasp.org/index.php/DOM_Based_XSS for more information)
2) client_id and client_secret being stolen: This does not seem to be possible in the way you require. In your scenario (where you distribute clientid&secret in javascript code) there is no way on server side to know whether the request is coming from your client or a fake one.
3) Data Sanitisation: I see two levels of sanitisation in the libraries you & blogpost mentioned. validator or express-validator is mostly used to validate individual data fields. Whereas others can validate a JSON object structure in addition to what "validator" does. If you require all exchanged data is in JSON format (as suggested for XSS protection as well) then you can use json object validators like tv4. (the only drawback of tv4 seems to be allowing latest json spec, which should not be a problem for you)
BTW: It would be easier if you specified your client application is purely client-side javascript (angularjs). I could not understand your question until I found this info in comments.
I have developed Restful Authentication System same as your case with NodeJS, MongoDB, ExpressJS in order to provide flexible authentication system for multiple clients like web, mobile. Let me summarize you the important points.
I have used html5 localstorage to keep user token after first time login by using login form. When user click login button, username and password sent to server and validated. After successfull validation, unique access token sent to client and stroed in local sotrage. If you have vulnerability on your client application, anyone can get your access token and make request by using your token. In order to prevent this, you need to use ssl connection for your app. This problem does not exists only restful auth systems, this can be happen in server side session storage. Let me explain this. I am using PHP for session. When user logs in, user session saved in to temp file on server and that session id sent to client browser. Somehow, if I can get that id, I can make request with header that contains someone's session id. When you compare, restful auth seems more flexible to me. I suggest you to ;
Use SSL connection prevent your access_token from to be stolen
Generate access token with powerfull encryption methods(SHA-256)
Small expire time for access_token the better
Implement a middleware for token validation for backend service usage. I mean make your requests like;
/use/update/{userid}
with custom headers contains your user token.
Design 5 attempt failed system for your backend. If user cannot success at 5 time try, this means someone tries to send random tokens in order to get in to system. Detect and block that IP
You can also deny requests other than browser clients.
Those are the informations that I have learnt while implementing the project.

Anyone know of a secure way to give Browser access to a specific view result set on a couchdb database

I am using CouchDB for my Data Layer in a Rails 3 application using CouchRest::Model hosted on Heroku.
I am requesting a List of Documents and returning them as JSON to my Browser and using jQuery Templates to represent that data.
Is there a way I could build the request on the server side, and return the request that would need to be called from the browser WITHOUT opening a huge security hole i.e. giving the browser access to the whole database?
Ideally it would be a one off token access to a specific query, Where the token would be generated on the server side, and CouchDB would take the token, and make sure it matches what the query should be, and give access to the results.
One way that comes to mind would be to generate a token Document and use a show function (http://guide.couchdb.org/draft/show.html) to return the results for that token Document's view results. Though I am not sure if that is possible.
Though another is to put a token on the Document itself and use a list function (http://guide.couchdb.org/draft/transforming.html)
Save that, any other ideas?
Thanks in Advance
Is there a way I could build the
request on the server side, and return
the request that would need to be
called from the browser WITHOUT
opening a huge security hole i.e.
giving the browser access to the whole
database?
Yes. One method is to create a rack app and mount it inside your rails app. You can have it receive requests from users' browsers at "/couch" and forward that request to your "real" couchdb url, returning couch's JSON response as-is or modifying it however you need.
You may also be able to use Couch's rewrite and virtual host features to control what Couch URLs the general public is able to reach. This probably will necessitate the use of list or show functions. http://blog.couchone.com/post/1602827844/of-rewrites-and-virtual-hosting-an-introduction
Ideally it would be a one off token access to a specific query, Where the token would be generated on the server side, and CouchDB would take the token, and make sure it matches what the query should be, and give access to the results.
You might use cookies for this since list and show functions can set and get cookie values on requests.
But you could also include a hash value as part of each request. Heroku's add-on API has a good example of how this works. https://addons.heroku.com/provider/resources/technical/build/sso
Notice that the API calls are invalid outside of a certain window of time, which may be exactly what you need.
I'm not sure I precisely understand your needs, but I hope I have been able to give you some helpful ideas.

Resources