I am making a web application in python and I would like to have a secure login system.
I have done login systems many times before by having the user login and then a random string is saved in a cookie which is also saved next to that user in a database which worked fine but it was not very secure.
I believe understand the principles of an advanced system like this but not the specifics:
Use HTTPS for the login page and important pages
Hash the password saved in the database(bcrypt, sha256? use salt?)
Use nonces(encrypted with the page url and ip?)
But apart from those I have no idea how to reliably check if the person logged in is really the user, or how to keep sessions between page requests and multiple open pages securely, etc.
Can I have some directions (preferably specific ones since I am new to this advanced security programming.
I am just trying to accomplish a basic user login-logout to one domain with security, nothing too complicated.
This answer mainly addresses password hashing, and not your other subquestions. For those, my main advice would be don't reinvent the wheel: use existing frameworks that work well with GAE. It offers builtin deployments of Django, but also has a builtin install of WebOb, so various WebOb-based frameworks (Pyramid, Turbogears, etc) should also be considered. All of these will have premade libraries to handle a lot of this for you (eg: many of the WebOb frameworks use Beaker for their cookie-based session handling)
Regarding password hashing... since you indicated in some other comments that you're using Google App Engine, you want to use the SHA512-Crypt password hash.
The other main choices for storing password hashes as securely as possible are BCrypt, PBKDF2, and SCrypt. However, GAE doesn't offer C-accelerated support for these algorithms, so the only way to deploy them is via a pure-python implementation. Unfortunately, their algorithms do way too much bit-fiddling for a pure-python implementation to do a fast enough job to be both secure and responsive. Whereas GAE's implementation of the Python crypt module offers C-accelerated SHA512-Crypt support (at least, every time I've tested it), so it could be run at sufficient strength.
As far as writing actual code goes, you can use the crypt module directly. You'll need to take care of generating your own salt strings when passing them into crypt, and when encrypting new passwords, call crypt.crypt(passwd, "$6$" + salt). The $6$ tells it to use SHA512-Crypt.
Alternately, you can use the Passlib library to handle most of this for you (disclaimer: I'm the author of that library). For quick GAE deployment:
from passlib.context import CryptContext
pwd_context = CryptContext(schemes=["sha512_crypt"],
default="sha512_crypt",
sha512_crypt__default_rounds=45000)
# encrypt password
hash = pwd_context.encrypt("toomanysecrets")
# verify password
ok = pwd_context.verify("wrongpass", hash)
Note: if care about password security, whatever you do, don't use a single HASH(salt+password) algorithm (eg Django, PHPass, etc), as these can be trivially brute-forced.
It's hard to be specific without knowing your setup. However, the one thing you should not do is reinventing the wheel. Security is tricky, if your wheel is lacking something you may not know until it's too late.
I wouldn't be surprised if your web framework came with a module/library/plugin for handling users, logins and sessions. Read its documentation and use it: it was hopefully written by people who know a bit about security.
If you want to know how it's done, study the documentation and source of said module.
Related
The attack
One possible threat model, in the context of credential storage, is an attacker which has the ability to :
inspect any (user) process memory
read local (user) files
AFAIK, the consensus on this type of attack is that it's impossible to prevent (since the credentials must be stored in memory for the program to actually use them), but there's a couple of techniques to mitigate it:
minimize the amount of time the sensitive data is stored in memory
overwrite the memory as soon as the data is not needed anymore
mangle the data in memory, keep moving it, and other security through obscurity measures
Python in particular
The first technique is easy enough to implement, possibly through a keyring (hopefully kernel space storage)
The second one is not achievable at all without writing a C module, to the best of my knowledge (but I'd love to be proved wrong here, or to have a list of existing modules)
The third one is tricky.
In particular, python being a language with very powerful introspection and reflection capabilities, it's difficult to prevent access to the credentials to anyone which can execute python code in the interpreter process.
There seems to be a consensus that there's no way to enforce private attributes and that attempts at it will at best annoy other programmers who are using your code.
The question
Taking all this into consideration, how does one securely store authentication credentials using python? What are the best practices? Can something be done about the language "everything is public" philosophy? I know "we're all consenting adults here", but should we be forced to choose between sharing our passwords with an attacker and using another language?
There are two very different reasons why you might store authentication credentials:
To authenticate your user: For example, you only allow the user access to the services after the user authenticates to your program
To authenticate the program with another program or service: For example, the user starts your program which then accesses the user's email over the Internet using IMAP.
In the first case, you should never store the password (or an encrypted version of the password). Instead, you should hash the password with a high-quality salt and ensure that the hashing algorithm you use is computationally expensive (to prevent dictionary attacks) such as PBKDF2 or bcrypt. See Salted Password Hashing - Doing it Right for many more details. If you follow this approach, even if the hacker retrieves the salted, slow-hashed token, they can't do very much with it.
In the second case, there are a number of things done to make secret discovery harder (as you outline in your question), such as:
Keeping secrets encrypted until needed, decrypting on demand, then re-encrypting immediately after
Using address space randomization so each time the application runs, the keys are stored at a different address
Using the OS keystores
Using a "hard" language such as C/C++ rather than a VM-based, introspective language such as Java or Python
Such approaches are certainly better than nothing, but a skilled hacker will break it sooner or later.
Tokens
From a theoretical perspective, authentication is the act of proving that the person challenged is who they say they are. Traditionally, this is achieved with a shared secret (the password), but there are other ways to prove yourself, including:
Out-of-band authentication. For example, where I live, when I try to log into my internet bank, I receive a one-time password (OTP) as a SMS on my phone. In this method, I prove I am by virtue of owning a specific telephone number
Security token: To log in to a service, I have to press a button on my token to get a OTP which I then use as my password.
Other devices:
SmartCard, in particular as used by the US DoD where it is called the CAC. Python has a module called pyscard to interface to this
NFC device
And a more complete list here
The commonality between all these approaches is that the end-user controls these devices and the secrets never actually leave the token/card/phone, and certainly are never stored in your program. This makes them much more secure.
Session stealing
However (there is always a however):
Let us suppose you manage to secure the login so the hacker cannot access the security tokens. Now your application is happily interacting with the secured service. Unfortunately, if the hacker can run arbitrary executables on your computer, the hacker can hijack your session for example by injecting additional commands into your valid use of the service. In other words, while you have protected the password, it's entirely irrelevant because the hacker still gains access to the 'secured' resource.
This is a very real threat, as the multiple cross-site scripting attacks have shows (one example is U.S. Bank and Bank of America Websites Vulnerable, but there are countless more).
Secure proxy
As discussed above, there is a fundamental issue in keeping the credentials of an account on a third-party service or system so that the application can log onto it, especially if the only log-on approach is a username and password.
One way to partially mitigate this by delegating the communication to the service to a secure proxy, and develop a secure sign-on approach between the application and proxy. In this approach
The application uses a PKI scheme or two-factor authentication to sign onto the secure proxy
The user adds security credentials to the third-party system to the secure proxy. The credentials are never stored in the application
Later, when the application needs to access the third-party system, it sends a request to the proxy. The proxy logs on using the security credentials and makes the request, returning results to the application.
The disadvantages to this approach are:
The user may not want to trust the secure proxy with the storage of the credentials
The user may not trust the secure proxy with the data flowing through it to the third-party application
The application owner has additional infrastructure and hosting costs for running the proxy
Some answers
So, on to specific answers:
How does one securely store authentication credentials using python?
If storing a password for the application to authenticate the user, use a PBKDF2 algorithm, such as https://www.dlitz.net/software/python-pbkdf2/
If storing a password/security token to access another service, then there is no absolutely secure way.
However, consider switching authentication strategies to, for example the smartcard, using, eg, pyscard. You can use smartcards to both authenticate a user to the application, and also securely authenticate the application to another service with X.509 certs.
Can something be done about the language "everything is public" philosophy? I know "we're all consenting adults here", but should we be forced to choose between sharing our passwords with an attacker and using another language?
IMHO there is nothing wrong with writing a specific module in Python that does it's damnedest to hide the secret information, making it a right bugger for others to reuse (annoying other programmers is its purpose). You could even code large portions in C and link to it. However, don't do this for other modules for obvious reasons.
Ultimately, though, if the hacker has control over the computer, there is no privacy on the computer at all. Theoretical worst-case is that your program is running in a VM, and the hacker has complete access to all memory on the computer, including the BIOS and graphics card, and can step your application though authentication to discover its secrets.
Given no absolute privacy, the rest is just obfuscation, and the level of protection is simply how hard it is obfuscated vs. how much a skilled hacker wants the information. And we all know how that ends, even for custom hardware and billion-dollar products.
Using Python keyring
While this will quite securely manage the key with respect to other applications, all Python applications share access to the tokens. This is not in the slightest bit secure to the type of attack you are worried about.
I'm no expert in this field and am really just looking to solve the same problem that you are, but it looks like something like Hashicorp's Vault might be able to help out quite nicely.
In particular WRT to the problem of storing credentials for 3rd part services. e.g.:
In the modern world of API-driven everything, many systems also support programmatic creation of access credentials. Vault takes advantage of this support through a feature called dynamic secrets: secrets that are generated on-demand, and also support automatic revocation.
For Vault 0.1, Vault supports dynamically generating AWS, SQL, and Consul credentials.
More links:
Github
Vault Website
Use Cases
I'm trying to understand OAuth, and I'm having a hard time figuring this basic thing out...
I have developed a service (with Python and Flask), which supports classic authentification through a dedicated login & password combination, and an "official" client in the form of a webapp. I would like my service to support OAuth and looked into flask-oauthprovider, which seems like a perfect fit for this task, but I can't seem to understand how everything should articulate.
My questions are:
Today, all my API entry points required the user to be logged in: once my service supports OAuth, should every entry points become "oauth_required" rather than "login_required"?
What is the proper way to support my "official" webapp front-end? I'd rather not have it go through the regular OAuth flow (with the extra redirections to login on the service). Should it go through OAuth with automatically granted access tokens, or should it bypass OAuth and directly use the "resource owner" login & password?
I think one of the problems with the concept behind oauthlib is that it tries too hard to be everything and the result is a difficult-to-reason-about set of abstractions (this is very similar to the python-oauth2 approach). OAuth providers in particular are tricky because you implicitly need to persist things like tokens not to mention the assumption of some kind of pre-exisiting user management. As such a "good" or idiomatic implementation tends to be more opinionated from framework to framework. In my opinion this is part of why we don't see a single Python OAuth provider implementation as an abstraction: there just aren't great solutions, but plenty of messy ones. Looking at flask-oauthprovider and we see some direct examples of these issues. I've had similar problems with flask-login, which I maintain. At any rate, this past weekend I wrote a very rough first pass of a OAuth provider in Flask that "just works"; feel free to take a look and adapt it to your needs. It assumes some things like, like MongoDB but with minimal work I think any datastore could be used.
1) Protect whichever endpoints you want to be accessible via a third-party, e.g. your public API.
2) I would avoid automatic access tokens, that defeats the person of negotiating authorization on a per-user basis, unless of course you have a different scheme, e.g. a predefined set of clients. I believe the second option you're talking about is xauth, in which case, why not just use OAuth 2.0 and grant_type=password? Bearer tokens are similar in concept but may be a little easier to implement so long as you can provide HTTPS.
It seems like the security model fits very small projects, but that it is probably not feasible to write all possible registered users' hashed passwords in security.py. Do you know any examples of scaling up Pyramid's authentication, or are there any benefits to calling through Pyramid's security scheme into my own database of security information?
I dont think the size of the project is related to the security model. Either you want a simple or a complex security model. Both can be applied to projects of any size. One of Pyramid's strong points is its extensibility.
Why would you store hashed passwords in security.py? (cmiiw here, I probably misunderstood) If you read this on someone's code, that's probably just an example. In real apps, you save them in a storage/persistence system of your choice.
Again, I don't understand what you mean by "scaling up authentication". My guess is you want some working examples:
tutorial from the docs
shootout application: small and good example with forms
pyramid auth demo: complex/granular/row-level permission
pyramid apex: 3rd party auth (google, twitter, etc) with velruse, forms etc
pyramid registration: unfinished library; you can steal some ideas from it
No idea what your needs are or what you mean by "scaling up security", but pyramids authentication policy is very flexible. You need to understand though that it doesn't maintain users and passwords it merely provides a mechanism for obtaining a user identifier from the incoming request. For example, the AuthTktAuthenticationPolicy keeps track of the user id by cookie that you set using the remember method.
What meaningful information you derive from that user id is totally up to you and is application specific.
So really the question you may want to ask is can your application "scale up security".
I can't show you code because it's proprietary but I've needed to support openid, http auth and your typical db backed user store on the same application, with the extra added complication that users are stored in different database shards and the shard can't be immediately determined. It takes very little code to support this.
I ended up building something for myself that makes authentication a little easier if you happen to be using MongoDB.
https://github.com/mosesn/mongauth
It isn't built into pyramid, but hooks in easily enough. Everything is pretty transparent.
I'm looking at building a website using Web.py, and there is no built-in authentication system. Having read various things about authentication on websites, a common theme I keep hearing is "Don't roll your own, use someone else's." There are some examples of simple authentication on the site, like this one, but they all say at the bottom "Don't use this in production code."
So then, is there a generic authentication library for Python that I could use with Web.py? Or, is it really not that hard to roll my own?
If you can't find one easily, then probably discarding the advice and rolling your own is not a bad choice.
I don't think you'll find anything out of the box. The authentication system, is coupled with and dependent on the architecture (in your case probably it is Web only). Having said that it'll perhaps be easier to integrate django's authentication (django.contrib.auth) by putting some hooks here and there with web.py. Even then, it'll import a lot of django'ish ORM and other stuff behind the scene, but it is definitely possible.
Try repoze.who / what - it's implemented as WSGI middleware, so should fit into your stack well.
I'm building a centralized desktop application using Python/wxPython. One of the requirements is User authentication, which I'm trying to implement using LDAP (although this is not mandatory).
Users of the system will be mechanical and electrical engineers making budgets, and the biggest problem would be industrial espionage. Its a common problem that leaks occur commonly from the bottom on informal ways, and this could pose problems. The system is set up in such a way that every user has access to all and only the information it needs, so that no one person but the people on top has monetary information on the whole project.
The problem is that, for every way I can think to implement the authentication system, Python's openness makes me think of at least one way of bypassing/getting sensible information from the system, because "compiling" with py2exe is the closest I can get to obfuscation of the code on Windows.
I'm not really trying to hide the code, but rather make the authentication routine secure by itself, make it in such a way that access to the code doesn't mean capability to access the application. One thing I wanted to add, was some sort of code signing to the access routine, so the user can be sure that he is not running a modified client app.
One of the ways I've thought to avoid this is making a C module for the authentication, but I would rather not have to do that.
Of course this question is changing now and is not just "Could anyone point me in the right direction as to how to build a secure authentication system running on Python? Does something like this already exist?", but "How do you harden an scripting (Python) against wrongful modification?"
How malicious are your users? Really.
Exactly how malicious?
If your users are evil sociopaths and can't be trusted with a desktop solution, then don't build a desktop solution. Build a web site.
If your users are ordinary users, they'll screw the environment up by installing viruses, malware and keyloggers from porn sites before they try to (a) learn Python (b) learn how your security works and (c) make a sincere effort at breaking it.
If you actually have desktop security issues (i.e., public safety, military, etc.) then rethink using the desktop.
Otherwise, relax, do the right thing, and don't worry about "scripting".
C++ programs are easier to hack because people are lazy and permit SQL injection.
Possibly:
The user enters their credentials into the desktop client.
The client says to the server: "Hi, my name username and my password is password".
The server checks these.
The server says to the client: "Hi, username. Here is your secret token: ..."
Subsequently the client uses the secret token together with the username to "sign" communications with the server.