Python 保留密钥

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14786072/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:25:42  来源:igfitidea点击:

Keep Secret Keys Out

pythondjangosettings

提问by

One of the causes of the local_settings.py anti-pattern is that putting SECRET_KEY, AWS keys, etc.. values into settings files has problem:

local_settings.py 反模式的原因之一是将 SECRET_KEY、AWS 密钥等值放入设置文件中存在问题:

  • Secrets often should be just that: secret! Keeping them in version control means that everyone with repository access has access to them.
  • 秘密通常应该是这样的:秘密!将它们保持在版本控制中意味着每个拥有存储库访问权限的人都可以访问它们。

My question is how to keep all keys as secret?

我的问题是如何将所有密钥保密?

回答by Rohan

Ideally, local_settings.pyshould not be checked in for production/deployed server. You can keep backup copy somewhere else, but not in source control.

理想情况下,local_settings.py不应为生产/部署的服务器签入。您可以将备份副本保存在其他地方,但不能保存在源代码管理中。

local_settings.pycan be checked in with development configuration just for convenience, so that each developer need to change it.

local_settings.py可以用开发配置签入只是为了方便,以便每个开发人员需要更改它。

Does that solve your problem?

这能解决你的问题吗?

回答by Spacedman

Store your local_settings.pydata in a file encrypted with GPG - preferably as strictly key=valuelines which you parse and assign to a dict (the other attractive approach would be to have it as executable python, but executable code in config files makes me shiver).

将您的local_settings.py数据存储在用 GPG 加密的文件中 - 最好是key=value您解析并分配给字典的严格行(另一种有吸引力的方法是将其作为可执行的 python,但配置文件中的可执行代码让我不寒而栗)。

There's a python gpg module so that's not a problem. Get your keys from your keyring, and use the GPG keyring management tools so you don't have to keep typing in your keychain password. Make sure you are reading the data straight from the encrypted file, and not just creating a decrypted temporary file which you read in. That's a recipe for fail.

有一个 python gpg 模块,所以这不是问题。从您的钥匙圈中获取钥匙,并使用 GPG 钥匙圈管理工具,这样您就不必一直输入钥匙串密码。确保您直接从加密文件中读取数据,而不仅仅是创建一个您读入的解密临时文件。这是失败的秘诀。

That's just an outline, you'll have to build it yourself.

这只是一个大纲,你必须自己构建它。

This way the secret data remains solely in the process memory space, and not in a file or in environment variables.

通过这种方式,秘密数据仅保留在进程内存空间中,而不是文件或环境变量中。

回答by Aaron Lelevier

I doing my Django projects using Windows 7 and Powershell, so for me it was slightly different to set the environment variable. Once it was set though, I just did the following in my settings.pyfile:

我使用 Windows 7 和 Powershell 做我的 Django 项目,所以对我来说设置环境变量略有不同。设置好后,我只是在我的settings.py文件中执行了以下操作:

import os
SECRET_KEY = os.environ["SOME_SECRET_KEY"]

To set a environment variable in Windows using PowerShell follow the instructions in the link below:

要使用 PowerShell 在 Windows 中设置环境变量,请按照以下链接中的说明进行操作:

http://technet.microsoft.com/en-us/library/ff730964.aspx

http://technet.microsoft.com/en-us/library/ff730964.aspx

回答by lava-lava

You may need to use os.environ.get("SOME_SECRET_KEY")

您可能需要使用 os.environ。获取(“SOME_SECRET_KEY”)

回答by Mike Dewhirst

I wrote a getcreds() function which gets the secret key from a file. I keep the file in a place accessible to www-data so wherever I need credentials in settings.py I just make the call to getcreds() passing in the filename as an argument. It returns a list of all lines in the file and bingo I have the hidden secrets. Here is the code ...

我编写了一个 getcreds() 函数,它从文件中获取密钥。我将文件保存在 www-data 可访问的位置,因此无论我在 settings.py 中需要凭据,我都只需调用 getcreds() 将文件名作为参数传递。它返回文件中所有行的列表,宾果游戏我有隐藏的秘密。这是代码...

from __future__ import unicode_literals, absolute_import
import os


def getcreds(fname, project, credsroot='/var/www/creds', credsdir=None):
    """ return a list of userid and password and perhaps other data """
    if credsdir is None:
        credsdir = os.path.join(credsroot, project)
    creds = list()
    fname = os.path.join(credsdir, fname).replace("\", "/")
    with open(fname, 'r') as f:
        for line in f:
            # remove leading/trailing whitespace and append to list
            creds.append(line.strip())
    assert creds, "The list of credentials is empty"
    return creds

回答by Aaron Hall

The original question was about how to keep secrets in environment variables. This is discussed extensively in the book Two Scoops of Django. Below is a summary of what they said, followed by a caveat about using this technique.

最初的问题是关于如何在环境变量中保密。这在《Django 的两个勺子》一书中进行了广泛的讨论。下面是他们所说的摘要,然后是有关使用此技术的警告。

Starting on page 48 (Section 5.3) of the edition for 1.11:

从 1.11 版的第 48 页(第 5.3 节)开始:

Every operating system supported by Django (and Python) provides the easy capability to create environment variables.

Here are the benefits of using environment variables for secret keys:

  • Keeping secrets out of settings allows you to store every settings file in version control without hesitation. All of your Python code really should be stored in version control, including your settings.
  • Instead of each developer maintaining their own copy-and-pasted version of local_settings.py.example for development, everyone shares the same version-controlled settings/local.py .
  • System administrators can rapidly deploy the project without having to modify files containing Python code.
  • Most platforms-as-a-service recommend the use of environment variables for configuration and have built-in features for setting and managing them.

Django(和 Python)支持的每个操作系统都提供了创建环境变量的简单功能。

以下是使用环境变量作为密钥的好处:

  • 保密设置允许您毫不犹豫地将每个设置文件存储在版本控制中。您的所有 Python 代码都应该存储在版本控制中,包括您的设置。
  • 不是每个开发人员都为开发维护自己复制粘贴的 local_settings.py.example 版本,而是每个人都共享相同的版本控制 settings/local.py 。
  • 系统管理员无需修改包含 Python 代码的文件即可快速部署项目。
  • 大多数平台即服务建议使用环境变量进行配置,并具有用于设置和管理它们的内置功能。

On the following page, the book continues:

在下一页,本书继续:

Before you begin setting environment variables, you should have the following:

  • A way to manage the secret information you are going to store.
  • A good understanding of how bash settings work on servers, or a willingness to have your project hosted by a platform-as-a-service.

在开始设置环境变量之前,您应该具备以下条件:

  • 一种管理您要存储的秘密信息的方法。
  • 很好地了解 bash 设置如何在服务器上工作,或者愿意让您的项目由平台即服务托管。

They describe how to set the environment variables locally and in production (with Heroku as an example--you will need to check if you are using a different host this is just one possibility):

他们描述了如何在本地和生产中设置环境变量(以 Heroku 为例——您需要检查是否使用不同的主机,这只是一种可能性):

How To Set Environment Variables Locally
export SOME_SECRET_KEY=1c3-cr3am-15-yummy

How To Set Environment Variables in Production
heroku config:set SOME_SECRET_KEY=1c3-cr3am-15-yummy

如何在本地设置环境变量
export SOME_SECRET_KEY=1c3-cr3am-15-yummy

如何在生产
heroku 配置中设置环境变量:set SOME_SECRET_KEY=1c3-cr3am-15-yummy

Finally, on page 52 they give instructions for how to access the key. For instance you could put the first two lines below in your settings file to replace the raw key string that is put there by default:

最后,在第 52 页,他们给出了如何访问密钥的说明。例如,您可以将下面的前两行放在您的设置文件中以替换默认情况下放置在那里的原始密钥字符串:

>>> import os
>>> os.environ['SOME_SECRET_KEY'] 
'1c3-cr3am-15-yummy'

This snippet simply gets the value of the SOME_SECRET_KEY environment variable from the operating system and saves it to a Python variable called SOME_SECRET_KEY.

Following this pattern means all code can remain in version control, and all secrets remain safe.

>>> import os
>>> os.environ['SOME_SECRET_KEY'] 
'1c3-cr3am-15-yummy'

此代码段只是从操作系统获取 SOME_SECRET_KEY 环境变量的值,并将其保存到名为 SOME_SECRET_KEY 的 Python 变量中。

遵循此模式意味着所有代码都可以保留在版本控制中,并且所有机密都保持安全。

Note this will not work in some cases, for instance if you are using an Apache server. To deal with situations where this pattern will not work, you should see Section 5.4 of their book ('When You Can't Use Environment Variables'). In that case, they recommend use a secret file.

请注意,这在某些情况下不起作用,例如,如果您使用的是 Apache 服务器。要处理此模式不起作用的情况,您应该查看他们书中的第 5.4 节(“当您无法使用环境变量时”)。在这种情况下,他们建议使用机密文件。

As of late 2017, this technique of storing secrets in your environment variables is the recommended best practice in Two Scoops and in the Twelve Factor App design pattern. It is also recommended at the Django docs. However, there are some security risks: if some developer, or some code, has access to your system, they will have access to your environment variables and may inadvertently (or advertently) make them public. This point was made by Michael Reinsch here:
http://movingfast.io/articles/environment-variables-considered-harmful/

截至 2017 年底,这种在环境变量中存储秘密的技术是两勺和十二因素应用程序设计模式中推荐的最佳实践。在 Django 文档中也推荐使用它。但是,存在一些安全风险:如果某些开发人员或某些代码可以访问您的系统,他们将可以访问您的环境变量,并且可能会无意(或无意中)将它们公开。这一点是由 Michael Reinsch 在这里提出的:http:
//movingfast.io/articles/environment-variables-thinked-harmful/

回答by krubo

Here's one way to do it that is compatible with deployment on Heroku:

这是一种与 Heroku 上的部署兼容的方法:

  1. Create a gitignored file named .envcontaining:

    export DJANGO_SECRET_KEY = 'replace-this-with-the-secret-key'

  2. Then edit settings.pyto remove the actual SECRET_KEYand add this instead:

    SECRET_KEY = os.environ['DJANGO_SECRET_KEY']

  3. Then when you want to run the development server locally, use:

    source .env
    python manage.py runserver

  4. When you finally deploy to Heroku, go to your app Settings tab and add DJANGO_SECRET_KEY to the Config Vars.

  1. 创建一个名为 gitignored 的文件,.env其中包含:

    export DJANGO_SECRET_KEY = 'replace-this-with-the-secret-key'

  2. 然后编辑settings.py以删除实际SECRET_KEY并添加它:

    SECRET_KEY = os.environ['DJANGO_SECRET_KEY']

  3. 然后当你想在本地运行开发服务器时,使用:

    source .env
    python manage.py runserver

  4. 当您最终部署到 Heroku 时,转到您的应用设置选项卡并将 DJANGO_SECRET_KEY 添加到配置变量。