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(firewall): guard self-block and default-zone lockouts

Juan Denisfe986c8f35d9
diff --git a/backend/app/api/firewall.py b/backend/app/api/firewall.py
index 3dee719a..f4b1d969 100644
--- a/backend/app/api/firewall.py
+++ b/backend/app/api/firewall.py
@@ -158,10 +158,18 @@ def block_ip():
permanent = data.get('permanent', True)
- result = FirewallService.block_ip(ip, permanent)
+ # request.remote_addr is the real client when TRUST_PROXY_HEADERS is on
+ # (ProxyFix rewrites it); otherwise it is the proxy, which is still worth
+ # refusing to block. Read here rather than in the service, so the service
+ # stays free of request context.
+ result = FirewallService.block_ip(ip, permanent,
+ force=bool(data.get('force')),
+ caller_ip=request.remote_addr)
if result.get('success'):
return jsonify(result), 201
+ if result.get('blocked_by') == 'ssh_lockout':
+ return jsonify(result), 409
return jsonify(result), 400
@@ -273,10 +281,12 @@ def set_default_zone():
if not zone:
return jsonify({'success': False, 'error': 'Zone name required'}), 400
- result = FirewallService.set_default_zone(zone)
+ result = FirewallService.set_default_zone(zone, force=bool(data.get('force')))
if result.get('success'):
return jsonify(result), 200
+ if result.get('blocked_by') == 'ssh_lockout':
+ return jsonify(result), 409
return jsonify(result), 400
diff --git a/backend/app/services/firewall_service.py b/backend/app/services/firewall_service.py
index 6f67da94..ecb0ce1c 100644
--- a/backend/app/services/firewall_service.py
+++ b/backend/app/services/firewall_service.py
@@ -843,13 +843,124 @@ class FirewallService:
except Exception as e:
return {'success': False, 'error': str(e)}
+ # ------------------------------------------------------------------
+ # Blocking your own address
+ # ------------------------------------------------------------------
+ #: The port-based guards do not help here: the SSH rule stays exactly as it
+ #: is, and the operator is still locked out because their *source* address
+ #: is now rejected.
+
@classmethod
- def block_ip(cls, ip: str, permanent: bool = True) -> Dict:
- """Quick method to block an IP address."""
+ def active_ssh_peers(cls) -> set:
+ """Source addresses of live SSH sessions.
+
+ Read from `ss`, whose established-connection view is authoritative;
+ `who` is empty for sessions that never allocated a utmp entry.
+ """
+ ports = cls.ssh_ports() or []
+ peers = set()
+ try:
+ result = run_privileged(['ss', '-Htn', 'state', 'established'],
+ timeout=PROBE_TIMEOUT)
+ except Exception:
+ return peers
+ if result.returncode != 0:
+ return peers
+
+ # `0 0 146.190.213.37:22 73.244.95.52:59085` — Recv-Q, Send-Q, local,
+ # peer. The State column is absent because `state established` filtered it.
+ for line in (result.stdout or '').splitlines():
+ fields = line.split()
+ if len(fields) < 4:
+ continue
+ local, peer = fields[2], fields[3]
+ try:
+ local_port = int(local.rsplit(':', 1)[-1])
+ except (ValueError, IndexError):
+ continue
+ if ports and local_port not in ports:
+ continue
+ address = peer.rsplit(':', 1)[0].strip('[]')
+ if address:
+ peers.add(address)
+ return peers
+
+ @staticmethod
+ def _covers_address(blocked: str, address: str) -> bool:
+ """Does *blocked* (an IP or CIDR) match *address*?"""
+ import ipaddress
+ try:
+ network = ipaddress.ip_network(blocked.strip(), strict=False)
+ return ipaddress.ip_address(address.strip()) in network
+ except ValueError:
+ return blocked.strip() == address.strip()
+
+ @classmethod
+ def check_ip_block(cls, ip: str, caller_ip: str = None) -> Dict:
+ """Would blocking *ip* cut off the person doing the blocking?
+
+ ``caller_ip`` is the address of the HTTP request asking for the block —
+ passed in by the API layer rather than read here, so the service stays
+ free of request context.
+ """
+ import ipaddress
+
+ try:
+ network = ipaddress.ip_network(ip.strip(), strict=False)
+ if network.is_loopback:
+ return {
+ 'safe': False,
+ 'reason': ('Blocking loopback cuts the panel off from its own '
+ 'reverse proxy — nginx forwards to 127.0.0.1.'),
+ 'ip': ip, 'conflicts': ['loopback'],
+ }
+ except ValueError:
+ pass
+
+ conflicts = []
+ for peer in sorted(cls.active_ssh_peers()):
+ if cls._covers_address(ip, peer):
+ conflicts.append(peer)
+
+ if caller_ip and cls._covers_address(ip, caller_ip) and caller_ip not in conflicts:
+ conflicts.append(caller_ip)
+
+ if conflicts:
+ listed = ', '.join(conflicts)
+ return {
+ 'safe': False,
+ 'reason': (f'{ip} covers an address you are currently connected '
+ f'from ({listed}). Blocking it ends your own session.'),
+ 'ip': ip,
+ 'conflicts': conflicts,
+ }
+
+ return {'safe': True, 'reason': 'not an address you are connected from',
+ 'ip': ip, 'conflicts': []}
+
+ @classmethod
+ def block_ip(cls, ip: str, permanent: bool = True, force: bool = False,
+ caller_ip: str = None) -> Dict:
+ """Quick method to block an IP address.
+
+ Refuses when the address covers a live SSH session or the caller's own
+ connection. ``force=True`` is the operator accepting the risk.
+ """
# Validate IP format
if not cls._is_valid_ip(ip):
return {'success': False, 'error': 'Invalid IP address format'}
+ if not force:
+ preflight = cls.check_ip_block(ip, caller_ip=caller_ip)
+ if not preflight['safe']:
+ return {
+ 'success': False,
+ 'error': preflight['reason'],
+ 'blocked_by': 'ssh_lockout',
+ 'conflicts': preflight['conflicts'],
+ 'override': 'Send force=true to block it anyway.',
+ }
+
return cls.add_rule('block_ip', ip=ip, permanent=permanent)
@classmethod
@@ -938,8 +1049,70 @@ class FirewallService:
return {'success': False, 'error': str(e)}
@classmethod
- def set_default_zone(cls, zone: str) -> Dict:
- """Set default firewalld zone."""
+ def check_default_zone(cls, zone: str) -> Dict:
+ """Does *zone* admit SSH?
+
+ Switching the default zone re-homes every interface that has no explicit
+ zone. A target that does not permit ssh drops the operator's session the
+ instant it applies — the rules were never touched, the zone around them
+ changed.
+ """
+ status = cls.get_status()
+ if not status.get('firewalld', {}).get('running'):
+ return {'safe': True, 'reason': 'firewalld is not running',
+ 'ssh_ports': None, 'zone': zone}
+
+ ssh = cls.ssh_ports()
+ if ssh is None:
+ return {
+ 'safe': False,
+ 'reason': ('Could not determine which port sshd is listening on, '
+ f'so there is no way to confirm zone {zone} keeps it '
+ 'reachable.'),
+ 'ssh_ports': None, 'zone': zone,
+ }
+
+ for flag in ('--list-services', '--list-ports'):
+ try:
+ result = run_privileged(['firewall-cmd', f'--zone={zone}', flag],
+ timeout=PROBE_TIMEOUT)
+ except Exception:
+ continue
+ if result.returncode != 0:
+ continue
+ for token in (result.stdout or '').split():
+ if token == 'ssh' or cls._ports_in(token) & set(ssh):
+ return {'safe': True,
+ 'reason': f'zone {zone} admits SSH via {token}',
+ 'ssh_ports': ssh, 'zone': zone}
+
+ listed = ', '.join(str(p) for p in ssh)
+ return {
+ 'safe': False,
+ 'reason': (f'Zone {zone} does not permit SSH on port {listed}. Making '
+ f'it the default drops your session as soon as it applies.'),
+ 'ssh_ports': ssh, 'zone': zone,
+ }
+
+ @classmethod
+ def set_default_zone(cls, zone: str, force: bool = False) -> Dict:
+ """Set default firewalld zone.
+
+ Refuses when the target zone would not admit SSH. ``force=True`` is the
+ operator accepting the risk.
+ """
+ if not force:
+ preflight = cls.check_default_zone(zone)
+ if not preflight['safe']:
+ return {
+ 'success': False,
+ 'error': preflight['reason'],
+ 'blocked_by': 'ssh_lockout',
+ 'ssh_ports': preflight['ssh_ports'],
+ 'zone': zone,
+ 'override': 'Send force=true to switch anyway.',
+ }
+
try:
result = run_privileged(['firewall-cmd', f'--set-default-zone={zone}'])
if result.returncode == 0:
diff --git a/backend/tests/test_firewall_self_block_guard.py b/backend/tests/test_firewall_self_block_guard.py
new file mode 100644
index 00000000..ea79bcc1
--- /dev/null
+++ b/backend/tests/test_firewall_self_block_guard.py
@@ -0,0 +1,267 @@
+"""Two lockouts the port-based guards cannot see.
+
+`enable()` and `remove_rule()` reason about *ports*. These two paths never touch
+the SSH rule at all, and lock the operator out anyway:
+
+ block_ip(<your own address>) — the SSH rule is untouched; your source address
+ is now rejected before it reaches the rule.
+ set_default_zone(<zone without ssh>) — firewalld re-homes every interface with
+ no explicit zone; the rules did not change,
+ the zone around them did.
+
+Peer detection is read from `ss`, verified against a real host whose only
+established SSH connection was `146.190.213.37:22 <- 73.244.95.52:59085` — the
+operator's own laptop, and exactly the address a careless block would target.
+"""
+
+import subprocess
+from unittest.mock import patch
+
+import pytest
+
+from app.services.firewall_service import FirewallService
+
+# Real `ss -Htn state established` output: Recv-Q Send-Q Local Peer.
+# The State column is absent because `state established` already filtered it.
+SS_OUTPUT = (
+ '0 0 146.190.213.37:22 73.244.95.52:59085\n'
+ '0 0 146.190.213.37:443 203.0.113.9:44100\n'
+)
+SSHD_22 = 'port 22\n'
+
+
+def _completed(stdout='', returncode=0):
+ return subprocess.CompletedProcess([], returncode, stdout=stdout, stderr='')
+
+
+def _router(ss=SS_OUTPUT, sshd=SSHD_22):
+ def _run(cmd, *args, **kwargs):
+ if cmd[0] == 'sshd':
+ return _completed(sshd)
+ if cmd[0] == 'ss':
+ return _completed(ss)
+ return _completed()
+ return _run
+
+
+# --------------------------------------------------------------------------- #
+# block_ip
+# --------------------------------------------------------------------------- #
+
+@patch('app.services.firewall_service.run_privileged')
+def test_peers_are_read_from_ss_and_filtered_to_ssh_ports(run):
+ """The :443 connection is not an SSH session and must not be protected."""
+ run.side_effect = _router()
+
+ assert FirewallService.active_ssh_peers() == {'73.244.95.52'}
+
+
+@patch('app.services.firewall_service.run_privileged')
+def test_blocking_your_own_ssh_source_is_refused(run):
+ run.side_effect = _router()
+
+ check = FirewallService.check_ip_block('73.244.95.52')
+
+ assert check['safe'] is False
+ assert check['conflicts'] == ['73.244.95.52']
+
+
+@patch('app.services.firewall_service.run_privileged')
+def test_blocking_someone_else_is_allowed(run):
+ run.side_effect = _router()
+
+ assert FirewallService.check_ip_block('198.51.100.7')['safe'] is True
+
+
+@patch('app.services.firewall_service.run_privileged')
+def test_a_cidr_that_swallows_your_session_is_refused(run):
+ """Blocking 73.244.0.0/16 is the same lockout wearing a wider mask."""
+ run.side_effect = _router()
+
+ check = FirewallService.check_ip_block('73.244.0.0/16')
+
+ assert check['safe'] is False
+ assert '73.244.95.52' in check['conflicts']
+
+
+@patch('app.services.firewall_service.run_privileged')
+def test_a_cidr_that_misses_your_session_is_allowed(run):
+ run.side_effect = _router()
+
+ assert FirewallService.check_ip_block('198.51.100.0/24')['safe'] is True
+
+
+@patch('app.services.firewall_service.run_privileged')
+def test_blocking_loopback_is_refused(run):
+ """nginx forwards to 127.0.0.1 — blocking it takes the panel down."""
+ run.side_effect = _router(ss='')
+
+ check = FirewallService.check_ip_block('127.0.0.1')
+
+ assert check['safe'] is False
+ assert check['conflicts'] == ['loopback']
+
+
+@patch('app.services.firewall_service.run_privileged')
+def test_the_panel_callers_own_address_is_refused(run):
+ """No SSH session at all, but blocking it still locks them out of the UI."""
+ run.side_effect = _router(ss='')
+
+ check = FirewallService.check_ip_block('203.0.113.5', caller_ip='203.0.113.5')
+
+ assert check['safe'] is False
+ assert check['conflicts'] == ['203.0.113.5']
+
+
+@patch('app.services.firewall_service.run_privileged')
+def test_caller_ip_is_not_double_reported(run):
+ """Same address via SSH and the panel is one conflict, not two."""
+ run.side_effect = _router()
+
+ check = FirewallService.check_ip_block('73.244.95.52', caller_ip='73.244.95.52')
+
+ assert check['conflicts'] == ['73.244.95.52']
+
+
+@patch('app.services.firewall_service.run_privileged')
+def test_unreadable_ss_does_not_fabricate_peers(run):
+ """A failed probe must not invent conflicts and block every request."""
+ run.side_effect = _router(ss='')
+
+ assert FirewallService.active_ssh_peers() == set()
+ assert FirewallService.check_ip_block('198.51.100.7')['safe'] is True
+
+
[email protected](FirewallService, 'add_rule')
+@patch('app.services.firewall_service.run_privileged')
+def test_block_ip_refuses_and_never_adds_the_rule(run, add_rule):
+ run.side_effect = _router()
+
+ result = FirewallService.block_ip('73.244.95.52')
+
+ assert result['success'] is False
+ assert result['blocked_by'] == 'ssh_lockout'
+ add_rule.assert_not_called()
+
+
[email protected](FirewallService, 'add_rule', return_value={'success': True})
+@patch('app.services.firewall_service.run_privileged')
+def test_force_overrides_the_self_block_guard(run, add_rule):
+ run.side_effect = _router()
+
+ assert FirewallService.block_ip('73.244.95.52', force=True)['success'] is True
+ add_rule.assert_called_once()
+
+
[email protected](FirewallService, 'add_rule', return_value={'success': True})
+@patch('app.services.firewall_service.run_privileged')
+def test_blocking_an_unrelated_ip_proceeds(run, add_rule):
+ run.side_effect = _router()
+
+ assert FirewallService.block_ip('198.51.100.7')['success'] is True
+ add_rule.assert_called_once()
+
+
[email protected](FirewallService, 'add_rule')
+def test_invalid_ip_is_still_rejected_first(add_rule):
+ result = FirewallService.block_ip('not-an-ip')
+
+ assert result['error'] == 'Invalid IP address format'
+ add_rule.assert_not_called()
+
+
+# --------------------------------------------------------------------------- #
+# set_default_zone
+# --------------------------------------------------------------------------- #
+
+def _running_firewalld():
+ with patch.object(FirewallService, 'get_status', return_value={
+ 'firewalld': {'installed': True, 'running': True, 'default_zone': 'public'},
+ 'ufw': {'installed': False, 'active': False},
+ 'active_firewall': 'firewalld', 'any_installed': True, 'any_active': True,
+ }):
+ yield
+
+
+def _zone_router(services='', ports='', sshd=SSHD_22):
+ def _run(cmd, *args, **kwargs):
+ if cmd[0] == 'sshd':
+ return _completed(sshd)
+ if len(cmd) > 2 and cmd[2] == '--list-services':
+ return _completed(services)
+ if len(cmd) > 2 and cmd[2] == '--list-ports':
+ return _completed(ports)
+ return _completed()
+ return _run
+
+
+@patch('app.services.firewall_service.run_privileged')
+def test_zone_without_ssh_is_refused(run, _running_firewalld):
+ run.side_effect = _zone_router(services='dhcpv6-client')
+
+ check = FirewallService.check_default_zone('drop')
+
+ assert check['safe'] is False
+ assert 'does not permit SSH' in check['reason']
+
+
+@patch('app.services.firewall_service.run_privileged')
+def test_zone_with_the_ssh_service_is_allowed(run, _running_firewalld):
+ run.side_effect = _zone_router(services='ssh dhcpv6-client')
+
+ assert FirewallService.check_default_zone('public')['safe'] is True
+
+
+@patch('app.services.firewall_service.run_privileged')
+def test_zone_with_the_ssh_port_is_allowed(run, _running_firewalld):
+ """Coverage by explicit port counts, not just the named service."""
+ run.side_effect = _zone_router(services='http', ports='22/tcp')
+
+ assert FirewallService.check_default_zone('custom')['safe'] is True
+
+
+@patch('app.services.firewall_service.run_privileged')
+def test_zone_change_refuses_when_ssh_port_is_undeterminable(run, _running_firewalld):
+ run.side_effect = _zone_router(services='ssh', sshd='')
+
+ def _run(cmd, *args, **kwargs):
+ if cmd[0] == 'sshd':
+ return _completed(returncode=1)
+ return _completed('ssh')
+ run.side_effect = _run
+
+ check = FirewallService.check_default_zone('public')
+
+ assert check['safe'] is False
+ assert check['ssh_ports'] is None
+
+
+def test_zone_guard_is_a_noop_when_firewalld_is_not_running():
+ with patch.object(FirewallService, 'get_status', return_value={
+ 'firewalld': {'installed': True, 'running': False, 'default_zone': None},
+ 'ufw': {'installed': False, 'active': False},
+ 'active_firewall': 'firewalld', 'any_installed': True, 'any_active': False,
+ }):
+ assert FirewallService.check_default_zone('drop')['safe'] is True
+
+
+@patch('app.services.firewall_service.run_privileged')
+def test_set_default_zone_refuses_and_never_shells_out(run, _running_firewalld):
+ run.side_effect = _zone_router(services='dhcpv6-client')
+
+ result = FirewallService.set_default_zone('drop')
+
+ assert result['success'] is False
+ assert result['blocked_by'] == 'ssh_lockout'
+ assert not any('--set-default-zone' in str(c) for c in run.call_args_list)
+
+
+@patch('app.services.firewall_service.run_privileged')
+def test_force_overrides_the_zone_guard(run, _running_firewalld):
+ run.side_effect = _zone_router(services='dhcpv6-client')
+
+ result = FirewallService.set_default_zone('drop', force=True)
+
+ assert result['success'] is True
+ assert any('--set-default-zone' in str(c) for c in run.call_args_list)