From fb16429867b1255ef1074bdf0fd29fd32b4b4189 Mon Sep 17 00:00:00 2001 From: Ozzieisaacs Date: Mon, 4 May 2020 19:02:03 +0200 Subject: [PATCH] Randomize flask secret_key --- cps/__init__.py | 2 +- cps/config_sql.py | 22 ++++++++++++++++++++-- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/cps/__init__.py b/cps/__init__.py index ae1378de..7dd4e11f 100644 --- a/cps/__init__.py +++ b/cps/__init__.py @@ -88,7 +88,7 @@ def create_app(): log.info('Starting Calibre Web...') Principal(app) lm.init_app(app) - app.secret_key = os.getenv('SECRET_KEY', 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT') + app.secret_key = os.getenv('SECRET_KEY', config_sql.get_flask_session_key(ub.session)) web_server.init_app(app, config) db.setup_db(config) diff --git a/cps/config_sql.py b/cps/config_sql.py index 241e583a..590b8eea 100644 --- a/cps/config_sql.py +++ b/cps/config_sql.py @@ -22,7 +22,7 @@ import os import json import sys -from sqlalchemy import exc, Column, String, Integer, SmallInteger, Boolean +from sqlalchemy import exc, Column, String, Integer, SmallInteger, Boolean, BLOB from sqlalchemy.ext.declarative import declarative_base from . import constants, cli, logger, ub @@ -31,6 +31,15 @@ from . import constants, cli, logger, ub log = logger.create() _Base = declarative_base() +class _Flask_Settings(_Base): + __tablename__ = 'flask_settings' + + id = Column(Integer, primary_key=True) + flask_session_key = Column(BLOB, default="") + + def __init__(self, key): + self.flask_session_key = key + # Baseclass for representing settings in app.db with email server settings and Calibre database settings # (application settings) @@ -301,7 +310,7 @@ def _migrate_table(session, orm_class): log.debug("%s: %s", column_name, err.args[0]) if column.default is not None: if sys.version_info < (3, 0): - if isinstance(column.default.arg,unicode): + if isinstance(column.default.arg, unicode): column.default.arg = column.default.arg.encode('utf-8') if column.default is None: column_default = "" @@ -337,6 +346,7 @@ def _migrate_database(session): # make sure the table is created, if it does not exist _Base.metadata.create_all(session.bind) _migrate_table(session, _Settings) + _migrate_table(session, _Flask_Settings) def load_configuration(session): @@ -354,3 +364,11 @@ def load_configuration(session): update({"denied_tags": conf.config_mature_content_tags}, synchronize_session=False) session.commit() return conf + +def get_flask_session_key(session): + flask_settings = session.query(_Flask_Settings).one_or_none() + if flask_settings == None: + flask_settings = _Flask_Settings(os.urandom(32)) + session.add(flask_settings) + session.commit() + return flask_settings.flask_session_key