Is it possible to send data from a client to a server without the API being public? - flask

I'm currently trying to make an account signup page for a small project I'm working on and I don't know how to send data back to the server (I'm using the Flask framework) without also allowing everyone to send data. Let's say that I've set up an API endpoint on /createAccount. I can then send POST requests to that endpoint: {"username": "test", "password": "test"}. The web server will then handle that request by inserting that data into a database and responding with 201. The problem is, anybody would be able to send these requests, and I only want users to be able to register through the login page, and not by making an API call. Is there any way of doing this?
Edit: I've given this problem a bit more thought and I think that the only API that is difficult to secure is the signup API. When a user has created an account, I can just assign them an API key, which they will send to the API every time they want to make a request, which means that an account is required to make API calls. If a certain key is making too many requests, they can be rate limited or temporarily banned from making further requests. The problem with the signup API however, is that there is no information by witch a request sender could be identified. I could use the IP address, but that can be changed and wouldn't really help if multiple IPs are spamming the API at the same time. Is there a way I can identify non-registered users?

Short answer: no.
You have to check data to make sure the account being created is something legit and not trash data to fill your database or any other malicious intents.
This is the reason you usually have to confirm an account clicking on a confirmation link sent to your mail: this way the app is sure that your account is legit.
You could also check info on the front end, but that is never as secure as back end checking, because of your concern in the question: in the end, anyone who gets to know your endpoints could potentially send direct requests to your server with whatever data they wanted.

Assuming you have a trusted source of registrations, an if that source can make an ssh connection to the server where your Flask app is running, an alternative to trying to lock down a registration API is to provide a command line script to do the registration.
The trusted source does something like
ssh someuser#youripaddress /path/to/register.py "username" "password" "other info"
If you use a Flask custom command you can share model definitions db configuration.

Related

Advice how to implement a simple user login and authenication

We are in the process of building a simple Android application together with a simple back-end web server to allow the user to get some information form the server.
We need to login the user, to make sure he is authorized to view the data, but apart form that I do not think we have particular security concerns.
I need some advice on how we can implement the server to keep things as simple as possible.
For example, we could use something like this to make sure the user is authorized to see the data:
http://ourwebservice/user/password/viewsuchandsuchdata
Is that a good way of doing things?
Do you have any suggestions or comments?
There are many ways to secure web-services.
The simplest is possible "Basic Auth" (http://en.wikipedia.org/wiki/Basic_access_authentication). On every request, you send the user credentials in the "Authorization" HTTP header concatenated with ":" and base 64 encoded. To keep it safe, you need to make sure the connection to your web-server is using SSL (HTTPS), otherwise the user password could be intercepted.
Another "newer" solution is OAuth2, and in your case the "Resource Owner Credentials" flow. Instead of passing the user credentials on every request, you use them once to "exchange" them for a short-lived access token issued by your server. Then on any request to the web-service you pass that access token in lieu of authentication. The server must then verify that the token is valid and find out for which user it was issued. For more info see this article: http://aaronparecki.com/articles/2012/07/29/1/oauth2-simplified.
There are potentially many more "custom" ways of doing authentication...
Going the OAuth2 flow is probably more difficult but there are lots of open-source libraries out there to help you build a OAuth2 provider (http://oauth.net/2/). The advantage is that you don't have to store the user password on the device, which is safer (the less you touch passwords, the better).

Choosing the right place to write logic in a client/api/server solution

I'm currently designing a solution with this pretty standard pattern:
1 web-app using Django (it hosts the one and only DB)
1 client mobile app using AngularJS
This client app uses a REST API (implemented on the Django Server with Tastypie) to get and set data.
As a beginner in these architectures, I'm just asking myself where the logic should go and I'd like to use a simple example case to answer my concerns:
On the mobile client App, a client is asked to subscribe by entering only an email address in a form.
a) If the address is unused, inscription is done (stuff is written on the DB).
b) If the address is used, an error is raised, and the user is asked to try again.
What is the workflow to perform these simple operations?
I'm asking for example how to compare the entered e-mail address in the mobile app with the existing e-mail adresses in my DB:
Should I GET the list of all email adresses from the server, then perform the logic in my client app to state if the entered address already exists ? This seems really a bad way to do because getting lots of elements isn't performant with web services, and client should not be able to see all email adresses.
Should I send the entered e-mail address to the server and let it make the comparison? But if yes, how am I supposed to send the data? As far as I know, PUT/POST are made to write in the DB, not to just send data to server to analyse it and proceed some logic.
I have the feeling I am clearly missing something here...
Thanks a lot for help.
PUT and POST are designed to be used to create and update resources. The server may or may not have a database behind it. It might use a local filesystem, or it might handle anything in memory. It's none of the client's business. It is certainly common to have business logic on most servers which provide APIs.
Use PUT/POST to send up the email address to the server. The server checks to see if the email address is (a) valid, and (b) allowed. If it fails either check, return a relevant response to the client as documented in the RFC. I would go with 403 Forbidden, which indicates a problem with the data being sent up to the server. Use the entity in the response to detail what the problem was with the request.
I had done similar thing in a angular web app,
I have disabled the submit button, and added a check availability button beside the email field.
I have send the email to server and checked if it already exist and got the result to client,
then asked the user to enter an alternate email if not valid or enable the form's submit button
Alternatively
when the user leaves the email field, You can send the email to a service that validates the email, and get the response, and show a message that this email already exist and disable the submit, or enable the submit button otherwise

How to approach this issue with django

I just started of in Django and want to implement this. But not sure whether my approach is correct or not. Can you validate?
Requirement : My Server will provide a service via an url endpoint. Client will authenticate (with id and password supplied to him via separate channel. So, no signup page available) with his credentials and avail the service. i will do the work asynchronously and reply with status.
My Approach.
. Client will be provided a username and password via separate channel.
. Client will do an https connection.
. Client will encrypt the password with my public Key and will call my URL endpoint with id, password, data.
. i will acknowledge the request and will ping client back when the work is done.
Things i am worried about:
. how to stop snoopers from replacing the data portion and reforwarding the request to me.
. how to stop snoopers from reusing the encrypted password from original request and sending their own request.
Are there any frameworks which will provide this support inbuilt?
OR
This will not occur at all in my current setup?
I know Django provides an authentication module. But not sure about its capabilities.
The framework will help you enable security at an application level. You can use Django to help you ensure that only users that have been properly authenticated will be granted access to restricted pages and provides a number of other security measures out of the box.
Replay attacks will typically be prevented by using sessions, which is well documented by Django.
Based on the description of your implementation, the greatest source of concern would be the statement "client will be provided a username and password via separate channel".

embedded linux clients and authentication

I need to come up with a scheme for remote devices running linux to push data to a web service via https. I'm not sure how I want to handle authentication. Can anyone see any security risks by including some kind of authentication in the body of the request itself? I'm thinking of having the request body be JSON, and it would look like this:
{
'id':'some unique id',
'password':'my password',
'data':1234
}
If the id and password in the JSON don't match what is in my database, the request gets rejected.
Is there a problem with this? Is there a better way to ensure that only my clients can push data?
That scheme is primitive, but it works.
Usually a real session is preferred since it offers some advantages:
separation of authentication and request
history of requests in a session
credentials get sent only once for multiple requests
flexible change of authentication strategy
...

Securing REST API without reinventing the wheel

When designing REST API is it common to authenticate a user first?
The typical use case I am looking for is:
User wants to get data. Sure cool we like to share! Get a public API key and read away!
User wants to store/update data... woah wait up! who are you, can you do this?
I would like to build it once and allow say a web-app, an android application or an iPhone application to use it.
A REST API appears to be a logical choice with requirements like this
To illustrate my question I'll use a simple example.
I have an item in a database, which has a rating attribute (integer 1 to 5).
If I understand REST correctly I would implement a GET request using the language of my choice that returns csv, xml or json like this:
http://example.com/product/getrating/{id}/
Say we pick JSON we return:
{
"id": "1",
"name": "widget1",
"attributes": { "rating": {"type":"int", "value":4} }
}
This is fine for public facing APIs. I get that part.
Where I have tons of question is how do I combine this with a security model? I'm used to web-app security where I have a session state identifying my user at all time so I can control what they can do no matter what they decide to send me. As I understand it this isn't RESTful so would be a bad solution in this case.
I'll try to use another example using the same item/rating.
If user "JOE" wants to add a rating to an item
This could be done using:
http://example.com/product/addrating/{id}/{givenRating}/
At this point I want to store the data saying that "JOE" gave product {id} a rating of {givenRating}.
Question: How do I know the request came from "JOE" and not "BOB".
Furthermore, what if it was for more sensible data like a user's phone number?
What I've got so far is:
1) Use the built-in feature of HTTP to authenticate at every request, either plain HTTP or HTTPS.
This means that every request now take the form of:
https://joe:joepassword#example.com/product/addrating/{id}/{givenRating}/
2) Use an approach like Amazon's S3 with private and public key: http://www.thebuzzmedia.com/designing-a-secure-rest-api-without-oauth-authentication/
3) Use a cookie anyway and break the stateless part of REST.
The second approach appears better to me, but I am left wondering do I really have to re-invent this whole thing? Hashing, storing, generating the keys, etc all by myself?
This sounds a lot like using session in a typical web application and rewriting the entire stack yourself, which usually to me mean "You're doing it wrong" especially when dealing with security.
EDIT: I guess I should have mentioned OAuth as well.
Edit 5 years later
Use OAuth2!
Previous version
No, there is absolutely no need to use a cookie. It's not half as secure as HTTP Digest, OAuth or Amazon's AWS (which is not hard to copy).
The way you should look at a cookie is that it's an authentication token as much as Basic/Digest/OAuth/whichever would be, but less appropriate.
However, I don't feel using a cookie goes against RESTful principles per se, as long as the contents of the session cookie does not influence the contents of the resource you're returning from the server.
Cookies are evil, stop using them.
Don't worry about being "RESTful", worry about security. Here's how I do it:
Step 1: User hits authentication service with credentials.
Step 2: If credentials check out, return a fingerprint, session id, etc..., and pop them into shared memory for quick retrieval later or use a database if you don't mind adding a few milliseconds to your web service turnaround time.
Step 3: Add an entry point call to the top of every web service script that validates the fingerprint and session id for every web service request.
Step 4: If the fingerprint and session id aren't valid or have timed out redirect to authentication.
READ THIS:
RESTful Authentication
Edit 3 years later
I completely agree with Evert, use OAuth2 with HTTPS, and don't reinvent the wheel! :-)
By simpler REST APIs - not meant for 3rd party clients - JSON Web Tokens can be good as well.
Previous version
Use a cookie anyway and break the stateless part of REST.
Don't use sessions, with sessions your REST service won't be well scalable... There are 2 states here: application state (or client state or session s) and resource state. Application state contains the session data and it is maintained by the REST client. Resource state contains the resource properties and relations and is maintained by the REST service. You can decide very easy whether a particular variable is part of the application state or the resource state. If the amount of data increases with the number of active sessions, then it belongs to the application state. So for example user identity by the current session belongs to the application state, but the list of the users or user permissions belongs to the resource state.
So the REST client should store the identification factors and send them with every request. Don't confuse the REST client with the HTTP client. They are not the same. REST client can be on the server side too if it uses curl, or it can create for example a server side http only cookie which it can share with the REST service via CORS. The only thing what matters that the REST service has to authenticate by every request, so you have to send the credentials (username, password) with every request.
If you write a client side REST client, then this can be done with SSL + HTTP auth. In that case you can create a credentials -> (identity, permissions) cache on the server to make authentication faster. Be aware of that if you clear that cache, and the users send the same request, they will get the same response, just it will take a bit longer. You can compare this with sessions: if you clear the session store, then users will get a status: 401 unauthorized response...
If you write a server side REST client and you send identification factors to the REST service via curl, then you have 2 choices. You can use http auth as well, or you can use a session manager in your REST client but not in the REST service.
If somebody untrusted writes your REST client, then you have to write an application to authenticate the users and to give them the availability to decide whether they want to grant permissions to different clients or not. Oauth is an already existing solution for that. Oauth1 is more secure, oauth2 is less secure but simpler, and I guess there are several other solution for this problem... You don't have to reinvent this. There are complete authentication and authorization solutions using oauth, for example: the wso identity server.
Cookies are not necessarily bad. You can use them in a RESTful way until they hold client state and the service holds resource state only. For example you can store the cart or the preferred pagination settings in cookies...