-
Notifications
You must be signed in to change notification settings - Fork 713
Expand file tree
/
Copy pathagent.py
More file actions
1604 lines (1417 loc) · 68.5 KB
/
Copy pathagent.py
File metadata and controls
1604 lines (1417 loc) · 68.5 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
#!/usr/bin/env python3
"""
agent.py — LangGraph-style ReAct hunting agent for bug bounty automation.
Architecture
────────────
Primary: Real LangGraph + langchain-ollama (pip install langgraph langchain-ollama)
Fallback: Built-in ReAct loop using Ollama native tool calling (works out of the box)
Both paths expose identical tools and persistent memory — the difference is
that the real LangGraph backend handles interrupts, checkpoints, and parallel
subgraphs correctly.
ReAct loop:
Observe (state) → Think (LLM) → Act (tool) → Observe (result) → loop
↳ LLM picks next tool based on ALL prior findings, not a priority table
↳ Working memory is compressed every 5 steps to stay within context window
↳ Full finding history persists to JSON session — survives crashes/restarts
Memory layers
─────────────
working_memory : LLM-maintained running notes (updated after each step)
findings_log : [{tool, severity, summary, timestamp}, ...]
observation_buf : last 5 raw tool outputs (sliding window, avoids bloat)
session_file : everything above persisted to disk (JSON)
Usage
─────
python3 agent.py --target example.com
python3 agent.py --target example.com --cookie "JSESSIONID=abc" --time 4
python3 agent.py --target example.com --scope-lock --no-brain
python3 agent.py --target example.com --langgraph # force LangGraph
python3 agent.py --target example.com --resume SESSION_ID
From hunt.py:
hunt.py --target x --agent # drops into agent mode
hunt.py --target x --agent --langgraph # with real LangGraph
"""
from __future__ import annotations
import argparse
import json
import os
import sys
import time
import traceback
from datetime import datetime
from pathlib import Path
from typing import Any
# ── LangGraph optional import ──────────────────────────────────────────────────
try:
from langgraph.graph import StateGraph, END
from langgraph.graph.message import add_messages
from langgraph.prebuilt import ToolNode, tools_condition
from langchain_core.messages import HumanMessage, SystemMessage, AIMessage, ToolMessage
from langchain_core.tools import tool as lc_tool
try:
from langchain_ollama import ChatOllama
_LANGGRAPH_OK = True
except ImportError:
from langchain_community.chat_models import ChatOllama
_LANGGRAPH_OK = True
except ImportError:
_LANGGRAPH_OK = False
StateGraph = END = None
add_messages = None
# ── Ollama native tool calling (fallback / always available) ───────────────────
try:
import ollama as _ollama_lib
_OLLAMA_OK = True
except ImportError:
_ollama_lib = None
_OLLAMA_OK = False
# ── hunt.py lazy imports (avoids running main()) ───────────────────────────────
_hunt = None
def _h():
"""Lazy-load hunt module once."""
global _hunt
if _hunt is None:
import importlib.util, sys as _sys
_here = os.path.dirname(os.path.abspath(__file__))
spec = importlib.util.spec_from_file_location("hunt", os.path.join(_here, "hunt.py"))
_hunt = importlib.util.module_from_spec(spec)
_sys.modules.setdefault("hunt", _hunt)
spec.loader.exec_module(_hunt)
return _hunt
# ── brain.py import ───────────────────────────────────────────────────────────
try:
_here = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, _here)
from brain import Brain, BRAIN_SYSTEM, MODEL_PRIORITY, OLLAMA_HOST, _pick_model
_BRAIN_OK = True
except Exception as _brain_err:
_BRAIN_OK = False
BRAIN_SYSTEM = ""
MODEL_PRIORITY = ["qwen3:8b"]
OLLAMA_HOST = "http://localhost:11434"
# ── Colours ───────────────────────────────────────────────────────────────────
GREEN = "\033[0;32m"
CYAN = "\033[0;36m"
YELLOW = "\033[1;33m"
RED = "\033[0;31m"
MAGENTA = "\033[0;35m"
BOLD = "\033[1m"
DIM = "\033[2m"
NC = "\033[0m"
MAX_OBS_CHARS = 3000 # truncate tool output kept in observation buffer
MAX_CTX_CHARS = 18000 # max chars sent to LLM per step
MAX_FINDINGS_LOG = 200 # cap stored findings
MEMORY_REFRESH_N = 5 # compress working_memory every N steps
# ──────────────────────────────────────────────────────────────────────────────
# Tool definitions (JSON Schema — compatible with Ollama native tool calling)
# ──────────────────────────────────────────────────────────────────────────────
TOOLS: list[dict] = [
{
"type": "function",
"function": {
"name": "run_recon",
"description": (
"Run full subdomain enumeration + live host discovery on the target domain. "
"This MUST be the first step if recon data does not exist. "
"Returns: number of live hosts found, key tech stacks detected."
),
"parameters": {
"type": "object",
"properties": {
"scope_lock": {
"type": "boolean",
"description": "If true, skip subdomain enum and only probe the exact target given.",
"default": False,
},
"max_urls": {
"type": "integer",
"description": "Max URLs to collect (default 100, use 200+ for thorough recon).",
"default": 100,
},
},
"required": [],
},
},
},
{
"type": "function",
"function": {
"name": "run_vuln_scan",
"description": (
"Run the core vulnerability scanner (nuclei templates + custom checks). "
"Tests for CVEs, misconfigs, exposed panels, default creds, takeover candidates. "
"Returns: finding count by severity."
),
"parameters": {
"type": "object",
"properties": {
"quick": {
"type": "boolean",
"description": "If true, run fast subset of templates only.",
"default": False,
},
"full": {
"type": "boolean",
"description": "If true, run all templates including slow ones.",
"default": False,
},
},
"required": [],
},
},
},
{
"type": "function",
"function": {
"name": "run_js_analysis",
"description": (
"Download and analyse all JavaScript files found during recon. "
"Extracts: API keys, secrets, hardcoded tokens, internal endpoints, "
"GraphQL schemas, and auth-bypass hints. Use when JS files were discovered."
),
"parameters": {"type": "object", "properties": {}, "required": []},
},
},
{
"type": "function",
"function": {
"name": "run_secret_hunt",
"description": (
"Scan for leaked secrets: TruffleHog on JS/git repos, GitHound on GitHub, "
"hardcoded AWS/GCP/Azure keys, API tokens, private keys. "
"Always worth running — secrets bypass all other controls."
),
"parameters": {"type": "object", "properties": {}, "required": []},
},
},
{
"type": "function",
"function": {
"name": "run_param_discovery",
"description": (
"Brute-force GET URL parameters using arjun + paramspider on all live hosts. "
"Use when parameterized URLs are sparse or the site returns data conditionally. "
"Returns: new parameterized URLs added to the attack surface."
),
"parameters": {"type": "object", "properties": {}, "required": []},
},
},
{
"type": "function",
"function": {
"name": "run_post_param_discovery",
"description": (
"Discover POST form endpoints and their parameter names using lightpanda "
"(JS-rendered HTML) + arjun POST brute-force. "
"Mandatory for JSP/Java/Spring apps, ASP.NET WebForms, any app with login forms. "
"Then runs sqlmap on discovered POST endpoints automatically. "
"Pass cookies if the forms are behind authentication."
),
"parameters": {
"type": "object",
"properties": {
"cookies": {
"type": "string",
"description": "Session cookie string e.g. 'JSESSIONID=abc; token=xyz'",
"default": "",
},
},
"required": [],
},
},
},
{
"type": "function",
"function": {
"name": "run_api_fuzz",
"description": (
"Fuzz API endpoints for IDOR, auth bypass, privilege escalation, "
"and unauthenticated access. Tests REST + GraphQL + gRPC. "
"Use when API endpoints or numeric IDs were found in recon."
),
"parameters": {"type": "object", "properties": {}, "required": []},
},
},
{
"type": "function",
"function": {
"name": "run_cors_check",
"description": (
"Test all live hosts for CORS misconfigurations: null origin, "
"wildcard with credentials, trusted subdomain bypass. "
"High-priority when authenticated API endpoints are present."
),
"parameters": {"type": "object", "properties": {}, "required": []},
},
},
{
"type": "function",
"function": {
"name": "run_cms_exploit",
"description": (
"Run CMS-specific exploit checks: Drupalgeddon (CVE-2014-3704, CVE-2018-7600), "
"WordPress plugin vulns + user enum, Joomla RCE, Magento SQLi. "
"Use immediately when a CMS is detected — especially Drupal < 8 or WordPress."
),
"parameters": {"type": "object", "properties": {}, "required": []},
},
},
{
"type": "function",
"function": {
"name": "run_rce_scan",
"description": (
"Scan for Remote Code Execution vectors: Log4Shell (JNDI), Tomcat PUT upload, "
"JBoss admin consoles, SSTI (Jinja2/Twig/Freemarker), shellshock, "
"interactsh OOB callbacks. Use when Java/Tomcat/JBoss/Struts is detected."
),
"parameters": {"type": "object", "properties": {}, "required": []},
},
},
{
"type": "function",
"function": {
"name": "run_sqlmap_targeted",
"description": (
"Run sqlmap against parameterized GET URLs found in recon. "
"Tests error-based, boolean-blind, time-blind, UNION injection. "
"Use when parameterized URLs exist OR nuclei flagged SQL-related findings."
),
"parameters": {"type": "object", "properties": {}, "required": []},
},
},
{
"type": "function",
"function": {
"name": "run_sqlmap_on_file",
"description": (
"Run sqlmap against a specific raw HTTP request file (Burp-style). "
"Use when you know a specific endpoint with POST params that needs SQLi testing. "
"Provide the full path to the saved request file."
),
"parameters": {
"type": "object",
"properties": {
"request_file": {
"type": "string",
"description": "Absolute path to raw HTTP request file.",
},
"level": {
"type": "integer",
"description": "sqlmap level 1-5 (default 5).",
"default": 5,
},
"risk": {
"type": "integer",
"description": "sqlmap risk 1-3 (default 3).",
"default": 3,
},
},
"required": ["request_file"],
},
},
},
{
"type": "function",
"function": {
"name": "run_jwt_audit",
"description": (
"Audit JWT tokens found in recon artifacts: algorithm confusion (alg=none, "
"RS256→HS256), weak HMAC secret cracking, forged claims. "
"Use when JWT tokens appear in URLs, cookies, or response headers."
),
"parameters": {"type": "object", "properties": {}, "required": []},
},
},
{
"type": "function",
"function": {
"name": "read_recon_summary",
"description": (
"Read and summarize current recon data: live hosts, tech stack, "
"discovered paths, parameterized URLs, CMS detections. "
"Use to refresh your understanding before deciding next action."
),
"parameters": {"type": "object", "properties": {}, "required": []},
},
},
{
"type": "function",
"function": {
"name": "read_findings_summary",
"description": (
"Read and summarize all vulnerability findings discovered so far. "
"Returns severity breakdown, top findings, and suggested exploit chains. "
"Use before deciding to run additional tools or write the final report."
),
"parameters": {"type": "object", "properties": {}, "required": []},
},
},
{
"type": "function",
"function": {
"name": "update_working_memory",
"description": (
"Update your working notes about this target. Call this after making "
"a significant discovery or after each tool run to keep your notes current. "
"These notes persist across all steps and are always visible to you."
),
"parameters": {
"type": "object",
"properties": {
"notes": {
"type": "string",
"description": "Your updated notes about the target, findings, and next priorities.",
}
},
"required": ["notes"],
},
},
},
{
"type": "function",
"function": {
"name": "finish",
"description": (
"Signal that the hunt is complete. Call this when: all high-priority tools "
"have run, time budget is close to exhausted, or no further tools would "
"add new findings. Provide a brief verdict."
),
"parameters": {
"type": "object",
"properties": {
"verdict": {
"type": "string",
"description": "Brief summary: what was found, what's worth reporting.",
}
},
"required": ["verdict"],
},
},
},
]
TOOL_NAMES = {t["function"]["name"] for t in TOOLS}
# ──────────────────────────────────────────────────────────────────────────────
# Memory
# ──────────────────────────────────────────────────────────────────────────────
class HuntMemory:
"""
Three-layer memory:
1. working_memory — LLM's rolling notes (updated by update_working_memory tool)
2. findings_log — structured list of all discoveries [{tool, severity, text, ts}]
3. observation_buf — last N raw tool outputs, used to build LLM context
All layers are persisted to a JSON session file.
"""
def __init__(self, session_file: str):
self.session_file = session_file
self.working_memory = ""
self.findings_log: list[dict] = []
self.observation_buf: list[dict] = [] # {tool, ts, text}
self.completed_steps: list[str] = []
self.step_count = 0
self._load()
def _load(self) -> None:
if os.path.isfile(self.session_file):
try:
data = json.loads(Path(self.session_file).read_text())
self.working_memory = data.get("working_memory", "")
self.findings_log = data.get("findings_log", [])
self.observation_buf = data.get("observation_buf", [])[-10:]
self.completed_steps = data.get("completed_steps", [])
self.step_count = data.get("step_count", 0)
except Exception:
pass
def save(self) -> None:
Path(self.session_file).parent.mkdir(parents=True, exist_ok=True)
data = {
"working_memory": self.working_memory,
"findings_log": self.findings_log[-MAX_FINDINGS_LOG:],
"observation_buf": self.observation_buf[-10:],
"completed_steps": self.completed_steps,
"step_count": self.step_count,
"saved_at": datetime.now().isoformat(),
}
Path(self.session_file).write_text(json.dumps(data, indent=2))
def add_observation(self, tool: str, text: str) -> None:
"""Record a tool output to the sliding observation window."""
entry = {
"tool": tool,
"ts": datetime.now().isoformat(),
"text": text[:MAX_OBS_CHARS],
}
self.observation_buf.append(entry)
if len(self.observation_buf) > 15:
self.observation_buf = self.observation_buf[-10:]
def add_finding(self, tool: str, severity: str, text: str) -> None:
self.findings_log.append({
"tool": tool,
"severity": severity,
"text": text[:500],
"ts": datetime.now().isoformat(),
})
def findings_summary(self) -> str:
"""Compact summary of all findings for LLM context."""
if not self.findings_log:
return "No findings yet."
by_sev: dict[str, list[str]] = {}
for f in self.findings_log[-50:]:
by_sev.setdefault(f["severity"].upper(), []).append(f"{f['tool']}: {f['text'][:120]}")
lines = []
for sev in ("CRITICAL", "HIGH", "MEDIUM", "LOW", "INFO"):
if sev in by_sev:
lines.append(f"[{sev}] ({len(by_sev[sev])} items)")
lines.extend(f" • {x}" for x in by_sev[sev][:5])
return "\n".join(lines) or "No classified findings."
def recent_observations(self, n: int = 3) -> str:
"""Last n tool outputs formatted for LLM context."""
recents = self.observation_buf[-n:]
if not recents:
return "No tool outputs yet."
parts = []
for obs in recents:
parts.append(f"[{obs['tool']}]\n{obs['text']}")
return "\n\n".join(parts)
# ──────────────────────────────────────────────────────────────────────────────
# Tool dispatcher (maps tool names → hunt.py functions)
# ──────────────────────────────────────────────────────────────────────────────
class ToolDispatcher:
"""Execute tool calls and return plain-text observations."""
def __init__(self, domain: str, memory: HuntMemory,
scope_lock: bool = False, max_urls: int = 100,
default_cookies: str = ""):
self.domain = domain
self.memory = memory
self.scope_lock = scope_lock
self.max_urls = max_urls
self.default_cookies = default_cookies
def dispatch(self, name: str, args: dict) -> str:
"""Execute named tool and return text observation."""
h = _h()
domain = self.domain
t0 = time.time()
try:
if name == "run_recon":
ok = h.run_recon(
domain,
scope_lock=args.get("scope_lock", self.scope_lock),
max_urls=int(args.get("max_urls", self.max_urls)),
)
obs = self._summarize_recon(domain, ok)
elif name == "run_vuln_scan":
ok = h.run_vuln_scan(
domain,
quick=bool(args.get("quick", False)),
full=bool(args.get("full", False)),
)
obs = self._summarize_findings(domain, "scan", ok)
elif name == "run_js_analysis":
ok = h.run_js_analysis(domain)
obs = self._summarize_findings(domain, "js", ok)
elif name == "run_secret_hunt":
ok = h.run_secret_hunt(domain)
obs = self._summarize_findings(domain, "secrets", ok)
elif name == "run_param_discovery":
ok = h.run_param_discovery(domain)
obs = self._summarize_params(domain, ok)
elif name == "run_post_param_discovery":
cookies = args.get("cookies", self.default_cookies)
ok = h.run_post_param_discovery(domain, cookies=cookies)
obs = self._summarize_post_params(domain, ok)
elif name == "run_api_fuzz":
ok = h.run_api_fuzz(domain)
obs = self._summarize_findings(domain, "api", ok)
elif name == "run_cors_check":
ok = h.run_cors_check(domain)
obs = self._summarize_findings(domain, "cors", ok)
elif name == "run_cms_exploit":
ok = h.run_cms_exploit(domain)
obs = self._summarize_findings(domain, "cms", ok)
elif name == "run_rce_scan":
ok = h.run_rce_scan(domain)
obs = self._summarize_findings(domain, "rce", ok)
elif name == "run_sqlmap_targeted":
ok = h.run_sqlmap_targeted(domain)
obs = self._summarize_findings(domain, "sqlmap", ok)
elif name == "run_sqlmap_on_file":
req_file = args.get("request_file", "")
if not req_file or not os.path.isfile(req_file):
return f"ERROR: request_file not found: {req_file}"
ok = h.run_sqlmap_request_file(
req_file, domain=domain,
level=int(args.get("level", 5)),
risk=int(args.get("risk", 3)),
)
obs = f"sqlmap (request-file) completed. Injectable: {ok}"
elif name == "run_jwt_audit":
ok = h.run_jwt_audit(domain)
obs = self._summarize_findings(domain, "jwt", ok)
elif name == "read_recon_summary":
obs = self._read_recon_files(domain)
elif name == "read_findings_summary":
obs = self._read_findings_files(domain)
elif name == "update_working_memory":
notes = args.get("notes", "")
self.memory.working_memory = notes
self.memory.save()
return f"Working memory updated ({len(notes)} chars)."
elif name == "finish":
return f"FINISH: {args.get('verdict', 'Hunt complete.')}"
else:
return f"Unknown tool: {name}"
except Exception as exc:
tb = traceback.format_exc()
return f"Tool {name} raised exception: {exc}\n{tb[:500]}"
elapsed = round(time.time() - t0, 1)
obs_full = f"{obs}\n\n[{name} completed in {elapsed}s]"
# Update memory
self.memory.add_observation(name, obs_full)
self.memory.completed_steps.append(name)
self.memory.step_count += 1
# Classify any critical/high findings into findings_log
self._classify_obs(name, obs_full)
self.memory.save()
return obs_full
# ── Observation formatters ──────────────────────────────────────────────
def _summarize_recon(self, domain: str, ok: bool) -> str:
h = _h()
recon_dir = h._resolve_recon_dir(domain)
lines = [f"run_recon: {'OK' if ok else 'PARTIAL'}"]
# Count live hosts
for fn in ("live/httpx_full.txt", "httpx_full.txt"):
fp = os.path.join(recon_dir, fn)
if os.path.isfile(fp):
count = sum(1 for _ in open(fp) if _.strip())
lines.append(f"Live hosts: {count}")
break
# Count resolved subdomains
for fn in ("resolved.txt", "all.txt"):
fp = os.path.join(recon_dir, fn)
if os.path.isfile(fp):
count = sum(1 for _ in open(fp) if _.strip())
lines.append(f"Subdomains: {count}")
break
# Tech detections
for fn in ("tech_priority.txt", "tech.txt"):
fp = os.path.join(recon_dir, fn)
if os.path.isfile(fp):
techs = [l.strip() for l in open(fp) if l.strip()][:10]
lines.append(f"Tech detected: {', '.join(techs)}")
break
# Parameterized URLs
for fn in ("urls/with_params.txt", "params/with_params.txt"):
fp = os.path.join(recon_dir, fn)
if os.path.isfile(fp):
count = sum(1 for _ in open(fp) if _.strip())
lines.append(f"Parameterized URLs: {count}")
break
return "\n".join(lines)
def _summarize_findings(self, domain: str, label: str, ok: bool) -> str:
h = _h()
findings_dir = h._resolve_findings_dir(domain, create=False)
lines = [f"{label}: {'OK' if ok else 'ran (check manually)'}"]
# Walk findings dir for any .txt with content
if findings_dir and os.path.isdir(findings_dir):
for root, _, files in os.walk(findings_dir):
for fn in files:
if not fn.endswith(".txt"):
continue
fp = os.path.join(root, fn)
try:
content = Path(fp).read_text(errors="replace")
if any(kw in content.lower() for kw in
("critical", "high", "vulnerable", "injectable",
"rce", "sqli", "open redirect", "exposed", "default cred")):
head = content[:400].replace("\n", " ")
lines.append(f" [{fn}] {head}")
except Exception:
pass
if len(lines) == 1:
lines.append(" No HIGH/CRITICAL findings in artifacts (check logs above for details).")
return "\n".join(lines[:20])
def _summarize_params(self, domain: str, ok: bool) -> str:
h = _h()
recon_dir = h._resolve_recon_dir(domain)
params_dir = os.path.join(recon_dir, "params")
lines = [f"run_param_discovery: {'OK' if ok else 'partial'}"]
for fn in ("paramspider.txt", "arjun.json"):
fp = os.path.join(params_dir, fn)
if os.path.isfile(fp):
count = sum(1 for _ in open(fp) if _.strip())
lines.append(f" {fn}: {count} lines")
return "\n".join(lines)
def _summarize_post_params(self, domain: str, ok: bool) -> str:
h = _h()
recon_dir = h._resolve_recon_dir(domain)
params_dir = os.path.join(recon_dir, "params")
lines = [f"run_post_param_discovery: {'found POST params' if ok else 'no POST params found'}"]
fp = os.path.join(params_dir, "post_params.json")
if os.path.isfile(fp):
try:
data = json.loads(Path(fp).read_text())
for url, info in list(data.items())[:8]:
params = ", ".join(info.get("params", [])[:6])
lines.append(f" POST {url} → [{params}]")
except Exception:
pass
return "\n".join(lines)
def _read_recon_files(self, domain: str) -> str:
h = _h()
recon_dir = h._resolve_recon_dir(domain)
parts = []
for label, fn in [
("Live hosts (sample)", "httpx_full.txt"),
("Tech priority", "tech_priority.txt"),
("Parameterized URLs", "urls/with_params.txt"),
("All URLs (sample)", "urls/all.txt"),
]:
fp = os.path.join(recon_dir, fn)
if os.path.isfile(fp):
lines = [l.strip() for l in open(fp) if l.strip()]
count = len(lines)
sample = lines[:20]
parts.append(f"=== {label} ({count} total) ===\n" + "\n".join(sample))
return "\n\n".join(parts) if parts else "No recon data found. Run run_recon first."
def _read_findings_files(self, domain: str) -> str:
h = _h()
findings_dir = h._resolve_findings_dir(domain, create=False)
if not findings_dir or not os.path.isdir(findings_dir):
return "No findings directory. Run vulnerability scans first."
parts = []
for root, _, files in os.walk(findings_dir):
for fn in sorted(files):
if not fn.endswith((".txt", ".json")):
continue
fp = os.path.join(root, fn)
try:
content = Path(fp).read_text(errors="replace")
if content.strip():
rel = os.path.relpath(fp, findings_dir)
parts.append(f"=== {rel} ===\n{content[:800]}")
except Exception:
pass
if not parts:
return "Findings directory exists but is empty."
combined = "\n\n".join(parts)
# Truncate to avoid blowing context
if len(combined) > MAX_CTX_CHARS:
combined = combined[:MAX_CTX_CHARS] + "\n...[truncated]"
return combined
def _classify_obs(self, tool: str, obs: str) -> None:
"""Extract severity labels from observation text and add to findings_log."""
obs_l = obs.lower()
if any(kw in obs_l for kw in ("rce_confirmed", "injectable", "critical")):
sev = "CRITICAL"
elif any(kw in obs_l for kw in ("high", "sql injection", "rce", "default cred")):
sev = "HIGH"
elif any(kw in obs_l for kw in ("medium", "exposed", "open redirect", "cors")):
sev = "MEDIUM"
elif any(kw in obs_l for kw in ("low", "info")):
sev = "LOW"
else:
return # not a finding, skip
# Take first relevant line as summary
for ln in obs.splitlines():
if any(kw in ln.lower() for kw in
("critical", "high", "injectable", "rce", "exposed", "found", "medium", "sql")):
self.memory.add_finding(tool, sev, ln.strip()[:300])
break
# ──────────────────────────────────────────────────────────────────────────────
# Core ReAct agent (Ollama native tool calling)
# ──────────────────────────────────────────────────────────────────────────────
# ──────────────────────────────────────────────────────────────────────────────
# Loop Detector (ctf-agent technique: signature hashing, sliding window 12)
# ──────────────────────────────────────────────────────────────────────────────
class LoopDetector:
"""
Detects when the agent is repeating the same tool call in a loop.
Sliding window of last 12 tool signatures.
Warn at 3 repetitions, force direction change at 5.
Signature = tool_name + first 300 chars of serialised args.
"""
WINDOW = 12
WARN_AT = 3
BREAK_AT = 5
def __init__(self):
self._history: list[str] = []
self._counts: dict[str, int] = {}
def record(self, tool: str, args: dict) -> tuple[bool, bool]:
"""
Record a tool call. Returns (warn, must_break).
warn=True at WARN_AT repeats; must_break=True at BREAK_AT.
"""
sig = tool + ":" + json.dumps(args, sort_keys=True)[:300]
self._history.append(sig)
if len(self._history) > self.WINDOW:
evicted = self._history.pop(0)
self._counts[evicted] = max(0, self._counts.get(evicted, 0) - 1)
self._counts[sig] = self._counts.get(sig, 0) + 1
n = self._counts[sig]
return n >= self.WARN_AT, n >= self.BREAK_AT
def reset(self) -> None:
self._history.clear()
self._counts.clear()
# ──────────────────────────────────────────────────────────────────────────────
# JSONL Tracer (ctf-agent technique: append-only, immediate flush, tail -f)
# ──────────────────────────────────────────────────────────────────────────────
class AgentTracer:
"""
Append-only JSONL event log — one JSON object per line, flushed immediately.
`tail -f session.jsonl` gives live stream of what the agent is doing.
"""
def __init__(self, log_path: str):
self.log_path = log_path
Path(log_path).parent.mkdir(parents=True, exist_ok=True)
self._f = open(log_path, "a", buffering=1) # line-buffered
def _write(self, event: dict) -> None:
event.setdefault("ts", datetime.now().isoformat())
self._f.write(json.dumps(event) + "\n")
self._f.flush()
def tool_call(self, tool: str, args: dict, step: int) -> None:
self._write({"event": "tool_call", "step": step, "tool": tool, "args": args})
def tool_result(self, tool: str, result: str, elapsed: float, step: int) -> None:
self._write({"event": "tool_result", "step": step, "tool": tool,
"elapsed_s": elapsed, "result_preview": result[:400]})
def loop_warn(self, tool: str, count: int, step: int) -> None:
self._write({"event": "loop_warn", "step": step, "tool": tool, "count": count})
def loop_break(self, tool: str, step: int) -> None:
self._write({"event": "loop_break", "step": step, "tool": tool})
def bump(self, message: str, step: int) -> None:
self._write({"event": "bump", "step": step, "message": message})
def finding(self, severity: str, tool: str, text: str) -> None:
self._write({"event": "finding", "severity": severity, "tool": tool, "text": text[:300]})
def finish(self, verdict: str, step: int, elapsed_mins: float) -> None:
self._write({"event": "finish", "step": step,
"elapsed_mins": elapsed_mins, "verdict": verdict})
def close(self) -> None:
self._f.close()
# ──────────────────────────────────────────────────────────────────────────────
# Multi-model racer (ctf-agent: asyncio FIRST_COMPLETED pattern)
# ──────────────────────────────────────────────────────────────────────────────
def race_analysis(prompt: str, models: list[str], client,
system: str = "", timeout: int = 120) -> str:
"""
Ask multiple Ollama models the same analysis question.
Return whichever completes first with a non-empty answer.
Used for: triage decisions, next-action advice, finding classification.
Falls back to sequential if only one model available.
"""
import threading
result_holder: dict[str, str] = {}
done_event = threading.Event()
def _call(model: str) -> None:
try:
resp = client.chat(
model=model,
messages=[
{"role": "system", "content": system or AGENT_SYSTEM},
{"role": "user", "content": prompt},
],
options={"num_predict": 800, "temperature": 0.1, "num_ctx": 8192},
)
text = (resp.get("message", {}).get("content") or "").strip()
if text and not done_event.is_set():
result_holder["winner"] = model
result_holder["text"] = text
done_event.set()
except Exception:
pass
threads = [threading.Thread(target=_call, args=(m,), daemon=True) for m in models]
for t in threads:
t.start()
done_event.wait(timeout=timeout)
if "text" in result_holder:
winner = result_holder["winner"]
print(f"{DIM}[Race] Winner: {winner}{NC}", flush=True)
return result_holder["text"]
# Sequential fallback
for m in models:
try:
resp = client.chat(
model=m,
messages=[
{"role": "system", "content": system or AGENT_SYSTEM},
{"role": "user", "content": prompt},
],
options={"num_predict": 800, "temperature": 0.1, "num_ctx": 8192},
)
text = (resp.get("message", {}).get("content") or "").strip()
if text:
return text
except Exception:
continue
return ""
AGENT_SYSTEM = """\
You are an elite autonomous bug bounty hunter operating within an authorized bug bounty program or VAPT engagement.
You have a set of tools that execute real security scans. Use them strategically.
CORE RULES:
1. Always start with run_recon if no recon data exists yet.
2. After recon, read_recon_summary to understand the attack surface before choosing next tool.
3. Prioritize by impact: CMS exploits > RCE > SQLi > IDOR > secrets > info.
4. If Drupal or WordPress is detected → run_cms_exploit immediately.
5. If Java/Tomcat/JBoss/Spring is detected → run_rce_scan + run_post_param_discovery.
6. If parameterized URLs found → run_sqlmap_targeted.
7. If JWT tokens appear in any recon data → run_jwt_audit.
8. Maintain your notes via update_working_memory after each significant discovery.
9. Call finish when: all high-priority tools done, time running low, or no new attack surface.
10. DO NOT repeat a tool that already completed in this session unless explicitly justified.
Think step by step. Pick the highest-impact next action given what you know."""
class ReActAgent:
"""
Built-in ReAct loop using Ollama native tool calling.
Works without LangGraph installed — just needs `pip install ollama`.
"""
MIN_STEPS_BEFORE_FINISH = 6 # persistence: must run at least N tools before finish allowed
def __init__(self, domain: str, memory: HuntMemory,
dispatcher: ToolDispatcher,
max_steps: int = 20,
time_budget_hours: float = 2.0,
model: str | None = None,
tracer: AgentTracer | None = None):
self.domain = domain
self.memory = memory
self.dispatcher = dispatcher
self.max_steps = max_steps
self.time_start = time.time()
self.time_budget_secs = time_budget_hours * 3600
self.done = False
self.verdict = ""
# ctf-agent techniques
self.loop_detector = LoopDetector()
self.tracer = tracer # set externally after session_file is known
self.bump_file = "" # set by run_agent_hunt — path to bump file
# racing models (analysis + triage) — baron-llm races qwen3 on quick decisions
self._race_models: list[str] = []
if not _OLLAMA_OK:
raise RuntimeError("Ollama Python package not installed: pip install ollama")