【问题标题】:How safe is a solution of writing/reading secret file from within Django app?从 Django 应用程序中写入/读取秘密文件的解决方案有多安全?
【发布时间】:2023-03-25 02:59:01
【问题描述】:

以下将随机密钥存储在服务器文件系统上的解决方案对安全 POV 的攻击程度如何?

import os
import random
import string
import time

def secret_key_gen(path, max_age=86400):
    """
    Try to load the SECRET_KEY from SECRET_FILE. 
    If that fails, then generate random SECRET_KEY 
    and save it into our SECRET_FILE for future loading. 
    If everything fails, then just raise an exception.

    Given the app is running by a user with with sufficient rights 
    to write into app directory, key file will be auto-generated 
    the first time it's been looked for. 
    """

    SECRET_FILE = os.path.join(path, 'SECURITY_HASH')
    try:       
        last_modified = os.stat(SECRET_FILE).st_mtime
        lifespan = (time.time() - last_modified)

        # update key if file age is older than allowed
        if lifespan > max_age: 
            raise IOError

        SECRET_KEY = open(SECRET_FILE).read().strip()
    except (OSError, IOError):
        try:
            l = lambda _: random.SystemRandom().choice(string.printable)
            SECRET_KEY = ''.join(map(l, range(32)))
            with open(SECRET_FILE, 'w') as f:
                f.write(SECRET_KEY)
        except IOError:
            raise Exception('Cannot open file `%s` for writing.' % SECRET_FILE)
    return SECRET_KEY

# usage
SECURITY_HASH = secret_key_gen(
    path=os.path.dirname(__file__),
    max_age=60 * 60 * 24)

服务器环境为linux,运行多线程apache服务器。

sn-p 的信用:https://www.rdegges.com/2011/the-perfect-django-settings-file/

【问题讨论】:

    标签: python django multithreading security


    【解决方案1】:

    您可能要记住,通过该 max_age 变量更改 SECRET_KEY 设置可能会产生一些影响您的应用的后果。这个 SO question 讨论了 SECRET_KEY 与 Django 一起使用的一些方式。

    Effects of changing Django's SECRET_KEY

    您可以检查以确保您在使用应用时没有以更改该设置会影响您的方式使用。

    【讨论】:

    • 我明白你的意思,谢谢你强调它。应该避免保留名称。这个特殊的问题与 django 内部布线无关;让我们假设它不会掩盖框架内部的任何内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-07
    • 2016-04-28
    相关资源
    最近更新 更多