Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat(security): job-backed malware scans with a web-shell YARA pass

Juan Denisc192e4f383ae
diff --git a/backend/app/api/security.py b/backend/app/api/security.py
index 612f6aa9..18116b5a 100644
--- a/backend/app/api/security.py
+++ b/backend/app/api/security.py
@@ -2,9 +2,16 @@ from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required
from app.middleware.rbac import admin_required
from app.services.security_service import SecurityService
+from app.services.malware_scan_service import MalwareScanService
+from app.services.yara_scan_service import YaraScanService
security_bp = Blueprint('security', __name__)
+# Register the security.malware_scan job handler at boot (this module is
+# imported by create_app); registration is idempotent and also re-asserted on
+# every enqueue.
+MalwareScanService.register_jobs()
+
# ==========================================
# STATUS & CONFIG
@@ -111,6 +118,34 @@ def scan_directory():
return jsonify(result), 200 if result['success'] else 400
+@security_bp.route('/scan/app/<int:app_id>', methods=['POST'])
+@jwt_required()
+@admin_required
+def scan_app(app_id):
+ """Enqueue a job-backed malware scan (YARA + ClamAV) of an app's docroot."""
+ try:
+ job = MalwareScanService.enqueue_scan(app_id=app_id)
+ except ValueError as e:
+ return jsonify({'error': str(e)}), 404 if 'not found' in str(e) else 400
+ return jsonify({'job_id': job.id, 'kind': job.kind,
+ 'path': (job.get_payload() or {}).get('path')}), 202
+
+
+@security_bp.route('/scan/job', methods=['POST'])
+@jwt_required()
+@admin_required
+def scan_path_job():
+ """Enqueue a job-backed malware scan of an arbitrary path."""
+ data = request.get_json()
+ if not data or not data.get('path'):
+ return jsonify({'error': 'Path required'}), 400
+ try:
+ job = MalwareScanService.enqueue_scan(path=data['path'])
+ except ValueError as e:
+ return jsonify({'error': str(e)}), 400
+ return jsonify({'job_id': job.id, 'kind': job.kind, 'path': data['path']}), 202
+
+
@security_bp.route('/scan/status', methods=['GET'])
@jwt_required()
def get_scan_status():
@@ -171,6 +206,51 @@ def delete_quarantined_file(filename):
return jsonify(result), 200 if result['success'] else 400
+@security_bp.route('/quarantine/<filename>/restore', methods=['POST'])
+@jwt_required()
+@admin_required
+def restore_quarantined_file(filename):
+ """Restore a quarantined file to its recorded original location."""
+ result = SecurityService.restore_quarantined_file(filename)
+ return jsonify(result), 200 if result['success'] else 400
+
+
+# ==========================================
+# YARA RULES (web-shell pass)
+# ==========================================
+@security_bp.route('/yara/rules', methods=['GET'])
+@jwt_required()
+@admin_required
+def list_yara_rules():
+ """List builtin (curated) and custom YARA rule files."""
+ return jsonify(YaraScanService.list_rules()), 200
+
+
+@security_bp.route('/yara/rules', methods=['POST'])
+@jwt_required()
+@admin_required
+def upload_yara_rule():
+ """Upload a custom .yar rule file (size-capped; requires real yara to run)."""
+ data = request.get_json()
+ if not data or not data.get('filename'):
+ return jsonify({'error': 'filename required'}), 400
+ result = YaraScanService.save_custom_rule(data['filename'], data.get('content', ''))
+ if not result['success']:
+ return jsonify({'error': result['error']}), 400
+ return jsonify(result), 200
+
+
+@security_bp.route('/yara/rules/<filename>', methods=['DELETE'])
+@jwt_required()
+@admin_required
+def delete_yara_rule(filename):
+ """Delete a custom .yar rule file."""
+ result = YaraScanService.delete_custom_rule(filename)
+ if not result['success']:
+ return jsonify({'error': result['error']}), 400
+ return jsonify(result), 200
+
+
# ==========================================
# FILE INTEGRITY
# ==========================================
@@ -577,3 +657,89 @@ def get_sbom(sbom_id):
if not sbom:
return jsonify({'error': 'SBOM not found'}), 404
return jsonify(sbom.to_dict(include_sbom=True)), 200
+
+
+# ==========================================
+# FILE INTEGRITY MONITORING (SCOPED FIM)
+# ==========================================
+# Baseline-and-diff over ServerKit-managed paths (nginx / systemd /
+# opted-in app docroots). The legacy /integrity/* endpoints above are kept
+# as-is for compatibility; this is the scoped surface the UI uses.
+
+@security_bp.route('/fim', methods=['GET'])
+@jwt_required()
+def get_fim_status():
+ """Get FIM scopes, baselines and last check results."""
+ from app.services.file_integrity_service import FileIntegrityService
+ return jsonify(FileIntegrityService.get_status()), 200
+
+
+@security_bp.route('/fim/<scope>/baseline', methods=['POST'])
+@jwt_required()
+@admin_required
+def fim_baseline(scope):
+ """Create (or recreate) the baseline for a scope."""
+ from app.services.file_integrity_service import (
+ FileIntegrityService, FileIntegrityScopeError,
+ )
+ data = request.get_json(silent=True) or {}
+ options = data.get('options') if isinstance(data.get('options'), dict) else None
+ try:
+ result = FileIntegrityService.baseline(scope, options=options)
+ except FileIntegrityScopeError as exc:
+ return jsonify({'error': str(exc)}), 400
+ except Exception as exc:
+ return jsonify({'error': str(exc)}), 500
+ return jsonify(result), 200
+
+
+@security_bp.route('/fim/<scope>/check', methods=['POST'])
+@jwt_required()
+@admin_required
+def fim_check(scope):
+ """Diff the scope against its baseline."""
+ from app.services.file_integrity_service import (
+ FileIntegrityService, FileIntegrityScopeError,
+ )
+ try:
+ result = FileIntegrityService.check(scope)
+ except FileIntegrityScopeError as exc:
+ return jsonify({'error': str(exc)}), 400
+ except Exception as exc:
+ return jsonify({'error': str(exc)}), 500
+ return jsonify(result), 200
+
+
+@security_bp.route('/fim/<scope>/accept', methods=['POST'])
+@jwt_required()
+@admin_required
+def fim_accept(scope):
+ """Accept current state (re-baseline the scope)."""
+ from app.services.file_integrity_service import (
+ FileIntegrityService, FileIntegrityScopeError,
+ )
+ try:
+ result = FileIntegrityService.accept(scope)
+ except FileIntegrityScopeError as exc:
+ return jsonify({'error': str(exc)}), 400
+ except Exception as exc:
+ return jsonify({'error': str(exc)}), 500
+ return jsonify(result), 200
+
+
+@security_bp.route('/fim/apps', methods=['PUT'])
+@jwt_required()
+@admin_required
+def fim_set_app_optins():
+ """Set the per-app FIM opt-in list: {app_ids: [1, 2, ...]}."""
+ from app.services.file_integrity_service import (
+ FileIntegrityService, FileIntegrityScopeError,
+ )
+ data = request.get_json(silent=True)
+ if not data or 'app_ids' not in data:
+ return jsonify({'error': 'app_ids required'}), 400
+ try:
+ ids = FileIntegrityService.set_app_optins(data['app_ids'])
+ except FileIntegrityScopeError as exc:
+ return jsonify({'error': str(exc)}), 400
+ return jsonify({'app_optins': ids}), 200
diff --git a/backend/app/services/malware_scan_service.py b/backend/app/services/malware_scan_service.py
new file mode 100644
index 00000000..d6df8ceb
--- /dev/null
+++ b/backend/app/services/malware_scan_service.py
@@ -0,0 +1,201 @@
+"""
+Malware Scan Job Service
+
+Job-backed on-demand malware scan of a path or an application's docroot.
+Runs the fast curated YARA web-shell pass first (works everywhere via the
+pure-Python fallback), then ClamAV when ``clamscan`` is installed. Findings
+from both engines are merged into one report, tagged ``source: 'yara'`` or
+``source: 'clamav'``, and every finding can be quarantined through the
+existing quarantine mechanics (:meth:`SecurityService.quarantine_file`).
+
+Job kind: ``security.malware_scan`` — payload ``{'path': ...}`` OR
+``{'app_id': ...}`` (docroot resolved from the Application row). Registered
+via :meth:`MalwareScanService.register_jobs` following the
+backup_policy_service pattern; also invoked defensively before every enqueue
+so the handler is present even if boot-time registration was skipped.
+
+Best-effort / Linux-only posture: missing tools degrade gracefully (YARA
+falls back to the builtin matcher, a missing clamscan is reported in the
+result, never an exception).
+"""
+
+import os
+import subprocess
+import logging
+from datetime import datetime
+from typing import Dict, Optional
+
+from app import paths
+from app.utils.system import is_command_available
+from app.services.security_service import SecurityService
+from app.services.yara_scan_service import YaraScanService
+
+logger = logging.getLogger(__name__)
+
+MALWARE_SCAN_JOB_KIND = 'security.malware_scan'
+
+CLAMAV_TIMEOUT = 3600 # seconds — matches the legacy synchronous scan
+
+
+class MalwareScanService:
+ """Enqueue + execute ``security.malware_scan`` jobs."""
+
+ # ------------------------------------------------------------------ #
+ # Enqueue
+ # ------------------------------------------------------------------ #
+ @classmethod
+ def enqueue_scan(cls, path: Optional[str] = None, app_id: Optional[int] = None):
+ """Enqueue a malware scan job for a path or an application docroot.
+ Returns the Job row. Raises ``ValueError`` on bad input."""
+ from app.jobs.service import JobService
+
+ if not path and not app_id:
+ raise ValueError('Either path or app_id is required')
+ if app_id is not None:
+ # Resolve now so a bad app id fails the request, not the job.
+ path = cls.resolve_app_path(app_id)
+
+ cls.register_jobs() # idempotent — survives registry resets
+ return JobService.enqueue(
+ MALWARE_SCAN_JOB_KIND,
+ payload={'path': path, 'app_id': app_id},
+ owner_type='application' if app_id is not None else None,
+ owner_id=app_id,
+ )
+
+ @classmethod
+ def resolve_app_path(cls, app_id: int) -> str:
+ """Resolve an application's docroot on disk from its DB row."""
+ from app.models.application import Application
+
+ app_row = Application.query.get(app_id)
+ if not app_row:
+ raise ValueError(f'Application {app_id} not found')
+
+ candidates = []
+ if app_row.root_path:
+ candidates.append(app_row.root_path)
+ if app_row.name:
+ candidates.append(os.path.join(paths.APPS_DIR, app_row.name))
+
+ for candidate in candidates:
+ if candidate and os.path.isdir(candidate):
+ return candidate
+
+ raise ValueError(
+ f'No docroot found on disk for application {app_row.name or app_id} '
+ f'(checked: {", ".join(candidates) or "none"})'
+ )
+
+ # ------------------------------------------------------------------ #
+ # Job handler
+ # ------------------------------------------------------------------ #
+ @classmethod
+ def run_malware_scan_job(cls, job) -> Dict:
+ payload = job.get_payload() or {}
+ app_id = payload.get('app_id')
+ path = payload.get('path')
+ if app_id is not None and not path:
+ path = cls.resolve_app_path(app_id)
+ if not path:
+ raise ValueError('security.malware_scan payload requires path or app_id')
+ if not os.path.exists(path):
+ raise ValueError(f'Scan path not found: {path}')
+ return cls.execute_scan(path, app_id=app_id, job_id=job.id)
+
+ @classmethod
+ def execute_scan(cls, path: str, app_id: Optional[int] = None,
+ job_id: Optional[str] = None) -> Dict:
+ """Run the YARA pass then ClamAV against ``path``; log + return the
+ merged report. Also mirrors progress into the legacy scan-status
+ surface so the existing Scanner tab polling picks it up."""
+ report = {
+ 'status': 'running',
+ 'directory': path,
+ 'app_id': app_id,
+ 'job_id': job_id,
+ 'started_at': datetime.now().isoformat(),
+ 'findings': [],
+ 'infected_files': [],
+ 'errors': [],
+ 'yara_engine': YaraScanService.engine(),
+ 'clamav_available': is_command_available('clamscan'),
+ }
+ # Surface job-backed progress through the existing /scan/status poll.
+ SecurityService._current_scan = report
+
+ # 1) YARA pass — much faster than ClamAV, always available (fallback).
+ try:
+ report['findings'].extend(YaraScanService.scan_path(path))
+ except Exception as exc: # noqa: BLE001 — YARA errors must not kill the clam pass
+ logger.warning('YARA pass failed for %s: %s', path, exc)
+ report['errors'].append(f'yara: {exc}')
+
+ # 2) ClamAV pass — best-effort, skipped when clamscan is absent.
+ if report['clamav_available']:
+ report['findings'].extend(cls._clamav_pass(path, report['errors']))
+
+ report['infected_files'] = sorted({f['file'] for f in report['findings']})
+ report['counts'] = {
+ 'yara': sum(1 for f in report['findings'] if f['source'] == 'yara'),
+ 'clamav': sum(1 for f in report['findings'] if f['source'] == 'clamav'),
+ }
+ report['status'] = 'completed'
+ report['completed_at'] = datetime.now().isoformat()
+
+ SecurityService._current_scan = report
+ SecurityService._log_scan(report)
+
+ if report['findings']:
+ SecurityService._send_security_notification(
+ 'malware_detected',
+ f"Malware scan found {len(report['findings'])} finding(s) in "
+ f"{len(report['infected_files'])} file(s) under {path}",
+ severity='critical',
+ details={'count': len(report['findings']),
+ 'files': report['infected_files'][:50]},
+ )
+
+ return report
+
+ @classmethod
+ def _clamav_pass(cls, path: str, errors: list) -> list:
+ findings = []
+ try:
+ result = subprocess.run(
+ ['clamscan', '-r', '--infected', '--no-summary', path],
+ capture_output=True, text=True, timeout=CLAMAV_TIMEOUT,
+ )
+ # 0 = clean, 1 = infections found, 2 = error
+ if result.returncode == 2:
+ errors.append(f"clamav: {(result.stderr or result.stdout or 'scan error').strip()[:300]}")
+ for line in (result.stdout or '').strip().split('\n'):
+ if ': ' in line and line.endswith('FOUND'):
+ file_path, rest = line.rsplit(': ', 1)
+ signature = rest[:-len('FOUND')].strip()
+ findings.append({
+ 'rule': signature or 'clamav.match',
+ 'severity': 'critical',
+ 'file': file_path,
+ 'matched': '',
+ 'description': 'ClamAV signature match',
+ 'source': 'clamav',
+ })
+ except FileNotFoundError:
+ errors.append('clamav: clamscan not found')
+ except subprocess.TimeoutExpired:
+ errors.append('clamav: scan timed out')
+ except Exception as exc: # noqa: BLE001
+ errors.append(f'clamav: {exc}')
+ return findings
+
+ # ------------------------------------------------------------------ #
+ # Registration
+ # ------------------------------------------------------------------ #
+ @classmethod
+ def register_jobs(cls):
+ """Register the malware-scan handler with the job registry. Invoked at
+ import of the security API blueprint (app boot) and again before each
+ enqueue (idempotent)."""
+ from app.jobs import registry
+ registry.register(MALWARE_SCAN_JOB_KIND, cls.run_malware_scan_job, replace=True)
diff --git a/backend/app/services/security_service.py b/backend/app/services/security_service.py
index 42b36b0e..ac33b98a 100644
--- a/backend/app/services/security_service.py
+++ b/backend/app/services/security_service.py
@@ -385,13 +385,18 @@ class SecurityService:
@classmethod
def quarantine_file(cls, file_path: str) -> Dict:
- """Move infected file to quarantine."""
+ """Move infected file to quarantine (with a sidecar recording the
+ original location so it can be restored)."""
config = cls.get_config()
quarantine_path = config.get('clamav', {}).get('quarantine_path', paths.SERVERKIT_QUARANTINE_DIR)
if not os.path.exists(file_path):
return {'success': False, 'error': 'File not found'}
+ # Never quarantine something already inside the quarantine directory.
+ if os.path.abspath(file_path).startswith(os.path.abspath(quarantine_path) + os.sep):
+ return {'success': False, 'error': 'File is already in quarantine'}
+
try:
# Create quarantine directory
os.makedirs(quarantine_path, exist_ok=True)
@@ -405,6 +410,16 @@ class SecurityService:
# Move file
os.rename(file_path, quarantine_full_path)
+ # Sidecar with the original location (enables restore)
+ try:
+ with open(quarantine_full_path + '.meta.json', 'w') as f:
+ json.dump({
+ 'original_path': os.path.abspath(file_path),
+ 'quarantined_at': datetime.now().isoformat(),
+ }, f)
+ except Exception:
+ pass # restore becomes unavailable, quarantine itself succeeded
+
# Log the quarantine action
cls._log_alert('quarantine', f'File quarantined: {file_path}', {
'original_path': file_path,
@@ -433,14 +448,21 @@ class SecurityService:
try:
files = []
for filename in os.listdir(quarantine_path):
+ if filename.endswith('.meta.json'):
+ continue # restore sidecars, not quarantined payloads
full_path = os.path.join(quarantine_path, filename)
stat = os.stat(full_path)
- files.append({
+ entry = {
'name': filename,
'path': full_path,
'size': stat.st_size,
- 'quarantined_at': datetime.fromtimestamp(stat.st_mtime).isoformat()
- })
+ 'quarantined_at': datetime.fromtimestamp(stat.st_mtime).isoformat(),
+ 'original_path': None,
+ }
+ meta = cls._read_quarantine_meta(full_path)
+ if meta:
+ entry['original_path'] = meta.get('original_path')
+ files.append(entry)
return {'success': True, 'files': files}
@@ -463,10 +485,66 @@ class SecurityService:
try:
os.remove(file_path)
+ try:
+ os.remove(file_path + '.meta.json')
+ except OSError:
+ pass
return {'success': True, 'message': 'File deleted'}
except Exception as e:
return {'success': False, 'error': str(e)}
+ @classmethod
+ def _read_quarantine_meta(cls, quarantine_full_path: str) -> Optional[Dict]:
+ """Read the restore sidecar for a quarantined file, if present."""
+ try:
+ with open(quarantine_full_path + '.meta.json', 'r') as f:
+ return json.load(f)
+ except Exception:
+ return None
+
+ @classmethod
+ def restore_quarantined_file(cls, filename: str) -> Dict:
+ """Move a quarantined file back to its recorded original location."""
+ config = cls.get_config()
+ quarantine_path = config.get('clamav', {}).get('quarantine_path', paths.SERVERKIT_QUARANTINE_DIR)
+ file_path = os.path.join(quarantine_path, filename)
+
+ # Security check: ensure file is in quarantine directory
+ if not os.path.abspath(file_path).startswith(os.path.abspath(quarantine_path)):
+ return {'success': False, 'error': 'Invalid file path'}
+
+ if not os.path.exists(file_path):
+ return {'success': False, 'error': 'File not found'}
+
+ meta = cls._read_quarantine_meta(file_path)
+ original_path = (meta or {}).get('original_path')
+ if not original_path:
+ return {'success': False,
+ 'error': 'Original location unknown — this file was quarantined '
+ 'before restore metadata existed'}
+
+ if os.path.exists(original_path):
+ return {'success': False,
+ 'error': f'A file already exists at {original_path}; '
+ 'remove it first to restore'}
+
+ try:
+ os.makedirs(os.path.dirname(original_path), exist_ok=True)
+ os.rename(file_path, original_path)
+ try:
+ os.remove(file_path + '.meta.json')
+ except OSError:
+ pass
+
+ cls._log_alert('quarantine_restore', f'File restored from quarantine: {original_path}', {
+ 'quarantine_name': filename,
+ 'restored_to': original_path,
+ })
+ return {'success': True, 'message': 'File restored',
+ 'restored_to': original_path}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
# ==========================================
# FILE INTEGRITY MONITORING
# ==========================================
diff --git a/backend/app/services/yara_rules/webshells.yar b/backend/app/services/yara_rules/webshells.yar
new file mode 100644
index 00000000..357826e9
--- /dev/null
+++ b/backend/app/services/yara_rules/webshells.yar
@@ -0,0 +1,207 @@
+/*
+ ServerKit curated web-shell / injected-code indicators.
+
+ These rules intentionally use regex atoms (not long literal strings) so
+ this rules file itself is unlikely to trip other content scanners. The
+ rule names MUST stay in sync with the builtin rule table in
+ app/services/yara_scan_service.py — severity/description meta is resolved
+ from that table when parsing CLI output.
+
+ Note: php_in_image and htaccess_auto_prepend are contextual (they depend
+ on the *filename*), which plain YARA cannot express; their matches are
+ post-filtered by file extension/name in YaraScanService for both the CLI
+ and the fallback engine.
+*/
+
+rule php_eval_base64
+{
+ meta:
+ name = "php_eval_base64"
+ severity = "critical"
+ description = "eval() of base64-decoded payload (classic obfuscated backdoor loader)"
+ strings:
+ $a = /eval\s*\(\s*@?\s*base64_[d]ecode\s*\(/ nocase
+ condition:
+ $a
+}
+
+rule php_gzinflate_base64
+{
+ meta:
+ name = "php_gzinflate_base64"
+ severity = "critical"
+ description = "gzinflate(base64_decode(...)) double-obfuscated payload"
+ strings:
+ $a = /gzinflate\s*\(\s*@?\s*base64_[d]ecode\s*\(/ nocase
+ condition:
+ $a
+}
+
+rule php_gzuncompress_base64
+{
+ meta:
+ name = "php_gzuncompress_base64"
+ severity = "critical"
+ description = "gzuncompress/str_rot13 of base64-decoded payload"
+ strings:
+ $a = /(gzuncompress|str_rot13)\s*\(\s*@?\s*base64_[d]ecode\s*\(/ nocase
+ condition:
+ $a
+}
+
+rule preg_replace_e_eval
+{
+ meta:
+ name = "preg_replace_e_eval"
+ severity = "critical"
+ description = "preg_replace() with the /e modifier (evaluates the replacement as PHP)"
+ strings:
+ $a = /preg_replace\s*\(\s*["'][^"']{0,60}\/[imsxu]{0,4}e[imsxu]{0,4}["']\s*,/ nocase
+ condition:
+ $a
+}
+
+rule assert_request_input
+{
+ meta:
+ name = "assert_request_input"
+ severity = "critical"
+ description = "assert() fed directly from request input (code execution primitive)"
+ strings:
+ $a = /assert\s*\(\s*@?\s*\$_(REQUEST|GET|POST|COOKIE)\b/ nocase
+ condition:
+ $a
+}
+
+rule system_request_input
+{
+ meta:
+ name = "system_request_input"
+ severity = "critical"
+ description = "system() executing raw request input"
+ strings:
+ $a = /system\s*\(\s*@?\s*\$_(REQUEST|GET|POST|COOKIE)\b/ nocase
+ condition:
+ $a
+}
+
+rule passthru_request_input
+{
+ meta:
+ name = "passthru_request_input"
+ severity = "critical"
+ description = "passthru() executing raw request input"
+ strings:
+ $a = /passthru\s*\(\s*@?\s*\$_(REQUEST|GET|POST|COOKIE)\b/ nocase
+ condition:
+ $a
+}
+
+rule shell_exec_request_input
+{
+ meta:
+ name = "shell_exec_request_input"
+ severity = "critical"
+ description = "shell_exec() executing raw request input"
+ strings:
+ $a = /shell_exec\s*\(\s*@?\s*\$_(REQUEST|GET|POST|COOKIE)\b/ nocase
+ condition:
+ $a
+}
+
+rule eval_request_input
+{
+ meta:
+ name = "eval_request_input"
+ severity = "critical"
+ description = "eval() fed directly from request input"
+ strings:
+ $a = /eval\s*\(\s*@?\s*\$_(REQUEST|GET|POST|COOKIE)\b/ nocase
+ condition:
+ $a
+}
+
+rule upload_chmod_777_combo
+{
+ meta:
+ name = "upload_chmod_777_combo"
+ severity = "high"
+ description = "move_uploaded_file combined with chmod 777 in the same file (dropper pattern)"
+ strings:
+ $a = /move_uploaded_file\s*\(/ nocase
+ $b = /chmod\s*\([^)]{0,120}0?777/ nocase
+ condition:
+ $a and $b
+}
+
+rule c99_shell_marker
+{
+ meta:
+ name = "c99_shell_marker"
+ severity = "critical"
+ description = "c99 web shell family marker"
+ strings:
+ $a = /c99(sh(ell)?|_launcher|madshell)/ nocase
+ condition:
+ $a
+}
+
+rule r57_shell_marker
+{
+ meta:
+ name = "r57_shell_marker"
+ severity = "critical"
+ description = "r57 web shell family marker"
+ strings:
+ $a = /r57(shell|_tricks|\s+shell)/ nocase
+ condition:
+ $a
+}
+
+rule wso_shell_marker
+{
+ meta:
+ name = "wso_shell_marker"
+ severity = "critical"
+ description = "WSO (web shell by orb) family marker"
+ strings:
+ $a = /(wso_version|wsoshell|wso\s*2\.[0-9]|\$wso\b)/ nocase
+ condition:
+ $a
+}
+
+rule filesman_marker
+{
+ meta:
+ name = "filesman_marker"
+ severity = "critical"
+ description = "FilesMan backdoor file-manager marker"
+ strings:
+ $a = /Files[M]an/
+ condition:
+ $a
+}
+
+rule php_in_image
+{
+ meta:
+ name = "php_in_image"
+ severity = "high"
+ description = "PHP open tag inside an image file (.ico/.jpg/.png/...) - mismatched extension dropper"
+ strings:
+ $a = /<\?php/ nocase
+ condition:
+ $a
+}
+
+rule htaccess_auto_prepend
+{
+ meta:
+ name = "htaccess_auto_prepend"
+ severity = "high"
+ description = "auto_prepend_file injection via .htaccess/.user.ini (loads a payload before every request)"
+ strings:
+ $a = /auto_prepend_[f]ile/ nocase
+ condition:
+ $a
+}
diff --git a/backend/app/services/yara_scan_service.py b/backend/app/services/yara_scan_service.py
new file mode 100644
index 00000000..0127e64d
--- /dev/null
+++ b/backend/app/services/yara_scan_service.py
@@ -0,0 +1,413 @@
+"""
+YARA Web-Shell Scan Service
+
+Runs a curated web-shell / injected-code rule set against a path (typically an
+application docroot). Two engines, best-effort and Linux-friendly:
+
+* Real ``yara`` CLI when installed (adds support for arbitrary custom ``.yar``
+ rule files dropped in :attr:`YaraScanService.CUSTOM_RULES_DIR`).
+* A built-in pure-Python fallback matcher covering the curated set, so the
+ feature works everywhere without yara installed. Custom ``.yar`` files are
+ NOT evaluated by the fallback (real YARA is required for those).
+
+The curated rules ship both as Python metadata (below — the source of truth
+for severity/description) and as ``yara_rules/webshells.yar`` for the CLI.
+Indicator strings in this module are assembled from fragments so this file
+does not itself trip content scanners.
+
+Result shape (both engines):
+ [{'rule', 'severity', 'file', 'matched', 'description', 'source': 'yara'}]
+"""
+
+import os
+import re
+import subprocess
+import logging
+from typing import Dict, List, Optional
+
+from app.utils.system import is_command_available
+
+logger = logging.getLogger(__name__)
+
+# Fragment-assembled indicators (keeps literal signatures out of this file).
+_B64 = 'base64_' + 'decode'
+_APF = 'auto_prepend_' + 'file'
+_FMAN = 'Files' + 'Man'
+
+_REQ_SOURCES = r'\$_(REQUEST|GET|POST|COOKIE)\b'
+
+# Extensions treated as scannable script/config content by the fallback engine.
+SCRIPT_EXTENSIONS = {
+ '.php', '.phtml', '.php3', '.php4', '.php5', '.php7', '.phps',
+ '.inc', '.cgi', '.pl', '.py', '.sh', '.js', '.html', '.htm', '.txt',
+ '.ini', '.conf',
+}
+IMAGE_EXTENSIONS = {'.ico', '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg'}
+CONFIG_BASENAMES = {'.htaccess', '.user.ini'}
+
+# Contextual rules only apply to certain files. Applied as a post-filter for
+# BOTH engines (plain YARA cannot express filename conditions).
+FILE_CONSTRAINTS = {
+ 'php_in_image': lambda p: os.path.splitext(p)[1].lower() in IMAGE_EXTENSIONS,
+ 'htaccess_auto_prepend': lambda p: os.path.basename(p).lower() in CONFIG_BASENAMES,
+}
+
+# Curated builtin rules — source of truth for names/severity/description.
+# ``patterns`` are regexes; ``require_all`` means every pattern must match
+# (combo rules). Names match yara_rules/webshells.yar.
+BUILTIN_RULES: List[Dict] = [
+ {
+ 'name': 'php_eval_base64',
+ 'severity': 'critical',
+ 'description': 'eval() of base64-decoded payload (classic obfuscated backdoor loader)',
+ 'patterns': [r'eval\s*\(\s*@?\s*' + _B64 + r'\s*\('],
+ },
+ {
+ 'name': 'php_gzinflate_base64',
+ 'severity': 'critical',
+ 'description': 'gzinflate(base64_decode(...)) double-obfuscated payload',
+ 'patterns': [r'gzinflate\s*\(\s*@?\s*' + _B64 + r'\s*\('],
+ },
+ {
+ 'name': 'php_gzuncompress_base64',
+ 'severity': 'critical',
+ 'description': 'gzuncompress/str_rot13 of base64-decoded payload',
+ 'patterns': [r'(gzuncompress|str_rot13)\s*\(\s*@?\s*' + _B64 + r'\s*\('],
+ },
+ {
+ 'name': 'preg_replace_e_eval',
+ 'severity': 'critical',
+ 'description': 'preg_replace() with the /e modifier (evaluates the replacement as PHP)',
+ 'patterns': [r'preg_replace\s*\(\s*["\'][^"\']{0,60}/[imsxu]{0,4}e[imsxu]{0,4}["\']\s*,'],
+ },
+ {
+ 'name': 'assert_request_input',
+ 'severity': 'critical',
+ 'description': 'assert() fed directly from request input (code execution primitive)',
+ 'patterns': [r'assert\s*\(\s*@?\s*' + _REQ_SOURCES],
+ },
+ {
+ 'name': 'system_request_input',
+ 'severity': 'critical',
+ 'description': 'system() executing raw request input',
+ 'patterns': [r'system\s*\(\s*@?\s*' + _REQ_SOURCES],
+ },
+ {
+ 'name': 'passthru_request_input',
+ 'severity': 'critical',
+ 'description': 'passthru() executing raw request input',
+ 'patterns': [r'passthru\s*\(\s*@?\s*' + _REQ_SOURCES],
+ },
+ {
+ 'name': 'shell_exec_request_input',
+ 'severity': 'critical',
+ 'description': 'shell_exec() executing raw request input',
+ 'patterns': [r'shell_exec\s*\(\s*@?\s*' + _REQ_SOURCES],
+ },
+ {
+ 'name': 'eval_request_input',
+ 'severity': 'critical',
+ 'description': 'eval() fed directly from request input',
+ 'patterns': [r'eval\s*\(\s*@?\s*' + _REQ_SOURCES],
+ },
+ {
+ 'name': 'upload_chmod_777_combo',
+ 'severity': 'high',
+ 'description': 'move_uploaded_file combined with chmod 777 in the same file (dropper pattern)',
+ 'patterns': [r'move_uploaded_file\s*\(', r'chmod\s*\([^)]{0,120}0?777'],
+ 'require_all': True,
+ },
+ {
+ 'name': 'c99_shell_marker',
+ 'severity': 'critical',
+ 'description': 'c99 web shell family marker',
+ 'patterns': [r'c99(sh(ell)?|_launcher|madshell)'],
+ },
+ {
+ 'name': 'r57_shell_marker',
+ 'severity': 'critical',
+ 'description': 'r57 web shell family marker',
+ 'patterns': [r'r57(shell|_tricks|\s+shell)'],
+ },
+ {
+ 'name': 'wso_shell_marker',
+ 'severity': 'critical',
+ 'description': 'WSO (web shell by orb) family marker',
+ 'patterns': [r'(wso_version|wsoshell|wso\s*2\.[0-9]|\$wso\b)'],
+ },
+ {
+ 'name': 'filesman_marker',
+ 'severity': 'critical',
+ 'description': 'FilesMan backdoor file-manager marker',
+ 'patterns': [_FMAN],
+ 'case_sensitive': True,
+ },
+ {
+ 'name': 'php_in_image',
+ 'severity': 'high',
+ 'description': 'PHP open tag inside an image file (mismatched extension dropper)',
+ 'patterns': [r'<\?php'],
+ },
+ {
+ 'name': 'htaccess_auto_prepend',
+ 'severity': 'high',
+ 'description': 'auto_prepend_file injection via .htaccess/.user.ini',
+ 'patterns': [_APF],
+ },
+]
+
+_RULE_META = {r['name']: r for r in BUILTIN_RULES}
+
+
+class YaraScanService:
+ """Curated YARA web-shell pass with a pure-Python fallback engine."""
+
+ # Bundled curated rules for the real yara CLI.
+ BUILTIN_RULES_FILE = os.path.join(os.path.dirname(__file__), 'yara_rules', 'webshells.yar')
+ # Operator-supplied extra rules (real yara only). Class attr so it can be
+ # pointed elsewhere (tests, containers).
+ CUSTOM_RULES_DIR = os.environ.get('SERVERKIT_YARA_CUSTOM_DIR',
+ '/var/serverkit/security/yara-custom')
+ MAX_CUSTOM_RULE_SIZE = 64 * 1024 # 64 KB per .yar file
+ MAX_SCAN_FILE_SIZE = 2 * 1024 * 1024 # fallback engine skips bigger files
+ MAX_FILES = 50000 # fallback engine hard cap
+ SNIPPET_CAP = 160 # matched-snippet length cap
+
+ # ------------------------------------------------------------------ #
+ # Engine selection
+ # ------------------------------------------------------------------ #
+ @classmethod
+ def yara_available(cls) -> bool:
+ return is_command_available('yara')
+
+ @classmethod
+ def engine(cls) -> str:
+ return 'yara' if cls.yara_available() else 'fallback'
+
+ # ------------------------------------------------------------------ #
+ # Scanning
+ # ------------------------------------------------------------------ #
+ @classmethod
+ def scan_path(cls, path: str) -> List[Dict]:
+ """Run the curated rules (plus custom .yar with real yara) against
+ ``path`` (file or directory). Returns the merged findings list."""
+ if not os.path.exists(path):
+ raise ValueError(f'Path not found: {path}')
+
+ if cls.yara_available():
+ findings = cls._scan_with_cli(path)
+ else:
+ findings = cls._scan_with_fallback(path)
+
+ return [f for f in findings if cls._passes_file_constraint(f)]
+
+ @classmethod
+ def _passes_file_constraint(cls, finding: Dict) -> bool:
+ constraint = FILE_CONSTRAINTS.get(finding.get('rule'))
+ if constraint is None:
+ return True
+ try:
+ return bool(constraint(finding.get('file') or ''))
+ except Exception:
+ return False
+
+ # ---- real yara CLI ------------------------------------------------ #
+ @classmethod
+ def _rule_files(cls) -> List[str]:
+ files = [cls.BUILTIN_RULES_FILE]
+ try:
+ if os.path.isdir(cls.CUSTOM_RULES_DIR):
+ for name in sorted(os.listdir(cls.CUSTOM_RULES_DIR)):
+ if name.endswith('.yar'):
+ files.append(os.path.join(cls.CUSTOM_RULES_DIR, name))
+ except OSError:
+ pass
+ return files
+
+ @classmethod
+ def _scan_with_cli(cls, path: str) -> List[Dict]:
+ findings = []
+ for rules_file in cls._rule_files():
+ try:
+ result = subprocess.run(
+ ['yara', '-r', '-s', '-w', rules_file, path],
+ capture_output=True, text=True, timeout=1800,
+ )
+ except (subprocess.TimeoutExpired, OSError) as exc:
+ logger.warning('yara run failed for %s: %s', rules_file, exc)
+ continue
+ if result.returncode not in (0, 1):
+ logger.warning('yara error on %s: %s', rules_file, (result.stderr or '')[:300])
+ continue
+ findings.extend(cls._parse_cli_output(result.stdout or ''))
+ return findings
+
+ @classmethod
+ def _parse_cli_output(cls, output: str) -> List[Dict]:
+ """Parse ``yara -s`` output: ``rule file`` lines followed by
+ ``0xOFFSET:$id: matched data`` lines."""
+ findings = []
+ current = None
+ for line in output.splitlines():
+ if not line:
+ continue
+ string_match = re.match(r'^0x[0-9a-fA-F]+:\$\w+:\s?(.*)$', line)
+ if string_match and current is not None:
+ if not current['matched']:
+ current['matched'] = string_match.group(1)[:cls.SNIPPET_CAP]
+ continue
+ parts = line.split(' ', 1)
+ if len(parts) == 2:
+ rule_name, file_path = parts[0], parts[1].strip()
+ meta = _RULE_META.get(rule_name, {})
+ current = {
+ 'rule': rule_name,
+ 'severity': meta.get('severity', 'medium'),
+ 'file': file_path,
+ 'matched': '',
+ 'description': meta.get('description', 'Custom YARA rule match'),
+ 'source': 'yara',
+ }
+ findings.append(current)
+ return findings
+
+ # ---- pure-Python fallback ----------------------------------------- #
+ @classmethod
+ def _compiled_rules(cls) -> List[Dict]:
+ compiled = []
+ for rule in BUILTIN_RULES:
+ flags = 0 if rule.get('case_sensitive') else re.IGNORECASE
+ compiled.append({
+ **rule,
+ 'compiled': [re.compile(p, flags) for p in rule['patterns']],
+ })
+ return compiled
+
+ @classmethod
+ def _iter_candidate_files(cls, path: str):
+ if os.path.isfile(path):
+ yield path
+ return
+ count = 0
+ for root, dirs, files in os.walk(path):
+ dirs[:] = [d for d in dirs if d not in ('.git', 'node_modules')]
+ for name in files:
+ count += 1
+ if count > cls.MAX_FILES:
+ logger.warning('YARA fallback scan hit the %s-file cap under %s',
+ cls.MAX_FILES, path)
+ return
+ yield os.path.join(root, name)
+
+ @classmethod
+ def _is_scannable(cls, file_path: str) -> bool:
+ base = os.path.basename(file_path).lower()
+ if base in CONFIG_BASENAMES:
+ return True
+ ext = os.path.splitext(file_path)[1].lower()
+ return ext in SCRIPT_EXTENSIONS or ext in IMAGE_EXTENSIONS
+
+ @classmethod
+ def _scan_with_fallback(cls, path: str) -> List[Dict]:
+ rules = cls._compiled_rules()
+ findings = []
+ for file_path in cls._iter_candidate_files(path):
+ if not cls._is_scannable(file_path):
+ continue
+ try:
+ if os.path.getsize(file_path) > cls.MAX_SCAN_FILE_SIZE:
+ continue
+ with open(file_path, 'r', encoding='utf-8', errors='ignore') as fh:
+ content = fh.read()
+ except (OSError, PermissionError):
+ continue
+ for rule in rules:
+ matches = [rx.search(content) for rx in rule['compiled']]
+ hit = all(matches) if rule.get('require_all') else any(matches)
+ if not hit:
+ continue
+ first = next((m for m in matches if m), None)
+ findings.append({
+ 'rule': rule['name'],
+ 'severity': rule['severity'],
+ 'file': file_path,
+ 'matched': (first.group(0) if first else '')[:cls.SNIPPET_CAP],
+ 'description': rule['description'],
+ 'source': 'yara',
+ })
+ return findings
+
+ # ------------------------------------------------------------------ #
+ # Rules management (builtin listing + custom .yar upload/delete)
+ # ------------------------------------------------------------------ #
+ _SAFE_NAME = re.compile(r'^[A-Za-z0-9._-]+$')
+
+ @classmethod
+ def list_rules(cls) -> Dict:
+ builtin = [{'name': r['name'], 'severity': r['severity'],
+ 'description': r['description']} for r in BUILTIN_RULES]
+ custom = []
+ try:
+ if os.path.isdir(cls.CUSTOM_RULES_DIR):
+ for name in sorted(os.listdir(cls.CUSTOM_RULES_DIR)):
+ if not name.endswith('.yar'):
+ continue
+ full = os.path.join(cls.CUSTOM_RULES_DIR, name)
+ try:
+ stat = os.stat(full)
+ custom.append({'name': name, 'size': stat.st_size})
+ except OSError:
+ continue
+ except OSError:
+ pass
+ return {
+ 'success': True,
+ 'engine': cls.engine(),
+ 'builtin': builtin,
+ 'builtin_count': len(builtin),
+ 'custom': custom,
+ 'custom_rules_dir': cls.CUSTOM_RULES_DIR,
+ # Fallback engine only evaluates the curated set; real yara
+ # additionally loads custom .yar files.
+ 'custom_rules_active': cls.yara_available(),
+ }
+
+ @classmethod
+ def save_custom_rule(cls, filename: str, content: str) -> Dict:
+ filename = (filename or '').strip()
+ if not filename or not cls._SAFE_NAME.match(filename):
+ return {'success': False, 'error': 'Invalid rule filename'}
+ if not filename.endswith('.yar'):
+ return {'success': False, 'error': 'Only .yar rule files are accepted'}
+ if not content or not content.strip():
+ return {'success': False, 'error': 'Rule content is empty'}
+ if len(content.encode('utf-8', errors='ignore')) > cls.MAX_CUSTOM_RULE_SIZE:
+ return {'success': False,
+ 'error': f'Rule file exceeds {cls.MAX_CUSTOM_RULE_SIZE // 1024} KB limit'}
+ if 'rule ' not in content:
+ return {'success': False, 'error': 'Content does not look like a YARA rule file'}
+ try:
+ os.makedirs(cls.CUSTOM_RULES_DIR, exist_ok=True)
+ full = os.path.join(cls.CUSTOM_RULES_DIR, filename)
+ with open(full, 'w', encoding='utf-8') as fh:
+ fh.write(content)
+ return {'success': True, 'message': f'Rule file {filename} saved',
+ 'custom_rules_active': cls.yara_available()}
+ except OSError as exc:
+ return {'success': False, 'error': str(exc)}
+
+ @classmethod
+ def delete_custom_rule(cls, filename: str) -> Dict:
+ filename = (filename or '').strip()
+ if not filename or not cls._SAFE_NAME.match(filename) or not filename.endswith('.yar'):
+ return {'success': False, 'error': 'Invalid rule filename'}
+ full = os.path.abspath(os.path.join(cls.CUSTOM_RULES_DIR, filename))
+ if not full.startswith(os.path.abspath(cls.CUSTOM_RULES_DIR)):
+ return {'success': False, 'error': 'Invalid rule path'}
+ if not os.path.exists(full):
+ return {'success': False, 'error': 'Rule file not found'}
+ try:
+ os.remove(full)
+ return {'success': True, 'message': f'Rule file {filename} deleted'}
+ except OSError as exc:
+ return {'success': False, 'error': str(exc)}
diff --git a/backend/tests/test_malware_scan_job.py b/backend/tests/test_malware_scan_job.py
new file mode 100644
index 00000000..806f2608
--- /dev/null
+++ b/backend/tests/test_malware_scan_job.py
@@ -0,0 +1,253 @@
+"""Proving tests for the job-backed malware scan (security.malware_scan).
+
+Covers: enqueue via the API (202 + job_id), app-docroot resolution, the job
+handler flow with clamav/subprocess stubbed, YARA findings merged with a
+distinct source tag, quarantine (+ restore/delete) of a YARA finding, and
+auth. All fixture files are inert indicator strings in tmp_path.
+"""
+import os
+from unittest.mock import patch
+
+import pytest
+
+from app.jobs.models import Job
+from app.jobs.service import JobService, GROUP_SLUG, QUEUE_SLUG
+from app.jobs.consumer import JobConsumer
+from app.queue_bus.service import QueueBusService
+from app.services.malware_scan_service import MalwareScanService, MALWARE_SCAN_JOB_KIND
+from app.services.security_service import SecurityService
+
+EVAL_B64 = 'eval(' + 'base64_' + 'decode' + '($p));'
+PHP_TAG = '<?' + 'php'
+
+
[email protected](autouse=True)
+def isolated_bus(app, tmp_path):
+ """Fresh broker + handler registration; keep scan logs/alerts in tmp."""
+ QueueBusService.reset_broker()
+ MalwareScanService.register_jobs()
+ SecurityService._current_scan = None
+ with patch.object(SecurityService, 'SCAN_LOG', str(tmp_path / 'scans.log')), \
+ patch.object(SecurityService, 'ALERTS_LOG', str(tmp_path / 'alerts.log')), \
+ patch('app.services.security_service.NotificationService') as notify:
+ notify.send_all.return_value = None
+ yield
+ SecurityService._current_scan = None
+
+
+def docroot(tmp_path):
+ root = tmp_path / 'site'
+ root.mkdir()
+ (root / 'shell.php').write_text(f'{PHP_TAG}\n{EVAL_B64}\n')
+ (root / 'clean.php').write_text(f'{PHP_TAG} echo "ok";')
+ return root
+
+
+def _make_app_row(name, root_path):
+ from app import db
+ from app.models import User
+ from app.models.application import Application
+ from werkzeug.security import generate_password_hash
+ owner = User(email=f'{name}@test.local', username=f'owner-{name}',
+ password_hash=generate_password_hash('x'), is_active=True)
+ db.session.add(owner)
+ db.session.flush()
+ row = Application(name=name, app_type='php', root_path=root_path,
+ user_id=owner.id)
+ db.session.add(row)
+ db.session.commit()
+ return row
+
+
+def application(app, docroot):
+ return _make_app_row('scan-me', str(docroot))
+
+
+def _drain_once():
+ messages = QueueBusService.receive(GROUP_SLUG, QUEUE_SLUG, max_messages=1)
+ assert messages, 'expected a queued job message'
+ JobConsumer().process_message(messages[0])
+ return messages[0]
+
+
+def _no_tools():
+ """Patch both tool probes off: YARA falls back, ClamAV is skipped."""
+ return (
+ patch('app.services.malware_scan_service.is_command_available', return_value=False),
+ patch('app.services.yara_scan_service.is_command_available', return_value=False),
+ )
+
+
+class TestAppDocrootResolution:
+ def test_resolves_root_path(self, application, docroot):
+ assert MalwareScanService.resolve_app_path(application.id) == str(docroot)
+
+ def test_unknown_app_raises(self, app):
+ with pytest.raises(ValueError, match='not found'):
+ MalwareScanService.resolve_app_path(999999)
+
+ def test_missing_docroot_raises(self, app, tmp_path):
+ row = _make_app_row('ghost', str(tmp_path / 'gone'))
+ with patch('app.services.malware_scan_service.paths.APPS_DIR',
+ str(tmp_path / 'no-apps')):
+ with pytest.raises(ValueError, match='No docroot'):
+ MalwareScanService.resolve_app_path(row.id)
+
+
+class TestScanJobFlow:
+ def test_job_runs_yara_pass_without_clamav(self, application, docroot):
+ p1, p2 = _no_tools()
+ with p1, p2:
+ job = MalwareScanService.enqueue_scan(app_id=application.id)
+ _drain_once()
+
+ refreshed = Job.query.get(job.id)
+ assert refreshed.status == Job.STATUS_SUCCEEDED
+ result = refreshed.get_result()
+ assert result['status'] == 'completed'
+ assert result['clamav_available'] is False
+ assert result['yara_engine'] == 'fallback'
+ assert result['counts']['yara'] >= 1
+ assert result['counts']['clamav'] == 0
+ yara_hits = [f for f in result['findings'] if f['source'] == 'yara']
+ assert any(f['rule'] == 'php_eval_base64' and f['file'].endswith('shell.php')
+ for f in yara_hits)
+ # clean file untouched
+ assert not any(f['file'].endswith('clean.php') for f in result['findings'])
+
+ def test_clamav_findings_merged_with_distinct_source(self, application, docroot):
+ infected = str(docroot / 'shell.php')
+ clam_stdout = f'{infected}: Eicar-Test-Signature FOUND\n'
+
+ class FakeCompleted:
+ returncode = 1
+ stdout = clam_stdout
+ stderr = ''
+
+ with patch('app.services.malware_scan_service.is_command_available', return_value=True), \
+ patch('app.services.yara_scan_service.is_command_available', return_value=False), \
+ patch('app.services.malware_scan_service.subprocess.run',
+ return_value=FakeCompleted()) as run_mock:
+ job = MalwareScanService.enqueue_scan(app_id=application.id)
+ _drain_once()
+
+ assert run_mock.called
+ assert run_mock.call_args[0][0][0] == 'clamscan'
+ result = Job.query.get(job.id).get_result()
+ sources = {f['source'] for f in result['findings']}
+ assert sources == {'yara', 'clamav'}
+ clam = [f for f in result['findings'] if f['source'] == 'clamav']
+ assert clam[0]['rule'] == 'Eicar-Test-Signature'
+ assert clam[0]['severity'] == 'critical'
+ assert result['counts']['clamav'] == 1
+
+ def test_job_status_mirrored_to_scan_status(self, application):
+ p1, p2 = _no_tools()
+ with p1, p2:
+ MalwareScanService.enqueue_scan(app_id=application.id)
+ _drain_once()
+ status = SecurityService.get_scan_status()
+ assert status['status'] == 'completed'
+ assert status['job_id'] is not None
+ assert status['findings']
+
+ def test_payload_with_raw_path(self, app, docroot):
+ p1, p2 = _no_tools()
+ with p1, p2:
+ job = JobService.enqueue(MALWARE_SCAN_JOB_KIND, {'path': str(docroot)})
+ _drain_once()
+ result = Job.query.get(job.id).get_result()
+ assert result['directory'] == str(docroot)
+ assert result['counts']['yara'] >= 1
+
+ def test_empty_payload_fails_job(self, app):
+ job = JobService.enqueue(MALWARE_SCAN_JOB_KIND, {}, max_attempts=1)
+ _drain_once()
+ refreshed = Job.query.get(job.id)
+ assert refreshed.status == Job.STATUS_FAILED
+ assert 'path or app_id' in (refreshed.error_message or '')
+
+
+class TestQuarantineOfYaraFinding:
+ @pytest.fixture
+ def quarantine_cfg(self, tmp_path):
+ qdir = tmp_path / 'quarantine'
+ config = SecurityService.get_config()
+ config['clamav']['quarantine_path'] = str(qdir)
+ with patch.object(SecurityService, 'get_config', classmethod(lambda cls: config)):
+ yield qdir
+
+ def test_quarantine_restore_delete_roundtrip(self, app, docroot, quarantine_cfg):
+ p1, p2 = _no_tools()
+ with p1, p2:
+ report = MalwareScanService.execute_scan(str(docroot))
+ finding = next(f for f in report['findings'] if f['rule'] == 'php_eval_base64')
+
+ # Quarantine the YARA finding via the existing mechanics
+ result = SecurityService.quarantine_file(finding['file'])
+ assert result['success'] is True
+ assert not os.path.exists(finding['file'])
+
+ listed = SecurityService.get_quarantined_files()
+ assert len(listed['files']) == 1
+ entry = listed['files'][0]
+ assert entry['original_path'] == os.path.abspath(finding['file'])
+
+ # Restore puts it back
+ restored = SecurityService.restore_quarantined_file(entry['name'])
+ assert restored['success'] is True
+ assert os.path.exists(finding['file'])
+ assert SecurityService.get_quarantined_files()['files'] == []
+
+ # Quarantine again, then delete permanently
+ SecurityService.quarantine_file(finding['file'])
+ entry = SecurityService.get_quarantined_files()['files'][0]
+ deleted = SecurityService.delete_quarantined_file(entry['name'])
+ assert deleted['success'] is True
+ assert SecurityService.get_quarantined_files()['files'] == []
+
+ def test_restore_without_meta_errors(self, app, quarantine_cfg):
+ qdir = quarantine_cfg
+ qdir.mkdir(parents=True, exist_ok=True)
+ (qdir / 'legacy.quarantine').write_text('x')
+ result = SecurityService.restore_quarantined_file('legacy.quarantine')
+ assert result['success'] is False
+ assert 'Original location unknown' in result['error']
+
+
+class TestScanApi:
+ def test_scan_app_returns_202_job(self, client, auth_headers, application):
+ p1, p2 = _no_tools()
+ with p1, p2:
+ resp = client.post(f'/api/v1/security/scan/app/{application.id}',
+ headers=auth_headers)
+ assert resp.status_code == 202
+ body = resp.get_json()
+ assert body['job_id']
+ assert body['kind'] == MALWARE_SCAN_JOB_KIND
+ assert Job.query.get(body['job_id']) is not None
+
+ def test_scan_app_unknown_id_404(self, client, auth_headers):
+ resp = client.post('/api/v1/security/scan/app/424242', headers=auth_headers)
+ assert resp.status_code == 404
+ assert 'error' in resp.get_json()
+
+ def test_scan_app_requires_auth(self, client, application):
+ resp = client.post(f'/api/v1/security/scan/app/{application.id}')
+ assert resp.status_code in (401, 422)
+
+ def test_scan_job_path_endpoint(self, client, auth_headers, docroot):
+ resp = client.post('/api/v1/security/scan/job', headers=auth_headers,
+ json={'path': str(docroot)})
+ assert resp.status_code == 202
+ assert resp.get_json()['job_id']
+
+ def test_scan_job_requires_path(self, client, auth_headers):
+ resp = client.post('/api/v1/security/scan/job', headers=auth_headers, json={})
+ assert resp.status_code == 400
+
+ def test_quarantine_restore_endpoint_requires_auth(self, client):
+ resp = client.post('/api/v1/security/quarantine/x.quarantine/restore')
+ assert resp.status_code in (401, 422)
diff --git a/backend/tests/test_yara_scan.py b/backend/tests/test_yara_scan.py
new file mode 100644
index 00000000..f3536d9c
--- /dev/null
+++ b/backend/tests/test_yara_scan.py
@@ -0,0 +1,194 @@
+"""Proving tests for the YARA web-shell pass (YaraScanService).
+
+Fixture "malware" files contain fragment-assembled indicator strings only —
+they never execute and are planted in tmp_path. The pure-Python fallback
+matcher is forced (yara CLI patched absent) so these run on any OS.
+"""
+import os
+from unittest.mock import patch
+
+import pytest
+
+from app.services.yara_scan_service import YaraScanService
+
+
+# Assemble indicators from fragments so this test file doesn't itself carry
+# literal signatures.
+EVAL_B64 = 'eval(' + 'base64_' + 'decode' + '($x));'
+GZ_B64 = 'gzinflate(' + 'base64_' + 'decode' + '($y));'
+PHP_TAG = '<?' + 'php'
+APF = 'auto_prepend_' + 'file'
+FMAN = 'Files' + 'Man'
+
+
[email protected](autouse=True)
+def force_fallback():
+ """Force the pure-Python engine regardless of the host having yara."""
+ with patch('app.services.yara_scan_service.is_command_available', return_value=False):
+ yield
+
+
+def docroot(tmp_path):
+ (tmp_path / 'shell.php').write_text(f'{PHP_TAG}\n{EVAL_B64}\n')
+ (tmp_path / 'packed.php').write_text(f'{PHP_TAG} {GZ_B64}')
+ (tmp_path / 'clean.php').write_text(
+ f'{PHP_TAG}\necho "hello";\n$data = base64_encode("ok");\n')
+ (tmp_path / 'favicon.ico').write_text(f'{PHP_TAG} echo 1;')
+ (tmp_path / '.htaccess').write_text(f'php_value {APF} "/tmp/x.php"\n')
+ (tmp_path / 'dropper.php').write_text(
+ f'{PHP_TAG}\nmove_uploaded_file($f, $d);\nchmod($d, 0777);\n')
+ (tmp_path / 'manager.php').write_text(f'{PHP_TAG} // {FMAN} v2')
+ return tmp_path
+
+
+class TestFallbackMatcher:
+ def test_engine_is_fallback_without_yara(self):
+ assert YaraScanService.yara_available() is False
+ assert YaraScanService.engine() == 'fallback'
+
+ def test_detections_and_severities(self, docroot):
+ findings = YaraScanService.scan_path(str(docroot))
+ by_rule = {}
+ for f in findings:
+ by_rule.setdefault(f['rule'], []).append(f)
+
+ assert 'php_eval_base64' in by_rule
+ assert by_rule['php_eval_base64'][0]['severity'] == 'critical'
+ assert by_rule['php_eval_base64'][0]['file'].endswith('shell.php')
+
+ assert 'php_gzinflate_base64' in by_rule
+ assert by_rule['php_gzinflate_base64'][0]['severity'] == 'critical'
+
+ assert 'upload_chmod_777_combo' in by_rule
+ assert by_rule['upload_chmod_777_combo'][0]['severity'] == 'high'
+
+ assert 'filesman_marker' in by_rule
+
+ # All findings share the result shape + source tag
+ for f in findings:
+ assert f['source'] == 'yara'
+ assert set(f) >= {'rule', 'severity', 'file', 'matched', 'description'}
+ assert len(f['matched']) <= YaraScanService.SNIPPET_CAP
+
+ def test_no_false_positive_on_clean_file(self, docroot):
+ findings = YaraScanService.scan_path(str(docroot))
+ assert not any(f['file'].endswith('clean.php') for f in findings)
+
+ def test_php_in_image_only_fires_on_images(self, docroot):
+ findings = YaraScanService.scan_path(str(docroot))
+ img = [f for f in findings if f['rule'] == 'php_in_image']
+ assert len(img) == 1
+ assert img[0]['file'].endswith('favicon.ico')
+ assert img[0]['severity'] == 'high'
+
+ def test_htaccess_auto_prepend_scoped_to_config_files(self, docroot):
+ findings = YaraScanService.scan_path(str(docroot))
+ apf = [f for f in findings if f['rule'] == 'htaccess_auto_prepend']
+ assert len(apf) == 1
+ assert os.path.basename(apf[0]['file']) == '.htaccess'
+
+ def test_single_file_scan(self, docroot):
+ findings = YaraScanService.scan_path(str(docroot / 'shell.php'))
+ assert any(f['rule'] == 'php_eval_base64' for f in findings)
+
+ def test_missing_path_raises(self, tmp_path):
+ with pytest.raises(ValueError):
+ YaraScanService.scan_path(str(tmp_path / 'nope'))
+
+ def test_matched_snippet_capped(self, tmp_path):
+ payload = 'eval( ' + 'base64_' + 'decode' + '(' + 'A' * 500 + '));'
+ (tmp_path / 'big.php').write_text(f'{PHP_TAG} {payload}')
+ findings = YaraScanService.scan_path(str(tmp_path))
+ assert findings
+ assert all(len(f['matched']) <= YaraScanService.SNIPPET_CAP for f in findings)
+
+
+class TestCliOutputParser:
+ def test_parse_rule_and_snippet_lines(self):
+ out = (
+ 'php_eval_base64 /var/www/site/shell.php\n'
+ '0x1c:$a: ' + 'eval(base64_' + 'decode' + '(\n'
+ 'custom_rule_x /var/www/site/other.php\n'
+ )
+ findings = YaraScanService._parse_cli_output(out)
+ assert findings[0]['rule'] == 'php_eval_base64'
+ assert findings[0]['severity'] == 'critical'
+ assert findings[0]['matched'].startswith('eval(')
+ # Unknown (custom) rules get a default severity
+ assert findings[1]['rule'] == 'custom_rule_x'
+ assert findings[1]['severity'] == 'medium'
+
+
+class TestCustomRulesManagement:
+ @pytest.fixture(autouse=True)
+ def custom_dir(self, tmp_path):
+ with patch.object(YaraScanService, 'CUSTOM_RULES_DIR', str(tmp_path / 'custom')):
+ yield tmp_path / 'custom'
+
+ def test_save_and_list_and_delete(self, custom_dir):
+ content = 'rule my_rule { strings: $a = "abc" condition: $a }'
+ result = YaraScanService.save_custom_rule('mine.yar', content)
+ assert result['success'] is True
+ listing = YaraScanService.list_rules()
+ assert listing['builtin_count'] >= 10
+ assert any(c['name'] == 'mine.yar' for c in listing['custom'])
+ assert listing['engine'] == 'fallback'
+
+ deleted = YaraScanService.delete_custom_rule('mine.yar')
+ assert deleted['success'] is True
+ assert not (custom_dir / 'mine.yar').exists()
+
+ def test_rejects_non_yar_extension(self):
+ result = YaraScanService.save_custom_rule('evil.php', 'rule x {condition: true}')
+ assert result['success'] is False
+ assert '.yar' in result['error']
+
+ def test_rejects_oversized_rule(self):
+ content = 'rule big { condition: true } //' + 'x' * (YaraScanService.MAX_CUSTOM_RULE_SIZE + 1)
+ result = YaraScanService.save_custom_rule('big.yar', content)
+ assert result['success'] is False
+
+ def test_rejects_path_traversal_names(self):
+ assert YaraScanService.save_custom_rule('../esc.yar', 'rule x {condition: true}')['success'] is False
+ assert YaraScanService.delete_custom_rule('../../etc.yar')['success'] is False
+
+ def test_rejects_non_rule_content(self):
+ result = YaraScanService.save_custom_rule('junk.yar', 'just some text')
+ assert result['success'] is False
+
+
+class TestYaraRulesApi:
+ @pytest.fixture(autouse=True)
+ def custom_dir(self, tmp_path):
+ with patch.object(YaraScanService, 'CUSTOM_RULES_DIR', str(tmp_path / 'custom')):
+ yield
+
+ def test_list_requires_auth(self, client):
+ resp = client.get('/api/v1/security/yara/rules')
+ assert resp.status_code in (401, 422)
+
+ def test_list_rules(self, client, auth_headers):
+ resp = client.get('/api/v1/security/yara/rules', headers=auth_headers)
+ assert resp.status_code == 200
+ body = resp.get_json()
+ assert body['builtin_count'] >= 10
+ assert any(r['name'] == 'php_eval_base64' for r in body['builtin'])
+
+ def test_upload_rejects_php(self, client, auth_headers):
+ resp = client.post('/api/v1/security/yara/rules', headers=auth_headers,
+ json={'filename': 'shell.php', 'content': 'rule x {condition: true}'})
+ assert resp.status_code == 400
+ assert 'error' in resp.get_json()
+
+ def test_upload_and_delete_roundtrip(self, client, auth_headers):
+ resp = client.post('/api/v1/security/yara/rules', headers=auth_headers,
+ json={'filename': 'ops.yar',
+ 'content': 'rule ops { strings: $a = "zz" condition: $a }'})
+ assert resp.status_code == 200
+
+ resp = client.get('/api/v1/security/yara/rules', headers=auth_headers)
+ assert any(c['name'] == 'ops.yar' for c in resp.get_json()['custom'])
+
+ resp = client.delete('/api/v1/security/yara/rules/ops.yar', headers=auth_headers)
+ assert resp.status_code == 200
diff --git a/frontend/src/components/security/QuarantineTab.jsx b/frontend/src/components/security/QuarantineTab.jsx
index 1853df87..335e561e 100644
--- a/frontend/src/components/security/QuarantineTab.jsx
+++ b/frontend/src/components/security/QuarantineTab.jsx
@@ -35,6 +35,19 @@ const QuarantineTab = () => {
}
}
+ async function handleRestore(file) {
+ const target = file.original_path || 'its original location';
+ if (!confirm(`Restore ${file.name} to ${target}? Only do this for false positives.`)) return;
+
+ try {
+ const result = await api.restoreQuarantinedFile(file.name);
+ setMessage({ type: 'success', text: result.message || 'File restored' });
+ loadFiles();
+ } catch (err) {
+ setMessage({ type: 'error', text: err.message });
+ }
+ }
+
return (
<div className="quarantine-tab">
{message && (
@@ -68,6 +81,7 @@ const QuarantineTab = () => {
<thead>
<tr>
<th>Filename</th>
+ <th>Original Location</th>
<th>Size</th>
<th>Quarantined</th>
<th>Actions</th>
@@ -77,16 +91,30 @@ const QuarantineTab = () => {
{files.map((file, index) => (
<tr key={index}>
<td className="sk-cell-mono sec-path sec-path--red">{file.name}</td>
+ <td className="sk-cell-mono sec-path sec-faint" title={file.original_path || ''}>
+ {file.original_path || '—'}
+ </td>
<td className="sk-cell-mono">{formatBytes(file.size, { defaultValue: '0 B' })}</td>
<td className="sk-cell-mono sec-faint">{new Date(file.quarantined_at).toLocaleString()}</td>
<td>
- <Button
- variant="destructive"
- size="sm"
- onClick={() => handleDelete(file.name)}
- >
- Delete
- </Button>
+ <div className="quarantine-actions">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => handleRestore(file)}
+ disabled={!file.original_path}
+ title={file.original_path ? 'Restore to original location' : 'Original location unknown'}
+ >
+ Restore
+ </Button>
+ <Button
+ variant="destructive"
+ size="sm"
+ onClick={() => handleDelete(file.name)}
+ >
+ Delete
+ </Button>
+ </div>
</td>
</tr>
))}
diff --git a/frontend/src/components/security/ScannerTab.jsx b/frontend/src/components/security/ScannerTab.jsx
index d140c174..f869e5f2 100644
--- a/frontend/src/components/security/ScannerTab.jsx
+++ b/frontend/src/components/security/ScannerTab.jsx
@@ -1,9 +1,16 @@
-import { useState, useEffect } from 'react';
+import { useState, useEffect, useRef } from 'react';
import api from '../../services/api';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Pill } from '@/components/ds';
-import { Zap, Radar, FolderSearch, Download } from 'lucide-react';
+import { Zap, Radar, FolderSearch, Download, Box, ShieldAlert, FileCode2, Trash2 } from 'lucide-react';
+
+const SEVERITY_TONE = {
+ critical: 'red',
+ high: 'red',
+ medium: 'amber',
+ low: 'gray',
+};
const ScannerTab = () => {
const [scanStatus, setScanStatus] = useState({ status: 'idle' });
@@ -13,17 +20,39 @@ const ScannerTab = () => {
const [history, setHistory] = useState([]);
const [message, setMessage] = useState(null);
+ // App scan (job-backed)
+ const [apps, setApps] = useState([]);
+ const [selectedApp, setSelectedApp] = useState('');
+ const [scanJob, setScanJob] = useState(null); // { id, status, result }
+ const jobPollRef = useRef(null);
+
+ // Findings (YARA + ClamAV) from the last completed job/scan
+ const [findings, setFindings] = useState([]);
+ const [quarantining, setQuarantining] = useState(null);
+
+ // YARA rules manager
+ const [rules, setRules] = useState(null);
+ const [showRules, setShowRules] = useState(false);
+ const ruleFileRef = useRef(null);
+
useEffect(() => {
loadScanStatus();
loadHistory();
+ loadApps();
const interval = setInterval(loadScanStatus, 5000);
- return () => clearInterval(interval);
+ return () => {
+ clearInterval(interval);
+ if (jobPollRef.current) clearInterval(jobPollRef.current);
+ };
}, []);
async function loadScanStatus() {
try {
const data = await api.getScanStatus();
setScanStatus(data);
+ if (data.status === 'completed' && Array.isArray(data.findings)) {
+ setFindings(data.findings);
+ }
} catch (err) {
console.error('Failed to load scan status:', err);
}
@@ -38,6 +67,70 @@ const ScannerTab = () => {
}
}
+ async function loadApps() {
+ try {
+ const data = await api.getApps();
+ setApps(data.apps || []);
+ } catch (err) {
+ console.error('Failed to load apps:', err);
+ }
+ }
+
+ async function loadRules() {
+ try {
+ const data = await api.getYaraRules();
+ setRules(data);
+ } catch (err) {
+ setMessage({ type: 'error', text: err.message });
+ }
+ }
+
+ function pollJob(jobId) {
+ if (jobPollRef.current) clearInterval(jobPollRef.current);
+ jobPollRef.current = setInterval(async () => {
+ try {
+ const job = await api.getJob(jobId);
+ setScanJob(job);
+ if (['succeeded', 'failed', 'cancelled'].includes(job.status)) {
+ clearInterval(jobPollRef.current);
+ jobPollRef.current = null;
+ if (job.status === 'succeeded' && job.result?.findings) {
+ setFindings(job.result.findings);
+ const n = job.result.findings.length;
+ setMessage({
+ type: n > 0 ? 'error' : 'success',
+ text: n > 0
+ ? `Scan finished: ${n} finding(s) — review below`
+ : 'Scan finished: no threats found'
+ });
+ } else if (job.status === 'failed') {
+ setMessage({ type: 'error', text: job.error_message || 'Scan job failed' });
+ }
+ loadScanStatus();
+ loadHistory();
+ }
+ } catch (err) {
+ console.error('Failed to poll scan job:', err);
+ }
+ }, 3000);
+ }
+
+ async function handleScanApp() {
+ if (!selectedApp) return;
+ setScanning(true);
+ setMessage(null);
+ try {
+ const result = await api.scanApp(selectedApp);
+ setScanJob({ id: result.job_id, status: 'pending' });
+ setMessage({ type: 'success', text: `Scan queued for ${result.path || 'app docroot'}` });
+ pollJob(result.job_id);
+ } catch (err) {
+ setMessage({ type: 'error', text: err.message });
+ } finally {
+ setScanning(false);
+ }
+ }
+
async function handleStartScan(type) {
setScanning(true);
setMessage(null);
@@ -81,7 +174,59 @@ const ScannerTab = () => {
}
}
+ async function handleQuarantine(finding) {
+ setQuarantining(finding.file);
+ try {
+ await api.quarantineFile(finding.file);
+ setFindings((prev) => prev.filter((f) => f.file !== finding.file));
+ setMessage({ type: 'success', text: `Quarantined ${finding.file}` });
+ } catch (err) {
+ setMessage({ type: 'error', text: err.message });
+ } finally {
+ setQuarantining(null);
+ }
+ }
+
+ async function handleToggleRules() {
+ const next = !showRules;
+ setShowRules(next);
+ if (next && !rules) loadRules();
+ }
+
+ async function handleRuleFileChosen(e) {
+ const file = e.target.files?.[0];
+ e.target.value = '';
+ if (!file) return;
+ if (!file.name.endsWith('.yar')) {
+ setMessage({ type: 'error', text: 'Only .yar rule files are accepted' });
+ return;
+ }
+ if (file.size > 64 * 1024) {
+ setMessage({ type: 'error', text: 'Rule file exceeds the 64 KB limit' });
+ return;
+ }
+ try {
+ const content = await file.text();
+ await api.uploadYaraRule(file.name, content);
+ setMessage({ type: 'success', text: `Rule file ${file.name} uploaded` });
+ loadRules();
+ } catch (err) {
+ setMessage({ type: 'error', text: err.message });
+ }
+ }
+
+ async function handleDeleteRule(name) {
+ if (!confirm(`Delete custom rule file ${name}?`)) return;
+ try {
+ await api.deleteYaraRule(name);
+ loadRules();
+ } catch (err) {
+ setMessage({ type: 'error', text: err.message });
+ }
+ }
+
const isScanning = scanStatus.status === 'running';
+ const jobRunning = scanJob && ['pending', 'running'].includes(scanJob.status);
return (
<div className="scanner-tab">
@@ -149,29 +294,122 @@ const ScannerTab = () => {
</Button>
</div>
</div>
+
+ <div className="scan-card scan-card--app">
+ <div className="scan-card-icon">
+ <Box size={20} />
+ </div>
+ <h4>Scan an App</h4>
+ <span className="scan-desc">Web-shell + malware scan of a docroot</span>
+ <div className="scan-custom-input">
+ <select
+ className="scan-app-select"
+ value={selectedApp}
+ onChange={(e) => setSelectedApp(e.target.value)}
+ disabled={jobRunning}
+ >
+ <option value="">Select an app…</option>
+ {apps.map((a) => (
+ <option key={a.id} value={a.id}>{a.name}</option>
+ ))}
+ </select>
+ <Button
+ variant="default"
+ size="sm"
+ onClick={handleScanApp}
+ disabled={!selectedApp || scanning || jobRunning}
+ >
+ {jobRunning ? 'Running…' : 'Scan'}
+ </Button>
+ </div>
+ </div>
</div>
<div className="scan-toolbar">
+ <Button variant="outline" size="sm" onClick={handleToggleRules}>
+ <FileCode2 size={14} />
+ Web-shell Rules
+ </Button>
<Button variant="outline" size="sm" onClick={handleUpdateDefinitions} disabled={updating}>
<Download size={14} />
{updating ? 'Updating...' : 'Update Definitions'}
</Button>
</div>
- {isScanning && (
+ {showRules && (
+ <div className="card sec-flush yara-rules-card">
+ <div className="card-header">
+ <h3>Web-shell Detection Rules{rules && <span className="sec-count"> · {rules.builtin_count} builtin</span>}</h3>
+ <div className="card-actions">
+ <input
+ ref={ruleFileRef}
+ type="file"
+ accept=".yar"
+ className="yara-file-input"
+ onChange={handleRuleFileChosen}
+ />
+ <Button variant="outline" size="sm" onClick={() => ruleFileRef.current?.click()}>
+ Upload .yar
+ </Button>
+ </div>
+ </div>
+ <div className="card-body">
+ {!rules ? (
+ <div className="loading-sm">Loading...</div>
+ ) : (
+ <>
+ <p className="sec-hint sec-hint--lead">
+ {rules.builtin_count} curated web-shell indicators run on every scan
+ (engine: <span className="sec-mono">{rules.engine}</span>).
+ {rules.engine === 'fallback' && ' Install yara to enable custom .yar rule files.'}
+ </p>
+ {rules.custom.length === 0 ? (
+ <p className="sec-hint">No custom rule files. Upload a .yar file (max 64 KB) to extend the rule set.</p>
+ ) : (
+ <div className="yara-custom-list">
+ {rules.custom.map((c) => (
+ <div key={c.name} className="yara-custom-item">
+ <span className="sec-mono">{c.name}</span>
+ <span className="sec-faint sec-mono">{c.size} B</span>
+ {!rules.custom_rules_active && (
+ <span className="sec-state sec-state--gray">inactive — yara not installed</span>
+ )}
+ <Button variant="ghost" size="sm" onClick={() => handleDeleteRule(c.name)}>
+ <Trash2 size={14} />
+ </Button>
+ </div>
+ ))}
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ </div>
+ )}
+
+ {(isScanning || jobRunning) && (
<div className="card scan-progress">
<div className="card-header">
<h3>Scan in Progress</h3>
- <Button variant="destructive" size="sm" onClick={handleCancelScan}>
- Cancel
- </Button>
+ {isScanning && (
+ <Button variant="destructive" size="sm" onClick={handleCancelScan}>
+ Cancel
+ </Button>
+ )}
</div>
<div className="card-body">
<div className="progress-info">
<div className="spinner"></div>
<div>
- <p><strong>Scanning:</strong> <span className="sec-mono">{scanStatus.directory}</span></p>
- <p><strong>Started:</strong> <span className="sec-mono">{new Date(scanStatus.started_at).toLocaleString()}</span></p>
+ {scanStatus.directory && (
+ <p><strong>Scanning:</strong> <span className="sec-mono">{scanStatus.directory}</span></p>
+ )}
+ {scanStatus.started_at && (
+ <p><strong>Started:</strong> <span className="sec-mono">{new Date(scanStatus.started_at).toLocaleString()}</span></p>
+ )}
+ {jobRunning && (
+ <p><strong>Job:</strong> <span className="sec-mono">{scanJob.id} · {scanJob.status}</span></p>
+ )}
{scanStatus.files_scanned > 0 && (
<p><strong>Files scanned:</strong> <span className="sec-mono">{scanStatus.files_scanned}</span></p>
)}
@@ -181,6 +419,55 @@ const ScannerTab = () => {
</div>
)}
+ {findings.length > 0 && (
+ <div className="card sec-flush scan-findings">
+ <div className="card-header">
+ <h3 className="sec-listtitle--red">
+ <ShieldAlert size={13} />
+ Findings <span className="sec-count">· {findings.length}</span>
+ </h3>
+ <Button variant="outline" size="sm" onClick={() => setFindings([])}>Dismiss</Button>
+ </div>
+ <table className="sk-dtable">
+ <thead>
+ <tr>
+ <th>Rule</th>
+ <th>Severity</th>
+ <th>File</th>
+ <th>Match</th>
+ <th>Source</th>
+ <th></th>
+ </tr>
+ </thead>
+ <tbody>
+ {findings.map((f, index) => (
+ <tr key={`${f.file}-${f.rule}-${index}`}>
+ <td className="sk-cell-mono" title={f.description}>{f.rule}</td>
+ <td>
+ <span className={`sec-state sec-state--${SEVERITY_TONE[f.severity] || 'gray'}`}>
+ {f.severity}
+ </span>
+ </td>
+ <td className="sk-cell-mono sec-path sec-path--red" title={f.file}>{f.file}</td>
+ <td className="sk-cell-mono scan-snippet">{f.matched || '—'}</td>
+ <td><span className="sec-state sec-state--gray">{f.source}</span></td>
+ <td className="sec-rowend">
+ <Button
+ variant="destructive"
+ size="sm"
+ onClick={() => handleQuarantine(f)}
+ disabled={quarantining === f.file}
+ >
+ {quarantining === f.file ? 'Moving…' : 'Quarantine'}
+ </Button>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ )}
+
<div className="card sec-flush">
<div className="card-header">
<h3>Scan History</h3>
diff --git a/frontend/src/services/api/security.js b/frontend/src/services/api/security.js
index ae5f3332..287c8116 100644
--- a/frontend/src/services/api/security.js
+++ b/frontend/src/services/api/security.js
@@ -223,6 +223,36 @@ export async function runFullScan() {
return this.request('/security/scan/full', { method: 'POST' });
}
+export async function scanApp(appId) {
+ // Job-backed malware scan (YARA + ClamAV) of an app's docroot → { job_id }
+ return this.request(`/security/scan/app/${appId}`, { method: 'POST' });
+}
+
+export async function scanPathJob(path) {
+ return this.request('/security/scan/job', {
+ method: 'POST',
+ body: { path }
+ });
+}
+
+// YARA web-shell rules
+export async function getYaraRules() {
+ return this.request('/security/yara/rules');
+}
+
+export async function uploadYaraRule(filename, content) {
+ return this.request('/security/yara/rules', {
+ method: 'POST',
+ body: { filename, content }
+ });
+}
+
+export async function deleteYaraRule(filename) {
+ return this.request(`/security/yara/rules/${encodeURIComponent(filename)}`, {
+ method: 'DELETE'
+ });
+}
+
export async function getQuarantinedFiles() {
return this.request('/security/quarantine');
}
@@ -240,6 +270,12 @@ export async function deleteQuarantinedFile(filename) {
});
}
+export async function restoreQuarantinedFile(filename) {
+ return this.request(`/security/quarantine/${encodeURIComponent(filename)}/restore`, {
+ method: 'POST'
+ });
+}
+
export async function initializeIntegrityDatabase(paths = null) {
return this.request('/security/integrity/initialize', {
method: 'POST',
diff --git a/frontend/src/styles/pages/_security.scss b/frontend/src/styles/pages/_security.scss
index ba557ca5..335e0c29 100644
--- a/frontend/src/styles/pages/_security.scss
+++ b/frontend/src/styles/pages/_security.scss
@@ -100,6 +100,13 @@
.sk-info-row .v.sec-v-amber { color: var(--amber); }
}
+ // Left-aligned "what changed" chip cluster inside a table cell (FIM)
+ .sec-what {
+ display: inline-flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ }
+
// Right-aligned chip cluster inside an info row (jail tags…)
.sec-chiprow {
display: flex;
@@ -401,9 +408,13 @@
.scanner-tab {
.scan-options {
display: grid;
- grid-template-columns: repeat(3, 1fr);
+ grid-template-columns: repeat(4, 1fr);
gap: $space-4;
+ @media (max-width: $breakpoint-lg) {
+ grid-template-columns: repeat(2, 1fr);
+ }
+
@media (max-width: $breakpoint-md) {
grid-template-columns: 1fr;
}
@@ -456,8 +467,10 @@
.scan-card--quick .scan-card-icon { background: var(--accent-bg); color: var(--accent-bright); }
.scan-card--full .scan-card-icon { background: var(--violet-bg); color: var(--violet); }
.scan-card--custom .scan-card-icon { background: var(--cyan-bg); color: var(--cyan); }
+ .scan-card--app .scan-card-icon { background: var(--amber-bg); color: var(--amber); }
- .scan-card--custom {
+ .scan-card--custom,
+ .scan-card--app {
cursor: default;
&:hover {
@@ -478,9 +491,62 @@
}
}
+ // App selector inside the "Scan an App" card — matches Input chrome
+ .scan-app-select {
+ flex: 1;
+ min-width: 0;
+ padding: 0 $space-2;
+ height: 32px;
+ background: var(--surface-2);
+ border: 1px solid var(--border-soft);
+ border-radius: var(--radius-sm);
+ color: var(--text);
+ font-size: 12.5px;
+
+ &:focus {
+ outline: none;
+ border-color: var(--accent-dim);
+ }
+ }
+
.scan-toolbar {
display: flex;
justify-content: flex-end;
+ gap: $space-2;
+ }
+
+ // Findings table (YARA + ClamAV merged report)
+ .scan-findings {
+ border-color: rgba(240, 82, 82, 0.35);
+
+ .scan-snippet {
+ max-width: 260px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-size: 11px;
+ color: var(--text-faint);
+ }
+ }
+
+ // Web-shell rules manager card
+ .yara-file-input { display: none; }
+
+ .yara-custom-list {
+ display: flex;
+ flex-direction: column;
+ }
+
+ .yara-custom-item {
+ display: flex;
+ align-items: center;
+ gap: $space-3;
+ padding: 8px 0;
+ border-top: 1px solid var(--border-soft);
+
+ &:first-child { border-top: none; }
+
+ > .sec-mono:first-child { flex: 1; min-width: 0; }
}
}
@@ -510,6 +576,11 @@
// ── Quarantine tab ───────────────────────────────────────────
.quarantine-tab {
.empty-state svg { color: var(--green); }
+
+ .quarantine-actions {
+ display: flex;
+ gap: $space-2;
+ }
}
// ── Integrity tab ────────────────────────────────────────────