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
Use system utils for commands and services
Juan Denis06de89617524
diff --git a/backend/app/services/deployment_service.py b/backend/app/services/deployment_service.pyindex 03b73764..29b21d6d 100644--- a/backend/app/services/deployment_service.py+++ b/backend/app/services/deployment_service.py@@ -17,6 +17,7 @@ from datetime import datetimefrom typing import Dict, List, Optional, Callablefrom app import db+from app.utils.system import ServiceControlfrom app.models.deployment import Deployment, DeploymentDifffrom app.models.application import Applicationfrom app.services.build_service import BuildService@@ -315,11 +316,7 @@ class DeploymentService:service_name = f"serverkit-{app.name}"try:- subprocess.run(- ['systemctl', 'restart', service_name],- capture_output=True,- check=True- )+ ServiceControl.restart(service_name, check=True)except subprocess.CalledProcessError as e:return {'success': False, 'error': f'Service restart failed: {e.stderr}'}@@ -468,7 +465,7 @@ class DeploymentService:# Restart serviceif app.app_type in ['flask', 'django']:service_name = f"serverkit-{app.name}"- subprocess.run(['systemctl', 'restart', service_name], check=True)+ ServiceControl.restart(service_name, check=True)return {'success': True}diff --git a/backend/app/services/firewall_service.py b/backend/app/services/firewall_service.pyindex f14d95fd..1842aca5 100644--- a/backend/app/services/firewall_service.py+++ b/backend/app/services/firewall_service.py@@ -6,6 +6,13 @@ import refrom typing import Dict, List, Optionalfrom datetime import datetime+from app.utils.system import (+ PackageManager,+ ServiceControl,+ is_command_available,+ run_privileged,+)+class FirewallService:"""Service for managing firewall (firewalld or ufw)."""@@ -38,41 +45,17 @@ class FirewallService:def _check_firewalld(cls) -> Dict:"""Check firewalld status."""try:- # Check if installed using dpkg or by checking common paths- installed = False-- # Try dpkg first (Debian/Ubuntu)- result = subprocess.run(- ['dpkg', '-s', 'firewalld'],- capture_output=True, text=True- )- if result.returncode == 0 and 'Status: install ok installed' in result.stdout:- installed = True-- # Also check if binary exists at common paths- if not installed:- for path in ['/usr/bin/firewall-cmd', '/usr/sbin/firewall-cmd']:- if os.path.exists(path):- installed = True- break+ installed = PackageManager.is_installed('firewalld') or is_command_available('firewall-cmd')running = Falsedefault_zone = Noneif installed:- # Check if running- result = subprocess.run(- ['firewall-cmd', '--state'],- capture_output=True, text=True- )+ result = run_privileged(['firewall-cmd', '--state'])running = 'running' in result.stdout.lower()if running:- # Get default zone- result = subprocess.run(- ['firewall-cmd', '--get-default-zone'],- capture_output=True, text=True- )+ result = run_privileged(['firewall-cmd', '--get-default-zone'])default_zone = result.stdout.strip()return {@@ -87,30 +70,11 @@ class FirewallService:def _check_ufw(cls) -> Dict:"""Check ufw status."""try:- # Check if installed using dpkg or by checking common paths- installed = False-- # Try dpkg first (Debian/Ubuntu)- result = subprocess.run(- ['dpkg', '-s', 'ufw'],- capture_output=True, text=True- )- if result.returncode == 0 and 'Status: install ok installed' in result.stdout:- installed = True-- # Also check if binary exists at common paths- if not installed:- for path in ['/usr/sbin/ufw', '/usr/bin/ufw']:- if os.path.exists(path):- installed = True- break+ installed = PackageManager.is_installed('ufw') or is_command_available('ufw')active = Falseif installed:- result = subprocess.run(- ['sudo', 'ufw', 'status'],- capture_output=True, text=True- )+ result = run_privileged(['ufw', 'status'])active = 'Status: active' in result.stdoutreturn {@@ -138,11 +102,8 @@ class FirewallService:def _enable_firewalld(cls) -> Dict:"""Enable firewalld."""try:- subprocess.run(['sudo', 'systemctl', 'enable', 'firewalld'], capture_output=True)- result = subprocess.run(- ['sudo', 'systemctl', 'start', 'firewalld'],- capture_output=True, text=True- )+ ServiceControl.enable('firewalld')+ result = ServiceControl.start('firewalld')if result.returncode == 0:return {'success': True, 'message': 'Firewalld enabled and started'}return {'success': False, 'error': result.stderr or 'Failed to start firewalld'}@@ -153,10 +114,7 @@ class FirewallService:def _enable_ufw(cls) -> Dict:"""Enable ufw."""try:- result = subprocess.run(- ['sudo', 'ufw', '--force', 'enable'],- capture_output=True, text=True- )+ result = run_privileged(['ufw', '--force', 'enable'])if result.returncode == 0:return {'success': True, 'message': 'UFW enabled'}return {'success': False, 'error': result.stderr or 'Failed to enable UFW'}@@ -181,10 +139,7 @@ class FirewallService:def _disable_firewalld(cls) -> Dict:"""Disable firewalld."""try:- result = subprocess.run(- ['sudo', 'systemctl', 'stop', 'firewalld'],- capture_output=True, text=True- )+ result = ServiceControl.stop('firewalld')if result.returncode == 0:return {'success': True, 'message': 'Firewalld stopped'}return {'success': False, 'error': result.stderr or 'Failed to stop firewalld'}@@ -195,10 +150,7 @@ class FirewallService:def _disable_ufw(cls) -> Dict:"""Disable ufw."""try:- result = subprocess.run(- ['sudo', 'ufw', 'disable'],- capture_output=True, text=True- )+ result = run_privileged(['ufw', 'disable'])if result.returncode == 0:return {'success': True, 'message': 'UFW disabled'}return {'success': False, 'error': result.stderr or 'Failed to disable UFW'}@@ -226,17 +178,11 @@ class FirewallService:rules = []# Get default zone- result = subprocess.run(- ['firewall-cmd', '--get-default-zone'],- capture_output=True, text=True- )+ result = run_privileged(['firewall-cmd', '--get-default-zone'])default_zone = result.stdout.strip()# Get services- result = subprocess.run(- ['firewall-cmd', '--list-services'],- capture_output=True, text=True- )+ result = run_privileged(['firewall-cmd', '--list-services'])services = result.stdout.strip().split() if result.stdout.strip() else []for service in services:rules.append({@@ -247,10 +193,7 @@ class FirewallService:})# Get ports- result = subprocess.run(- ['firewall-cmd', '--list-ports'],- capture_output=True, text=True- )+ result = run_privileged(['firewall-cmd', '--list-ports'])ports = result.stdout.strip().split() if result.stdout.strip() else []for port in ports:port_num, protocol = port.split('/') if '/' in port else (port, 'tcp')@@ -263,10 +206,7 @@ class FirewallService:})# Get rich rules (includes IP blocks)- result = subprocess.run(- ['firewall-cmd', '--list-rich-rules'],- capture_output=True, text=True- )+ result = run_privileged(['firewall-cmd', '--list-rich-rules'])rich_rules = result.stdout.strip().split('\n') if result.stdout.strip() else []for rule in rich_rules:if rule:@@ -289,10 +229,7 @@ class FirewallService:def _get_ufw_rules(cls) -> Dict:"""Get ufw rules."""try:- result = subprocess.run(- ['sudo', 'ufw', 'status', 'numbered'],- capture_output=True, text=True- )+ result = run_privileged(['ufw', 'status', 'numbered'])rules = []lines = result.stdout.strip().split('\n')@@ -341,20 +278,20 @@ class FirewallService:service = kwargs.get('service')if not service:return {'success': False, 'error': 'Service name required'}- cmd = ['sudo', 'firewall-cmd'] + perm_flag + [f'--add-service={service}']+ cmd = ['firewall-cmd'] + perm_flag + [f'--add-service={service}']elif rule_type == 'port':port = kwargs.get('port')protocol = kwargs.get('protocol', 'tcp')if not port:return {'success': False, 'error': 'Port number required'}- cmd = ['sudo', 'firewall-cmd'] + perm_flag + [f'--add-port={port}/{protocol}']+ cmd = ['firewall-cmd'] + perm_flag + [f'--add-port={port}/{protocol}']elif rule_type == 'block_ip':ip = kwargs.get('ip')if not ip:return {'success': False, 'error': 'IP address required'}- cmd = ['sudo', 'firewall-cmd'] + perm_flag + [+ cmd = ['firewall-cmd'] + perm_flag + [f'--add-rich-rule=rule family="ipv4" source address="{ip}" reject']@@ -364,23 +301,23 @@ class FirewallService:if not ip:return {'success': False, 'error': 'IP address required'}if port:- cmd = ['sudo', 'firewall-cmd'] + perm_flag + [+ cmd = ['firewall-cmd'] + perm_flag + [f'--add-rich-rule=rule family="ipv4" source address="{ip}" port port="{port}" protocol="tcp" accept']else:- cmd = ['sudo', 'firewall-cmd'] + perm_flag + [+ cmd = ['firewall-cmd'] + perm_flag + [f'--add-rich-rule=rule family="ipv4" source address="{ip}" accept']else:return {'success': False, 'error': f'Unknown rule type: {rule_type}'}- result = subprocess.run(cmd, capture_output=True, text=True)+ result = run_privileged(cmd)if result.returncode == 0:# Reload if permanentif permanent:- subprocess.run(['sudo', 'firewall-cmd', '--reload'], capture_output=True)+ run_privileged(['firewall-cmd', '--reload'])return {'success': True, 'message': 'Rule added successfully'}return {'success': False, 'error': result.stderr or 'Failed to add rule'}@@ -398,20 +335,20 @@ class FirewallService:action = kwargs.get('action', 'allow')if not port:return {'success': False, 'error': 'Port number required'}- cmd = ['sudo', 'ufw', action, f'{port}/{protocol}']+ cmd = ['ufw', action, f'{port}/{protocol}']elif rule_type == 'service':service = kwargs.get('service')action = kwargs.get('action', 'allow')if not service:return {'success': False, 'error': 'Service name required'}- cmd = ['sudo', 'ufw', action, service]+ cmd = ['ufw', action, service]elif rule_type == 'block_ip':ip = kwargs.get('ip')if not ip:return {'success': False, 'error': 'IP address required'}- cmd = ['sudo', 'ufw', 'deny', 'from', ip]+ cmd = ['ufw', 'deny', 'from', ip]elif rule_type == 'allow_ip':ip = kwargs.get('ip')@@ -419,14 +356,14 @@ class FirewallService:if not ip:return {'success': False, 'error': 'IP address required'}if port:- cmd = ['sudo', 'ufw', 'allow', 'from', ip, 'to', 'any', 'port', str(port)]+ cmd = ['ufw', 'allow', 'from', ip, 'to', 'any', 'port', str(port)]else:- cmd = ['sudo', 'ufw', 'allow', 'from', ip]+ cmd = ['ufw', 'allow', 'from', ip]else:return {'success': False, 'error': f'Unknown rule type: {rule_type}'}- result = subprocess.run(cmd, capture_output=True, text=True)+ result = run_privileged(cmd)if result.returncode == 0:return {'success': True, 'message': 'Rule added successfully'}@@ -458,31 +395,31 @@ class FirewallService:if rule_type == 'service':service = kwargs.get('service')- cmd = ['sudo', 'firewall-cmd'] + perm_flag + [f'--remove-service={service}']+ cmd = ['firewall-cmd'] + perm_flag + [f'--remove-service={service}']elif rule_type == 'port':port = kwargs.get('port')protocol = kwargs.get('protocol', 'tcp')- cmd = ['sudo', 'firewall-cmd'] + perm_flag + [f'--remove-port={port}/{protocol}']+ cmd = ['firewall-cmd'] + perm_flag + [f'--remove-port={port}/{protocol}']elif rule_type == 'block_ip':ip = kwargs.get('ip')- cmd = ['sudo', 'firewall-cmd'] + perm_flag + [+ cmd = ['firewall-cmd'] + perm_flag + [f'--remove-rich-rule=rule family="ipv4" source address="{ip}" reject']elif rule_type == 'rich':rule = kwargs.get('rule')- cmd = ['sudo', 'firewall-cmd'] + perm_flag + [f'--remove-rich-rule={rule}']+ cmd = ['firewall-cmd'] + perm_flag + [f'--remove-rich-rule={rule}']else:return {'success': False, 'error': f'Unknown rule type: {rule_type}'}- result = subprocess.run(cmd, capture_output=True, text=True)+ result = run_privileged(cmd)if result.returncode == 0:if permanent:- subprocess.run(['sudo', 'firewall-cmd', '--reload'], capture_output=True)+ run_privileged(['firewall-cmd', '--reload'])return {'success': True, 'message': 'Rule removed successfully'}return {'success': False, 'error': result.stderr or 'Failed to remove rule'}@@ -496,27 +433,16 @@ class FirewallService:try:rule_number = kwargs.get('number')if rule_number:- # Remove by number- result = subprocess.run(- ['sudo', 'ufw', '--force', 'delete', str(rule_number)],- capture_output=True, text=True- )+ result = run_privileged(['ufw', '--force', 'delete', str(rule_number)])else:- # Remove by specificationif rule_type == 'port':port = kwargs.get('port')protocol = kwargs.get('protocol', 'tcp')action = kwargs.get('action', 'allow')- result = subprocess.run(- ['sudo', 'ufw', 'delete', action, f'{port}/{protocol}'],- capture_output=True, text=True- )+ result = run_privileged(['ufw', 'delete', action, f'{port}/{protocol}'])elif rule_type == 'block_ip':ip = kwargs.get('ip')- result = subprocess.run(- ['sudo', 'ufw', 'delete', 'deny', 'from', ip],- capture_output=True, text=True- )+ result = run_privileged(['ufw', 'delete', 'deny', 'from', ip])else:return {'success': False, 'error': 'Rule number or specification required'}@@ -561,10 +487,7 @@ class FirewallService:blocked_ips = []if firewall == 'firewalld':- result = subprocess.run(- ['firewall-cmd', '--list-rich-rules'],- capture_output=True, text=True- )+ result = run_privileged(['firewall-cmd', '--list-rich-rules'])for line in result.stdout.strip().split('\n'):if 'reject' in line.lower() or 'drop' in line.lower():match = re.search(r'source address="([^"]+)"', line)@@ -575,10 +498,7 @@ class FirewallService:})elif firewall == 'ufw':- result = subprocess.run(- ['sudo', 'ufw', 'status', 'numbered'],- capture_output=True, text=True- )+ result = run_privileged(['ufw', 'status', 'numbered'])for line in result.stdout.strip().split('\n'):if 'DENY' in line:# Parse IP from rule@@ -599,26 +519,15 @@ class FirewallService:def get_zones(cls) -> Dict:"""Get firewalld zones (firewalld only)."""try:- # Get all zones- result = subprocess.run(- ['firewall-cmd', '--get-zones'],- capture_output=True, text=True- )+ result = run_privileged(['firewall-cmd', '--get-zones'])zones = result.stdout.strip().split()- # Get default zone- result = subprocess.run(- ['firewall-cmd', '--get-default-zone'],- capture_output=True, text=True- )+ result = run_privileged(['firewall-cmd', '--get-default-zone'])default_zone = result.stdout.strip()zone_details = []for zone in zones:- result = subprocess.run(- ['firewall-cmd', f'--zone={zone}', '--list-all'],- capture_output=True, text=True- )+ result = run_privileged(['firewall-cmd', f'--zone={zone}', '--list-all'])zone_details.append({'name': zone,'is_default': zone == default_zone,@@ -637,10 +546,7 @@ class FirewallService:def set_default_zone(cls, zone: str) -> Dict:"""Set default firewalld zone."""try:- result = subprocess.run(- ['sudo', 'firewall-cmd', f'--set-default-zone={zone}'],- capture_output=True, text=True- )+ result = run_privileged(['firewall-cmd', f'--set-default-zone={zone}'])if result.returncode == 0:return {'success': True, 'message': f'Default zone set to {zone}'}return {'success': False, 'error': result.stderr or 'Failed to set default zone'}@@ -654,14 +560,7 @@ class FirewallService:return {'success': False, 'error': 'Invalid firewall. Use ufw or firewalld'}try:- # Update package list- subprocess.run(['sudo', 'apt-get', 'update'], capture_output=True, timeout=120)-- # Install- result = subprocess.run(- ['sudo', 'apt-get', 'install', '-y', firewall],- capture_output=True, text=True, timeout=300- )+ result = PackageManager.install(firewall)if result.returncode == 0:return {'success': True, 'message': f'{firewall} installed successfully'}@@ -669,6 +568,8 @@ class FirewallService:except subprocess.TimeoutExpired:return {'success': False, 'error': 'Installation timed out'}+ except RuntimeError as e:+ return {'success': False, 'error': str(e)}except Exception as e:return {'success': False, 'error': str(e)}diff --git a/backend/app/services/ftp_service.py b/backend/app/services/ftp_service.pyindex 22f36bf1..ac29575c 100644--- a/backend/app/services/ftp_service.py+++ b/backend/app/services/ftp_service.py@@ -3,6 +3,8 @@import osimport subprocessimport re++from app.utils.system import PackageManager, ServiceControl, run_privilegedtry:import pwdexcept ImportError:@@ -61,35 +63,19 @@ class FTPService:version = Nonetry:- # Check if installed+ # Check if installed via which or package managerresult = subprocess.run(- ['which', service if service != 'proftpd' else 'proftpd'],+ ['which', service],capture_output=True, text=True)installed = result.returncode == 0if not installed:- # Try checking if package is installed- result = subprocess.run(- ['dpkg', '-l', service],- capture_output=True, text=True- )- installed = 'ii' in result.stdout+ installed = PackageManager.is_installed(service)if installed:- # Check if running- result = subprocess.run(- ['systemctl', 'is-active', service],- capture_output=True, text=True- )- running = result.stdout.strip() == 'active'-- # Check if enabled- result = subprocess.run(- ['systemctl', 'is-enabled', service],- capture_output=True, text=True- )- enabled = result.stdout.strip() == 'enabled'+ running = ServiceControl.is_active(service)+ enabled = ServiceControl.is_enabled(service)# Get versionif service == 'vsftpd':@@ -129,10 +115,8 @@ class FTPService:return {'success': False, 'error': 'Invalid action'}try:- result = subprocess.run(- ['sudo', 'systemctl', action, service],- capture_output=True, text=True, timeout=30- )+ handler = getattr(ServiceControl, action)+ result = handler(service, timeout=30)if result.returncode == 0:return {'success': True, 'service': service, 'action': action}@@ -609,14 +593,7 @@ class FTPService:return {'success': False, 'error': 'Invalid service. Use vsftpd or proftpd'}try:- # Update package list- subprocess.run(['sudo', 'apt-get', 'update'], capture_output=True, timeout=120)-- # Install the service- result = subprocess.run(- ['sudo', 'apt-get', 'install', '-y', service],- capture_output=True, text=True, timeout=300- )+ result = PackageManager.install(service)if result.returncode != 0:return {'success': False, 'error': result.stderr or 'Installation failed'}@@ -656,8 +633,8 @@ userlist_deny=NOf.write('')# Enable and start the service- subprocess.run(['sudo', 'systemctl', 'enable', service], capture_output=True)- subprocess.run(['sudo', 'systemctl', 'start', service], capture_output=True)+ ServiceControl.enable(service)+ ServiceControl.start(service)return {'success': True,diff --git a/backend/app/services/nginx_service.py b/backend/app/services/nginx_service.pyindex c610da0b..88b2bda0 100644--- a/backend/app/services/nginx_service.py+++ b/backend/app/services/nginx_service.py@@ -4,6 +4,8 @@ import refrom typing import Dict, List, Optionalfrom pathlib import Path+from app.utils.system import ServiceControl, run_privileged+class NginxService:"""Service for Nginx configuration management."""@@ -292,12 +294,7 @@ server {{def test_config(cls) -> Dict:"""Test Nginx configuration syntax."""try:- result = subprocess.run(- ['sudo', cls.NGINX_BIN, '-t'],- capture_output=True,- text=True,- timeout=30- )+ result = run_privileged([cls.NGINX_BIN, '-t'], timeout=30)return {'success': result.returncode == 0,'message': result.stderr if result.returncode == 0 else result.stderr@@ -314,12 +311,7 @@ server {{return {'success': False, 'error': f"Config test failed: {test_result.get('message', test_result.get('error'))}"}try:- result = subprocess.run(- ['sudo', 'systemctl', 'reload', 'nginx'],- capture_output=True,- text=True,- timeout=30- )+ result = ServiceControl.reload('nginx', timeout=30)return {'success': result.returncode == 0,'message': 'Nginx reloaded successfully' if result.returncode == 0 else result.stderr@@ -331,12 +323,7 @@ server {{def restart(cls) -> Dict:"""Restart Nginx service."""try:- result = subprocess.run(- ['sudo', 'systemctl', 'restart', 'nginx'],- capture_output=True,- text=True,- timeout=30- )+ result = ServiceControl.restart('nginx', timeout=30)return {'success': result.returncode == 0,'message': 'Nginx restarted successfully' if result.returncode == 0 else result.stderr@@ -348,12 +335,7 @@ server {{def get_status(cls) -> Dict:"""Get Nginx service status."""try:- result = subprocess.run(- ['sudo', 'systemctl', 'status', 'nginx'],- capture_output=True,- text=True,- timeout=30- )+ result = run_privileged(['systemctl', 'status', 'nginx'], timeout=30)# Parse statusis_running = 'active (running)' in result.stdout@@ -470,11 +452,9 @@ server {{config_path = os.path.join(cls.SITES_AVAILABLE, name)try:# Use sudo to write- process = subprocess.run(- ['sudo', 'tee', config_path],+ process = run_privileged(+ ['tee', config_path],input=config,- capture_output=True,- text=True)if process.returncode != 0:return {'success': False, 'error': process.stderr}@@ -493,11 +473,7 @@ server {{return {'success': False, 'error': f'Site {name} not found in sites-available'}try:- result = subprocess.run(- ['sudo', 'ln', '-sf', available_path, enabled_path],- capture_output=True,- text=True- )+ result = run_privileged(['ln', '-sf', available_path, enabled_path])if result.returncode == 0:# Reload nginxreload_result = cls.reload()@@ -514,11 +490,7 @@ server {{enabled_path = os.path.join(cls.SITES_ENABLED, name)try:- result = subprocess.run(- ['sudo', 'rm', '-f', enabled_path],- capture_output=True,- text=True- )+ result = run_privileged(['rm', '-f', enabled_path])if result.returncode == 0:reload_result = cls.reload()if reload_result['success']:@@ -536,11 +508,7 @@ server {{available_path = os.path.join(cls.SITES_AVAILABLE, name)try:- result = subprocess.run(- ['sudo', 'rm', '-f', available_path],- capture_output=True,- text=True- )+ result = run_privileged(['rm', '-f', available_path])if result.returncode == 0:return {'success': True, 'message': f'Site {name} deleted'}return {'success': False, 'error': result.stderr}@@ -579,11 +547,9 @@ server {{final_content = redirect_block + '\n' + new_content# Write updated config- process = subprocess.run(- ['sudo', 'tee', config_path],+ process = run_privileged(+ ['tee', config_path],input=final_content,- capture_output=True,- text=True)if process.returncode == 0:@@ -835,23 +801,14 @@ server {{# Write config fileconfig_path = os.path.join(cls.SITES_AVAILABLE, cls.PRIVATE_URL_CONFIG_NAME)- process = subprocess.run(- ['sudo', 'tee', config_path],- input=config,- capture_output=True,- text=True- )+ process = run_privileged(['tee', config_path], input=config)if process.returncode != 0:return {'success': False, 'error': f'Failed to write config: {process.stderr}'}# Enable the site if not already enabledenabled_path = os.path.join(cls.SITES_ENABLED, cls.PRIVATE_URL_CONFIG_NAME)if not os.path.exists(enabled_path):- result = subprocess.run(- ['sudo', 'ln', '-sf', config_path, enabled_path],- capture_output=True,- text=True- )+ result = run_privileged(['ln', '-sf', config_path, enabled_path])if result.returncode != 0:return {'success': False, 'error': f'Failed to enable config: {result.stderr}'}@@ -896,22 +853,13 @@ server {{config_path = os.path.join(cls.SITES_AVAILABLE, cls.GITEA_CONFIG_NAME)# Write config file- process = subprocess.run(- ['sudo', 'tee', config_path],- input=config,- capture_output=True,- text=True- )+ process = run_privileged(['tee', config_path], input=config)if process.returncode != 0:return {'success': False, 'error': f'Failed to write config: {process.stderr}'}# Enable the siteenabled_path = os.path.join(cls.SITES_ENABLED, cls.GITEA_CONFIG_NAME)- result = subprocess.run(- ['sudo', 'ln', '-sf', config_path, enabled_path],- capture_output=True,- text=True- )+ result = run_privileged(['ln', '-sf', config_path, enabled_path])if result.returncode != 0:return {'success': False, 'error': f'Failed to enable config: {result.stderr}'}@@ -940,11 +888,11 @@ server {{try:# Remove symlinkenabled_path = os.path.join(cls.SITES_ENABLED, cls.GITEA_CONFIG_NAME)- subprocess.run(['sudo', 'rm', '-f', enabled_path], capture_output=True, text=True)+ run_privileged(['rm', '-f', enabled_path])# Remove config fileconfig_path = os.path.join(cls.SITES_AVAILABLE, cls.GITEA_CONFIG_NAME)- subprocess.run(['sudo', 'rm', '-f', config_path], capture_output=True, text=True)+ run_privileged(['rm', '-f', config_path])# Reload Nginxcls.reload()@@ -980,22 +928,13 @@ server {{config_path = os.path.join(cls.SITES_AVAILABLE, cls.WORDPRESS_CONFIG_NAME)# Write config file- process = subprocess.run(- ['sudo', 'tee', config_path],- input=config,- capture_output=True,- text=True- )+ process = run_privileged(['tee', config_path], input=config)if process.returncode != 0:return {'success': False, 'error': f'Failed to write config: {process.stderr}'}# Enable the siteenabled_path = os.path.join(cls.SITES_ENABLED, cls.WORDPRESS_CONFIG_NAME)- result = subprocess.run(- ['sudo', 'ln', '-sf', config_path, enabled_path],- capture_output=True,- text=True- )+ result = run_privileged(['ln', '-sf', config_path, enabled_path])if result.returncode != 0:return {'success': False, 'error': f'Failed to enable config: {result.stderr}'}@@ -1024,11 +963,11 @@ server {{try:# Remove symlinkenabled_path = os.path.join(cls.SITES_ENABLED, cls.WORDPRESS_CONFIG_NAME)- subprocess.run(['sudo', 'rm', '-f', enabled_path], capture_output=True, text=True)+ run_privileged(['rm', '-f', enabled_path])# Remove config fileconfig_path = os.path.join(cls.SITES_AVAILABLE, cls.WORDPRESS_CONFIG_NAME)- subprocess.run(['sudo', 'rm', '-f', config_path], capture_output=True, text=True)+ run_privileged(['rm', '-f', config_path])# Reload Nginxcls.reload()diff --git a/backend/app/services/php_service.py b/backend/app/services/php_service.pyindex 0d096e5c..1832335f 100644--- a/backend/app/services/php_service.py+++ b/backend/app/services/php_service.py@@ -4,6 +4,8 @@ import refrom typing import Dict, List, Optionalfrom pathlib import Path+from app.utils.system import PackageManager, ServiceControl, run_privileged+class PHPService:"""Service for PHP-FPM management."""@@ -85,12 +87,7 @@ env[TEMP] = /tmpfpm_running = Falseif fpm_installed:try:- result = subprocess.run(- ['systemctl', 'is-active', f'php{version}-fpm'],- capture_output=True,- text=True- )- fpm_running = result.stdout.strip() == 'active'+ fpm_running = ServiceControl.is_active(f'php{version}-fpm')except:pass@@ -135,11 +132,9 @@ env[TEMP] = /tmptry:# Update alternatives- result = subprocess.run(- ['sudo', 'update-alternatives', '--set', 'php', php_bin],- capture_output=True,- text=True,- timeout=30+ result = run_privileged(+ ['update-alternatives', '--set', 'php', php_bin],+ timeout=30,)if result.returncode == 0:@@ -156,19 +151,12 @@ env[TEMP] = /tmptry:# Add PHP repository if needed- subprocess.run(- ['sudo', 'add-apt-repository', '-y', 'ppa:ondrej/php'],- capture_output=True,- text=True,- timeout=120+ run_privileged(+ ['add-apt-repository', '-y', 'ppa:ondrej/php'],+ timeout=120,)- subprocess.run(- ['sudo', 'apt-get', 'update'],- capture_output=True,- text=True,- timeout=120- )+ run_privileged(['apt-get', 'update'], timeout=120)# Install PHP and common extensionspackages = [@@ -189,25 +177,15 @@ env[TEMP] = /tmpf'php{version}-bcmath',]- result = subprocess.run(- ['sudo', 'apt-get', 'install', '-y'] + packages,- capture_output=True,- text=True,- timeout=600+ result = run_privileged(+ ['apt-get', 'install', '-y'] + packages,+ timeout=600,)if result.returncode == 0:# Start FPM service- subprocess.run(- ['sudo', 'systemctl', 'enable', f'php{version}-fpm'],- capture_output=True,- text=True- )- subprocess.run(- ['sudo', 'systemctl', 'start', f'php{version}-fpm'],- capture_output=True,- text=True- )+ ServiceControl.enable(f'php{version}-fpm')+ ServiceControl.start(f'php{version}-fpm')return {'success': True, 'message': f'PHP {version} installed successfully'}return {'success': False, 'error': result.stderr}@@ -249,11 +227,9 @@ env[TEMP] = /tmppackage = f'php{version}-{extension}'try:- result = subprocess.run(- ['sudo', 'apt-get', 'install', '-y', package],- capture_output=True,- text=True,- timeout=120+ result = run_privileged(+ ['apt-get', 'install', '-y', package],+ timeout=120,)if result.returncode == 0:@@ -344,15 +320,10 @@ env[TEMP] = /tmptry:# Ensure log directory exists- subprocess.run(['sudo', 'mkdir', '-p', '/var/log/php'], capture_output=True)+ run_privileged(['mkdir', '-p', '/var/log/php'])# Write pool config- process = subprocess.run(- ['sudo', 'tee', pool_file],- input=pool_content,- capture_output=True,- text=True- )+ process = run_privileged(['tee', pool_file], input=pool_content)if process.returncode == 0:# Restart FPM@@ -377,11 +348,7 @@ env[TEMP] = /tmpreturn {'success': False, 'error': 'Cannot delete default www pool'}try:- result = subprocess.run(- ['sudo', 'rm', pool_file],- capture_output=True,- text=True- )+ result = run_privileged(['rm', pool_file])if result.returncode == 0:cls.restart_fpm(version)@@ -397,12 +364,7 @@ env[TEMP] = /tmpservice = cls.PHP_FPM_SERVICE.format(version=version)try:- result = subprocess.run(- ['sudo', 'systemctl', 'restart', service],- capture_output=True,- text=True,- timeout=30- )+ result = ServiceControl.restart(service, timeout=30)return {'success': result.returncode == 0,@@ -417,12 +379,7 @@ env[TEMP] = /tmpservice = cls.PHP_FPM_SERVICE.format(version=version)try:- result = subprocess.run(- ['sudo', 'systemctl', 'reload', service],- capture_output=True,- text=True,- timeout=30- )+ result = ServiceControl.reload(service, timeout=30)return {'success': result.returncode == 0,diff --git a/backend/app/services/python_service.py b/backend/app/services/python_service.pyindex e23c2705..3d96732d 100644--- a/backend/app/services/python_service.py+++ b/backend/app/services/python_service.py@@ -5,6 +5,8 @@ import jsonimport secretsfrom pathlib import Path+from app.utils.system import ServiceControl+class PythonService:"""Service for managing Python applications, virtual environments, and Gunicorn."""@@ -391,7 +393,7 @@ application = get_wsgi_application()f.write(service_content)# Reload systemd- subprocess.run(['systemctl', 'daemon-reload'], capture_output=True)+ ServiceControl.daemon_reload()return {'success': True,@@ -406,18 +408,12 @@ application = get_wsgi_application()"""Start the Gunicorn service for an app."""service_name = f'gunicorn-{app_name}'try:- result = subprocess.run(- ['systemctl', 'start', service_name],- capture_output=True, text=True- )+ result = ServiceControl.start(service_name)if result.returncode != 0:return {'success': False, 'error': result.stderr}# Enable on boot- subprocess.run(- ['systemctl', 'enable', service_name],- capture_output=True, text=True- )+ ServiceControl.enable(service_name)return {'success': True, 'message': f'{app_name} started'}except Exception as e:@@ -428,10 +424,7 @@ application = get_wsgi_application()"""Stop the Gunicorn service for an app."""service_name = f'gunicorn-{app_name}'try:- result = subprocess.run(- ['systemctl', 'stop', service_name],- capture_output=True, text=True- )+ result = ServiceControl.stop(service_name)if result.returncode != 0:return {'success': False, 'error': result.stderr}return {'success': True, 'message': f'{app_name} stopped'}@@ -443,10 +436,7 @@ application = get_wsgi_application()"""Restart the Gunicorn service for an app."""service_name = f'gunicorn-{app_name}'try:- result = subprocess.run(- ['systemctl', 'restart', service_name],- capture_output=True, text=True- )+ result = ServiceControl.restart(service_name)if result.returncode != 0:return {'success': False, 'error': result.stderr}return {'success': True, 'message': f'{app_name} restarted'}@@ -458,11 +448,7 @@ application = get_wsgi_application()"""Get the status of a Gunicorn service."""service_name = f'gunicorn-{app_name}'try:- result = subprocess.run(- ['systemctl', 'is-active', service_name],- capture_output=True, text=True- )- status = result.stdout.strip()+ status = 'active' if ServiceControl.is_active(service_name) else 'inactive'# Get more detailsdetails_result = subprocess.run(@@ -667,15 +653,15 @@ tmp_upload_dir = Nonetry:# Stop and disable service- subprocess.run(['systemctl', 'stop', service_name], capture_output=True)- subprocess.run(['systemctl', 'disable', service_name], capture_output=True)+ ServiceControl.stop(service_name)+ ServiceControl.disable(service_name)# Remove service fileservice_file = f'/etc/systemd/system/{service_name}.service'if os.path.exists(service_file):os.remove(service_file)- subprocess.run(['systemctl', 'daemon-reload'], capture_output=True)+ ServiceControl.daemon_reload()# Remove files if requestedif remove_files and os.path.exists(app_path):diff --git a/backend/app/services/security_service.py b/backend/app/services/security_service.pyindex 1d0d8fbb..d88e4951 100644--- a/backend/app/services/security_service.py+++ b/backend/app/services/security_service.py@@ -20,6 +20,11 @@ from pathlib import Pathfrom .notification_service import NotificationServicefrom app import paths+from app.utils.system import (+ PackageManager,+ ServiceControl,+ run_privileged,+)class SecurityService:@@ -122,25 +127,12 @@ class SecurityService:# Check if clamd service is runningtry:- service_check = subprocess.run(- ['systemctl', 'is-active', 'clamav-daemon'],- capture_output=True,- text=True,- timeout=5- )- result['service_running'] = service_check.stdout.strip() == 'active'+ result['service_running'] = ServiceControl.is_active('clamav-daemon')+ if not result['service_running']:+ # Try alternative service name+ result['service_running'] = ServiceControl.is_active('clamd')except Exception:- # Try alternative service name- try:- service_check = subprocess.run(- ['systemctl', 'is-active', 'clamd'],- capture_output=True,- text=True,- timeout=5- )- result['service_running'] = service_check.stdout.strip() == 'active'- except Exception:- pass+ pass# Get database infotry:@@ -161,22 +153,16 @@ class SecurityService:def install_clamav(cls) -> Dict:"""Install ClamAV packages."""try:- # Detect package manager- if os.path.exists('/usr/bin/apt'):- install_cmd = ['apt', 'install', '-y', 'clamav', 'clamav-daemon', 'clamav-freshclam']- elif os.path.exists('/usr/bin/dnf'):- install_cmd = ['dnf', 'install', '-y', 'clamav', 'clamd', 'clamav-update']- elif os.path.exists('/usr/bin/yum'):- install_cmd = ['yum', 'install', '-y', 'clamav', 'clamd', 'clamav-update']- else:+ manager = PackageManager.detect()+ if manager is None:return {'success': False, 'error': 'Unsupported package manager'}- result = subprocess.run(- install_cmd,- capture_output=True,- text=True,- timeout=300- )+ if manager == 'apt':+ packages = ['clamav', 'clamav-daemon', 'clamav-freshclam']+ else:+ packages = ['clamav', 'clamd', 'clamav-update']++ result = PackageManager.install(packages, timeout=300)if result.returncode != 0:return {'success': False, 'error': result.stderr}@@ -196,7 +182,7 @@ class SecurityService:"""Update ClamAV virus definitions."""try:# Stop freshclam if running to avoid conflicts- subprocess.run(['systemctl', 'stop', 'clamav-freshclam'], capture_output=True, timeout=10)+ ServiceControl.stop('clamav-freshclam', timeout=10)result = subprocess.run(['freshclam'],@@ -206,7 +192,7 @@ class SecurityService:)# Restart freshclam- subprocess.run(['systemctl', 'start', 'clamav-freshclam'], capture_output=True, timeout=10)+ ServiceControl.start('clamav-freshclam', timeout=10)if result.returncode == 0:return {'success': True, 'message': 'Definitions updated', 'output': result.stdout}@@ -838,13 +824,7 @@ class SecurityService:if result['installed']:try:- service_check = subprocess.run(- ['systemctl', 'is-active', 'fail2ban'],- capture_output=True,- text=True,- timeout=5- )- result['service_running'] = service_check.stdout.strip() == 'active'+ result['service_running'] = ServiceControl.is_active('fail2ban')except Exception:pass@@ -871,27 +851,17 @@ class SecurityService:def install_fail2ban(cls) -> Dict:"""Install Fail2ban."""try:- if os.path.exists('/usr/bin/apt'):- install_cmd = ['apt', 'install', '-y', 'fail2ban']- elif os.path.exists('/usr/bin/dnf'):- install_cmd = ['dnf', 'install', '-y', 'fail2ban']- elif os.path.exists('/usr/bin/yum'):- install_cmd = ['yum', 'install', '-y', 'fail2ban']- else:+ manager = PackageManager.detect()+ if manager is None:return {'success': False, 'error': 'Unsupported package manager'}- result = subprocess.run(- install_cmd,- capture_output=True,- text=True,- timeout=300- )+ result = PackageManager.install('fail2ban', timeout=300)if result.returncode != 0:return {'success': False, 'error': result.stderr}- subprocess.run(['systemctl', 'enable', 'fail2ban'], capture_output=True, timeout=10)- subprocess.run(['systemctl', 'start', 'fail2ban'], capture_output=True, timeout=10)+ ServiceControl.enable('fail2ban', timeout=10)+ ServiceControl.start('fail2ban', timeout=10)return {'success': True, 'message': 'Fail2ban installed successfully'}@@ -1343,12 +1313,12 @@ class SecurityService:checks['total_checks'] += 1try:- ufw_result = subprocess.run(['ufw', 'status'], capture_output=True, text=True, timeout=5)+ ufw_result = run_privileged(['ufw', 'status'], timeout=5)if ufw_result.returncode == 0 and 'active' in ufw_result.stdout.lower():checks['passed_checks'] += 1checks['findings'].append({'severity': 'pass', 'message': 'UFW firewall is active'})else:- firewalld_result = subprocess.run(['firewall-cmd', '--state'], capture_output=True, text=True, timeout=5)+ firewalld_result = run_privileged(['firewall-cmd', '--state'], timeout=5)if firewalld_result.returncode == 0 and 'running' in firewalld_result.stdout.lower():checks['passed_checks'] += 1checks['findings'].append({'severity': 'pass', 'message': 'firewalld is active'})@@ -1391,7 +1361,7 @@ class SecurityService:checks['total_checks'] += 1try:- if os.path.exists('/usr/bin/apt'):+ if PackageManager.detect() == 'apt':result = subprocess.run(['apt', 'list', '--upgradable'], capture_output=True, text=True, timeout=60)if result.returncode == 0:lines = [l for l in result.stdout.split('\n') if '/' in l]@@ -1458,16 +1428,11 @@ class SecurityService:def install_lynis(cls) -> Dict:"""Install Lynis security auditing tool."""try:- if os.path.exists('/usr/bin/apt'):- install_cmd = ['apt', 'install', '-y', 'lynis']- elif os.path.exists('/usr/bin/dnf'):- install_cmd = ['dnf', 'install', '-y', 'lynis']- elif os.path.exists('/usr/bin/yum'):- install_cmd = ['yum', 'install', '-y', 'lynis']- else:+ manager = PackageManager.detect()+ if manager is None:return {'success': False, 'error': 'Unsupported package manager'}- result = subprocess.run(install_cmd, capture_output=True, text=True, timeout=300)+ result = PackageManager.install('lynis', timeout=300)if result.returncode != 0:return {'success': False, 'error': result.stderr}@@ -1560,18 +1525,14 @@ class SecurityService:'settings': {}}- if os.path.exists('/usr/bin/apt'):+ manager = PackageManager.detect()++ if manager == 'apt':result['supported'] = Trueresult['package'] = 'unattended-upgrades'try:- check = subprocess.run(- ['dpkg', '-l', 'unattended-upgrades'],- capture_output=True,- text=True,- timeout=10- )- result['installed'] = check.returncode == 0 and 'ii' in check.stdout+ result['installed'] = PackageManager.is_installed('unattended-upgrades')except Exception:result['installed'] = False@@ -1585,14 +1546,12 @@ class SecurityService:except Exception:pass- elif os.path.exists('/usr/bin/dnf'):+ elif manager == 'dnf':result['supported'] = Trueresult['package'] = 'dnf-automatic'try:- check = subprocess.run(['systemctl', 'is-enabled', 'dnf-automatic.timer'],- capture_output=True, text=True, timeout=10)- result['enabled'] = check.stdout.strip() == 'enabled'+ result['enabled'] = ServiceControl.is_enabled('dnf-automatic.timer')except Exception:pass@@ -1602,24 +1561,16 @@ class SecurityService:def install_auto_updates(cls) -> Dict:"""Install automatic security updates package."""try:- if os.path.exists('/usr/bin/apt'):- result = subprocess.run(- ['apt', 'install', '-y', 'unattended-upgrades', 'apt-listchanges'],- capture_output=True,- text=True,- timeout=300- )+ manager = PackageManager.detect()++ if manager == 'apt':+ result = PackageManager.install(['unattended-upgrades', 'apt-listchanges'], timeout=300)if result.returncode != 0:return {'success': False, 'error': result.stderr}return {'success': True, 'message': 'unattended-upgrades installed'}- elif os.path.exists('/usr/bin/dnf'):- result = subprocess.run(- ['dnf', 'install', '-y', 'dnf-automatic'],- capture_output=True,- text=True,- timeout=300- )+ elif manager == 'dnf':+ result = PackageManager.install('dnf-automatic', timeout=300)if result.returncode != 0:return {'success': False, 'error': result.stderr}return {'success': True, 'message': 'dnf-automatic installed'}@@ -1635,7 +1586,9 @@ class SecurityService:def enable_auto_updates(cls) -> Dict:"""Enable automatic security updates."""try:- if os.path.exists('/usr/bin/apt'):+ manager = PackageManager.detect()++ if manager == 'apt':config_content = '''APT::Periodic::Update-Package-Lists "1";APT::Periodic::Unattended-Upgrade "1";APT::Periodic::AutocleanInterval "7";@@ -1645,9 +1598,9 @@ APT::Periodic::AutocleanInterval "7";f.write(config_content)return {'success': True, 'message': 'Automatic updates enabled'}- elif os.path.exists('/usr/bin/dnf'):- subprocess.run(['systemctl', 'enable', 'dnf-automatic.timer'], capture_output=True, timeout=10)- subprocess.run(['systemctl', 'start', 'dnf-automatic.timer'], capture_output=True, timeout=10)+ elif manager == 'dnf':+ ServiceControl.enable('dnf-automatic.timer', timeout=10)+ ServiceControl.start('dnf-automatic.timer', timeout=10)return {'success': True, 'message': 'Automatic updates enabled'}return {'success': False, 'error': 'Unsupported package manager'}@@ -1659,7 +1612,9 @@ APT::Periodic::AutocleanInterval "7";def disable_auto_updates(cls) -> Dict:"""Disable automatic security updates."""try:- if os.path.exists('/usr/bin/apt'):+ manager = PackageManager.detect()++ if manager == 'apt':config_content = '''APT::Periodic::Update-Package-Lists "0";APT::Periodic::Unattended-Upgrade "0";'''@@ -1668,9 +1623,9 @@ APT::Periodic::Unattended-Upgrade "0";f.write(config_content)return {'success': True, 'message': 'Automatic updates disabled'}- elif os.path.exists('/usr/bin/dnf'):- subprocess.run(['systemctl', 'disable', 'dnf-automatic.timer'], capture_output=True, timeout=10)- subprocess.run(['systemctl', 'stop', 'dnf-automatic.timer'], capture_output=True, timeout=10)+ elif manager == 'dnf':+ ServiceControl.disable('dnf-automatic.timer', timeout=10)+ ServiceControl.stop('dnf-automatic.timer', timeout=10)return {'success': True, 'message': 'Automatic updates disabled'}return {'success': False, 'error': 'Unsupported package manager'}diff --git a/backend/app/services/ssl_service.py b/backend/app/services/ssl_service.pyindex 63f60890..536b7b2d 100644--- a/backend/app/services/ssl_service.py+++ b/backend/app/services/ssl_service.py@@ -5,6 +5,8 @@ from datetime import datetimefrom typing import Dict, List, Optionalfrom pathlib import Path+from app.utils.system import ServiceControl, run_privileged+class SSLService:"""Service for SSL certificate management with Let's Encrypt."""@@ -30,16 +32,16 @@ class SSLService:def install_certbot(cls) -> Dict:"""Install certbot if not present."""try:- # For Ubuntu/Debian- commands = [- ['sudo', 'apt-get', 'update'],- ['sudo', 'apt-get', 'install', '-y', 'certbot', 'python3-certbot-nginx']- ]+ result = run_privileged(['apt-get', 'update'], timeout=300)+ if result.returncode != 0:+ return {'success': False, 'error': result.stderr}- for cmd in commands:- result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)- if result.returncode != 0:- return {'success': False, 'error': result.stderr}+ result = run_privileged(+ ['apt-get', 'install', '-y', 'certbot', 'python3-certbot-nginx'],+ timeout=300,+ )+ if result.returncode != 0:+ return {'success': False, 'error': result.stderr}return {'success': True, 'message': 'Certbot installed successfully'}except Exception as e:@@ -56,7 +58,7 @@ class SSLService:try:# Build certbot command- cmd = ['sudo', cls.CERTBOT_BIN, 'certonly']+ cmd = [cls.CERTBOT_BIN, 'certonly']if use_nginx:cmd.append('--nginx')@@ -77,7 +79,7 @@ class SSLService:'--expand'])- result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)+ result = run_privileged(cmd, timeout=300)if result.returncode == 0:primary_domain = domains[0]@@ -103,12 +105,12 @@ class SSLService:def renew_certificate(cls, domain: str = None) -> Dict:"""Renew SSL certificate(s)."""try:- cmd = ['sudo', cls.CERTBOT_BIN, 'renew', '--non-interactive']+ cmd = [cls.CERTBOT_BIN, 'renew', '--non-interactive']if domain:cmd.extend(['--cert-name', domain])- result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)+ result = run_privileged(cmd, timeout=300)return {'success': result.returncode == 0,@@ -124,21 +126,21 @@ class SSLService:try:cmd = [- 'sudo', cls.CERTBOT_BIN, 'revoke',+ cls.CERTBOT_BIN, 'revoke','--cert-path', cert_path,'--non-interactive']- result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)+ result = run_privileged(cmd, timeout=120)if result.returncode == 0:# Also delete the certificatedelete_cmd = [- 'sudo', cls.CERTBOT_BIN, 'delete',+ cls.CERTBOT_BIN, 'delete','--cert-name', domain,'--non-interactive']- subprocess.run(delete_cmd, capture_output=True, text=True)+ run_privileged(delete_cmd)return {'success': True, 'message': f'Certificate for {domain} revoked and deleted'}@@ -152,12 +154,7 @@ class SSLService:certificates = []try:- result = subprocess.run(- ['sudo', cls.CERTBOT_BIN, 'certificates'],- capture_output=True,- text=True,- timeout=60- )+ result = run_privileged([cls.CERTBOT_BIN, 'certificates'], timeout=60)if result.returncode != 0:return certificates@@ -205,11 +202,9 @@ class SSLService:try:# Use openssl to get certificate details- result = subprocess.run(- ['sudo', 'openssl', 'x509', '-in', cert_path, '-noout',+ result = run_privileged(+ ['openssl', 'x509', '-in', cert_path, '-noout','-subject', '-issuer', '-dates', '-serial'],- capture_output=True,- text=True)if result.returncode != 0:@@ -241,19 +236,15 @@ class SSLService:cert_path = f'{cls.CERTS_DIR}/{domain}/fullchain.pem'# Check expiry with openssl- result = subprocess.run(- ['sudo', 'openssl', 'x509', '-in', cert_path, '-checkend', '2592000'], # 30 days- capture_output=True,- text=True+ result = run_privileged(+ ['openssl', 'x509', '-in', cert_path, '-checkend', '2592000'],)expiring_soon = result.returncode != 0# Get actual expiry date- date_result = subprocess.run(- ['sudo', 'openssl', 'x509', '-in', cert_path, '-noout', '-enddate'],- capture_output=True,- text=True+ date_result = run_privileged(+ ['openssl', 'x509', '-in', cert_path, '-noout', '-enddate'],)expiry_date = None@@ -275,20 +266,12 @@ class SSLService:"""Set up automatic certificate renewal via cron/systemd timer."""try:# Check if systemd timer exists- result = subprocess.run(- ['sudo', 'systemctl', 'is-enabled', 'certbot.timer'],- capture_output=True,- text=True- )-- if result.returncode == 0:+ if ServiceControl.is_enabled('certbot.timer'):return {'success': True, 'message': 'Auto-renewal already configured via systemd'}# Enable systemd timer- enable_result = subprocess.run(- ['sudo', 'systemctl', 'enable', '--now', 'certbot.timer'],- capture_output=True,- text=True+ enable_result = run_privileged(+ ['systemctl', 'enable', '--now', 'certbot.timer'],)if enable_result.returncode == 0:@@ -298,12 +281,7 @@ class SSLService:cron_job = '0 0,12 * * * root certbot renew --quiet --post-hook "systemctl reload nginx"'cron_file = '/etc/cron.d/certbot-renewal'- subprocess.run(- ['sudo', 'tee', cron_file],- input=cron_job + '\n',- capture_output=True,- text=True- )+ run_privileged(['tee', cron_file], input=cron_job + '\n')return {'success': True, 'message': 'Auto-renewal configured via cron'}diff --git a/backend/app/utils/system.py b/backend/app/utils/system.pynew file mode 100644index 00000000..84231ab2--- /dev/null+++ b/backend/app/utils/system.py@@ -0,0 +1,194 @@+"""Centralized system utilities for subprocess handling.++Provides consistent privilege escalation, distro detection, package management,+and systemd service control so individual services don't need to reinvent these.+"""++import os+import shutil+import subprocess+from typing import List, Optional, Union+++def run_privileged(cmd: Union[List[str], str], **kwargs) -> subprocess.CompletedProcess:+ """Run a command with sudo if the current process is not root.++ Prepends ``sudo`` when ``os.geteuid() != 0`` and the command does not+ already start with ``sudo``. Defaults to ``capture_output=True, text=True``+ but callers can override any kwarg.++ Returns the raw ``CompletedProcess`` so services keep their existing+ error-handling patterns.+ """+ if isinstance(cmd, str):+ # Shell-mode — caller is responsible for quoting+ needs_sudo = os.geteuid() != 0 and not cmd.lstrip().startswith('sudo ')+ if needs_sudo:+ cmd = f'sudo {cmd}'+ else:+ cmd = list(cmd)+ needs_sudo = os.geteuid() != 0 and cmd[0] != 'sudo'+ if needs_sudo:+ cmd = ['sudo'] + cmd++ kwargs.setdefault('capture_output', True)+ kwargs.setdefault('text', True)+ return subprocess.run(cmd, **kwargs)+++def is_command_available(cmd: str) -> bool:+ """Check whether *cmd* is available on the system.++ Uses ``shutil.which`` first, then falls back to checking common sbin/local+ paths that may not be on the current ``$PATH``.+ """+ if shutil.which(cmd):+ return True++ for directory in ('/usr/bin', '/usr/sbin', '/usr/local/bin', '/usr/local/sbin'):+ if os.path.exists(os.path.join(directory, cmd)):+ return True++ return False+++class PackageManager:+ """Cross-distro package management helpers.++ Detects ``apt``, ``dnf``, or ``yum`` once and caches the result.+ """++ _detected: Optional[str] = None+ _detection_done: bool = False++ @classmethod+ def detect(cls) -> Optional[str]:+ """Return ``'apt'``, ``'dnf'``, ``'yum'``, or ``None``."""+ if cls._detection_done:+ return cls._detected++ for manager in ('apt', 'dnf', 'yum'):+ if shutil.which(manager):+ cls._detected = manager+ cls._detection_done = True+ return cls._detected++ cls._detection_done = True+ return cls._detected++ @classmethod+ def is_available(cls) -> bool:+ """Return ``True`` if any supported package manager was found."""+ return cls.detect() is not None++ @classmethod+ def is_installed(cls, package: str) -> bool:+ """Check whether *package* is installed (cross-distro).++ Uses ``dpkg -s`` on apt systems and ``rpm -q`` on dnf/yum systems.+ Catches ``FileNotFoundError`` so it works on any distro.+ """+ manager = cls.detect()++ if manager == 'apt':+ try:+ result = subprocess.run(+ ['dpkg', '-s', package],+ capture_output=True, text=True,+ )+ return (+ result.returncode == 0+ and 'Status: install ok installed' in result.stdout+ )+ except FileNotFoundError:+ return False++ if manager in ('dnf', 'yum'):+ try:+ result = subprocess.run(+ ['rpm', '-q', package],+ capture_output=True, text=True,+ )+ return result.returncode == 0+ except FileNotFoundError:+ return False++ return False++ @classmethod+ def install(cls, packages: Union[str, List[str]], timeout: int = 300) -> subprocess.CompletedProcess:+ """Install one or more packages (cross-distro).++ Raises ``RuntimeError`` when no supported package manager is found.+ """+ manager = cls.detect()+ if manager is None:+ raise RuntimeError('No supported package manager found (apt/dnf/yum)')++ if isinstance(packages, str):+ packages = [packages]++ cmd = [manager, 'install', '-y'] + packages+ return run_privileged(cmd, timeout=timeout)++ @classmethod+ def reset_cache(cls) -> None:+ """Reset the cached detection (useful in tests)."""+ cls._detected = None+ cls._detection_done = False+++class ServiceControl:+ """Thin wrappers around ``systemctl`` that use :func:`run_privileged`."""++ @staticmethod+ def start(service: str, **kwargs) -> subprocess.CompletedProcess:+ return run_privileged(['systemctl', 'start', service], **kwargs)++ @staticmethod+ def stop(service: str, **kwargs) -> subprocess.CompletedProcess:+ return run_privileged(['systemctl', 'stop', service], **kwargs)++ @staticmethod+ def restart(service: str, **kwargs) -> subprocess.CompletedProcess:+ return run_privileged(['systemctl', 'restart', service], **kwargs)++ @staticmethod+ def reload(service: str, **kwargs) -> subprocess.CompletedProcess:+ return run_privileged(['systemctl', 'reload', service], **kwargs)++ @staticmethod+ def enable(service: str, **kwargs) -> subprocess.CompletedProcess:+ return run_privileged(['systemctl', 'enable', service], **kwargs)++ @staticmethod+ def disable(service: str, **kwargs) -> subprocess.CompletedProcess:+ return run_privileged(['systemctl', 'disable', service], **kwargs)++ @staticmethod+ def daemon_reload(**kwargs) -> subprocess.CompletedProcess:+ return run_privileged(['systemctl', 'daemon-reload'], **kwargs)++ @staticmethod+ def is_active(service: str) -> bool:+ """Return ``True`` when the service is active. No sudo needed."""+ try:+ result = subprocess.run(+ ['systemctl', 'is-active', service],+ capture_output=True, text=True,+ )+ return result.stdout.strip() == 'active'+ except FileNotFoundError:+ return False++ @staticmethod+ def is_enabled(service: str) -> bool:+ """Return ``True`` when the service is enabled. No sudo needed."""+ try:+ result = subprocess.run(+ ['systemctl', 'is-enabled', service],+ capture_output=True, text=True,+ )+ return result.stdout.strip() == 'enabled'+ except FileNotFoundError:+ return Falsediff --git a/backend/tests/test_utils_system.py b/backend/tests/test_utils_system.pynew file mode 100644index 00000000..ab0fb8e0--- /dev/null+++ b/backend/tests/test_utils_system.py@@ -0,0 +1,367 @@+"""Tests for backend/app/utils/system.py.++Uses a direct import path so the test can run without Flask dependencies+(system.py itself has no Flask imports).+"""++import importlib+import os+import subprocess+import sys+from unittest import mock+from unittest.mock import MagicMock, patch++import pytest++# Import system.py directly to avoid triggering app/__init__.py (Flask deps).+# We register stub entries for 'app' and 'app.utils' so that+# unittest.mock.patch('app.utils.system.X') can resolve the path without+# importing the real app package (which needs Flask).+import types++_backend = os.path.join(os.path.dirname(__file__), os.pardir)+_mod_path = os.path.join(_backend, 'app', 'utils', 'system.py')+_spec = importlib.util.spec_from_file_location('app.utils.system', _mod_path)+_module = importlib.util.module_from_spec(_spec)++# Stub parent packages so patch() resolution never hits Flask imports.+if 'app' not in sys.modules:+ sys.modules['app'] = types.ModuleType('app')+if 'app.utils' not in sys.modules:+ _utils = types.ModuleType('app.utils')+ sys.modules['app.utils'] = _utils+ sys.modules['app'].utils = _utils # type: ignore[attr-defined]++sys.modules['app.utils.system'] = _module+sys.modules['app.utils'].system = _module # type: ignore[attr-defined]+_spec.loader.exec_module(_module)++run_privileged = _module.run_privileged+is_command_available = _module.is_command_available+PackageManager = _module.PackageManager+ServiceControl = _module.ServiceControl+++# ---------------------------------------------------------------------------+# run_privileged+# ---------------------------------------------------------------------------+class TestRunPrivileged:+ """Tests for :func:`run_privileged`."""++ @patch('app.utils.system.subprocess.run')+ @patch('app.utils.system.os.geteuid', return_value=1000, create=True)+ def test_prepends_sudo_when_not_root(self, _euid, mock_run):+ mock_run.return_value = subprocess.CompletedProcess([], 0)+ run_privileged(['systemctl', 'restart', 'nginx'])+ mock_run.assert_called_once_with(+ ['sudo', 'systemctl', 'restart', 'nginx'],+ capture_output=True, text=True,+ )++ @patch('app.utils.system.subprocess.run')+ @patch('app.utils.system.os.geteuid', return_value=0, create=True)+ def test_skips_sudo_when_root(self, _euid, mock_run):+ mock_run.return_value = subprocess.CompletedProcess([], 0)+ run_privileged(['systemctl', 'restart', 'nginx'])+ mock_run.assert_called_once_with(+ ['systemctl', 'restart', 'nginx'],+ capture_output=True, text=True,+ )++ @patch('app.utils.system.subprocess.run')+ @patch('app.utils.system.os.geteuid', return_value=1000, create=True)+ def test_no_double_sudo(self, _euid, mock_run):+ mock_run.return_value = subprocess.CompletedProcess([], 0)+ run_privileged(['sudo', 'systemctl', 'restart', 'nginx'])+ mock_run.assert_called_once_with(+ ['sudo', 'systemctl', 'restart', 'nginx'],+ capture_output=True, text=True,+ )++ @patch('app.utils.system.subprocess.run')+ @patch('app.utils.system.os.geteuid', return_value=1000, create=True)+ def test_defaults_applied(self, _euid, mock_run):+ mock_run.return_value = subprocess.CompletedProcess([], 0)+ run_privileged(['ls'])+ _, kwargs = mock_run.call_args+ assert kwargs['capture_output'] is True+ assert kwargs['text'] is True++ @patch('app.utils.system.subprocess.run')+ @patch('app.utils.system.os.geteuid', return_value=1000, create=True)+ def test_kwargs_passed_through(self, _euid, mock_run):+ mock_run.return_value = subprocess.CompletedProcess([], 0)+ run_privileged(['apt', 'install', '-y', 'foo'], timeout=120, check=True)+ _, kwargs = mock_run.call_args+ assert kwargs['timeout'] == 120+ assert kwargs['check'] is True++ @patch('app.utils.system.subprocess.run')+ @patch('app.utils.system.os.geteuid', return_value=1000, create=True)+ def test_caller_can_override_defaults(self, _euid, mock_run):+ mock_run.return_value = subprocess.CompletedProcess([], 0)+ run_privileged(['ls'], capture_output=False)+ _, kwargs = mock_run.call_args+ assert kwargs['capture_output'] is False++ @patch('app.utils.system.subprocess.run')+ @patch('app.utils.system.os.geteuid', return_value=1000, create=True)+ def test_string_command_gets_sudo(self, _euid, mock_run):+ mock_run.return_value = subprocess.CompletedProcess([], 0)+ run_privileged('systemctl restart nginx')+ args, _ = mock_run.call_args+ assert args[0] == 'sudo systemctl restart nginx'++ @patch('app.utils.system.subprocess.run')+ @patch('app.utils.system.os.geteuid', return_value=1000, create=True)+ def test_string_command_no_double_sudo(self, _euid, mock_run):+ mock_run.return_value = subprocess.CompletedProcess([], 0)+ run_privileged('sudo systemctl restart nginx')+ args, _ = mock_run.call_args+ assert args[0] == 'sudo systemctl restart nginx'++ @patch('app.utils.system.subprocess.run')+ @patch('app.utils.system.os.geteuid', return_value=1000, create=True)+ def test_returns_completed_process(self, _euid, mock_run):+ expected = subprocess.CompletedProcess([], 0, stdout='ok')+ mock_run.return_value = expected+ result = run_privileged(['echo', 'ok'])+ assert result is expected+++# ---------------------------------------------------------------------------+# is_command_available+# ---------------------------------------------------------------------------+class TestIsCommandAvailable:+ """Tests for :func:`is_command_available`."""++ @patch('app.utils.system.shutil.which', return_value='/usr/bin/nginx')+ def test_found_in_path(self, _which):+ assert is_command_available('nginx') is True++ @patch('app.utils.system.os.path.exists', return_value=True)+ @patch('app.utils.system.shutil.which', return_value=None)+ def test_found_in_common_paths(self, _which, _exists):+ assert is_command_available('firewall-cmd') is True++ @patch('app.utils.system.os.path.exists', return_value=False)+ @patch('app.utils.system.shutil.which', return_value=None)+ def test_not_found(self, _which, _exists):+ assert is_command_available('nonexistent') is False+++# ---------------------------------------------------------------------------+# PackageManager+# ---------------------------------------------------------------------------+class TestPackageManager:+ """Tests for :class:`PackageManager`."""++ def setup_method(self):+ PackageManager.reset_cache()++ @patch('app.utils.system.shutil.which', side_effect=lambda c: '/usr/bin/apt' if c == 'apt' else None)+ def test_detect_apt(self, _which):+ assert PackageManager.detect() == 'apt'++ @patch('app.utils.system.shutil.which', side_effect=lambda c: '/usr/bin/dnf' if c == 'dnf' else None)+ def test_detect_dnf(self, _which):+ assert PackageManager.detect() == 'dnf'++ @patch('app.utils.system.shutil.which', return_value=None)+ def test_detect_none(self, _which):+ assert PackageManager.detect() is None++ @patch('app.utils.system.shutil.which', side_effect=lambda c: '/usr/bin/apt' if c == 'apt' else None)+ def test_is_available_true(self, _which):+ assert PackageManager.is_available() is True++ @patch('app.utils.system.shutil.which', return_value=None)+ def test_is_available_false(self, _which):+ assert PackageManager.is_available() is False++ @patch('app.utils.system.shutil.which', side_effect=lambda c: '/usr/bin/apt' if c == 'apt' else None)+ def test_detect_caches(self, mock_which):+ PackageManager.detect()+ PackageManager.detect()+ # shutil.which should only be called during the first detect()+ assert mock_which.call_count <= 3 # at most apt/dnf/yum on first call++ # -- is_installed --++ @patch('app.utils.system.subprocess.run')+ @patch('app.utils.system.shutil.which', side_effect=lambda c: '/usr/bin/apt' if c == 'apt' else None)+ def test_is_installed_apt_true(self, _which, mock_run):+ mock_run.return_value = subprocess.CompletedProcess(+ [], 0, stdout='Status: install ok installed\n',+ )+ assert PackageManager.is_installed('nginx') is True+ mock_run.assert_called_once_with(+ ['dpkg', '-s', 'nginx'], capture_output=True, text=True,+ )++ @patch('app.utils.system.subprocess.run')+ @patch('app.utils.system.shutil.which', side_effect=lambda c: '/usr/bin/apt' if c == 'apt' else None)+ def test_is_installed_apt_false(self, _which, mock_run):+ mock_run.return_value = subprocess.CompletedProcess([], 1, stdout='')+ assert PackageManager.is_installed('nginx') is False++ @patch('app.utils.system.subprocess.run', side_effect=FileNotFoundError)+ @patch('app.utils.system.shutil.which', side_effect=lambda c: '/usr/bin/apt' if c == 'apt' else None)+ def test_is_installed_apt_dpkg_missing(self, _which, _run):+ assert PackageManager.is_installed('nginx') is False++ @patch('app.utils.system.subprocess.run')+ @patch('app.utils.system.shutil.which', side_effect=lambda c: '/usr/bin/dnf' if c == 'dnf' else None)+ def test_is_installed_rpm_true(self, _which, mock_run):+ mock_run.return_value = subprocess.CompletedProcess([], 0, stdout='nginx-1.0\n')+ assert PackageManager.is_installed('nginx') is True++ @patch('app.utils.system.subprocess.run', side_effect=FileNotFoundError)+ @patch('app.utils.system.shutil.which', side_effect=lambda c: '/usr/bin/dnf' if c == 'dnf' else None)+ def test_is_installed_rpm_missing(self, _which, _run):+ assert PackageManager.is_installed('nginx') is False++ @patch('app.utils.system.shutil.which', return_value=None)+ def test_is_installed_no_manager(self, _which):+ assert PackageManager.is_installed('nginx') is False++ # -- install --++ @patch('app.utils.system.subprocess.run')+ @patch('app.utils.system.os.geteuid', return_value=1000, create=True)+ @patch('app.utils.system.shutil.which', side_effect=lambda c: '/usr/bin/apt' if c == 'apt' else None)+ def test_install_apt(self, _which, _euid, mock_run):+ mock_run.return_value = subprocess.CompletedProcess([], 0)+ result = PackageManager.install(['nginx', 'curl'])+ mock_run.assert_called_once_with(+ ['sudo', 'apt', 'install', '-y', 'nginx', 'curl'],+ capture_output=True, text=True, timeout=300,+ )++ @patch('app.utils.system.subprocess.run')+ @patch('app.utils.system.os.geteuid', return_value=1000, create=True)+ @patch('app.utils.system.shutil.which', side_effect=lambda c: '/usr/bin/dnf' if c == 'dnf' else None)+ def test_install_dnf(self, _which, _euid, mock_run):+ mock_run.return_value = subprocess.CompletedProcess([], 0)+ PackageManager.install('nginx')+ args = mock_run.call_args[0][0]+ assert args == ['sudo', 'dnf', 'install', '-y', 'nginx']++ @patch('app.utils.system.shutil.which', return_value=None)+ def test_install_no_manager_raises(self, _which):+ with pytest.raises(RuntimeError, match='No supported package manager'):+ PackageManager.install('nginx')+++# ---------------------------------------------------------------------------+# ServiceControl+# ---------------------------------------------------------------------------+class TestServiceControl:+ """Tests for :class:`ServiceControl`."""++ @patch('app.utils.system.subprocess.run')+ @patch('app.utils.system.os.geteuid', return_value=1000, create=True)+ def test_start(self, _euid, mock_run):+ mock_run.return_value = subprocess.CompletedProcess([], 0)+ ServiceControl.start('nginx')+ mock_run.assert_called_once_with(+ ['sudo', 'systemctl', 'start', 'nginx'],+ capture_output=True, text=True,+ )++ @patch('app.utils.system.subprocess.run')+ @patch('app.utils.system.os.geteuid', return_value=1000, create=True)+ def test_stop(self, _euid, mock_run):+ mock_run.return_value = subprocess.CompletedProcess([], 0)+ ServiceControl.stop('nginx')+ mock_run.assert_called_once_with(+ ['sudo', 'systemctl', 'stop', 'nginx'],+ capture_output=True, text=True,+ )++ @patch('app.utils.system.subprocess.run')+ @patch('app.utils.system.os.geteuid', return_value=1000, create=True)+ def test_restart(self, _euid, mock_run):+ mock_run.return_value = subprocess.CompletedProcess([], 0)+ ServiceControl.restart('nginx')+ mock_run.assert_called_once_with(+ ['sudo', 'systemctl', 'restart', 'nginx'],+ capture_output=True, text=True,+ )++ @patch('app.utils.system.subprocess.run')+ @patch('app.utils.system.os.geteuid', return_value=1000, create=True)+ def test_reload(self, _euid, mock_run):+ mock_run.return_value = subprocess.CompletedProcess([], 0)+ ServiceControl.reload('nginx')+ mock_run.assert_called_once_with(+ ['sudo', 'systemctl', 'reload', 'nginx'],+ capture_output=True, text=True,+ )++ @patch('app.utils.system.subprocess.run')+ @patch('app.utils.system.os.geteuid', return_value=1000, create=True)+ def test_enable(self, _euid, mock_run):+ mock_run.return_value = subprocess.CompletedProcess([], 0)+ ServiceControl.enable('nginx')+ mock_run.assert_called_once_with(+ ['sudo', 'systemctl', 'enable', 'nginx'],+ capture_output=True, text=True,+ )++ @patch('app.utils.system.subprocess.run')+ @patch('app.utils.system.os.geteuid', return_value=1000, create=True)+ def test_disable(self, _euid, mock_run):+ mock_run.return_value = subprocess.CompletedProcess([], 0)+ ServiceControl.disable('nginx')+ mock_run.assert_called_once_with(+ ['sudo', 'systemctl', 'disable', 'nginx'],+ capture_output=True, text=True,+ )++ @patch('app.utils.system.subprocess.run')+ @patch('app.utils.system.os.geteuid', return_value=1000, create=True)+ def test_daemon_reload(self, _euid, mock_run):+ mock_run.return_value = subprocess.CompletedProcess([], 0)+ ServiceControl.daemon_reload()+ mock_run.assert_called_once_with(+ ['sudo', 'systemctl', 'daemon-reload'],+ capture_output=True, text=True,+ )++ @patch('app.utils.system.subprocess.run')+ @patch('app.utils.system.os.geteuid', return_value=1000, create=True)+ def test_restart_with_kwargs(self, _euid, mock_run):+ mock_run.return_value = subprocess.CompletedProcess([], 0)+ ServiceControl.restart('nginx', check=True, timeout=30)+ _, kwargs = mock_run.call_args+ assert kwargs['check'] is True+ assert kwargs['timeout'] == 30++ @patch('app.utils.system.subprocess.run')+ def test_is_active_true(self, mock_run):+ mock_run.return_value = subprocess.CompletedProcess([], 0, stdout='active\n')+ assert ServiceControl.is_active('nginx') is True++ @patch('app.utils.system.subprocess.run')+ def test_is_active_false(self, mock_run):+ mock_run.return_value = subprocess.CompletedProcess([], 3, stdout='inactive\n')+ assert ServiceControl.is_active('nginx') is False++ @patch('app.utils.system.subprocess.run', side_effect=FileNotFoundError)+ def test_is_active_missing_systemctl(self, _run):+ assert ServiceControl.is_active('nginx') is False++ @patch('app.utils.system.subprocess.run')+ def test_is_enabled_true(self, mock_run):+ mock_run.return_value = subprocess.CompletedProcess([], 0, stdout='enabled\n')+ assert ServiceControl.is_enabled('nginx') is True++ @patch('app.utils.system.subprocess.run')+ def test_is_enabled_false(self, mock_run):+ mock_run.return_value = subprocess.CompletedProcess([], 1, stdout='disabled\n')+ assert ServiceControl.is_enabled('nginx') is False++ @patch('app.utils.system.subprocess.run', side_effect=FileNotFoundError)+ def test_is_enabled_missing_systemctl(self, _run):+ assert ServiceControl.is_enabled('nginx') is False