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(security): per-image CVE scanning (grype) and SBOM generation (syft)
Juan Denis57cbdfd5dea8
diff --git a/backend/app/api/security.py b/backend/app/api/security.pyindex 5f994e66..e8eb1be5 100644--- a/backend/app/api/security.py+++ b/backend/app/api/security.py@@ -484,3 +484,101 @@ def disable_auto_updates():"""Disable automatic security updates."""result = SecurityService.disable_auto_updates()return jsonify(result), 200 if result['success'] else 400+++# ==========================================+# IMAGE VULNERABILITY SCANNING+# ==========================================+@security_bp.route('/image-scans/install', methods=['POST'])+@jwt_required()+@admin_required+def install_image_scanner():+ """Install grype and syft scanner binaries."""+ from app.services.image_scanner_service import ImageScannerService+ grype = ImageScannerService.install_grype()+ syft = ImageScannerService.install_syft()+ return jsonify({'grype': grype, 'syft': syft}), 200+++@security_bp.route('/image-scans/applications/<int:application_id>', methods=['POST'])+@jwt_required()+@admin_required+def scan_application_image(application_id):+ """Trigger a CVE scan for an application image."""+ from app.services.image_scanner_service import ImageScannerService+ result = ImageScannerService.scan_application(application_id)+ return jsonify(result), 200 if result['success'] else 400+++@security_bp.route('/image-scans/applications/<int:application_id>', methods=['GET'])+@jwt_required()+@admin_required+def get_application_image_scans(application_id):+ """Get scan history for an application."""+ from app.services.image_scanner_service import ImageScannerService+ limit = request.args.get('limit', 20, type=int)+ scans = ImageScannerService.scan_history(application_id, limit=limit)+ latest = ImageScannerService.latest_scan(application_id)+ return jsonify({+ 'scans': scans,+ 'latest': latest.to_dict() if latest else None+ }), 200+++@security_bp.route('/image-scans/<int:scan_id>', methods=['GET'])+@jwt_required()+@admin_required+def get_image_scan(scan_id):+ """Get a single scan with findings."""+ from app.models import ImageVulnerabilityScan+ scan = ImageVulnerabilityScan.query.get(scan_id)+ if not scan:+ return jsonify({'error': 'Scan not found'}), 404+ return jsonify(scan.to_dict(include_findings=True)), 200+++@security_bp.route('/image-scans/applications/<int:application_id>/deploy-gate', methods=['GET'])+@jwt_required()+@admin_required+def get_image_deploy_gate(application_id):+ """Check whether the latest scan passes the deploy gate."""+ from app.services.image_scanner_service import ImageScannerService+ allowed = request.args.getlist('allowed') or None+ result = ImageScannerService.check_deploy_gate(application_id, allowed_severities=allowed)+ return jsonify(result), 200+++# ==========================================+# SBOM GENERATION+# ==========================================+@security_bp.route('/sboms/applications/<int:application_id>', methods=['POST'])+@jwt_required()+@admin_required+def generate_application_sbom(application_id):+ """Generate an SPDX SBOM for an application image."""+ from app.services.image_scanner_service import ImageScannerService+ result = ImageScannerService.generate_sbom(application_id)+ return jsonify(result), 200 if result['success'] else 400+++@security_bp.route('/sboms/applications/<int:application_id>', methods=['GET'])+@jwt_required()+@admin_required+def get_application_sboms(application_id):+ """List generated SBOMs for an application."""+ from app.models import SbomArtifact+ sboms = SbomArtifact.query.filter_by(application_id=application_id).order_by(+ SbomArtifact.created_at.desc()).limit(50).all()+ return jsonify({'sboms': [s.to_dict() for s in sboms]}), 200+++@security_bp.route('/sboms/<int:sbom_id>', methods=['GET'])+@jwt_required()+@admin_required+def get_sbom(sbom_id):+ """Download an SPDX SBOM JSON."""+ from app.models import SbomArtifact+ sbom = SbomArtifact.query.get(sbom_id)+ if not sbom:+ return jsonify({'error': 'SBOM not found'}), 404+ return jsonify(sbom.to_dict(include_sbom=True)), 200diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.pyindex 9d0e6f18..d8fde0e3 100644--- a/backend/app/models/__init__.py+++ b/backend/app/models/__init__.py@@ -37,6 +37,7 @@ from app.models.marketplace import Extension, ExtensionInstallfrom app.models.pending_agent import PendingAgentfrom app.models.plugin import InstalledPluginfrom app.models.ai import AiConversation, AiMessage, AiPendingAction+from app.models.image_scan import ImageVulnerabilityScan, SbomArtifact__all__ = ['User', 'Application', 'Domain', 'EnvironmentVariable', 'EnvironmentVariableHistory',@@ -60,4 +61,5 @@ __all__ = ['PendingAgent','InstalledPlugin','AiConversation', 'AiMessage', 'AiPendingAction',+ 'ImageVulnerabilityScan', 'SbomArtifact',]diff --git a/backend/app/models/application.py b/backend/app/models/application.pyindex dd39b3ac..6e13268e 100644--- a/backend/app/models/application.py+++ b/backend/app/models/application.py@@ -94,6 +94,18 @@ class Application(db.Model):'server_name': self.server.name if self.server else 'Local server','domains': [d.to_dict() for d in self.domains]}++ # Lightweight image-scan badge (latest scan only)+ latest_scan = self.image_scans.first()+ if latest_scan:+ result['image_scan'] = {+ 'status': latest_scan.status,+ 'highest_severity': latest_scan.highest_severity,+ 'severity_counts': latest_scan.get_counts(),+ 'scanned_at': latest_scan.completed_at.isoformat() if latest_scan.completed_at else None,+ }+ else:+ result['image_scan'] = Noneif include_linked and self.linked_app:result['linked_app'] = {'id': self.linked_app.id,diff --git a/backend/app/models/image_scan.py b/backend/app/models/image_scan.pynew file mode 100644index 00000000..ec02f482--- /dev/null+++ b/backend/app/models/image_scan.py@@ -0,0 +1,96 @@+from datetime import datetime+from app import db+import json+++class ImageVulnerabilityScan(db.Model):+ """CVE scan result for a Docker image used by an application."""+ __tablename__ = 'image_vulnerability_scans'++ id = db.Column(db.Integer, primary_key=True)+ application_id = db.Column(db.Integer, db.ForeignKey('applications.id'), nullable=False, index=True)+ image_ref = db.Column(db.String(500), nullable=False)+ scanner = db.Column(db.String(50), default='grype')+ scanner_version = db.Column(db.String(50))+ status = db.Column(db.String(20), default='pending') # pending, running, completed, failed+ severity_counts = db.Column(db.Text) # JSON: {'critical': 0, 'high': 1, ...}+ findings = db.Column(db.Text) # JSON list of grype matches+ error_message = db.Column(db.Text)+ started_at = db.Column(db.DateTime, default=datetime.utcnow)+ completed_at = db.Column(db.DateTime, nullable=True)++ application = db.relationship('Application', backref=db.backref('image_scans', lazy='dynamic', order_by='ImageVulnerabilityScan.started_at.desc()'))++ def set_counts(self, counts):+ self.severity_counts = json.dumps(counts)++ def get_counts(self):+ if not self.severity_counts:+ return {}+ try:+ return json.loads(self.severity_counts)+ except Exception:+ return {}++ def set_findings(self, findings):+ self.findings = json.dumps(findings) if findings else None++ def get_findings(self):+ if not self.findings:+ return []+ try:+ return json.loads(self.findings)+ except Exception:+ return []++ @property+ def highest_severity(self):+ counts = self.get_counts()+ for sev in ('critical', 'high', 'medium', 'low', 'negligible', 'unknown'):+ if counts.get(sev, 0) > 0:+ return sev+ return 'none'++ def to_dict(self, include_findings=False):+ return {+ 'id': self.id,+ 'application_id': self.application_id,+ 'image_ref': self.image_ref,+ 'scanner': self.scanner,+ 'scanner_version': self.scanner_version,+ 'status': self.status,+ 'severity_counts': self.get_counts(),+ 'highest_severity': self.highest_severity,+ 'error_message': self.error_message,+ 'started_at': self.started_at.isoformat() if self.started_at else None,+ 'completed_at': self.completed_at.isoformat() if self.completed_at else None,+ 'findings': self.get_findings() if include_findings else None,+ }+++class SbomArtifact(db.Model):+ """Generated SPDX SBOM for a Docker image."""+ __tablename__ = 'sbom_artifacts'++ id = db.Column(db.Integer, primary_key=True)+ application_id = db.Column(db.Integer, db.ForeignKey('applications.id'), nullable=False, index=True)+ image_ref = db.Column(db.String(500), nullable=False)+ generator = db.Column(db.String(50), default='syft')+ generator_version = db.Column(db.String(50))+ format = db.Column(db.String(20), default='spdx-json')+ sbom_json = db.Column(db.Text) # SPDX 2.3 JSON+ created_at = db.Column(db.DateTime, default=datetime.utcnow)++ application = db.relationship('Application', backref=db.backref('sboms', lazy='dynamic', order_by='SbomArtifact.created_at.desc()'))++ def to_dict(self, include_sbom=False):+ return {+ 'id': self.id,+ 'application_id': self.application_id,+ 'image_ref': self.image_ref,+ 'generator': self.generator,+ 'generator_version': self.generator_version,+ 'format': self.format,+ 'created_at': self.created_at.isoformat() if self.created_at else None,+ 'sbom': json.loads(self.sbom_json) if include_sbom and self.sbom_json else None,+ }diff --git a/backend/app/services/image_scanner_service.py b/backend/app/services/image_scanner_service.pynew file mode 100644index 00000000..7a15dfa5--- /dev/null+++ b/backend/app/services/image_scanner_service.py@@ -0,0 +1,273 @@+"""Image vulnerability scanning and SBOM generation using Anchore grype/syft."""+import json+import logging+import os+import platform+import subprocess+import threading+from datetime import datetime+from typing import Dict, List, Optional++from app import db+from app.models import Application, ImageVulnerabilityScan, SbomArtifact++logger = logging.getLogger(__name__)++SCANNERS_DIR = '/var/lib/serverkit/scanners'+GRYPE_BIN = os.path.join(SCANNERS_DIR, 'grype')+SYFT_BIN = os.path.join(SCANNERS_DIR, 'syft')+++class ImageScannerService:+ """Manage scanner binaries and run per-image CVE scans + SBOM generation."""++ _install_lock = threading.Lock()++ @classmethod+ def _arch(cls) -> str:+ machine = platform.machine().lower()+ if machine in ('x86_64', 'amd64'):+ return 'amd64'+ if machine in ('aarch64', 'arm64'):+ return 'arm64'+ return machine++ @classmethod+ def _ensure_scanners_dir(cls) -> None:+ os.makedirs(SCANNERS_DIR, exist_ok=True)++ @classmethod+ def grype_installed(cls) -> bool:+ return os.path.isfile(GRYPE_BIN) and os.access(GRYPE_BIN, os.X_OK)++ @classmethod+ def syft_installed(cls) -> bool:+ return os.path.isfile(SYFT_BIN) and os.access(SYFT_BIN, os.X_OK)++ @classmethod+ def install_grype(cls) -> Dict:+ """Download grype binary into /var/lib/serverkit/scanners."""+ with cls._install_lock:+ if cls.grype_installed():+ return {'success': True, 'message': 'grype already installed'}+ cls._ensure_scanners_dir()+ arch = cls._arch()+ version = os.environ.get('GRYPE_VERSION', 'v0.87.0')+ url = f'https://github.com/anchore/grype/releases/download/{version}/grype_{version.lstrip("v")}_linux_{arch}.tar.gz'+ tmp_tar = '/tmp/serverkit-grype.tar.gz'+ try:+ subprocess.run(['curl', '-fsSL', url, '-o', tmp_tar], check=True, capture_output=True)+ subprocess.run(['tar', '-xzf', tmp_tar, '-C', SCANNERS_DIR, 'grype'], check=True, capture_output=True)+ os.chmod(GRYPE_BIN, 0o755)+ version_out = subprocess.run([GRYPE_BIN, 'version'], capture_output=True, text=True)+ return {+ 'success': True,+ 'message': 'grype installed',+ 'version': version_out.stdout.strip().splitlines()[0] if version_out.returncode == 0 else version+ }+ except subprocess.CalledProcessError as e:+ return {'success': False, 'error': f'Failed to install grype: {e.stderr.decode(errors="ignore")[:200]}'}+ finally:+ if os.path.exists(tmp_tar):+ os.remove(tmp_tar)++ @classmethod+ def install_syft(cls) -> Dict:+ """Download syft binary into /var/lib/serverkit/scanners."""+ with cls._install_lock:+ if cls.syft_installed():+ return {'success': True, 'message': 'syft already installed'}+ cls._ensure_scanners_dir()+ arch = cls._arch()+ version = os.environ.get('SYFT_VERSION', 'v1.22.0')+ url = f'https://github.com/anchore/syft/releases/download/{version}/syft_{version.lstrip("v")}_linux_{arch}.tar.gz'+ tmp_tar = '/tmp/serverkit-syft.tar.gz'+ try:+ subprocess.run(['curl', '-fsSL', url, '-o', tmp_tar], check=True, capture_output=True)+ subprocess.run(['tar', '-xzf', tmp_tar, '-C', SCANNERS_DIR, 'syft'], check=True, capture_output=True)+ os.chmod(SYFT_BIN, 0o755)+ version_out = subprocess.run([SYFT_BIN, 'version'], capture_output=True, text=True)+ return {+ 'success': True,+ 'message': 'syft installed',+ 'version': version_out.stdout.strip().splitlines()[0] if version_out.returncode == 0 else version+ }+ except subprocess.CalledProcessError as e:+ return {'success': False, 'error': f'Failed to install syft: {e.stderr.decode(errors="ignore")[:200]}'}+ finally:+ if os.path.exists(tmp_tar):+ os.remove(tmp_tar)++ @classmethod+ def _run_grype(cls, image_ref: str) -> Dict:+ if not cls.grype_installed():+ install = cls.install_grype()+ if not install['success']:+ return install+ try:+ result = subprocess.run(+ [GRYPE_BIN, image_ref, '-o', 'json', '--quiet'],+ capture_output=True,+ text=True,+ timeout=600,+ env={**os.environ, 'GRYPE_DB_CACHE_DIR': os.path.join(SCANNERS_DIR, 'grype-db')}+ )+ if result.returncode not in (0, 1):+ return {'success': False, 'error': result.stderr[:500] or f'grype exited {result.returncode}'}+ data = json.loads(result.stdout)+ return {'success': True, 'data': data}+ except subprocess.TimeoutExpired:+ return {'success': False, 'error': 'grype scan timed out after 10 minutes'}+ except json.JSONDecodeError as e:+ return {'success': False, 'error': f'Failed to parse grype output: {e}'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def _run_syft(cls, image_ref: str) -> Dict:+ if not cls.syft_installed():+ install = cls.install_syft()+ if not install['success']:+ return install+ try:+ result = subprocess.run(+ [SYFT_BIN, image_ref, '-o', 'spdx-json'],+ capture_output=True,+ text=True,+ timeout=300+ )+ if result.returncode != 0:+ return {'success': False, 'error': result.stderr[:500] or f'syft exited {result.returncode}'}+ data = json.loads(result.stdout)+ return {'success': True, 'data': data}+ except subprocess.TimeoutExpired:+ return {'success': False, 'error': 'syft scan timed out after 5 minutes'}+ except json.JSONDecodeError as e:+ return {'success': False, 'error': f'Failed to parse syft output: {e}'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def _parse_grype_counts(cls, data: Dict) -> Dict:+ counts = {'critical': 0, 'high': 0, 'medium': 0, 'low': 0, 'negligible': 0, 'unknown': 0}+ for match in data.get('matches', []):+ sev = match.get('vulnerability', {}).get('severity', 'unknown')+ sev = sev.lower()+ if sev in counts:+ counts[sev] += 1+ else:+ counts['unknown'] += 1+ return counts++ @classmethod+ def _normalize_findings(cls, data: Dict) -> List[Dict]:+ findings = []+ for match in data.get('matches', []):+ vuln = match.get('vulnerability', {})+ artifact = match.get('artifact', {})+ findings.append({+ 'id': vuln.get('id'),+ 'severity': vuln.get('severity', 'unknown'),+ 'cvss': vuln.get('cvss', []),+ 'fix_versions': vuln.get('fix', {}).get('versions', []),+ 'artifact_name': artifact.get('name'),+ 'artifact_version': artifact.get('version'),+ 'artifact_type': artifact.get('type'),+ 'description': vuln.get('description'),+ 'urls': vuln.get('urls', []),+ })+ return findings++ @classmethod+ def scan_application(cls, application_id: int) -> Dict:+ """Run a CVE scan for the Docker image of an application."""+ app = Application.query.get(application_id)+ if not app:+ return {'success': False, 'error': 'Application not found'}+ image_ref = app.docker_image or app.container_id+ if not image_ref:+ return {'success': False, 'error': 'Application has no Docker image or container'}++ scan = ImageVulnerabilityScan(+ application_id=application_id,+ image_ref=image_ref,+ status='running'+ )+ db.session.add(scan)+ db.session.commit()++ def _run():+ try:+ result = cls._run_grype(image_ref)+ scan.completed_at = datetime.utcnow()+ if not result['success']:+ scan.status = 'failed'+ scan.error_message = result.get('error')+ else:+ data = result['data']+ scan.status = 'completed'+ scan.scanner_version = data.get('descriptor', {}).get('version')+ scan.set_counts(cls._parse_grype_counts(data))+ scan.set_findings(cls._normalize_findings(data))+ db.session.commit()+ except Exception as e:+ logger.exception('Image scan failed')+ scan.status = 'failed'+ scan.error_message = str(e)+ scan.completed_at = datetime.utcnow()+ db.session.commit()++ thread = threading.Thread(target=_run, daemon=True)+ thread.start()+ return {'success': True, 'scan_id': scan.id, 'status': 'running'}++ @classmethod+ def generate_sbom(cls, application_id: int) -> Dict:+ """Generate and persist an SPDX SBOM for an application image."""+ app = Application.query.get(application_id)+ if not app:+ return {'success': False, 'error': 'Application not found'}+ image_ref = app.docker_image or app.container_id+ if not image_ref:+ return {'success': False, 'error': 'Application has no Docker image or container'}++ result = cls._run_syft(image_ref)+ if not result['success']:+ return result++ data = result['data']+ sbom = SbomArtifact(+ application_id=application_id,+ image_ref=image_ref,+ generator_version=data.get('spdxVersion'),+ sbom_json=json.dumps(data)+ )+ db.session.add(sbom)+ db.session.commit()+ return {'success': True, 'sbom_id': sbom.id, 'sbom': sbom.to_dict(include_sbom=False)}++ @classmethod+ def latest_scan(cls, application_id: int) -> Optional[ImageVulnerabilityScan]:+ return ImageVulnerabilityScan.query.filter_by(application_id=application_id).order_by(+ ImageVulnerabilityScan.started_at.desc()).first()++ @classmethod+ def scan_history(cls, application_id: int, limit: int = 20) -> List[Dict]:+ scans = ImageVulnerabilityScan.query.filter_by(application_id=application_id).order_by(+ ImageVulnerabilityScan.started_at.desc()).limit(limit).all()+ return [s.to_dict() for s in scans]++ @classmethod+ def check_deploy_gate(cls, application_id: int, allowed_severities: Optional[List[str]] = None) -> Dict:+ """Return whether the latest scan allows deployment."""+ allowed_severities = allowed_severities or ['low', 'negligible', 'unknown']+ scan = cls.latest_scan(application_id)+ if not scan:+ return {'allowed': True, 'reason': 'No scan available'}+ if scan.status != 'completed':+ return {'allowed': False, 'reason': f'Scan status is {scan.status}'}+ counts = scan.get_counts()+ blocking = {sev: count for sev, count in counts.items() if sev not in allowed_severities and count > 0}+ if blocking:+ return {'allowed': False, 'reason': 'Image exceeds vulnerability threshold', 'blocking': blocking}+ return {'allowed': True, 'reason': 'Image passes vulnerability threshold'}diff --git a/backend/migrations/versions/018_image_scan_sbom.py b/backend/migrations/versions/018_image_scan_sbom.pynew file mode 100644index 00000000..f2e8d811--- /dev/null+++ b/backend/migrations/versions/018_image_scan_sbom.py@@ -0,0 +1,82 @@+"""Image vulnerability scans and SBOM artifacts.++Adds:+- image_vulnerability_scans table+- sbom_artifacts table++Revision ID: 018_image_scan_sbom+Revises: 017_manual_apps+Create Date: 2026-06-19+"""+from alembic import op+import sqlalchemy as sa++revision = '018_image_scan_sbom'+down_revision = '017_manual_apps'+branch_labels = None+depends_on = None+++def upgrade():+ conn = op.get_bind()+ inspector = sa.inspect(conn)+ tables = inspector.get_table_names()++ if 'image_vulnerability_scans' not in tables:+ op.create_table(+ 'image_vulnerability_scans',+ sa.Column('id', sa.Integer(), nullable=False),+ sa.Column('application_id', sa.Integer(), nullable=False),+ sa.Column('image_ref', sa.String(length=500), nullable=False),+ sa.Column('scanner', sa.String(length=50), nullable=True),+ sa.Column('scanner_version', sa.String(length=50), nullable=True),+ sa.Column('status', sa.String(length=20), nullable=True),+ sa.Column('severity_counts', sa.Text(), nullable=True),+ sa.Column('findings', sa.Text(), nullable=True),+ sa.Column('error_message', sa.Text(), nullable=True),+ sa.Column('started_at', sa.DateTime(), nullable=True),+ sa.Column('completed_at', sa.DateTime(), nullable=True),+ sa.ForeignKeyConstraint(['application_id'], ['applications.id']),+ sa.PrimaryKeyConstraint('id')+ )+ op.create_index(+ op.f('ix_image_vulnerability_scans_application_id'),+ 'image_vulnerability_scans',+ ['application_id'],+ unique=False+ )++ if 'sbom_artifacts' not in tables:+ op.create_table(+ 'sbom_artifacts',+ sa.Column('id', sa.Integer(), nullable=False),+ sa.Column('application_id', sa.Integer(), nullable=False),+ sa.Column('image_ref', sa.String(length=500), nullable=False),+ sa.Column('generator', sa.String(length=50), nullable=True),+ sa.Column('generator_version', sa.String(length=50), nullable=True),+ sa.Column('format', sa.String(length=20), nullable=True),+ sa.Column('sbom_json', sa.Text(), nullable=True),+ sa.Column('created_at', sa.DateTime(), nullable=True),+ sa.ForeignKeyConstraint(['application_id'], ['applications.id']),+ sa.PrimaryKeyConstraint('id')+ )+ op.create_index(+ op.f('ix_sbom_artifacts_application_id'),+ 'sbom_artifacts',+ ['application_id'],+ unique=False+ )+++def downgrade():+ conn = op.get_bind()+ inspector = sa.inspect(conn)+ tables = inspector.get_table_names()++ if 'sbom_artifacts' in tables:+ op.drop_index(op.f('ix_sbom_artifacts_application_id'), table_name='sbom_artifacts')+ op.drop_table('sbom_artifacts')++ if 'image_vulnerability_scans' in tables:+ op.drop_index(op.f('ix_image_vulnerability_scans_application_id'), table_name='image_vulnerability_scans')+ op.drop_table('image_vulnerability_scans')