What Django session engine should I use for enhanced security?
What is the most secure way to store sessions with Django?
93 views Asked by Aidas Bendoraitis AtThere are 2 answers
On
If by "secure" you mean you need to store data with low chance of loss, i.e. durability then the db or cached_db backends are the best ones. (file is generally to be avoided apart from in unusual circumstances, cache is designed for data that is closer to throwaway in nature, and signed_cookies depends too much on browser/user behaviour)
If you mean you want to store data privately, with no chance of a third party seeing it, and the attacks you envisage to be most likely are against your server and not user computers, then signed_cookies is probably the best (or directly use set_signed_cookie rather than use the session), because you won't be storing the data on your server at all. You need to be aware of the limitations of cookies.
If you mean you want to store data privately, but the attacks you envisage to be most likely are against your users' computers, then signed_cookies is out because the data in the cookies can be read easily by someone with access to the cookies in a browser. The cookie data is signed, but not encrypted.
If you care about data integrity i.e. that it cannot be tampered with, either by an attacker or by the user, then the different backends provide similar levels of assurance: signed cookies are difficult to tamper with due to the use of a MAC, and the database backend is difficult because an attacker shouldn't have access to the database (and if they do you probably have bigger problems).
In short, you need to know which specific security properties you are interested in, and what attack vectors you are considering.
TLDR; The
dbsession engine seems to be the most secure, but the backups need to be created with a special care.Django comes with these session engines:
django.contrib.sessions.backends.dbdjango.contrib.sessions.backends.filedjango.contrib.sessions.backends.cachedjango.contrib.sessions.backends.cached_dbdjango.contrib.sessions.backends.signed_cookiesIn addition, you can write your own or use a third party like
django-redis-sessions.After a little research, I found that only the
dbandfileengines have theclear_expiredmethod implemented. This method is called when you call theclearsessionsmanagement command.So when you use other session engines, the information that belongs to users who left the website without logging out, it's still possible to read what was in their sessions.
You can use the
filesession engine only on a single server, which doesn't work for scaling. So, my most secure choice is to use thedbsession engine and ensure that thedjango_sessiontable is excluded from the database backups with the PostgreSQL pg_dump--exclude-table-dataparameter.