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
fix(services): close the rest of the bare-name sbin exec class
Juan Denisb51d9c2018a8
diff --git a/backend/app/plugins/serverkit-email/dovecot_service.py b/backend/app/plugins/serverkit-email/dovecot_service.pyindex 55cf3d2f..a081c3d7 100644--- a/backend/app/plugins/serverkit-email/dovecot_service.py+++ b/backend/app/plugins/serverkit-email/dovecot_service.py@@ -4,7 +4,8 @@ import reimport subprocessfrom typing import Dict, Optional-from app.utils.system import PackageManager, ServiceControl, run_privileged+from app.utils.system import (PackageManager, ServiceControl, is_command_available,+ run_privileged)from app import paths@@ -109,20 +110,30 @@ ssl_prefer_server_ciphers = yesrunning = Falseenabled = Falseversion = None+ # `which` searches $PATH only, and dovecot lives in /usr/sbin — absent+ # from the panel unit's PATH — so it reported a false negative on a host+ # where dovecot was installed. is_command_available() also searches the+ # sbin dirs.try:- result = subprocess.run(['which', 'dovecot'], capture_output=True, text=True)- installed = result.returncode == 0+ installed = is_command_available('dovecot')if not installed:installed = PackageManager.is_installed('dovecot-core') or PackageManager.is_installed('dovecot')- if installed:- running = ServiceControl.is_active('dovecot')- enabled = ServiceControl.is_enabled('dovecot')- result = subprocess.run(['dovecot', '--version'], capture_output=True, text=True)- version_match = re.search(r'(\d+\.\d+\.\d+)', result.stdout)+ except Exception:+ installed = False++ if installed:+ running = ServiceControl.is_active('dovecot')+ enabled = ServiceControl.is_enabled('dovecot')+ # Its own try: failing to read the version says nothing about+ # whether dovecot is installed. Collapsing the two is how+ # FirewallService._check_ufw reported a working firewall as absent.+ try:+ result = run_privileged(['dovecot', '--version'])+ version_match = re.search(r'(\d+\.\d+\.\d+)', result.stdout or '')if version_match:version = version_match.group(1)- except (subprocess.SubprocessError, FileNotFoundError):- pass+ except Exception:+ passreturn {'installed': installed,diff --git a/backend/app/services/nginx_advanced_service.py b/backend/app/services/nginx_advanced_service.pyindex 2a5cb4b6..f4ac6341 100644--- a/backend/app/services/nginx_advanced_service.py+++ b/backend/app/services/nginx_advanced_service.py@@ -2,7 +2,7 @@ import osimport jsonimport loggingimport re-from app.utils.system import run_command+from app.utils.system import run_command, run_privilegedlogger = logging.getLogger(__name__)@@ -133,11 +133,15 @@ class NginxAdvancedService:@staticmethoddef test_config():"""Test nginx config syntax."""+ # run_privileged, not run_command: `nginx -t` reads root-owned config+ # and nginx lives in /usr/sbin, which the panel's unit PATH omits. The+ # unprivileged bare-name call raised FileNotFoundError and this method+ # reported every config as INVALID.try:- result = run_command(['nginx', '-t'], capture_stderr=True)+ result = run_privileged(['nginx', '-t'])return {- 'valid': True,- 'output': result.get('stdout', '') + result.get('stderr', ''),+ 'valid': result.returncode == 0,+ 'output': (result.stdout or '') + (result.stderr or ''),}except Exception as e:return {'valid': False, 'output': str(e)}@@ -164,7 +168,10 @@ class NginxAdvancedService:def reload_nginx():"""Reload nginx configuration."""try:- run_command(['sudo', 'nginx', '-s', 'reload'])+ result = run_privileged(['nginx', '-s', 'reload'])+ if result.returncode != 0:+ return {'success': False,+ 'error': (result.stderr or 'nginx reload failed').strip()}return {'success': True}except Exception as e:return {'success': False, 'error': str(e)}diff --git a/backend/app/services/security_service.py b/backend/app/services/security_service.pyindex ac33b98a..42042836 100644--- a/backend/app/services/security_service.py+++ b/backend/app/services/security_service.py@@ -23,6 +23,7 @@ from app import pathsfrom app.utils.system import (PackageManager,ServiceControl,+ is_command_available,run_privileged,)@@ -1515,16 +1516,26 @@ class SecurityService:# ==========================================@classmethoddef get_lynis_status(cls) -> Dict:- """Check if Lynis is installed."""+ """Check if Lynis is installed.++ Presence and version are separate questions. Inferring "installed" from+ a successful ``lynis --version`` exec makes any exec failure look like+ absence — and Debian ships lynis in a sbin directory the panel unit's+ PATH omits, so a bare-name call raises FileNotFoundError. Same trap as+ FirewallService._check_ufw.+ """+ installed = is_command_available('lynis') or PackageManager.is_installed('lynis')+ if not installed:+ return {'installed': False, 'version': None}++ version = Nonetry:- result = subprocess.run(['lynis', '--version'], capture_output=True, text=True, timeout=10)+ result = run_privileged(['lynis', '--version'], timeout=10)if result.returncode == 0:- return {'installed': True, 'version': result.stdout.strip()}- except FileNotFoundError:- pass+ version = (result.stdout or '').strip()except Exception:pass- return {'installed': False, 'version': None}+ return {'installed': True, 'version': version}@classmethoddef install_lynis(cls) -> Dict:diff --git a/backend/app/utils/system.py b/backend/app/utils/system.pyindex 1182dbfd..b9f9bbd9 100644--- a/backend/app/utils/system.py+++ b/backend/app/utils/system.py@@ -111,6 +111,18 @@ def run_command(cmd: Union[List[str], str], *, timeout: int = 60,This is a convenience wrapper used by services that need simple dict resultsrather than a raw ``CompletedProcess`` object."""+ # Same argv[0] resolution as privileged_cmd: this helper does no privilege+ # escalation, so nothing else would find a command outside $PATH. Without+ # it `run_command(['nginx', '-t'])` raised FileNotFoundError on every root+ # install (nginx is /usr/sbin/nginx) and the caller reported the config as+ # invalid. Only applied when $PATH genuinely misses the command.+ if isinstance(cmd, (list, tuple)):+ cmd = list(cmd)+ if cmd and cmd[0] != 'sudo' and not os.path.isabs(cmd[0]) and not shutil.which(cmd[0]):+ resolved = resolve_command(cmd[0])+ if resolved:+ cmd[0] = resolved+kwargs.setdefault('capture_output', True)kwargs.setdefault('text', True)result = subprocess.run(cmd, timeout=timeout, **kwargs)diff --git a/backend/tests/test_sbin_command_guard.py b/backend/tests/test_sbin_command_guard.pynew file mode 100644index 00000000..729f9d6f--- /dev/null+++ b/backend/tests/test_sbin_command_guard.py@@ -0,0 +1,162 @@+"""Guard: sbin-resident commands must never be exec'd by bare name.++The panel's systemd unit historically shipped++ Environment="PATH=<venv>/bin:/usr/local/bin:/usr/bin:/bin"++with no sbin directory, and it runs as root — so `_needs_sudo()` is False and+nothing prepends `sudo` to resolve the command through sudo's secure_path.+`subprocess` searches $PATH and nothing else, so every sbin-resident tool+raised FileNotFoundError. Callers wrapping the call in a broad `except` then+reported that as a *fact about the system*:++ - `ufw status` -> "No Firewall Installed", on a host where ufw was installed+ - `nginx -t` -> every config reported invalid++`fail2ban-client` and `certbot` live in /usr/bin, so they always worked — which+is exactly why the failure looked feature-specific instead of systemic.++Two layers keep it dead:++ 1. `privileged_cmd` and `run_command` resolve argv[0] to an absolute path+ when $PATH cannot (verified below against a PATH with no sbin).+ 2. this static scan, so a NEW raw `subprocess` call cannot reintroduce it by+ bypassing both helpers.+"""++import ast+import os+import subprocess+from pathlib import Path+from unittest.mock import patch++import pytest++from app.utils.system import privileged_cmd, resolve_command, run_command++APP_ROOT = Path(__file__).resolve().parent.parent / 'app'++#: Commands that live in /usr/sbin or /sbin on Debian/Ubuntu and RHEL. Bare-name+#: exec of any of these is a latent FileNotFoundError on a root install.+SBIN_COMMANDS = {+ 'a2enmod', 'a2ensite', 'blkid', 'dovecot', 'e2fsck', 'fail2ban-server',+ 'groupadd', 'ip', 'ip6tables', 'ipset', 'iptables', 'modprobe', 'nft',+ 'nginx', 'postfix', 'service', 'sshd', 'swapon', 'sysctl', 'tune2fs',+ 'ufw', 'useradd', 'userdel', 'usermod',+}++#: Direct subprocess entry points. These bypass both helpers, so they get no+#: argv[0] resolution and are the only way to reintroduce the bug.+RAW_SUBPROCESS_FUNCS = {'run', 'Popen', 'check_output', 'check_call', 'call'}+++def _python_files():+ for path in APP_ROOT.rglob('*.py'):+ if '__pycache__' in path.parts:+ continue+ yield path+++def _first_arg_command(node):+ """argv[0] of a subprocess call, when it is a plain literal list."""+ if not node.args:+ return None+ first = node.args[0]+ if not isinstance(first, (ast.List, ast.Tuple)) or not first.elts:+ return None+ head = first.elts[0]+ if isinstance(head, ast.Constant) and isinstance(head.value, str):+ return head.value+ return None+++def _is_raw_subprocess(node):+ """`subprocess.<fn>(...)` — not run_privileged / run_command."""+ func = node.func+ return (isinstance(func, ast.Attribute)+ and func.attr in RAW_SUBPROCESS_FUNCS+ and isinstance(func.value, ast.Name)+ and func.value.id == 'subprocess')+++def _scan(path):+ """[(lineno, command)] — bare sbin commands exec'd directly in *path*."""+ try:+ tree = ast.parse(path.read_text(encoding='utf-8'), filename=str(path))+ except (SyntaxError, UnicodeDecodeError):+ return []++ offenders = []+ for node in ast.walk(tree):+ if not isinstance(node, ast.Call) or not _is_raw_subprocess(node):+ continue+ command = _first_arg_command(node)+ # 'sudo' as argv[0] is safe: sudo resolves through its own secure_path,+ # which includes the sbin dirs on every distro we target.+ if command in SBIN_COMMANDS:+ offenders.append((node.lineno, command))+ return offenders+++def test_no_bare_sbin_command_in_raw_subprocess_calls():+ """A new raw subprocess call must not reintroduce the FileNotFoundError."""+ found = []+ for path in _python_files():+ for lineno, command in _scan(path):+ rel = path.relative_to(APP_ROOT.parent.parent)+ found.append(f'{rel}:{lineno} execs {command!r} by bare name')++ assert not found, (+ 'These commands live in /usr/sbin or /sbin, which the panel unit\'s '+ 'PATH may omit — subprocess would raise FileNotFoundError:\n '+ + '\n '.join(found)+ + '\n\nUse run_privileged() (or run_command() when no root is needed); '+ 'both resolve argv[0] to an absolute path when $PATH cannot.'+ )+++# --------------------------------------------------------------------------- #+# The helpers actually resolve, under the PATH that caused the outage+# --------------------------------------------------------------------------- #++CONSTRAINED_PATH = '/opt/serverkit/venv/bin:/usr/local/bin:/usr/bin:/bin'++[email protected]('command', sorted(SBIN_COMMANDS))+def test_helpers_resolve_every_sbin_command_without_sbin_on_path(command):+ """Simulates the real unit: sbin absent from $PATH, running as root."""+ sbin_path = f'/usr/sbin/{command}'++ with patch.dict(os.environ, {'PATH': CONSTRAINED_PATH}), \+ patch('app.utils.system.shutil.which', return_value=None), \+ patch('app.utils.system.os.path.exists',+ side_effect=lambda p: p == sbin_path), \+ patch('app.utils.system.os.name', 'posix'), \+ patch('app.utils.system.os.geteuid', return_value=0, create=True):++ assert resolve_command(command) == sbin_path+ assert privileged_cmd([command, '--version'])[0] == sbin_path+++@patch('app.utils.system.subprocess.run')+@patch('app.utils.system.os.path.exists')+@patch('app.utils.system.shutil.which', return_value=None)+def test_run_command_resolves_too(_which, exists, mock_run):+ """The sibling helper had the same gap — `nginx -t` went through it."""+ exists.side_effect = lambda p: p == '/usr/sbin/nginx'+ mock_run.return_value = subprocess.CompletedProcess([], 0, stdout='', stderr='')++ run_command(['nginx', '-t'])++ assert mock_run.call_args[0][0] == ['/usr/sbin/nginx', '-t']+++@patch('app.utils.system.subprocess.run')+@patch('app.utils.system.shutil.which', return_value='/usr/bin/git')+def test_run_command_leaves_resolvable_commands_alone(_which, mock_run):+ """A working $PATH must not have its argv rewritten underneath callers."""+ mock_run.return_value = subprocess.CompletedProcess([], 0, stdout='', stderr='')++ run_command(['git', 'status'])++ assert mock_run.call_args[0][0] == ['git', 'status']diff --git a/builtin-extensions/serverkit-email/backend/dovecot_service.py b/builtin-extensions/serverkit-email/backend/dovecot_service.pyindex 55cf3d2f..a081c3d7 100644--- a/builtin-extensions/serverkit-email/backend/dovecot_service.py+++ b/builtin-extensions/serverkit-email/backend/dovecot_service.py@@ -4,7 +4,8 @@ import reimport subprocessfrom typing import Dict, Optional-from app.utils.system import PackageManager, ServiceControl, run_privileged+from app.utils.system import (PackageManager, ServiceControl, is_command_available,+ run_privileged)from app import paths@@ -109,20 +110,30 @@ ssl_prefer_server_ciphers = yesrunning = Falseenabled = Falseversion = None+ # `which` searches $PATH only, and dovecot lives in /usr/sbin — absent+ # from the panel unit's PATH — so it reported a false negative on a host+ # where dovecot was installed. is_command_available() also searches the+ # sbin dirs.try:- result = subprocess.run(['which', 'dovecot'], capture_output=True, text=True)- installed = result.returncode == 0+ installed = is_command_available('dovecot')if not installed:installed = PackageManager.is_installed('dovecot-core') or PackageManager.is_installed('dovecot')- if installed:- running = ServiceControl.is_active('dovecot')- enabled = ServiceControl.is_enabled('dovecot')- result = subprocess.run(['dovecot', '--version'], capture_output=True, text=True)- version_match = re.search(r'(\d+\.\d+\.\d+)', result.stdout)+ except Exception:+ installed = False++ if installed:+ running = ServiceControl.is_active('dovecot')+ enabled = ServiceControl.is_enabled('dovecot')+ # Its own try: failing to read the version says nothing about+ # whether dovecot is installed. Collapsing the two is how+ # FirewallService._check_ufw reported a working firewall as absent.+ try:+ result = run_privileged(['dovecot', '--version'])+ version_match = re.search(r'(\d+\.\d+\.\d+)', result.stdout or '')if version_match:version = version_match.group(1)- except (subprocess.SubprocessError, FileNotFoundError):- pass+ except Exception:+ passreturn {'installed': installed,