Python/Django - Avoid saving passwords in source code

时光总嘲笑我的痴心妄想 提交于 2019-12-04 07:29:20

问题


I use Python and Django to create web applications, which we store in source control. The way Django is normally set up, the passwords are in plain text within the settings.py file.

Storing my password in plain text would open me up to a number of security problems, particularly because this is an open source project and my source code would be version controlled (through git, on Github, for the entire world to see!)

The question is, what would be the best practice for securely writing a settings.py file in a a Django/Python development environment?


回答1:


Although I wasn't able to come across anything Python-specific on stackoverflow, I did find a website that was helpful, and thought I'd share the solution with the rest of the community.

The solution: environment variables.

Note: Although environment variables are similar in both Linux/Unix/OS X and in the Windows worlds, I haven't tested this code on a Windows machine. Please let me know if it works.

In your bash/sh shell, type:

export MYAPP_DB_USER='myapp'
export MYAPP_DB_PASSWORD='testing123'

And in your Django settings.py file:

DATABASE_USER = os.environ.get("MYAPP_DB_USER", '')
DATABASE_PASSWORD = os.environ.get("MYAPP_DB_PASSWORD", '')

In this case, the username and password would default to an empty string if the environment variable didn't exist.




回答2:


Although environment variables are convenient for a lot of configuration, putting passwords in environment variables is not secure. With the alternative being a configuration file outside regular version control, here are some various cons:

  • Environment variables might accidentally leak (through debugging channels that might get transmitted via plaintext, to end-users, or to unexpected places in the filesystem like ~/.*sh_history).

  • Configuration files might accidentally get added to version control and end up in repositories accessible to people without deployment privileges.

Read the blog post Environment Variables Considered Harmful for Your Secrets for more arguments: The environment is accessible to the entire process, is inherited to child (and possibly 3rd-party) processes, and there exists no clear assumption among external developers to treat environment variables as confidential.

The simplest configuration file format in Python is simply a Python module.



来源:https://stackoverflow.com/questions/15327776/python-django-avoid-saving-passwords-in-source-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!