feat: 整合官方 2.7.0 安全修复与本地文件分享
This commit is contained in:
1 parent
b10113e5ab
commit
9e9571b031
42 files changed
+2824
-268
No files matched your search
+13
-3
@@ -1,3 +1,5 @@
|
||||
import time
|
||||
|
||||
from apps.base.models import KeyValue
|
||||
from apps.base.utils import ip_limit
|
||||
from core.database import db_startup_lock
|
||||
@@ -61,7 +63,7 @@ async def ensure_security_settings() -> None:
|
||||
logger.info("已将管理员密码迁移为哈希存储")
|
||||
if security_config.jwt_secret_rotated:
|
||||
logger.info("已生成独立 JWT 签名密钥")
|
||||
await refresh_settings()
|
||||
await refresh_settings(force=True)
|
||||
|
||||
|
||||
def _sync_ip_limits() -> None:
|
||||
@@ -75,11 +77,19 @@ def _sync_ip_limits() -> None:
|
||||
ip_limit["login"].count = settings.loginCount
|
||||
|
||||
|
||||
async def refresh_settings() -> None:
|
||||
CONFIG_CACHE_TTL_SECONDS = 2.0
|
||||
_config_cached_until = 0.0
|
||||
|
||||
|
||||
async def refresh_settings(force: bool = False) -> None:
|
||||
"""从数据库读取最新配置并应用到运行时。"""
|
||||
global _config_cached_until
|
||||
if not force and time.monotonic() < _config_cached_until:
|
||||
return
|
||||
config_record = await KeyValue.filter(key="settings").first()
|
||||
settings.user_config = config_record.value if config_record and config_record.value else {}
|
||||
_sync_ip_limits()
|
||||
_config_cached_until = time.monotonic() + CONFIG_CACHE_TTL_SECONDS
|
||||
|
||||
|
||||
def is_runtime_initialized() -> bool:
|
||||
@@ -118,4 +128,4 @@ async def initialize_system(
|
||||
next_config["jwt_secret"] = generate_jwt_secret()
|
||||
|
||||
await KeyValue.update_or_create(key="settings", defaults={"value": next_config})
|
||||
await refresh_settings()
|
||||
await refresh_settings(force=True)
|
||||
@@ -32,6 +32,8 @@ def is_config_initialized(config: dict[str, Any]) -> bool:
|
||||
admin_token = str(config.get("admin_token") or "")
|
||||
if not admin_token:
|
||||
return False
|
||||
if is_password_hashed(admin_token) and admin_token.startswith("scrypt$"):
|
||||
return True
|
||||
return not verify_password(LEGACY_DEFAULT_ADMIN_TOKEN, admin_token)
|
||||
|
||||
|
||||
|
||||
+71
-7
@@ -13,6 +13,27 @@ import time
|
||||
from core.settings import settings
|
||||
|
||||
|
||||
def validate_background_url(value) -> str:
|
||||
"""Validate the site background config before it reaches the theme template.
|
||||
|
||||
Themes inject this value into inline CSS ``url('...')`` where html escaping
|
||||
cannot neutralize a single-quote breakout, so only well-formed http(s) URLs
|
||||
(or an empty string) are accepted.
|
||||
"""
|
||||
value = str(value or "").strip()
|
||||
if not value:
|
||||
return ""
|
||||
from urllib.parse import urlparse
|
||||
|
||||
parsed = urlparse(value)
|
||||
if parsed.scheme not in ("http", "https") or not parsed.netloc:
|
||||
raise ValueError("background 必须是 http(s) 完整 URL 或留空")
|
||||
# quote()/whitespace would break out of the CSS url('') quoting context
|
||||
if any(ch in value for ch in ("'", '"', "(", ")", " ", "\\", ";")):
|
||||
raise ValueError("background URL 含有不允许的字符")
|
||||
return value
|
||||
|
||||
|
||||
async def get_random_num(length: int = 8):
|
||||
"""返回指定长度的纯数字取件码。"""
|
||||
normalized_length = max(1, int(length or 8))
|
||||
@@ -102,25 +123,61 @@ async def max_save_times_desc(max_save_seconds: int):
|
||||
return desc_zh, desc_en
|
||||
|
||||
|
||||
# scrypt work factors (OWASP-recommended memory-hard parameters; ~50ms/verify)
|
||||
SCRYPT_N = 2**14
|
||||
SCRYPT_R = 8
|
||||
SCRYPT_P = 1
|
||||
_SCRYPT_MAXMEM = 64 * 1024 * 1024 # hashlib default cap (32MB) is too low for n=2^14,r=8
|
||||
|
||||
PASSWORD_SCHEME = "scrypt" # current scheme for new hashes; sha256/plaintext stay verifiable
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
"""
|
||||
使用 SHA256 + salt 哈希密码
|
||||
返回格式: sha256$<salt>$<hash>
|
||||
使用 scrypt(memory-hard)哈希密码
|
||||
返回格式: scrypt$<n>$<r>$<p>$<salt>$<hash>
|
||||
"""
|
||||
salt = os.urandom(16).hex()
|
||||
password_hash = hashlib.sha256(f"{salt}{password}".encode()).hexdigest()
|
||||
return f"sha256${salt}${password_hash}"
|
||||
password_hash = hashlib.scrypt(
|
||||
password.encode(),
|
||||
salt=salt.encode(),
|
||||
n=SCRYPT_N,
|
||||
r=SCRYPT_R,
|
||||
p=SCRYPT_P,
|
||||
maxmem=_SCRYPT_MAXMEM,
|
||||
).hex()
|
||||
return f"scrypt${SCRYPT_N}${SCRYPT_R}${SCRYPT_P}${salt}${password_hash}"
|
||||
|
||||
|
||||
def verify_password(password: str, hashed: str) -> bool:
|
||||
"""
|
||||
验证密码是否匹配
|
||||
支持新格式 (sha256$salt$hash) 和旧格式 (明文)
|
||||
支持格式: scrypt$n$r$p$salt$hash(现行)、sha256$salt$hash(历史)、明文(最老)
|
||||
"""
|
||||
if not hashed:
|
||||
return False
|
||||
|
||||
# 新格式: sha256$salt$hash
|
||||
if hashed.startswith("scrypt$"):
|
||||
parts = hashed.split("$")
|
||||
if len(parts) != 6:
|
||||
return False
|
||||
try:
|
||||
scheme, n, r, p, salt, stored_hash = parts
|
||||
password_hash = hashlib.scrypt(
|
||||
password.encode(),
|
||||
salt=salt.encode(),
|
||||
n=int(n),
|
||||
r=int(r),
|
||||
p=int(p),
|
||||
maxmem=_SCRYPT_MAXMEM,
|
||||
).hex()
|
||||
# 默认解释器对超范围的 n/r/p 抛 TypeError/ValueError;部分构建会抛
|
||||
# OverflowError,一并视为校验失败,避免坏掉的存量哈希影响登录路径。
|
||||
except (ValueError, TypeError, OverflowError):
|
||||
return False
|
||||
return hmac.compare_digest(password_hash, stored_hash)
|
||||
|
||||
# sha256 格式: sha256$salt$hash(历史数据,验证逻辑保持原样)
|
||||
if hashed.startswith("sha256$"):
|
||||
parts = hashed.split("$")
|
||||
if len(parts) != 3:
|
||||
@@ -135,11 +192,18 @@ def verify_password(password: str, hashed: str) -> bool:
|
||||
|
||||
def is_password_hashed(password: str) -> bool:
|
||||
"""
|
||||
检查密码是否已经是哈希格式
|
||||
检查密码是否已经是哈希格式(现行或历史哈希均视为已哈希)
|
||||
"""
|
||||
if password.startswith("scrypt$") and len(password.split("$")) == 6:
|
||||
return True
|
||||
return password.startswith("sha256$") and len(password.split("$")) == 3
|
||||
|
||||
|
||||
def password_needs_rehash(hashed: str) -> bool:
|
||||
"""True when the stored hash uses a legacy scheme (sha256/plaintext)."""
|
||||
return bool(hashed) and not hashed.startswith(f"{PASSWORD_SCHEME}$")
|
||||
|
||||
|
||||
async def sanitize_filename(filename: str) -> str:
|
||||
"""
|
||||
安全处理文件名:
|
||||
|
||||
Reference in new issue
Block a user