-
Notifications
You must be signed in to change notification settings - Fork 251
Expand file tree
/
Copy pathexecutor.py
More file actions
1986 lines (1794 loc) · 77.2 KB
/
Copy pathexecutor.py
File metadata and controls
1986 lines (1794 loc) · 77.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Task execution engine with Docker sandboxing
"""
import asyncio
from asyncio import subprocess
import os
import signal
import base64
import uuid
import json
import time
from pathlib import Path
from datetime import datetime, timezone
from typing import Optional, Dict, Any, List, Tuple
import logging
import re
_CANCEL_GRACE_SECONDS = 5
from .auth import DEFAULT_OWNER_ID
from .redaction import redact
from .cache import get_cache
from .config import settings
from .database import get_db
from .executor_target_helpers import extract_target
from .plugins import get_plugin_manager
from .models import NotificationDeliveryStatus, TaskStatus, ScanPhase
from .ratelimit import concurrent_limiter
from .risk_scoring import compute_risk_score, compute_risk_factors
from .time_utils import to_utc_iso
from .capabilities import CapabilityEnforcer, CapabilityDeniedError, build_enforcer_from_settings
from .parser_sandbox import run_parser_in_sandbox, ParserSandboxError
from .network_policy import get_policy_engine
from .notification_service import process_task_notifications
from .execution_context import is_offensive_validation, normalize_execution_context
from .finding_intelligence import (
build_asset_summary,
build_finding_groups,
build_scan_diff,
normalize_and_correlate_findings,
)
from .platform_resources import (
get_credential_profile,
get_session_profile,
get_target_policy,
persist_crawl_run,
replace_asset_services,
serialize_execution_context,
)
from .vault import VaultCrypto
async def _terminate_process_group(pid: int, task_id: str, grace_seconds: int = _CANCEL_GRACE_SECONDS) -> None:
"""Send SIGTERM to the process group of *pid*, wait *grace_seconds*, then SIGKILL.
Using a process group (via start_new_session=True on subprocess creation)
ensures every child and grandchild spawned by the scanner receives the
signal, leaving no orphan processes after cancellation or timeout.
Errors are logged but never re-raised so callers can always proceed to
update task status regardless of OS-level kill failures.
"""
try:
pgid = os.getpgid(pid)
except (ProcessLookupError, PermissionError) as exc:
logger.debug("process group for pid %d already gone: %s", pid, exc)
return
try:
os.killpg(pgid, signal.SIGTERM)
except (ProcessLookupError, PermissionError) as exc:
logger.debug("SIGTERM to pgid %d failed (already exited?): %s", pgid, exc)
return
for _ in range(grace_seconds * 10):
await asyncio.sleep(0.1)
try:
os.killpg(pgid, 0)
except (ProcessLookupError, PermissionError) as exc:
logger.debug("pgid %d already exited during grace poll: %s", pgid, exc)
return
try:
os.killpg(pgid, signal.SIGKILL)
logger.warning(
"process group %d did not exit within %ds grace — SIGKILL sent (task %s)",
pgid, grace_seconds, task_id,
)
except (ProcessLookupError, PermissionError) as exc:
logger.debug("SIGKILL to pgid %d failed: %s", pgid, exc)
def _parse_discovered_at(finding: dict) -> Optional[datetime]:
"""Extract and parse discovered_at from a finding dict as timezone-aware UTC."""
from .time_utils import parse_to_utc, utc_now
parsed = parse_to_utc(finding.get("discovered_at"))
return parsed if parsed is not None else utc_now()
def _validate_risk_fields(finding: dict) -> None:
"""Validate exploitability, confidence, and asset_exposure bounds in-place."""
exp = finding.get("exploitability")
if exp is not None:
if not isinstance(exp, (int, float)):
raise ValueError(f"exploitability must be numeric, got {type(exp).__name__}")
if exp < 0 or exp > 10:
raise ValueError(f"exploitability must be in [0, 10], got {exp}")
conf = finding.get("confidence")
if conf is not None:
if not isinstance(conf, (int, float)):
raise ValueError(f"confidence must be numeric, got {type(conf).__name__}")
if conf < 0 or conf > 1:
raise ValueError(f"confidence must be in [0, 1], got {conf}")
ae = finding.get("asset_exposure")
if ae is not None and ae.lower() not in ("critical", "high", "medium", "low"):
raise ValueError(f"asset_exposure must be one of critical/high/medium/low, got {ae}")
# Modular Scanners
from .scanners.port_scanner import PortScanner
from .scanners.web_scanner import WebScanner
from .scanners.recon_scanner import ReconScanner
from .scanners.network_vulnerability_scanner import NetworkVulnerabilityScanner
from .scanners.api_scanner import APIScanner
from .scanners.zap_scanner import ZAPScanner
from .scanners.xss_validation_scanner import XSSValidationScanner
MODULAR_SCANNERS = {
"port_scanner": PortScanner,
"web_scanner": WebScanner,
"recon_scanner": ReconScanner,
"network_scanner": NetworkVulnerabilityScanner,
"api_scanner": APIScanner,
"zap_scanner": ZAPScanner,
"xss_exploiter": XSSValidationScanner,
}
logger = logging.getLogger(__name__)
STREAM_LISTENER_QUEUE_MAXSIZE = 100
def _stable_asset_id(target: str, host: Any, port: Any, protocol: Any) -> str:
material = "||".join(
[
str(target or "").strip().lower(),
str(host or "").strip().lower(),
str(port or "").strip().lower(),
str(protocol or "").strip().lower(),
]
)
return f"asset:{uuid.uuid5(uuid.NAMESPACE_URL, material).hex[:16]}"
def _row_value(row: Any, key: str, default: Any = None) -> Any:
"""Read a dict/sqlite row key with a default for backward-compatible mocks."""
if row is None:
return default
if isinstance(row, dict):
return row.get(key, default)
try:
return row[key]
except (KeyError, IndexError, TypeError):
return default
class TaskExecutor:
"""Executes security scanning tasks in isolated environments"""
def __init__(self):
self.running_tasks: Dict[str, asyncio.Task] = {}
self._process_pids: Dict[str, int] = {}
# PubSub: Map of task_id to list of active async queues listening for output/status updates
self._listeners: Dict[str, List[asyncio.Queue]] = {}
self._capability_enforcer: CapabilityEnforcer = build_enforcer_from_settings()
def subscribe(self, task_id: str) -> asyncio.Queue:
"""Subscribe to a task's real-time events."""
if task_id not in self._listeners:
self._listeners[task_id] = []
q = asyncio.Queue(maxsize=STREAM_LISTENER_QUEUE_MAXSIZE)
self._listeners[task_id].append(q)
return q
def unsubscribe(self, task_id: str, q: asyncio.Queue):
"""Unsubscribe from a task's real-time events."""
if task_id in self._listeners and q in self._listeners[task_id]:
self._listeners[task_id].remove(q)
if not self._listeners[task_id]:
self._listeners.pop(task_id, None)
async def _broadcast(self, task_id: str, event_type: str, data: Any):
"""Broadcast an event to all active listeners of a task."""
if task_id in self._listeners:
event = {"type": event_type, "data": data}
for q in list(self._listeners[task_id]):
self._enqueue_listener_event(task_id, q, event)
def _enqueue_listener_event(self, task_id: str, q: asyncio.Queue, event: Dict[str, Any]):
"""Add an event to a bounded listener queue without unbounded memory growth."""
try:
q.put_nowait(event)
return
except asyncio.QueueFull:
try:
q.get_nowait()
except asyncio.QueueEmpty:
pass
try:
q.put_nowait(event)
except asyncio.QueueFull:
logger.warning("Dropping stream event for slow listener on task %s", task_id)
def _cleanup_listeners(self, task_id: str):
"""Remove all listener queues for a completed task to prevent memory leaks."""
if task_id in self._listeners:
self._listeners.pop(task_id, None)
async def _broadcast_phase(self, task_id: str, phase: str):
"""Broadcast a scan phase transition and persist it to the database."""
await self._broadcast(task_id, "phase", phase)
db = await get_db()
now = datetime.now(timezone.utc).isoformat()
await db.execute(
"""
UPDATE tasks
SET scan_phase = ?,
phase_timestamps_json = json_set(
phase_timestamps_json,
'$.' || COALESCE(scan_phase, 'unknown') || '.completed_at', ?,
'$.' || ? || '.started_at', ?
)
WHERE id = ?
""",
(phase, now, phase, now, task_id)
)
async def create_task(
self,
plugin_id: str,
inputs: Dict[str, Any],
safe_mode: bool,
preset: Optional[str] = None,
execution_context: Optional[Dict[str, Any]] = None,
consent_granted: bool = False,
owner_id: str = DEFAULT_OWNER_ID,
) -> str:
"""
Create a new scan task.
Args:
plugin_id: Plugin identifier
inputs: User input values
preset: Optional preset name
consent_granted: Whether user granted consent
owner_id: Owning user/workspace identity used to scope later
access (issue #401). Defaults to the shared default owner for
internal callers (workflows, scheduler, CLI) that are not tied
to a request.
Returns:
Task ID
"""
task_id = str(uuid.uuid4())
plugin_manager = get_plugin_manager()
plugin = plugin_manager.get_plugin(plugin_id)
if not plugin:
raise ValueError(f"Plugin not found: {plugin_id}")
# Apply preset if provided
if preset and preset in plugin.presets:
preset_values = plugin.presets[preset]
# Merge preset with user inputs (user inputs take precedence)
inputs = {**preset_values, **inputs}
# Store task in database
db = await get_db()
await db.execute(
"""
INSERT INTO tasks (
id, owner_id, plugin_id, tool_name, target, inputs_json, preset,
execution_context_json, status, scan_phase, phase_timestamps_json, consent_granted, safe_mode
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
task_id,
owner_id,
plugin_id,
plugin.name,
extract_target(inputs),
json.dumps(inputs),
preset,
serialize_execution_context(execution_context),
TaskStatus.QUEUED.value,
ScanPhase.QUEUED.value,
json.dumps({ScanPhase.QUEUED.value: {"started_at": datetime.now(timezone.utc).isoformat()}}),
consent_granted,
bool(safe_mode)
)
)
# Log audit event
await db.log_audit(
"task_created",
f"Task created for {plugin.name}",
context={
"task_id": task_id,
"plugin_id": plugin_id,
"target": inputs.get("target"),
"execution_context": normalize_execution_context(execution_context),
},
task_id=task_id,
plugin_id=plugin_id
)
return task_id
async def mark_task_failed(self, task_id: str, reason: str) -> None:
"""
Mark a task as failed without running it.
Used to roll back a created-but-unscheduled task record.
Args:
task_id: Task identifier
reason: Human-readable failure reason stored as error_message
"""
db = await get_db()
await db.execute(
"""
UPDATE tasks SET
status = ?,
completed_at = ?,
duration_seconds = ?,
error_message = ?
WHERE id = ?
""",
(
TaskStatus.FAILED.value,
datetime.now().isoformat(),
0,
reason,
task_id,
)
)
await db.log_audit(
"task_failed",
f"Task rejected before execution: {reason}",
severity="warning",
context={"task_id": task_id, "reason": reason},
task_id=task_id,
)
async def _enforce_guardrails(
self,
target: str,
plugin_id: str,
safe_mode: bool,
task_id: str,
) -> Tuple[bool, Optional[str]]:
"""Enforce Safe Mode target validation and Network Policy access checks.
Returns:
Tuple of (all_checks_pass, pinned_ip).
pinned_ip is set when network policy is enforced and the target
hostname was resolved to a stable IP, preventing DNS rebinding attacks.
"""
if not target:
return (True, None)
plugin_manager = get_plugin_manager()
plugin = plugin_manager.get_plugin(plugin_id)
should_validate = True
if plugin and plugin.category == "code":
should_validate = False
# Use shared is_filesystem_target from validation to ensure
# consistent filesystem detection across route and executor layers.
from .validation import is_filesystem_target
is_fs = is_filesystem_target(target)
if should_validate and not is_fs:
from .validation import validate_target
try:
# Enforce safe mode validation of target address in a thread pool
is_valid, error_msg = await asyncio.wait_for(
asyncio.to_thread(validate_target, target, safe_mode),
timeout=float(settings.dns_resolution_timeout_seconds),
)
if not is_valid:
await self.mark_task_failed(
task_id,
f"Safe mode target validation failed: {error_msg}",
)
await self._broadcast(task_id, "status", TaskStatus.FAILED.value)
return (False, None)
except asyncio.TimeoutError:
await self.mark_task_failed(
task_id,
"Target validation timed out (SecuScan Guardrail)",
)
await self._broadcast(task_id, "status", TaskStatus.FAILED.value)
return (False, None)
# Check before launching any scanner or subprocess. Uses resolve_and_pin
# to resolve the hostname ONCE and pin the IP, preventing DNS rebinding
# attacks where the scanner subprocess resolves a different (malicious) IP.
if settings.enforce_network_policy:
engine = get_policy_engine()
try:
pinned_ip, allowed, reason = await asyncio.wait_for(
asyncio.to_thread(
engine.resolve_and_pin,
target,
plugin_id,
task_id,
),
timeout=float(settings.dns_resolution_timeout_seconds),
)
except asyncio.TimeoutError:
allowed, reason, pinned_ip = False, "Network policy check timed out (DNS resolution timeout)", None
if not allowed:
if settings.network_policy_failure_mode == "log_only":
logger.warning(
f"[Log Only] Network policy violation allowed for {target}: {reason}"
)
else:
await self.mark_task_failed(
task_id,
f"Network policy denied access to {target}: {reason}",
)
await self._broadcast(task_id, "status", TaskStatus.FAILED.value)
return (False, None)
return (True, pinned_ip)
return (True, None)
async def _ensure_docker_network(self) -> None:
"""Validate and automatically create the configured Docker network if missing."""
_net_check = await asyncio.create_subprocess_exec(
"docker", "network", "inspect", settings.docker_network,
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.DEVNULL,
)
await _net_check.wait()
if _net_check.returncode == 0:
return
logger.info(f"Docker network '{settings.docker_network}' not found. Creating isolated bridge network (ICC disabled)...")
_net_create = await asyncio.create_subprocess_exec(
"docker", "network", "create",
"--driver", "bridge",
"--opt", "com.docker.network.bridge.enable_icc=false",
settings.docker_network,
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.DEVNULL,
)
await _net_create.wait()
if _net_create.returncode == 0:
logger.info(f"Successfully created Docker network '{settings.docker_network}' with ICC disabled")
return
logger.warning("Failed to create isolated bridge network with ICC disabled. Falling back to standard bridge...")
_net_create_fallback = await asyncio.create_subprocess_exec(
"docker", "network", "create", "--driver", "bridge", settings.docker_network,
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.DEVNULL,
)
await _net_create_fallback.wait()
if _net_create_fallback.returncode != 0:
raise RuntimeError(
f"Docker network '{settings.docker_network}' does not exist and could not be created automatically."
)
logger.info(f"Successfully created Docker network '{settings.docker_network}' (fallback)")
async def _execute_modular_scanner(
self,
db,
task_id: str,
owner_id: str,
plugin_id: str,
target: str,
inputs: Dict[str, Any],
safe_mode: bool,
) -> tuple[str, float]:
"""Execute a modular scanner and persist findings/report."""
scanner_class = MODULAR_SCANNERS[plugin_id]
scanner = scanner_class(task_id, db, safe_mode=safe_mode)
logger.info(f"Executing modular scanner {plugin_id} for task {task_id}")
await self._broadcast(task_id, "status", TaskStatus.RUNNING.value)
await self._broadcast_phase(task_id, ScanPhase.RUNNING_COMMAND.value)
start_time = time.time()
result = await scanner.run(target, inputs)
duration = time.time() - start_time
final_status = (
TaskStatus.COMPLETED.value
if result.get("status") != "failed"
else TaskStatus.FAILED.value
)
await db.execute(
"""
UPDATE tasks SET
status = ?,
completed_at = ?,
duration_seconds = ?,
structured_json = ?,
error_message = ?
WHERE id = ?
""",
(
final_status,
datetime.now().isoformat(),
duration,
json.dumps(result),
result.get("error_message"),
task_id,
),
)
await self._broadcast_phase(task_id, ScanPhase.PARSING.value)
await self._upsert_findings_and_report_from_scanner(
db=db,
task_id=task_id,
owner_id=owner_id,
scanner=scanner,
plugin_id=plugin_id,
target=target,
status=final_status,
result=result,
)
await self._broadcast_phase(task_id, ScanPhase.REPORTING.value)
return final_status, duration
async def _execute_standard_scanner(
self,
db,
task_id: str,
owner_id: str,
plugin: Any,
plugin_id: str,
target: str,
inputs: Dict[str, Any],
safe_mode: bool,
) -> tuple[str, float, int]:
"""Execute a standard CLI/Docker plugin and persist findings/report."""
plugin_manager = get_plugin_manager()
command = plugin_manager.build_command(plugin_id, inputs)
if not command:
raise ValueError("Failed to build command")
from .validation import validate_command_network_egress
cmd_valid, cmd_err = validate_command_network_egress(
command, safe_mode, plugin_id, task_id
)
if not cmd_valid:
raise ValueError(f"Command network egress validation failed: {cmd_err}")
# Apply Docker Sandboxing if enabled
if settings.docker_enabled:
await self._ensure_docker_network()
docker_image = plugin.docker_image or "alpine:latest"
docker_cmd = [
"docker",
"run",
"--rm",
"--name",
f"secuscan_task_{task_id}",
"--memory",
f"{settings.sandbox_memory_mb}m",
"--cpus",
str(settings.sandbox_cpu_quota),
"--cap-drop", "NET_RAW",
"--network", settings.docker_network,
docker_image,
]
command = docker_cmd + command
logger.info(f"Executing task {task_id}: {' '.join(command)}")
await self._broadcast(task_id, "status", TaskStatus.RUNNING.value)
await self._broadcast_phase(task_id, ScanPhase.RUNNING_COMMAND.value)
# Execute command
start_time = time.time()
output, exit_code = await self._execute_command(
command,
task_id,
timeout=self._resolve_execution_timeout(inputs),
)
duration = time.time() - start_time
# Save raw output
raw_path = Path(settings.raw_output_dir) / f"{task_id}.txt"
output = redact(output)
with open(raw_path, 'w') as f:
f.write(output)
# Classify result
final_status, error_message = self._classify_command_result(
plugin=plugin,
output=output,
exit_code=exit_code,
)
await db.execute(
"""
UPDATE tasks SET
status = ?,
completed_at = ?,
duration_seconds = ?,
exit_code = ?,
raw_output_path = ?,
command_used = ?,
error_message = ?
WHERE id = ?
""",
(
final_status,
datetime.now().isoformat(),
duration,
exit_code,
str(raw_path),
" ".join(command),
error_message,
task_id,
),
)
# Upsert findings and report
await self._broadcast_phase(task_id, ScanPhase.PARSING.value)
await self._upsert_findings_and_report(
db=db,
task_id=task_id,
owner_id=owner_id,
plugin=plugin,
plugin_id=plugin_id,
target=target,
status=final_status,
output=output,
)
await self._broadcast_phase(task_id, ScanPhase.REPORTING.value)
return final_status, duration, exit_code
async def execute_task(self, task_id: str) -> None:
"""
Execute a task asynchronously.
Args:
task_id: Task identifier
"""
db = await get_db()
self.running_tasks[task_id] = asyncio.current_task()
start_time = time.time()
try:
# Update status to running — use optimistic lock to detect
# if the task was deleted or already running before this point.
result = await db.execute(
"UPDATE tasks SET status = ?, started_at = ? WHERE id = ? AND status = ?",
(TaskStatus.RUNNING.value, datetime.now().isoformat(), task_id, TaskStatus.QUEUED.value)
)
if result.rowcount == 0:
logger.warning(f"Task {task_id} was deleted or no longer queued before execution started. Aborting.")
self.running_tasks.pop(task_id, None)
return
await self._invalidate_cached_views()
# Get task details
task_row = await db.fetchone(
"SELECT owner_id, plugin_id, inputs_json, execution_context_json, safe_mode FROM tasks WHERE id = ?",
(task_id,)
)
if not task_row:
raise ValueError(f"Task not found: {task_id}")
owner_id = task_row["owner_id"]
plugin_id = task_row["plugin_id"]
inputs = json.loads(task_row["inputs_json"])
execution_context = normalize_execution_context(
json.loads(task_row["execution_context_json"] or "{}")
)
safe_mode = bool(task_row["safe_mode"])
target = extract_target(inputs)
inputs = await self._hydrate_inputs_with_execution_context(
db=db,
owner_id=owner_id,
inputs=inputs,
execution_context=execution_context,
)
# ── Safe Mode & Network policy enforcement ───────────────────────
guardrails_ok, pinned_ip = await self._enforce_guardrails(target, plugin_id, safe_mode, task_id)
if not guardrails_ok:
return
if pinned_ip:
inputs["__pinned_ip"] = pinned_ip
# Check if this is a modular scanner or a standard plugin
plugin_manager = get_plugin_manager()
plugin = plugin_manager.get_plugin(plugin_id)
if not plugin:
raise ValueError(f"Plugin not found: {plugin_id}")
self._capability_enforcer.check(
plugin_id=plugin.id,
declared=plugin.capabilities,
safety_level=plugin.safety.get("level", "safe"),
)
if plugin.safety.get("level") == "exploit" and not is_offensive_validation(execution_context):
raise ValueError(
"Exploit-level plugins require an execution context with validation_mode set to 'proof' or 'controlled_extract'."
)
if plugin_id in MODULAR_SCANNERS:
final_status, duration = await self._execute_modular_scanner(
db=db,
task_id=task_id,
owner_id=owner_id,
plugin_id=plugin_id,
target=target,
inputs=inputs,
safe_mode=safe_mode,
)
exit_code = 0
else:
final_status, duration, exit_code = await self._execute_standard_scanner(
db=db,
task_id=task_id,
owner_id=owner_id,
plugin=plugin,
plugin_id=plugin_id,
target=target,
inputs=inputs,
safe_mode=safe_mode,
)
await self._dispatch_task_notifications(db, task_id)
await self._broadcast_phase(task_id, ScanPhase.FINISHED.value)
await self._broadcast(task_id, "status", final_status)
await self._invalidate_cached_views()
# Log completion
await db.log_audit(
"task_completed",
f"Task completed in {duration:.2f}s",
context={"task_id": task_id, "exit_code": exit_code},
task_id=task_id,
plugin_id=plugin_id
)
logger.info(f"Task {task_id} completed in {duration:.2f}s")
except asyncio.CancelledError:
duration = (time.time() - start_time) if 'start_time' in locals() else 0
await db.execute(
"""
UPDATE tasks SET
status = ?,
completed_at = ?,
duration_seconds = ?
WHERE id = ? AND status = ?
""",
(
TaskStatus.CANCELLED.value,
datetime.now().isoformat(),
duration,
task_id,
TaskStatus.RUNNING.value,
)
)
await self._broadcast(task_id, "status", TaskStatus.CANCELLED.value)
await self._invalidate_cached_views()
raise # let asyncio complete the cancellation
except CapabilityDeniedError as e:
logger.warning("Task %s blocked by capability policy: %s", task_id, e)
duration = (time.time() - start_time) if "start_time" in locals() else 0
await db.execute(
"""
UPDATE tasks SET
status = ?,
completed_at = ?,
duration_seconds = ?,
error_message = ?
WHERE id = ?
""",
(
TaskStatus.FAILED.value,
datetime.now().isoformat(),
duration,
str(e),
task_id,
),
)
await self._broadcast(task_id, "status", TaskStatus.FAILED.value)
await self._invalidate_cached_views()
await db.log_audit(
"task_capability_denied",
f"Task blocked by capability policy: {str(e)}",
severity="warning",
context={
"task_id": task_id,
"denied_capabilities": sorted(e.denied_capabilities),
"plugin_id": plugin_id,
},
task_id=task_id,
)
await self._dispatch_task_notifications(db, task_id)
except Exception as e:
logger.error(f"Task {task_id} failed: {e}", exc_info=True)
duration = (time.time() - start_time) if 'start_time' in locals() else 0
safe_error = redact(str(e))
await db.execute(
"""
UPDATE tasks SET
status = ?,
completed_at = ?,
duration_seconds = ?,
error_message = ?
WHERE id = ?
""",
(
TaskStatus.FAILED.value,
datetime.now().isoformat(),
duration,
safe_error,
task_id
)
)
await self._broadcast(task_id, "status", TaskStatus.FAILED.value)
await self._invalidate_cached_views()
await db.log_audit(
"task_failed",
f"Task failed: {safe_error}",
severity="error",
context={"task_id": task_id, "error": safe_error},
task_id=task_id
)
await self._dispatch_task_notifications(db, task_id)
finally:
self.running_tasks.pop(task_id, None)
self._process_pids.pop(task_id, None)
await concurrent_limiter.release(task_id)
self._cleanup_listeners(task_id)
async def _execute_command(
self,
command: list,
task_id: str,
timeout: int = 600
) -> tuple:
"""
Execute command in subprocess and stream output.
Args:
command: Command as list
task_id: Task identifier for logging
timeout: Execution timeout in seconds
Returns:
Tuple of (output, exit_code)
"""
try:
process = await asyncio.create_subprocess_exec(
*command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
start_new_session=True,
)
self._process_pids[task_id] = process.pid
output_lines = []
async def read_stream():
stdout = process.stdout
if stdout is None:
return
while not stdout.at_eof():
line = await stdout.readline()
if line:
decoded_line = line.decode("utf-8", errors="replace")
output_lines.append(decoded_line)
await self._broadcast(task_id, "output", decoded_line)
try:
await asyncio.wait_for(read_stream(), timeout=timeout)
await process.wait()
self._process_pids.pop(task_id, None)
return "".join(output_lines), process.returncode if process.returncode is not None else -1
except asyncio.TimeoutError:
logger.warning(
"Task %s timed out after %ds — terminating process group (pid=%d)",
task_id, timeout, process.pid,
)
await _terminate_process_group(process.pid, task_id)
try:
await asyncio.wait_for(process.wait(), timeout=3)
except asyncio.TimeoutError:
pass
self._process_pids.pop(task_id, None)
return "".join(output_lines) + "\nTask timed out", -1
except asyncio.CancelledError:
logger.warning(
"Task %s cancelled — terminating process group (pid=%d)",
task_id, process.pid,
)
await _terminate_process_group(process.pid, task_id)
try:
await asyncio.wait_for(process.wait(), timeout=3)
except asyncio.TimeoutError:
pass
self._process_pids.pop(task_id, None)
raise
except asyncio.CancelledError:
self._process_pids.pop(task_id, None)
raise
except Exception as e:
self._process_pids.pop(task_id, None)
logger.error(f"Failed to execute command: {e}")
return f"Execution error: {str(e)}", -1
def _resolve_execution_timeout(self, inputs: Dict[str, Any]) -> int:
"""Resolve per-task process timeout from plugin inputs.
The caller may request a shorter timeout than the operator cap, but
never a longer one. ``settings.sandbox_timeout`` is the hard ceiling
and is always enforced regardless of what the client supplies.
"""
for key in ("max_scan_time", "timeout"):
raw_value = inputs.get(key)
try:
timeout = int(raw_value)
except (TypeError, ValueError):
continue
if timeout > 0:
return min(timeout, settings.sandbox_timeout)
return settings.sandbox_timeout
def _classify_command_result(self, plugin, output: str, exit_code: int) -> tuple[str, Optional[str]]:
"""Map raw process exit codes into task status with plugin-specific tolerances."""
normalized_output = output.lower()
if "unknown option:" in normalized_output or "flag provided but not defined:" in normalized_output:
return (
TaskStatus.FAILED.value,
output or "Tool rejected one or more generated CLI options. Check the final command and raw output for details.",
)
if exit_code == 0:
return TaskStatus.COMPLETED.value, None
output_config = plugin.output if isinstance(plugin.output, dict) else {}
tolerated_exit_codes = output_config.get("nonfatal_exit_codes", [])
success_patterns = output_config.get("success_output_patterns", [])
try:
tolerated = {int(code) for code in tolerated_exit_codes}
except (TypeError, ValueError):
tolerated = set()
matched_success_pattern = any(
isinstance(pattern, str) and pattern.lower() in normalized_output
for pattern in success_patterns
)
if exit_code in tolerated and matched_success_pattern:
logger.info(
"Treating exit code %s from %s as completed due to matching success output",
exit_code,
plugin.id,
)
return TaskStatus.COMPLETED.value, None
return (
TaskStatus.FAILED.value,
f"Tool returned non-zero exit code {exit_code}. Check raw output for details.",
)
async def cancel_task(self, task_id: str) -> bool:
"""
Cancel a running task.
Args: