Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat(security): trust reverse-proxy client IP via one gated seam

Juan Denis363a09dc7ec5
diff --git a/.env.example b/.env.example
index 9394618e..23cc74dd 100644
--- a/.env.example
+++ b/.env.example
@@ -44,6 +44,19 @@ CORS_ORIGINS=http://localhost,https://your-domain.com
PORT=80
SSL_PORT=443
+# ----------------------------------------
+# Trusted reverse proxy (client IP)
+# ----------------------------------------
+# The panel runs behind its bundled nginx, so the real client IP arrives in
+# X-Forwarded-For and the raw socket peer is nginx. Enable this so ServerKit
+# trusts the proxy and derives the real client IP (via Werkzeug ProxyFix) for
+# rate-limiting, login lockout and audit logs. Leave it FALSE / unset only for
+# a directly-exposed server with no proxy in front (otherwise a client could
+# forge X-Forwarded-For). TRUSTED_PROXY_HOPS = number of proxies in front of
+# Flask (bundled nginx = 1; raise it if you add e.g. Cloudflare on top).
+TRUST_PROXY_HEADERS=true
+TRUSTED_PROXY_HOPS=1
+
# ----------------------------------------
# Environment
# ----------------------------------------
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 59d52ed7..6ca052bf 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -577,6 +577,16 @@ awaiting a stable release:
### Security
+- **Client IP is no longer spoofable behind the proxy.** Rate-limit buckets,
+ login lockout and audit-log source IPs previously trusted the *leftmost*
+ `X-Forwarded-For` token — a value the client fully controls, so an attacker
+ could rotate it to dodge per-IP limits or forge audit trails. ServerKit now
+ derives the client IP from one trusted seam (Werkzeug `ProxyFix`, gated by the
+ new `TRUST_PROXY_HEADERS` / `TRUSTED_PROXY_HOPS` settings), taking the
+ rightmost proxy-appended hop; a forged prefix is discarded. Enabled by default
+ in the shipped proxied deploy; off for a directly-exposed dev server. **Note:**
+ audit-log source IPs now record the real client instead of nginx's address —
+ update any dashboards/alerts built on the old values.
- **Container CVE scanning & SBOM** — per-image vulnerability scans with grype
and software bill-of-materials generation with syft.
- **Optional, hardened TLS** — best-effort HTTPS that never blocks an install
diff --git a/backend/.env.example b/backend/.env.example
index 0e7bcf24..a338e118 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -19,6 +19,16 @@ CORS_ORIGINS=http://localhost:41921,http://127.0.0.1:41921,http://localhost:4792
# Server
PORT=47927
+# Trusted reverse proxy (client IP)
+# Default OFF for local dev: run.py is directly exposed with no proxy, so an
+# X-Forwarded-For header would be client-forgeable and must NOT be trusted.
+# In production the panel sits behind its bundled nginx — set this to true there
+# (the shipped .env.example does) so ServerKit derives the real client IP via
+# ProxyFix for rate-limiting / login lockout / audit logs. TRUSTED_PROXY_HOPS is
+# the number of proxies in front of Flask (bundled nginx = 1).
+# TRUST_PROXY_HEADERS=false
+# TRUSTED_PROXY_HOPS=1
+
# Security - Agent API Secret Encryption
# IMPORTANT: Generate a unique key for production!
# Run: python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
diff --git a/backend/app/__init__.py b/backend/app/__init__.py
index e4dd53f3..b491111a 100644
--- a/backend/app/__init__.py
+++ b/backend/app/__init__.py
@@ -40,6 +40,17 @@ def create_app(config_name=None):
)
app.config.from_object(config[config_name])
+ # Trust the reverse proxy's forwarding headers to derive the real client IP
+ # (config-gated; default off). ProxyFix rewrites request.remote_addr from the
+ # rightmost TRUSTED_PROXY_HOPS entries of X-Forwarded-For — the hops our own
+ # proxies appended — so a client-forged leftmost value is ignored. Applied
+ # before the limiter and request handlers so every remote_addr consumer
+ # (flask-limiter's get_remote_address, get_client_ip(), audit logs) benefits.
+ if app.config.get('TRUST_PROXY_HEADERS'):
+ from werkzeug.middleware.proxy_fix import ProxyFix
+ hops = app.config.get('TRUSTED_PROXY_HOPS', 1)
+ app.wsgi_app = ProxyFix(app.wsgi_app, x_for=hops, x_proto=1, x_host=0, x_port=0)
+
# Initialize extensions
db.init_app(app)
migrate.init_app(app, db)
diff --git a/backend/app/api/ddns.py b/backend/app/api/ddns.py
index 26531f1d..f0812229 100644
--- a/backend/app/api/ddns.py
+++ b/backend/app/api/ddns.py
@@ -57,10 +57,10 @@ def regenerate_token(host_id):
# --- Update endpoint (public, token-authenticated) ---
def _client_ip():
- forwarded = request.headers.get('X-Forwarded-For', '')
- if forwarded:
- return forwarded.split(',')[0].strip()
- return request.remote_addr
+ # DDNS legitimately wants the real client IP — the same trusted seam every
+ # other consumer uses (ProxyFix-corrected remote_addr, see utils.client_ip).
+ from app.utils.client_ip import get_client_ip
+ return get_client_ip()
@ddns_bp.route('/update', methods=['GET', 'POST'])
diff --git a/backend/app/middleware/api_analytics.py b/backend/app/middleware/api_analytics.py
index e3aa3d72..27a120e3 100644
--- a/backend/app/middleware/api_analytics.py
+++ b/backend/app/middleware/api_analytics.py
@@ -46,11 +46,8 @@ def register_api_analytics(app):
except Exception:
pass
- ip_address = request.remote_addr
- if request.headers.get('X-Forwarded-For'):
- ip_address = request.headers.get('X-Forwarded-For').split(',')[0].strip()
- elif request.headers.get('X-Real-IP'):
- ip_address = request.headers.get('X-Real-IP')
+ from app.utils.client_ip import get_client_ip
+ ip_address = get_client_ip()
log_entry = {
'api_key_id': api_key.id if api_key else None,
diff --git a/backend/app/middleware/api_key_auth.py b/backend/app/middleware/api_key_auth.py
index 64601885..bd853806 100644
--- a/backend/app/middleware/api_key_auth.py
+++ b/backend/app/middleware/api_key_auth.py
@@ -19,14 +19,9 @@ def register_api_key_auth(app):
if not api_key:
return jsonify({'error': 'Invalid or expired API key'}), 401
- # Record usage
- ip_address = request.remote_addr
- if request.headers.get('X-Forwarded-For'):
- ip_address = request.headers.get('X-Forwarded-For').split(',')[0].strip()
- elif request.headers.get('X-Real-IP'):
- ip_address = request.headers.get('X-Real-IP')
-
- api_key.record_usage(ip_address)
+ # Record usage against the trusted client IP (see app.utils.client_ip).
+ from app.utils.client_ip import get_client_ip
+ api_key.record_usage(get_client_ip())
from app import db
db.session.commit()
diff --git a/backend/app/middleware/audit.py b/backend/app/middleware/audit.py
index 0aa609b3..d784dc35 100644
--- a/backend/app/middleware/audit.py
+++ b/backend/app/middleware/audit.py
@@ -198,8 +198,6 @@ def _is_sensitive_key(key):
def _ip_address():
- if request.headers.get('X-Forwarded-For'):
- return request.headers.get('X-Forwarded-For').split(',')[0].strip()
- if request.headers.get('X-Real-IP'):
- return request.headers.get('X-Real-IP')
- return request.remote_addr
+ # Trusted client IP only — see app.utils.client_ip. Never hand-parse XFF.
+ from app.utils.client_ip import get_client_ip
+ return get_client_ip()
diff --git a/backend/app/middleware/rate_limit.py b/backend/app/middleware/rate_limit.py
index 111ffbb6..48c0b0d0 100644
--- a/backend/app/middleware/rate_limit.py
+++ b/backend/app/middleware/rate_limit.py
@@ -1,5 +1,5 @@
"""Enhanced rate limiting with per-tier limits and response headers."""
-from flask import g, request
+from flask import g
def get_rate_limit_key():
@@ -18,13 +18,10 @@ def get_rate_limit_key():
except Exception:
pass
- # Fall back to IP
- ip = request.remote_addr
- if request.headers.get('X-Forwarded-For'):
- ip = request.headers.get('X-Forwarded-For').split(',')[0].strip()
- elif request.headers.get('X-Real-IP'):
- ip = request.headers.get('X-Real-IP')
- return f'ip:{ip}'
+ # Fall back to the trusted client IP (ProxyFix-corrected remote_addr; never
+ # a hand-parsed, client-forgeable X-Forwarded-For — see utils.client_ip).
+ from app.utils.client_ip import get_client_ip
+ return f'ip:{get_client_ip()}'
def get_dynamic_limit():
diff --git a/backend/app/services/audit_service.py b/backend/app/services/audit_service.py
index 30ed0fa5..414750d4 100644
--- a/backend/app/services/audit_service.py
+++ b/backend/app/services/audit_service.py
@@ -25,12 +25,9 @@ class AuditService:
if not has_request_context():
return None, None
- ip_address = request.remote_addr
- # Handle proxy headers
- if request.headers.get('X-Forwarded-For'):
- ip_address = request.headers.get('X-Forwarded-For').split(',')[0].strip()
- elif request.headers.get('X-Real-IP'):
- ip_address = request.headers.get('X-Real-IP')
+ # Trusted client IP only — see app.utils.client_ip. Never hand-parse XFF.
+ from app.utils.client_ip import get_client_ip
+ ip_address = get_client_ip()
user_agent = request.headers.get('User-Agent', '')[:500]
return ip_address, user_agent
diff --git a/backend/app/utils/client_ip.py b/backend/app/utils/client_ip.py
new file mode 100644
index 00000000..c80a6b98
--- /dev/null
+++ b/backend/app/utils/client_ip.py
@@ -0,0 +1,30 @@
+"""Single seam for deriving the trusted client IP.
+
+Every consumer that keys on the client's IP — rate-limit buckets, audit-log
+source IPs, API-key attribution, the per-IP auth throttle, dynamic DNS — must
+call :func:`get_client_ip` instead of hand-parsing ``X-Forwarded-For``. That
+header is client-controlled: its leftmost token is whatever the caller chose,
+so ``X-Forwarded-For.split(',')[0]`` trusts a forgeable value and lets an
+attacker rotate the IP we rate-limit / lock out / audit on.
+
+The trust decision lives in exactly one place: the config-gated Werkzeug
+``ProxyFix`` applied in :func:`app.create_app` (see ``config.TRUST_PROXY_HEADERS``
+/ ``config.TRUSTED_PROXY_HOPS``). When a proxy is trusted, ProxyFix has already
+rewritten ``request.remote_addr`` to the real client (the rightmost trusted
+hops of XFF); when it isn't, ``remote_addr`` is the direct socket peer. Either
+way this returns the one value the app has decided to trust — never a
+hand-parsed header.
+"""
+from flask import has_request_context, request
+
+
+def get_client_ip():
+ """Return the client IP the app trusts for the current request.
+
+ Post-ProxyFix (when ``TRUST_PROXY_HEADERS`` is on) ``request.remote_addr``
+ is the real client IP; otherwise it is the direct socket peer. Returns
+ ``None`` when called outside a request context.
+ """
+ if not has_request_context():
+ return None
+ return request.remote_addr
diff --git a/backend/config.py b/backend/config.py
index b882f147..a189fd11 100644
--- a/backend/config.py
+++ b/backend/config.py
@@ -32,6 +32,23 @@ def is_insecure_secret(value):
)
+def _env_bool(name, default=False):
+ """Parse a boolean env var. Accepts the usual truthy spellings; anything
+ else (including unset) falls back to ``default``."""
+ raw = os.environ.get(name)
+ if raw is None:
+ return default
+ return raw.strip().lower() in ('1', 'true', 'yes', 'on')
+
+
+def _env_int(name, default):
+ """Parse an int env var, falling back to ``default`` on unset/garbage."""
+ try:
+ return int(os.environ.get(name, default))
+ except (TypeError, ValueError):
+ return default
+
+
def _resolve_ssl_mode():
"""Whether this deployment terminates real end-to-end HTTPS.
@@ -108,6 +125,22 @@ class Config:
SSL_MODE = _resolve_ssl_mode()
HSTS_ENABLED = SSL_MODE == 'secure'
+ # ── Trusted reverse-proxy client IP ─────────────────────────────────
+ # X-Forwarded-For is client-controlled: its leftmost token is whatever the
+ # caller chose, so hand-parsing split(',')[0] lets an attacker spoof the IP
+ # we key rate-limits, lockouts and audit logs on. When the panel runs behind
+ # its bundled nginx (the shipped deploy) the real client is appended to XFF
+ # and request.remote_addr is nginx's own address. Enabling TRUST_PROXY_HEADERS
+ # wraps the app in Werkzeug ProxyFix so remote_addr becomes the real client —
+ # the rightmost TRUSTED_PROXY_HOPS entries of XFF (the hops our own proxies
+ # appended); a forged leftmost value is discarded. Ship it TRUE only where a
+ # reverse proxy is guaranteed in front; keep it FALSE for a directly-exposed
+ # dev server so headers can't be forged. See docs/plans/48 and SECURITY.md.
+ TRUST_PROXY_HEADERS = _env_bool('TRUST_PROXY_HEADERS', False)
+ # Number of trusted reverse-proxy hops in front of Flask (bundled nginx = 1).
+ # Raise it only if you add another proxy (e.g. Cloudflare in front of nginx).
+ TRUSTED_PROXY_HOPS = _env_int('TRUSTED_PROXY_HOPS', 1)
+
# ── Build packs ─────────────────────────────────────────────────────
# Path to the optional nixpacks binary (used by build_service's opaque
# nixpacks path). The transparent build-pack layer (buildpack_service)
diff --git a/backend/tests/test_trusted_client_ip.py b/backend/tests/test_trusted_client_ip.py
new file mode 100644
index 00000000..8a137903
--- /dev/null
+++ b/backend/tests/test_trusted_client_ip.py
@@ -0,0 +1,150 @@
+"""Proving tests for the trusted client-IP seam (plan 48, Phase 1).
+
+The old code hand-parsed the *leftmost* X-Forwarded-For token — a value the
+client fully controls — to key rate-limit buckets, audit-log source IPs and
+API-key attribution. These tests pin the corrected behaviour:
+
+- With trust OFF (dev default), a forged X-Forwarded-For never changes the IP
+ the app trusts: get_client_ip() stays the socket peer (remote_addr).
+- With trust ON behind one proxy hop, ProxyFix takes the *rightmost* hop the
+ trusted proxy appended, so a forged leftmost value is discarded.
+- The rate-limit key follows the real client, so two requests forging the same
+ leftmost value from different real peers land in *different* buckets, and
+ flask-limiter isolates them.
+"""
+import pytest
+
+from app import create_app
+
+
+def _build_app(monkeypatch, trust, hops=1):
+ """Create a testing app with the trusted-proxy config forced on/off.
+
+ from_object reads the class attribute at create_app time, so monkeypatching
+ it before the call drives the real ProxyFix gating in create_app().
+ """
+ from config import TestingConfig
+ monkeypatch.setattr(TestingConfig, 'TRUST_PROXY_HEADERS', trust)
+ monkeypatch.setattr(TestingConfig, 'TRUSTED_PROXY_HOPS', hops)
+ app = create_app('testing')
+
+ from app.utils.client_ip import get_client_ip
+ from app.middleware.rate_limit import get_rate_limit_key
+
+ # Non-/api probe so the audit/analytics/2FA before-request handlers skip it.
+ def _probe():
+ return {'ip': get_client_ip() or '', 'rlkey': get_rate_limit_key()}
+
+ app.add_url_rule('/__probe_ip', '__probe_ip', _probe)
+ return app
+
+
+# --- Trust OFF: forged headers must be ignored --------------------------
+
+def test_forged_xff_ignored_when_trust_off(monkeypatch):
+ app = _build_app(monkeypatch, trust=False)
+ client = app.test_client()
+
+ resp = client.get(
+ '/__probe_ip',
+ headers={'X-Forwarded-For': '9.9.9.9'},
+ environ_overrides={'REMOTE_ADDR': '203.0.113.7'},
+ )
+ assert resp.status_code == 200
+ # remote_addr wins — the forged 9.9.9.9 is never trusted.
+ assert resp.get_json()['ip'] == '203.0.113.7'
+
+
+def test_forged_xreal_ip_ignored_when_trust_off(monkeypatch):
+ app = _build_app(monkeypatch, trust=False)
+ client = app.test_client()
+
+ resp = client.get(
+ '/__probe_ip',
+ headers={'X-Real-IP': '9.9.9.9', 'X-Forwarded-For': '8.8.8.8'},
+ environ_overrides={'REMOTE_ADDR': '198.51.100.4'},
+ )
+ assert resp.get_json()['ip'] == '198.51.100.4'
+
+
+# --- Trust ON, one hop: rightmost (proxy-appended) hop wins -------------
+
+def test_proxy_appended_hop_wins_when_trust_on(monkeypatch):
+ app = _build_app(monkeypatch, trust=True, hops=1)
+ client = app.test_client()
+
+ # nginx received "9.9.9.9" from the client and appended the real peer.
+ resp = client.get(
+ '/__probe_ip',
+ headers={'X-Forwarded-For': '9.9.9.9, 203.0.113.7'},
+ environ_overrides={'REMOTE_ADDR': '127.0.0.1'}, # nginx -> flask
+ )
+ assert resp.status_code == 200
+ assert resp.get_json()['ip'] == '203.0.113.7'
+
+
+def test_multiple_forged_hops_all_discarded(monkeypatch):
+ app = _build_app(monkeypatch, trust=True, hops=1)
+ client = app.test_client()
+
+ resp = client.get(
+ '/__probe_ip',
+ headers={'X-Forwarded-For': '1.2.3.4, 5.6.7.8, 203.0.113.7'},
+ environ_overrides={'REMOTE_ADDR': '127.0.0.1'},
+ )
+ # Only the rightmost (the single trusted hop) survives.
+ assert resp.get_json()['ip'] == '203.0.113.7'
+
+
+# --- Rate-limit key follows the real client, not the forged prefix ------
+
+def test_same_forged_prefix_different_peer_not_merged(monkeypatch):
+ app = _build_app(monkeypatch, trust=True, hops=1)
+ client = app.test_client()
+
+ a = client.get('/__probe_ip',
+ headers={'X-Forwarded-For': '1.1.1.1, 10.0.0.1'})
+ b = client.get('/__probe_ip',
+ headers={'X-Forwarded-For': '1.1.1.1, 10.0.0.2'})
+
+ # Same forged leftmost, different real peer -> different IPs and rl-keys.
+ assert a.get_json()['ip'] == '10.0.0.1'
+ assert b.get_json()['ip'] == '10.0.0.2'
+ assert a.get_json()['rlkey'] != b.get_json()['rlkey']
+ assert a.get_json()['rlkey'] == 'ip:10.0.0.1'
+
+
+def test_different_forged_prefix_same_peer_is_one_bucket(monkeypatch):
+ app = _build_app(monkeypatch, trust=True, hops=1)
+ client = app.test_client()
+
+ a = client.get('/__probe_ip',
+ headers={'X-Forwarded-For': '1.1.1.1, 10.0.0.9'})
+ b = client.get('/__probe_ip',
+ headers={'X-Forwarded-For': '2.2.2.2, 10.0.0.9'})
+
+ # Rotating the forged prefix cannot escape the real client's bucket.
+ assert a.get_json()['rlkey'] == b.get_json()['rlkey'] == 'ip:10.0.0.9'
+
+
+def test_flask_limiter_isolates_real_client_buckets(monkeypatch):
+ """flask-limiter's 5/min on /login must key on the real client, so
+ exhausting one client's bucket does not lock out a different client that
+ merely shares a forged leftmost XFF value."""
+ app = _build_app(monkeypatch, trust=True, hops=1)
+ client = app.test_client()
+
+ def _login(rightmost):
+ return client.post(
+ '/api/v1/auth/login',
+ json={'email': '[email protected]', 'password': 'wrong'},
+ headers={'X-Forwarded-For': f'1.1.1.1, {rightmost}'},
+ )
+
+ # Client A (real peer 203.0.113.10) exhausts its 5/min login budget.
+ statuses = [_login('203.0.113.10').status_code for _ in range(6)]
+ assert 429 in statuses, statuses # limiter tripped for client A
+
+ # Client B forges the SAME leftmost 1.1.1.1 but is a different real peer:
+ # it must not inherit A's exhausted bucket.
+ assert _login('203.0.113.20').status_code != 429