🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!
Security: framing protection header, trust forwarded headers only from local peers (CFG-07a, CFG-11)
Omega (QA)882706b90da9
diff --git a/backend/__init__.py b/backend/__init__.pyindex 164709c..b6db874 100644--- a/backend/__init__.py+++ b/backend/__init__.py@@ -1,4 +1,5 @@# backend/__init__.py+import ipaddressimport osimport loggingimport psycopg2.errors@@ -7,6 +8,67 @@ from werkzeug.middleware.proxy_fix import ProxyFixlogger = logging.getLogger(__name__)+def _forwarded_headers_trusted(remote_addr):+ """Whether X-Forwarded-* headers from this peer may be believed.++ ProxyFix trusts forwarded headers from any peer, so with the app+ directly exposed a spoofed X-Forwarded-For is stored as the login+ IP (CFG-11). The shipped topology has nginx on loopback in front of+ the app, and split deployments sit behind a LAN proxy, so only+ loopback, private, and link-local peers are trusted by default.+ TRUST_PROXY_HEADERS=true restores trust-everything for operators+ behind a public-IP proxy; TRUST_PROXY_HEADERS=false trusts none.+ """+ override = os.environ.get('TRUST_PROXY_HEADERS', '').lower()+ if override == 'true':+ return True+ if override == 'false':+ return False+ try:+ addr = ipaddress.ip_address(remote_addr or '')+ except ValueError:+ return False+ # Explicit networks, not is_private: ipaddress counts documentation+ # ranges such as 203.0.113.0/24 as private, and those are not peers+ # a proxy would ever connect from.+ trusted = (+ ipaddress.ip_network('127.0.0.0/8'),+ ipaddress.ip_network('10.0.0.0/8'),+ ipaddress.ip_network('172.16.0.0/12'),+ ipaddress.ip_network('192.168.0.0/16'),+ ipaddress.ip_network('169.254.0.0/16'),+ ipaddress.ip_network('::1/128'),+ ipaddress.ip_network('fc00::/7'),+ ipaddress.ip_network('fe80::/10'),+ )+ return any(+ addr.version == net.version and addr in net for net in trusted+ )+++class _ForwardedHeaderGuard:+ """Strip forwarded headers from untrusted peers, before ProxyFix.++ Runs outside ProxyFix so a spoofed header never reaches it. Peers+ trusted by _forwarded_headers_trusted pass through untouched.+ """+ _FORWARDED_HEADERS = (+ 'HTTP_X_FORWARDED_FOR',+ 'HTTP_X_FORWARDED_PROTO',+ 'HTTP_X_FORWARDED_HOST',+ 'HTTP_X_FORWARDED_PREFIX',+ )++ def __init__(self, app):+ self.app = app++ def __call__(self, environ, start_response):+ if not _forwarded_headers_trusted(environ.get('REMOTE_ADDR', '')):+ for header in self._FORWARDED_HEADERS:+ environ.pop(header, None)+ return self.app(environ, start_response)++def ensure_owner_exists():"""Ensure that an application owner exists. This is a backup mechanism@@ -121,8 +183,19 @@ def create_app(config_name=None):# Create Flask app instanceapp = Flask(__name__)- # Apply ProxyFix middleware for reverse proxy support+ # Apply ProxyFix middleware for reverse proxy support, guarded so+ # forwarded headers from untrusted (directly exposed) peers are+ # dropped before ProxyFix can act on them (CFG-11).app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1)+ app.wsgi_app = _ForwardedHeaderGuard(app.wsgi_app)++ @app.after_request+ def _set_framing_protection(response):+ # CFG-07a: never render framed by another origin. SAMEORIGIN+ # keeps any same-origin framing working while blocking the+ # cross-origin clickjacking case.+ response.headers.setdefault('X-Frame-Options', 'SAMEORIGIN')+ return response# Load configurationtry:diff --git a/tests/test_proxy_and_framing.py b/tests/test_proxy_and_framing.pynew file mode 100644index 0000000..6d4f666--- /dev/null+++ b/tests/test_proxy_and_framing.py@@ -0,0 +1,81 @@+"""Framing protection (CFG-07a) and forwarded-header trust (CFG-11).++CFG-07a: every response carries X-Frame-Options so the app never+renders framed by another origin.++CFG-11: with the app directly exposed, a spoofed X-Forwarded-For was+stored as the login IP because ProxyFix trusted every peer. Forwarded+headers are now honored only from loopback, private, or link-local+peers (the shipped nginx and LAN proxy shapes); other peers have them+stripped before ProxyFix sees them.+"""+import pytest++from backend import _forwarded_headers_trusted+++def test_frame_options_header_on_api_response(client):+ r = client.get("/api/health")+ assert r.headers.get("X-Frame-Options") == "SAMEORIGIN"++[email protected]("addr,trusted", [+ ("127.0.0.1", True),+ ("::1", True),+ ("10.1.2.3", True),+ ("172.16.0.5", True),+ ("192.168.1.1", True),+ ("169.254.1.1", True),+ ("203.0.113.5", False),+ ("8.8.8.8", False),+ ("", False),+ ("not-an-ip", False),+])+def test_forwarded_headers_trust_matrix(monkeypatch, addr, trusted):+ monkeypatch.delenv("TRUST_PROXY_HEADERS", raising=False)+ assert _forwarded_headers_trusted(addr) is trusted+++def test_trust_proxy_headers_override(monkeypatch):+ monkeypatch.setenv("TRUST_PROXY_HEADERS", "true")+ assert _forwarded_headers_trusted("8.8.8.8") is True+ monkeypatch.setenv("TRUST_PROXY_HEADERS", "false")+ assert _forwarded_headers_trusted("127.0.0.1") is False+++def _latest_session_ip(db_connection, username):+ with db_connection.cursor() as cur:+ cur.execute("SELECT id FROM users WHERE username = %s", (username,))+ user_id = cur.fetchone()[0]+ cur.execute(+ "SELECT ip_address FROM user_sessions WHERE user_id = %s "+ "ORDER BY id DESC LIMIT 1",+ (user_id,),+ )+ return cur.fetchone()[0]+++def test_spoofed_forwarded_for_ignored_from_public_peer(+ client, user_factory, db_connection):+ user = user_factory()+ r = client.post(+ "/api/auth/login",+ json={"username": user["username"], "password": "TestPass123!"},+ headers={"X-Forwarded-For": "198.51.100.77"},+ environ_base={"REMOTE_ADDR": "203.0.113.5"},+ )+ assert r.status_code == 200+ assert _latest_session_ip(db_connection, user["username"]) == "203.0.113.5"+++def test_forwarded_for_honored_from_loopback_peer(+ client, user_factory, db_connection):+ user = user_factory()+ r = client.post(+ "/api/auth/login",+ json={"username": user["username"], "password": "TestPass123!"},+ headers={"X-Forwarded-For": "198.51.100.77"},+ environ_base={"REMOTE_ADDR": "127.0.0.1"},+ )+ assert r.status_code == 200+ assert _latest_session_ip(db_connection, user["username"]) == "198.51.100.77"