How vulnerable from security POV is the following solution of having random secret key stored on server filesystem?
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.
Credit for snippet: https://www.rdegges.com/2011/the-perfect-django-settings-file/