[英]How safe is a solution of writing/reading secret file from within Django app?
以下將隨機密鑰存儲在服務器文件系統上的解決方案有多么容易受到安全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服務器。
摘錄內容摘錄: https : //www.rdegges.com/2011/the-perfect-django-settings-file/
您可能要記住,通過該max_age變量更改SECRET_KEY設置可能會影響您的應用程序。 這個SO問題討論了SECRET_KEY與Django一起使用的一些方式。
您可能會檢查以確保您沒有以更改設置會影響您的方式使用應用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.