-
Notifications
You must be signed in to change notification settings - Fork 371
Expand file tree
/
Copy pathraptor.py
More file actions
executable file
·436 lines (349 loc) · 14.4 KB
/
raptor.py
File metadata and controls
executable file
·436 lines (349 loc) · 14.4 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
#!/usr/bin/env python3
"""
RAPTOR - Unified Security Testing Launcher
Single entry point for all RAPTOR capabilities:
- Static analysis (Semgrep + CodeQL)
- Binary fuzzing (AFL++)
- Web application scanning
- Autonomous LLM-powered analysis
- And more...
Usage:
raptor.py <mode> [options]
Available Modes:
scan - Static code analysis (Semgrep + CodeQL)
fuzz - Binary fuzzing with AFL++
web - Web application security testing
agentic - Full autonomous workflow
codeql - CodeQL-only analysis
help - Show detailed help for a specific mode
Examples:
# Full autonomous workflow
python3 raptor.py agentic --repo /path/to/code
# Static analysis only
python3 raptor.py scan --repo /path/to/code --policy-groups secrets,owasp
# Binary fuzzing
python3 raptor.py fuzz --binary /path/to/binary --duration 3600
# Web scanning
python3 raptor.py web --url https://example.com
# CodeQL analysis
python3 raptor.py codeql --repo /path/to/code --languages java
"""
import argparse
import subprocess
import sys
from pathlib import Path
from core.run.output import get_output_dir, TargetMismatchError
from core.run.metadata import start_run, complete_run, fail_run
def _extract_target(args: list) -> str | None:
"""Extract the target path from command args (--repo, --binary, or --url)."""
for flag in ("--repo", "--binary", "--url"):
if flag in args:
idx = args.index(flag)
if idx + 1 < len(args):
return args[idx + 1]
return None
def _run_with_lifecycle(command: str, script_path: Path, args: list,
label: str) -> int:
"""Run a script with lifecycle start/complete/fail wrapping.
Resolves the output directory via the run lifecycle, injects --out
into the downstream script args, and marks the run complete or failed.
"""
target = _extract_target(args)
try:
out_dir = get_output_dir(command, target_path=target)
except TargetMismatchError as e:
print(f"✗ {e}", file=sys.stderr)
return 1
start_run(out_dir, command, target=target)
# SAGE: Pre-scan recall
try:
from core.sage.hooks import recall_context_for_scan
sage_context = recall_context_for_scan(target or "")
if sage_context:
print(f"📚 SAGE: Recalled {len(sage_context)} historical memories")
for mem in sage_context[:3]:
print(f" [{mem['confidence']:.0%}] {mem['content'][:80]}...")
except Exception:
pass
# Inject --out so the downstream script uses the lifecycle directory
if "--out" not in args:
args = args + ["--out", str(out_dir)]
print(f"\n[*] {label}\n")
rc = _run_script(script_path, args)
# Write coverage records from tool outputs (before lifecycle complete)
try:
from core.coverage.record import (
build_from_semgrep, build_from_codeql, write_record,
)
if not (out_dir / "coverage-semgrep.json").exists():
for json_path in out_dir.glob("semgrep_*.json"):
record = build_from_semgrep(out_dir, json_path)
if record:
write_record(out_dir, record, tool_name="semgrep")
break
if not (out_dir / "coverage-codeql.json").exists():
for sarif_path in out_dir.glob("codeql_*.sarif"):
record = build_from_codeql(sarif_path)
if record:
write_record(out_dir, record, tool_name="codeql")
break
except Exception:
pass
# SAGE: Post-scan storage
if rc == 0:
try:
from core.sage.hooks import store_scan_results
import json
# Try to find and store SARIF results
sarif_files = list(out_dir.glob("*.sarif")) + list(out_dir.glob("**/*.sarif"))
findings = []
for sf in sarif_files:
try:
sarif = json.loads(sf.read_text())
for run in sarif.get("runs", []):
for result in run.get("results", []):
findings.append({
"rule_id": result.get("ruleId", "unknown"),
"level": result.get("level", "warning"),
"message": result.get("message", {}).get("text", ""),
"file_path": (result.get("locations", [{}])[0]
.get("physicalLocation", {})
.get("artifactLocation", {})
.get("uri", "unknown")),
})
except Exception:
continue
if findings:
stored = store_scan_results(target or "", findings, {"total_findings": len(findings)})
if stored > 0:
print(f"\n📚 SAGE: Stored {stored} findings for cross-run learning")
except Exception:
pass
if rc == 0:
complete_run(out_dir)
else:
fail_run(out_dir, error=f"exit code {rc}")
return rc
def _run_script(script_path: Path, args: list) -> int:
"""
Run a RAPTOR script with given arguments.
Args:
script_path: Path to the Python script to run
args: Command-line arguments to pass to the script
Returns:
Exit code from the script
"""
cmd = [sys.executable, str(script_path)] + args
try:
from core.config import RaptorConfig
result = subprocess.run(cmd, env=RaptorConfig.get_safe_env())
return result.returncode
except KeyboardInterrupt:
print("\n\nInterrupted by user")
return 130
except Exception as e:
print(f"\n✗ Error running {script_path.name}: {e}")
return 1
def mode_scan(args: list) -> int:
"""Run static code analysis (Semgrep)."""
script_root = Path(__file__).parent
scanner_script = script_root / "packages/static-analysis/scanner.py"
if not scanner_script.exists():
print(f"✗ Scanner not found: {scanner_script}")
return 1
return _run_with_lifecycle("scan", scanner_script, args,
"Running static analysis with Semgrep...")
def mode_fuzz(args: list) -> int:
"""Run binary fuzzing with AFL++."""
script_root = Path(__file__).parent
fuzzing_script = script_root / "raptor_fuzzing.py"
if not fuzzing_script.exists():
print(f"✗ Fuzzing script not found: {fuzzing_script}")
return 1
return _run_with_lifecycle("fuzz", fuzzing_script, args,
"Starting binary fuzzing workflow...")
def mode_web(args: list) -> int:
"""Run web application security testing."""
script_root = Path(__file__).parent
web_script = script_root / "packages/web/scanner.py"
if not web_script.exists():
print(f"✗ Web scanner not found: {web_script}")
return 1
# Display alpha warning
print("\nWARNING: /web is a STUB and should not be relied upon. Consider a placeholder/in alpha.\n")
return _run_with_lifecycle("web", web_script, args,
"Running web application scanner...")
def mode_agentic(args: list) -> int:
"""Run full autonomous workflow."""
script_root = Path(__file__).parent
agentic_script = script_root / "raptor_agentic.py"
if not agentic_script.exists():
print(f"✗ Agentic workflow script not found: {agentic_script}")
return 1
# Enable CodeQL by default for comprehensive agentic mode
# unless user explicitly specifies --codeql-only or --no-codeql
if '--codeql' not in args and '--codeql-only' not in args and '--no-codeql' not in args:
args = ['--codeql'] + args
return _run_with_lifecycle("agentic", agentic_script, args,
"Starting full autonomous workflow (Semgrep + CodeQL)...")
def mode_codeql(args: list) -> int:
"""Run CodeQL analysis (scan only — no autonomous analysis)."""
script_root = Path(__file__).parent
codeql_script = script_root / "raptor_codeql.py"
if not codeql_script.exists():
print(f"✗ CodeQL script not found: {codeql_script}")
return 1
# Default to scan-only; autonomous analysis requires explicit --analyze
if '--scan-only' not in args and '--analyze' not in args:
args = ['--scan-only'] + args
return _run_with_lifecycle("codeql", codeql_script, args,
"Running CodeQL analysis...")
def mode_llm_analysis(args: list) -> int:
"""Run LLM-powered vulnerability analysis on existing SARIF files."""
script_root = Path(__file__).parent
llm_script = script_root / "packages/llm_analysis/agent.py"
if not llm_script.exists():
print(f"✗ LLM analysis script not found: {llm_script}")
return 1
print("\n[*] Running LLM-powered vulnerability analysis...\n")
return _run_script(llm_script, args)
def show_mode_help(mode: str) -> None:
"""Show detailed help for a specific mode."""
script_root = Path(__file__).parent
mode_scripts = {
'scan': script_root / "packages/static-analysis/scanner.py",
'fuzz': script_root / "raptor_fuzzing.py",
'web': script_root / "packages/web/scanner.py",
'agentic': script_root / "raptor_agentic.py",
'codeql': script_root / "raptor_codeql.py",
'analyze': script_root / "packages/llm_analysis/agent.py",
}
if mode not in mode_scripts:
print(f"✗ Unknown mode: {mode}")
print(f"Available modes: {', '.join(mode_scripts.keys())}")
return
script_path = mode_scripts[mode]
if not script_path.exists():
print(f"✗ Script not found: {script_path}")
return
print(f"\n[*] Help for mode: {mode}\n")
subprocess.run([sys.executable, str(script_path), "--help"])
def main():
"""Main entry point for unified RAPTOR launcher."""
# Pre-process --trust-repo at the top level so it works in any position
# (`raptor --trust-repo scan /x` or `raptor scan /x --trust-repo`).
# Sets the module-level flag in core.security.cc_trust; mode handlers
# don't need to know about it.
if "--trust-repo" in sys.argv:
from core.security.cc_trust import set_trust_override
set_trust_override(True)
sys.argv = [a for a in sys.argv if a != "--trust-repo"]
# If no arguments provided, show help
if len(sys.argv) == 1:
parser = argparse.ArgumentParser(
description="RAPTOR - Unified Security Testing Launcher",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Available Modes:
scan - Static code analysis with Semgrep
fuzz - Binary fuzzing with AFL++
web - Web application security testing
agentic - Full autonomous workflow (Semgrep + CodeQL + LLM analysis)
codeql - CodeQL-only analysis
analyze - LLM-powered vulnerability analysis (requires SARIF input)
Examples:
# Full autonomous workflow
python3 raptor.py agentic --repo /path/to/code
# Static analysis only
python3 raptor.py scan --repo /path/to/code --policy_groups secrets,owasp
# Binary fuzzing
python3 raptor.py fuzz --binary /path/to/binary --duration 3600
# Web scanning
python3 raptor.py web --url https://example.com
# CodeQL analysis
python3 raptor.py codeql --repo /path/to/code --languages java
# LLM analysis of existing SARIF
python3 raptor.py analyze --repo /path/to/code --sarif findings.sarif
# Get help for a specific mode
python3 raptor.py help scan
python3 raptor.py help fuzz
python3 raptor.py scan --help
For more information, visit: https://github.com/gadievron/raptor
"""
)
parser.print_help()
return 0
# Get mode from first argument
mode = sys.argv[1].lower()
remaining = sys.argv[2:]
# Handle --help or -h as first argument (show main help)
if mode in ['-h', '--help']:
parser = argparse.ArgumentParser(
description="RAPTOR - Unified Security Testing Launcher",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Available Modes:
scan - Static code analysis with Semgrep
fuzz - Binary fuzzing with AFL++
web - Web application security testing
agentic - Full autonomous workflow (Semgrep + CodeQL + LLM analysis)
codeql - CodeQL-only analysis
analyze - LLM-powered vulnerability analysis (requires SARIF input)
Examples:
# Full autonomous workflow
python3 raptor.py agentic --repo /path/to/code
# Static analysis only
python3 raptor.py scan --repo /path/to/code --policy_groups secrets,owasp
# Binary fuzzing
python3 raptor.py fuzz --binary /path/to/binary --duration 3600
# Web scanning
python3 raptor.py web --url https://example.com
# CodeQL analysis
python3 raptor.py codeql --repo /path/to/code --languages java
# LLM analysis of existing SARIF
python3 raptor.py analyze --repo /path/to/code --sarif findings.sarif
# Get help for a specific mode
python3 raptor.py help scan
python3 raptor.py help fuzz
python3 raptor.py scan --help
For more information, visit: https://github.com/gadievron/raptor
"""
)
parser.print_help()
return 0
# Handle help mode
if mode == 'help':
if remaining:
show_mode_help(remaining[0])
else:
print("Usage: raptor.py help <mode>")
print("Example: raptor.py help scan")
return 0
# Route to appropriate mode
mode_handlers = {
'scan': mode_scan,
'fuzz': mode_fuzz,
'web': mode_web,
'agentic': mode_agentic,
'codeql': mode_codeql,
'analyze': mode_llm_analysis,
}
if mode not in mode_handlers:
print(f"✗ Unknown mode: {mode}")
print(f"\nAvailable modes: {', '.join(mode_handlers.keys())}")
print("\nRun 'python3 raptor.py --help' for more information")
return 1
# Execute the mode handler
handler = mode_handlers[mode]
return handler(remaining)
if __name__ == "__main__":
try:
sys.exit(main())
except KeyboardInterrupt:
print("\n\nInterrupted by user")
sys.exit(130)
except Exception as e:
print(f"\n✗ Fatal error: {e}")
import traceback
traceback.print_exc()
sys.exit(1)