mirror of
https://github.com/jhd3197/ServerKit.git
synced 2026-12-01 12:45:10 +09:00
Malware scans run as jobs and can target an app's docroot; a curated web-shell rule set (yara CLI when present, pure-Python fallback) runs alongside ClamAV with custom .yar upload; quarantine gains restore via original-path metadata. Note: api/security.py also carries the FIM routes of the next commit. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
254 lines
10 KiB
Python
254 lines
10 KiB
Python
"""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'
|
|
|
|
|
|
@pytest.fixture(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
|
|
|
|
|
|
@pytest.fixture
|
|
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
|
|
|
|
|
|
@pytest.fixture
|
|
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)
|