forked from claw/flaskpaste
security: implement pentest remediation (PROXY-001, BURN-001, RATE-001)
PROXY-001: Add startup warning when TRUSTED_PROXY_SECRET empty in production - validate_security_config() checks for missing proxy secret - Additional warning when PKI enabled without proxy secret - Tests for security configuration validation BURN-001: HEAD requests now trigger burn-after-read deletion - Prevents attacker from probing paste existence before retrieval - Updated test to verify new behavior RATE-001: Add RATE_LIMIT_MAX_ENTRIES to cap memory usage - Default 10000 unique IPs tracked - Prunes oldest entries when limit exceeded - Protects against memory exhaustion DoS Test count: 284 -> 291 (7 new security tests)
This commit is contained in:
@@ -36,6 +36,32 @@ def setup_logging(app: Flask) -> None:
|
||||
app.logger.info("FlaskPaste starting", extra={"config": type(app.config).__name__})
|
||||
|
||||
|
||||
def validate_security_config(app: Flask) -> None:
|
||||
"""Validate security configuration and log warnings.
|
||||
|
||||
Checks for common security misconfigurations that could lead to
|
||||
vulnerabilities in production deployments.
|
||||
"""
|
||||
is_production = not app.debug and not app.config.get("TESTING")
|
||||
|
||||
# PROXY-001: Check TRUSTED_PROXY_SECRET
|
||||
proxy_secret = app.config.get("TRUSTED_PROXY_SECRET", "")
|
||||
if is_production and not proxy_secret:
|
||||
app.logger.warning(
|
||||
"SECURITY WARNING: TRUSTED_PROXY_SECRET is not set. "
|
||||
"Client certificate headers (X-SSL-Client-SHA1) can be spoofed. "
|
||||
"Set FLASKPASTE_PROXY_SECRET to a shared secret known only by your reverse proxy."
|
||||
)
|
||||
|
||||
# Warn if PKI is enabled without proxy secret
|
||||
pki_enabled = app.config.get("PKI_ENABLED", False)
|
||||
if pki_enabled and not proxy_secret:
|
||||
app.logger.warning(
|
||||
"SECURITY WARNING: PKI is enabled but TRUSTED_PROXY_SECRET is not set. "
|
||||
"Certificate-based authentication can be bypassed by spoofing headers."
|
||||
)
|
||||
|
||||
|
||||
def setup_security_headers(app: Flask) -> None:
|
||||
"""Add security headers to all responses."""
|
||||
|
||||
@@ -235,6 +261,9 @@ def create_app(config_name: str | None = None) -> Flask:
|
||||
# Setup logging first
|
||||
setup_logging(app)
|
||||
|
||||
# Validate security configuration
|
||||
validate_security_config(app)
|
||||
|
||||
# Setup request ID tracking
|
||||
setup_request_id(app)
|
||||
|
||||
|
||||
@@ -165,6 +165,7 @@ def check_rate_limit(client_ip: str, authenticated: bool = False) -> tuple[bool,
|
||||
|
||||
window = current_app.config["RATE_LIMIT_WINDOW"]
|
||||
max_requests = current_app.config["RATE_LIMIT_MAX"]
|
||||
max_entries = current_app.config.get("RATE_LIMIT_MAX_ENTRIES", 10000)
|
||||
|
||||
if authenticated:
|
||||
max_requests *= current_app.config.get("RATE_LIMIT_AUTH_MULTIPLIER", 5)
|
||||
@@ -173,6 +174,11 @@ def check_rate_limit(client_ip: str, authenticated: bool = False) -> tuple[bool,
|
||||
cutoff = now - window
|
||||
|
||||
with _rate_limit_lock:
|
||||
# RATE-001: Enforce maximum entries to prevent memory exhaustion
|
||||
if len(_rate_limit_requests) >= max_entries and client_ip not in _rate_limit_requests:
|
||||
# Evict oldest entries (those with oldest last request time)
|
||||
_prune_rate_limit_entries(max_entries // 2, cutoff)
|
||||
|
||||
# Clean old requests and get current list
|
||||
requests = _rate_limit_requests[client_ip]
|
||||
requests[:] = [t for t in requests if t > cutoff]
|
||||
@@ -192,6 +198,33 @@ def check_rate_limit(client_ip: str, authenticated: bool = False) -> tuple[bool,
|
||||
return True, remaining, max_requests, reset_timestamp
|
||||
|
||||
|
||||
def _prune_rate_limit_entries(target_size: int, cutoff: float) -> None:
|
||||
"""Prune rate limit entries to target size. Must hold _rate_limit_lock.
|
||||
|
||||
Removes entries with no recent activity first, then oldest entries.
|
||||
"""
|
||||
# First pass: remove entries with all expired requests
|
||||
to_remove = []
|
||||
for ip, requests in _rate_limit_requests.items():
|
||||
if not requests or all(t <= cutoff for t in requests):
|
||||
to_remove.append(ip)
|
||||
|
||||
for ip in to_remove:
|
||||
del _rate_limit_requests[ip]
|
||||
|
||||
# Second pass: if still over target, remove entries with oldest last activity
|
||||
if len(_rate_limit_requests) > target_size:
|
||||
# Sort by most recent request timestamp (ascending = oldest first)
|
||||
entries = sorted(
|
||||
_rate_limit_requests.items(),
|
||||
key=lambda x: max(x[1]) if x[1] else 0,
|
||||
)
|
||||
# Remove oldest until we're at target size
|
||||
remove_count = len(entries) - target_size
|
||||
for ip, _ in entries[:remove_count]:
|
||||
del _rate_limit_requests[ip]
|
||||
|
||||
|
||||
def cleanup_rate_limits(window: int | None = None) -> int:
|
||||
"""Remove expired rate limit entries. Returns count of cleaned entries.
|
||||
|
||||
@@ -1512,7 +1545,11 @@ class PasteRawView(MethodView):
|
||||
return response
|
||||
|
||||
def head(self, paste_id: str) -> Response:
|
||||
"""Return raw paste headers without triggering burn."""
|
||||
"""Return raw paste headers. HEAD triggers burn-after-read deletion.
|
||||
|
||||
Security note: HEAD requests count as paste access for burn-after-read
|
||||
to prevent attackers from probing paste existence before retrieval.
|
||||
"""
|
||||
# Validate and fetch
|
||||
if err := validate_paste_id(paste_id):
|
||||
return err
|
||||
@@ -1520,13 +1557,21 @@ class PasteRawView(MethodView):
|
||||
return err
|
||||
|
||||
row: Row = g.paste
|
||||
g.db.commit()
|
||||
db = g.db
|
||||
|
||||
# BURN-001: HEAD triggers burn-after-read like GET
|
||||
burn_after_read = row["burn_after_read"]
|
||||
if burn_after_read:
|
||||
db.execute("DELETE FROM pastes WHERE id = ?", (paste_id,))
|
||||
current_app.logger.info("Burn-after-read paste deleted via HEAD: %s", paste_id)
|
||||
|
||||
db.commit()
|
||||
|
||||
response = Response(mimetype=row["mime_type"])
|
||||
response.headers["Content-Length"] = str(row["size"])
|
||||
if row["mime_type"].startswith(("image/", "text/")):
|
||||
response.headers["Content-Disposition"] = "inline"
|
||||
if row["burn_after_read"]:
|
||||
if burn_after_read:
|
||||
response.headers["X-Burn-After-Read"] = "true"
|
||||
|
||||
return response
|
||||
|
||||
@@ -99,6 +99,8 @@ class Config:
|
||||
RATE_LIMIT_MAX = int(os.environ.get("FLASKPASTE_RATE_MAX", "10")) # requests per window
|
||||
# Authenticated users get higher limits (multiplier)
|
||||
RATE_LIMIT_AUTH_MULTIPLIER = int(os.environ.get("FLASKPASTE_RATE_AUTH_MULT", "5"))
|
||||
# Maximum unique IPs tracked in rate limit storage (RATE-001: memory DoS protection)
|
||||
RATE_LIMIT_MAX_ENTRIES = int(os.environ.get("FLASKPASTE_RATE_MAX_ENTRIES", "10000"))
|
||||
|
||||
# Audit Logging
|
||||
# Track security-relevant events (paste creation, deletion, rate limits, etc.)
|
||||
|
||||
Reference in New Issue
Block a user