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.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(firewall): refuse to enable ufw when it would cut off SSH
Juan Denis454ee552c2c4
diff --git a/backend/app/api/firewall.py b/backend/app/api/firewall.pyindex 2087126f..6fbb5d75 100644--- a/backend/app/api/firewall.py+++ b/backend/app/api/firewall.py@@ -17,17 +17,40 @@ def get_status():return jsonify(result), 200+@firewall_bp.route('/ssh-preflight', methods=['GET'])+@viewer_required+def ssh_preflight():+ """Would enabling the firewall cut off SSH?++ Lets the UI warn before the operator clicks, rather than reporting a+ lockout after it has already happened.+ """+ firewall = request.args.get('firewall') or (+ FirewallService.get_status().get('active_firewall') or 'ufw')+ return jsonify(FirewallService.check_ssh_lockout(firewall)), 200++@firewall_bp.route('/enable', methods=['POST'])@admin_requireddef enable_firewall():- """Enable the firewall."""+ """Enable the firewall.++ Blocked with 409 when no rule covers the live SSH port — `ufw --force+ enable` suppresses ufw's own "may disrupt existing ssh connections" prompt,+ so this is the only thing standing between a click and a locked-out box.+ Resend with force=true to override.+ """data = request.get_json() or {}firewall = data.get('firewall')+ force = bool(data.get('force'))- result = FirewallService.enable(firewall)+ result = FirewallService.enable(firewall, force=force)if result.get('success'):return jsonify(result), 200+ # 409, not 400: the request is well-formed, the server state conflicts.+ if result.get('blocked_by') == 'ssh_lockout':+ return jsonify(result), 409return jsonify(result), 400diff --git a/backend/app/services/firewall_service.py b/backend/app/services/firewall_service.pyindex 1b6980c1..50d99571 100644--- a/backend/app/services/firewall_service.py+++ b/backend/app/services/firewall_service.py@@ -7,6 +7,7 @@ from typing import Dict, List, Optionalfrom datetime import datetimefrom app.utils.system import (+ PROBE_TIMEOUT,PackageManager,ServiceControl,is_command_available,@@ -101,19 +102,175 @@ class FirewallService:'active': active}+ # ------------------------------------------------------------------+ # SSH lockout preflight+ # ------------------------------------------------------------------+ #: ufw's own `enable` asks "Command may disrupt existing ssh connections.+ #: Proceed?" — and `--force enable`, which this service uses because nothing+ #: here is attached to a terminal, suppresses exactly that prompt. Without a+ #: replacement check the panel will happily lock an operator out of a remote+ #: box in one click, with no way back in.++ @classmethod+ def ssh_ports(cls) -> Optional[List[int]]:+ """Ports sshd is actually listening on, or None if undeterminable.++ ``sshd -T`` is the authority: it resolves Includes, Match blocks and+ compiled-in defaults, which parsing sshd_config by hand does not.++ Returns None — never a guessed ``[22]`` — when sshd cannot be asked. A+ wrong guess here is a lockout, so "I don't know" has to stay a distinct+ answer the caller can refuse to act on.+ """+ try:+ result = run_privileged(['sshd', '-T'], timeout=PROBE_TIMEOUT)+ except Exception:+ return None+ if result.returncode != 0:+ return None++ ports = []+ for line in (result.stdout or '').splitlines():+ match = re.match(r'^\s*port\s+(\d+)\s*$', line, re.I)+ if match:+ ports.append(int(match.group(1)))+ return sorted(set(ports)) or None++ @classmethod+ def _ufw_default_incoming_allow(cls) -> bool:+ """True when ufw's default inbound policy is ACCEPT (no lockout risk)."""+ try:+ with open('/etc/default/ufw', 'r') as handle:+ for line in handle:+ match = re.match(r'^\s*DEFAULT_INPUT_POLICY\s*=\s*"?(\w+)"?',+ line)+ if match:+ return match.group(1).upper() == 'ACCEPT'+ except Exception:+ pass+ return False++ @classmethod+ def _ufw_allowed_ports(cls) -> set:+ """Ports covered by a staged ufw *allow* rule.++ Reads `ufw show added`, which lists rules staged while the firewall is+ still inactive — the only rules that will exist the instant it comes up.+ Named application profiles (``ufw allow OpenSSH``) are resolved through+ ``ufw app info`` rather than assumed, since guessing in the permissive+ direction is what would cause the lockout this check exists to prevent.+ """+ allowed = set()+ try:+ result = run_privileged(['ufw', 'show', 'added'], timeout=PROBE_TIMEOUT)+ except Exception:+ return allowed+ if result.returncode != 0:+ return allowed++ for line in (result.stdout or '').splitlines():+ line = line.strip()+ if 'allow' not in line:+ continue+ numbers = re.findall(r'\b(\d{1,5})(?:/(?:tcp|udp))?\b', line)+ allowed.update(int(n) for n in numbers if 0 < int(n) <= 65535)++ profile = re.search(r'allow\s+([A-Za-z][\w .-]*)$', line)+ if profile:+ allowed.update(cls._app_profile_ports(profile.group(1).strip()))+ return allowed++ @classmethod+ def _app_profile_ports(cls, profile: str) -> set:+ """Ports behind a ufw application profile name."""+ ports = set()+ try:+ result = run_privileged(['ufw', 'app', 'info', profile],+ timeout=PROBE_TIMEOUT)+ except Exception:+ return ports+ if result.returncode != 0:+ return ports+ for match in re.finditer(r'\b(\d{1,5})(?:/(?:tcp|udp))?\b',+ (result.stdout or '')):+ ports.add(int(match.group(1)))+ return ports++ @classmethod+ def check_ssh_lockout(cls, firewall: str = 'ufw') -> Dict:+ """Would enabling *firewall* right now cut off SSH?++ Returns ``{'safe': bool, 'reason': str, 'ssh_ports': [...] | None,+ 'allowed_ports': [...]}``. Advisory data — ``enable()`` decides.+ """+ if firewall != 'ufw':+ # firewalld's default zone keeps the ssh service open, and enabling+ # it does not flush existing rules the way `ufw enable` applies a+ # fresh default-deny.+ return {'safe': True, 'reason': 'not applicable to firewalld',+ 'ssh_ports': None, 'allowed_ports': []}++ if cls._ufw_default_incoming_allow():+ return {'safe': True, 'reason': 'default incoming policy is ACCEPT',+ 'ssh_ports': None, 'allowed_ports': []}++ ports = cls.ssh_ports()+ allowed = cls._ufw_allowed_ports()++ if ports is None:+ return {+ 'safe': False,+ 'reason': ('Could not determine which port sshd is listening on, '+ 'so there is no way to confirm it stays reachable.'),+ 'ssh_ports': None,+ 'allowed_ports': sorted(allowed),+ }++ uncovered = [p for p in ports if p not in allowed]+ if uncovered:+ listed = ', '.join(str(p) for p in uncovered)+ return {+ 'safe': False,+ 'reason': (f'No ufw rule allows SSH on port {listed}. Enabling now '+ f'applies a default-deny and closes your own session. '+ f'Add a rule first: ufw allow {uncovered[0]}/tcp'),+ 'ssh_ports': ports,+ 'allowed_ports': sorted(allowed),+ }++ return {'safe': True, 'reason': 'SSH port is covered by an allow rule',+ 'ssh_ports': ports, 'allowed_ports': sorted(allowed)}+@classmethod- def enable(cls, firewall: str = None) -> Dict:- """Enable the firewall."""+ def enable(cls, firewall: str = None, force: bool = False) -> Dict:+ """Enable the firewall.++ Refuses when the preflight cannot prove SSH survives. ``force=True`` is+ the operator saying they accept the risk (console access, a rule the+ probe could not see); it is never set by default.+ """if firewall is None:status = cls.get_status()firewall = status['active_firewall']+ if firewall not in ('firewalld', 'ufw'):+ return {'success': False, 'error': 'No firewall detected'}++ if not force:+ preflight = cls.check_ssh_lockout(firewall)+ if not preflight['safe']:+ return {+ 'success': False,+ 'error': preflight['reason'],+ 'blocked_by': 'ssh_lockout',+ 'ssh_ports': preflight['ssh_ports'],+ 'allowed_ports': preflight['allowed_ports'],+ 'override': 'Send force=true to enable anyway.',+ }+if firewall == 'firewalld':return cls._enable_firewalld()- elif firewall == 'ufw':- return cls._enable_ufw()- else:- return {'success': False, 'error': 'No firewall detected'}+ return cls._enable_ufw()@classmethoddef _enable_firewalld(cls) -> Dict:diff --git a/backend/tests/test_firewall_ssh_lockout.py b/backend/tests/test_firewall_ssh_lockout.pynew file mode 100644index 00000000..4137b8b6--- /dev/null+++ b/backend/tests/test_firewall_ssh_lockout.py@@ -0,0 +1,208 @@+"""Enabling ufw must not be able to lock the operator out over SSH.++Found on a live box: ufw was installed, inactive, and had exactly one staged+rule — `ufw allow 25/tcp`. sshd was on 22. ufw defaults to deny-incoming, so+enabling would have severed the only way back in.++`ufw enable` normally asks "Command may disrupt existing ssh connections.+Proceed?" — and `--force enable`, which the service must use because nothing+here is attached to a terminal, suppresses exactly that prompt. So the panel+had removed the one safeguard and offered a one-click lockout.++The rule that matters most: an undeterminable SSH port must REFUSE, never fall+back to assuming 22. Guessing in the permissive direction is the lockout.+"""++import subprocess+from unittest.mock import patch++import pytest++from app.services.firewall_service import FirewallService+++def _completed(stdout='', returncode=0):+ return subprocess.CompletedProcess([], returncode, stdout=stdout, stderr='')+++def _router(sshd=None, added='', app_info=''):+ """Dispatch run_privileged by command, so each probe answers separately."""+ def _run(cmd, *args, **kwargs):+ if cmd[0] == 'sshd':+ return sshd if sshd is not None else _completed(returncode=1)+ if cmd[:3] == ['ufw', 'show', 'added']:+ return _completed(added)+ if cmd[:3] == ['ufw', 'app', 'info']:+ return _completed(app_info)+ return _completed()+ return _run++[email protected](autouse=True)+def _deny_by_default():+ """ufw's shipped default: deny incoming."""+ with patch.object(FirewallService, '_ufw_default_incoming_allow',+ return_value=False):+ yield+++SSHD_22 = 'port 22\nlistenaddress 0.0.0.0:22\npermitrootlogin yes\n'+SSHD_2222 = 'port 2222\nlistenaddress 0.0.0.0:2222\n'+++# --------------------------------------------------------------------------- #+# Preflight+# --------------------------------------------------------------------------- #++@patch('app.services.firewall_service.run_privileged')+def test_the_live_box_case_is_refused(run):+ """sshd on 22, one staged rule for 25/tcp — the real configuration."""+ run.side_effect = _router(sshd=_completed(SSHD_22),+ added='Added user rules:\nufw allow 25/tcp\n')++ check = FirewallService.check_ssh_lockout('ufw')++ assert check['safe'] is False+ assert check['ssh_ports'] == [22]+ assert 'ufw allow 22/tcp' in check['reason']+++@patch('app.services.firewall_service.run_privileged')+def test_covered_ssh_port_is_allowed(run):+ run.side_effect = _router(sshd=_completed(SSHD_22),+ added='ufw allow 22/tcp\nufw allow 25/tcp\n')++ assert FirewallService.check_ssh_lockout('ufw')['safe'] is True+++@patch('app.services.firewall_service.run_privileged')+def test_non_default_ssh_port_is_honoured(run):+ """A rule for 22 does not protect an sshd listening on 2222."""+ run.side_effect = _router(sshd=_completed(SSHD_2222),+ added='ufw allow 22/tcp\n')++ check = FirewallService.check_ssh_lockout('ufw')++ assert check['safe'] is False+ assert check['ssh_ports'] == [2222]+++@patch('app.services.firewall_service.run_privileged')+def test_undeterminable_ssh_port_refuses_rather_than_assuming_22(run):+ """The rule that matters most — no answer must not become "probably 22"."""+ run.side_effect = _router(sshd=_completed(returncode=1),+ added='ufw allow 22/tcp\n')++ check = FirewallService.check_ssh_lockout('ufw')++ assert check['safe'] is False+ assert check['ssh_ports'] is None+ assert 'could not determine' in check['reason'].lower()+++@patch('app.services.firewall_service.run_privileged')+def test_named_app_profile_is_resolved_not_guessed(run):+ """`ufw allow OpenSSH` does cover 22 — but only because we looked."""+ run.side_effect = _router(+ sshd=_completed(SSHD_22),+ added='ufw allow OpenSSH\n',+ app_info='Profile: OpenSSH\nTitle: Secure shell server\n\nPorts:\n 22/tcp\n',+ )++ assert FirewallService.check_ssh_lockout('ufw')['safe'] is True+++@patch('app.services.firewall_service.run_privileged')+def test_unresolvable_app_profile_does_not_count_as_coverage(run):+ """An app profile we cannot read must not be assumed to include SSH."""+ run.side_effect = _router(sshd=_completed(SSHD_22),+ added='ufw allow SomeProfile\n',+ app_info='')++ assert FirewallService.check_ssh_lockout('ufw')['safe'] is False+++@patch('app.services.firewall_service.run_privileged')+def test_multiple_ssh_ports_all_need_cover(run):+ run.side_effect = _router(sshd=_completed('port 22\nport 2222\n'),+ added='ufw allow 22/tcp\n')++ assert FirewallService.check_ssh_lockout('ufw')['safe'] is False+++def test_accept_default_policy_cannot_lock_anyone_out():+ with patch.object(FirewallService, '_ufw_default_incoming_allow',+ return_value=True):+ assert FirewallService.check_ssh_lockout('ufw')['safe'] is True+++def test_firewalld_is_not_subject_to_the_ufw_guard():+ assert FirewallService.check_ssh_lockout('firewalld')['safe'] is True+++# --------------------------------------------------------------------------- #+# enable() honours it+# --------------------------------------------------------------------------- #+[email protected](FirewallService, '_enable_ufw')+@patch('app.services.firewall_service.run_privileged')+def test_enable_refuses_and_never_runs_force_enable(run, enable_ufw):+ run.side_effect = _router(sshd=_completed(SSHD_22),+ added='ufw allow 25/tcp\n')++ result = FirewallService.enable('ufw')++ assert result['success'] is False+ assert result['blocked_by'] == 'ssh_lockout'+ enable_ufw.assert_not_called() # the whole point++[email protected](FirewallService, '_enable_ufw', return_value={'success': True})+@patch('app.services.firewall_service.run_privileged')+def test_force_overrides_the_guard(run, enable_ufw):+ """An operator with console access can still say "do it anyway"."""+ run.side_effect = _router(sshd=_completed(SSHD_22),+ added='ufw allow 25/tcp\n')++ result = FirewallService.enable('ufw', force=True)++ assert result['success'] is True+ enable_ufw.assert_called_once()++[email protected](FirewallService, '_enable_ufw', return_value={'success': True})+@patch('app.services.firewall_service.run_privileged')+def test_enable_proceeds_when_ssh_is_covered(run, enable_ufw):+ run.side_effect = _router(sshd=_completed(SSHD_22),+ added='ufw allow 22/tcp\n')++ assert FirewallService.enable('ufw')['success'] is True+ enable_ufw.assert_called_once()++[email protected](FirewallService, '_enable_ufw')+def test_unknown_firewall_still_reports_cleanly(enable_ufw):+ result = FirewallService.enable('nothing-here')++ assert result['success'] is False+ assert result['error'] == 'No firewall detected'+ enable_ufw.assert_not_called()+++# --------------------------------------------------------------------------- #+# ssh_ports() parsing+# --------------------------------------------------------------------------- #++@patch('app.services.firewall_service.run_privileged')+def test_ssh_ports_reads_sshd_dash_T(run):+ """`sshd -T` resolves Includes and Match blocks; parsing config does not."""+ run.return_value = _completed('port 22\nport 2222\naddressfamily any\n')++ assert FirewallService.ssh_ports() == [22, 2222]+++@patch('app.services.firewall_service.run_privileged')+def test_ssh_ports_returns_none_when_sshd_cannot_be_asked(run):+ run.side_effect = FileNotFoundError(2, 'No such file or directory', 'sshd')++ assert FirewallService.ssh_ports() is None