简体   繁体   English

从Django应用程序写入/读取机密文件的解决方案有多安全?

[英]How safe is a solution of writing/reading secret file from within Django app?

How vulnerable from security POV is the following solution of having random secret key stored on server filesystem? 以下将随机密钥存储在服务器文件系统上的解决方案有多么容易受到安全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)

Server environment is linux, running multithreaded apache server. 服务器环境是linux,运行多线程apache服务器。

Credit for snippet: https://www.rdegges.com/2011/the-perfect-django-settings-file/ 摘录内容摘录: https//www.rdegges.com/2011/the-perfect-django-settings-file/

You might keep in mind that changing the SECRET_KEY setting via that max_age variable might have some consequences that impact your app. 您可能要记住,通过该max_age变量更改SECRET_KEY设置可能会影响您的应用程序。 This SO question discusses some of the ways that the SECRET_KEY is used with Django. 这个SO问题讨论了SECRET_KEY与Django一起使用的一些方式。

Effects of changing Django's SECRET_KEY 更改Django的SECRET_KEY的影响

You might check to make sure that you are not using your app in such a way that changing that setting would impact you. 您可能会检查以确保您没有以更改设置会影响您的方式使用应用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM