ether-core 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. ether/__init__.py +32 -0
  2. ether/assets/wordlists/common_dirs.txt.gz +0 -0
  3. ether/assets/wordlists/common_params.txt.gz +0 -0
  4. ether/assets/wordlists/common_passwords.txt.gz +0 -0
  5. ether/assets/wordlists/common_usernames.txt.gz +0 -0
  6. ether/assets/wordlists/subdomains_500.txt.gz +0 -0
  7. ether/cli/__init__.py +5 -0
  8. ether/cli/__main__.py +8 -0
  9. ether/cli/commands/__init__.py +1 -0
  10. ether/cli/commands/doctor.py +21 -0
  11. ether/cli/commands/graph.py +311 -0
  12. ether/cli/commands/logs.py +45 -0
  13. ether/cli/commands/mcp.py +49 -0
  14. ether/cli/commands/run.py +146 -0
  15. ether/cli/commands/session.py +61 -0
  16. ether/cli/commands/telemetry.py +51 -0
  17. ether/cli/commands/tool.py +131 -0
  18. ether/cli/context.py +71 -0
  19. ether/cli/formatters.py +39 -0
  20. ether/cli/router.py +368 -0
  21. ether/common/__init__.py +201 -0
  22. ether/common/algorithms.py +407 -0
  23. ether/common/canonicalize.py +93 -0
  24. ether/common/context.py +25 -0
  25. ether/common/crypto.py +183 -0
  26. ether/common/embeddings.py +93 -0
  27. ether/common/exceptions.py +13 -0
  28. ether/common/logging.py +386 -0
  29. ether/common/secure_memory.py +159 -0
  30. ether/common/ssrf.py +93 -0
  31. ether/core/__init__.py +25 -0
  32. ether/core/diagnostics.py +368 -0
  33. ether/core/executor.py +296 -0
  34. ether/core/sandbox.py +118 -0
  35. ether/core/session.py +956 -0
  36. ether/gateway/__init__.py +21 -0
  37. ether/gateway/gate.py +392 -0
  38. ether/gateway/network.py +98 -0
  39. ether/gateway/preflight.py +802 -0
  40. ether/graph/__init__.py +13 -0
  41. ether/graph/analytics.py +334 -0
  42. ether/graph/store.py +1615 -0
  43. ether/graph/telemetry.py +334 -0
  44. ether/graph/timeline.py +185 -0
  45. ether/mcp/__init__.py +5 -0
  46. ether/mcp/server.py +382 -0
  47. ether/paths.py +176 -0
  48. ether/py.typed +0 -0
  49. ether/registry/__init__.py +7 -0
  50. ether/registry/adapter.py +194 -0
  51. ether/registry/manifest.py +53 -0
  52. ether/registry/registry.py +150 -0
  53. ether/registry/wordlists.py +156 -0
  54. ether/schemas/__init__.py +50 -0
  55. ether/schemas/base.py +122 -0
  56. ether/schemas/credential.py +50 -0
  57. ether/schemas/dns.py +116 -0
  58. ether/schemas/host_internal.py +58 -0
  59. ether/schemas/network.py +142 -0
  60. ether/schemas/power.py +68 -0
  61. ether/schemas/vulnerability.py +221 -0
  62. ether/schemas/web.py +172 -0
  63. ether_core-0.1.0.dist-info/METADATA +440 -0
  64. ether_core-0.1.0.dist-info/RECORD +104 -0
  65. ether_core-0.1.0.dist-info/WHEEL +4 -0
  66. ether_core-0.1.0.dist-info/entry_points.txt +2 -0
  67. ether_core-0.1.0.dist-info/licenses/LICENSE +21 -0
  68. tools/__init__.py +0 -0
  69. tools/dnspython/__init__.py +1 -0
  70. tools/dnspython/adapter.py +302 -0
  71. tools/dnspython/cli.py +202 -0
  72. tools/dnspython/manifest.toml +138 -0
  73. tools/ffuf/__init__.py +1 -0
  74. tools/ffuf/adapter.py +183 -0
  75. tools/ffuf/manifest.toml +121 -0
  76. tools/gobuster/__init__.py +0 -0
  77. tools/gobuster/adapter.py +90 -0
  78. tools/gobuster/manifest.toml +104 -0
  79. tools/http_probe/adapter.py +256 -0
  80. tools/http_probe/manifest.toml +40 -0
  81. tools/netexec/__init__.py +1 -0
  82. tools/netexec/adapter.py +163 -0
  83. tools/netexec/manifest.toml +83 -0
  84. tools/nikto/__init__.py +0 -0
  85. tools/nikto/adapter.py +145 -0
  86. tools/nikto/manifest.toml +108 -0
  87. tools/nmap/__init__.py +0 -0
  88. tools/nmap/adapter.py +97 -0
  89. tools/nmap/manifest.toml +159 -0
  90. tools/nuclei/__init__.py +1 -0
  91. tools/nuclei/adapter.py +171 -0
  92. tools/nuclei/manifest.toml +117 -0
  93. tools/searchsploit/__init__.py +1 -0
  94. tools/searchsploit/adapter.py +139 -0
  95. tools/searchsploit/manifest.toml +103 -0
  96. tools/sqlmap/__init__.py +1 -0
  97. tools/sqlmap/adapter.py +214 -0
  98. tools/sqlmap/manifest.toml +89 -0
  99. tools/subfinder/__init__.py +0 -0
  100. tools/subfinder/adapter.py +71 -0
  101. tools/subfinder/manifest.toml +104 -0
  102. tools/whois/__init__.py +0 -0
  103. tools/whois/adapter.py +80 -0
  104. tools/whois/manifest.toml +95 -0
ether/cli/router.py ADDED
@@ -0,0 +1,368 @@
1
+ """CLI argument parsing, subcommand routing, and execution dispatch for Ether."""
2
+
3
+ import argparse
4
+ import asyncio
5
+ import sys
6
+ from typing import List, Optional
7
+
8
+ from ether import __version__
9
+ from ether.cli.commands.doctor import handle_doctor
10
+ from ether.cli.commands.graph import (
11
+ handle_graph_export,
12
+ handle_graph_import,
13
+ handle_graph_list_nodes,
14
+ handle_graph_prune,
15
+ handle_graph_search,
16
+ )
17
+ from ether.cli.commands.logs import handle_logs
18
+ from ether.cli.commands.mcp import handle_mcp
19
+ from ether.cli.commands.run import handle_run
20
+ from ether.cli.commands.session import handle_session_create, handle_session_list
21
+ from ether.cli.commands.telemetry import handle_telemetry_diff, handle_telemetry_snapshot
22
+ from ether.cli.commands.tool import handle_tool_info, handle_tool_list
23
+ from ether.cli.context import (
24
+ EXIT_RUNTIME_ERROR,
25
+ EXIT_SUCCESS,
26
+ EXIT_USAGE_ERROR,
27
+ CliContext,
28
+ )
29
+ from ether.cli.formatters import print_error
30
+
31
+
32
+ def build_parser() -> argparse.ArgumentParser:
33
+ """Construct the Ether CLI argument parser with noun-verb subcommands."""
34
+ common_options = argparse.ArgumentParser(add_help=False)
35
+ common_options.add_argument(
36
+ "--data-dir",
37
+ metavar="PATH",
38
+ default=argparse.SUPPRESS,
39
+ help="Path to Ether unified data directory (default: ~/.ether or $ETHER_DATA_DIR)",
40
+ )
41
+ common_options.add_argument(
42
+ "--db",
43
+ metavar="PATH",
44
+ default=argparse.SUPPRESS,
45
+ help="Path to SQLite database (default: ~/.ether/ether.db)",
46
+ )
47
+ common_options.add_argument(
48
+ "--tools",
49
+ metavar="DIR",
50
+ default=argparse.SUPPRESS,
51
+ help="Path to tool adapters directory (default: bundled tools/)",
52
+ )
53
+ common_options.add_argument(
54
+ "-j",
55
+ "--json",
56
+ action="store_true",
57
+ help="Output in machine-readable JSON format",
58
+ )
59
+ common_options.add_argument(
60
+ "-v",
61
+ "--verbose",
62
+ action="store_true",
63
+ help="Enable verbose debug logging to stderr",
64
+ )
65
+ common_options.add_argument(
66
+ "--policy",
67
+ choices=["safe", "unrestricted"],
68
+ default="safe",
69
+ help="Execution gateway policy mode (default: safe)",
70
+ )
71
+
72
+ parser = argparse.ArgumentParser(
73
+ prog="ether",
74
+ description="Ether: Headless reactive process supervisor and deterministic graph telemetry engine.",
75
+ parents=[common_options],
76
+ )
77
+ parser.add_argument(
78
+ "-V",
79
+ "--version",
80
+ action="version",
81
+ version=f"Ether v{__version__}",
82
+ help="Show Ether engine version and exit.",
83
+ )
84
+
85
+ subparsers = parser.add_subparsers(dest="subcommand", help="Available subcommands")
86
+
87
+ # 1. doctor
88
+ subparsers.add_parser(
89
+ "doctor",
90
+ parents=[common_options],
91
+ help="Run comprehensive system, database, and tool diagnostics",
92
+ )
93
+
94
+ # 2. tool
95
+ tool_parser = subparsers.add_parser(
96
+ "tool",
97
+ parents=[common_options],
98
+ help="Inspect registered security tool adapters",
99
+ )
100
+ tool_subs = tool_parser.add_subparsers(dest="tool_action")
101
+ tool_subs.add_parser("list", parents=[common_options], help="List all available tools")
102
+ tool_info_p = tool_subs.add_parser(
103
+ "info", parents=[common_options], help="Show details for a tool"
104
+ )
105
+ tool_info_p.add_argument("name", help="Name of the tool to inspect")
106
+
107
+ # 3. run
108
+ run_parser = subparsers.add_parser(
109
+ "run",
110
+ parents=[common_options],
111
+ help="Supervise and execute a tool scan action",
112
+ )
113
+ run_parser.add_argument("tool", help="Tool to execute (e.g. nmap, subfinder, gobuster)")
114
+ run_parser.add_argument("target", help="Target IP, hostname, URL, or CIDR")
115
+ run_parser.add_argument(
116
+ "--flags",
117
+ nargs=argparse.REMAINDER,
118
+ default=[],
119
+ help="Extra flags to pass to the tool binary",
120
+ )
121
+ run_parser.add_argument(
122
+ "-s", "--session-id", dest="session_id", help="Session ID to record findings into"
123
+ )
124
+
125
+ # 4. session
126
+ session_parser = subparsers.add_parser(
127
+ "session",
128
+ parents=[common_options],
129
+ help="Manage investigation sessions",
130
+ )
131
+ session_subs = session_parser.add_subparsers(dest="session_action")
132
+ sess_list_p = session_subs.add_parser("list", parents=[common_options], help="List sessions")
133
+ sess_list_p.add_argument(
134
+ "-w", "--workspace-id", dest="workspace_id", help="Filter by workspace ID"
135
+ )
136
+ sess_create_p = session_subs.add_parser(
137
+ "create", parents=[common_options], help="Create a new session"
138
+ )
139
+ sess_create_p.add_argument(
140
+ "name", nargs="?", default="New Session", help="Session display name"
141
+ )
142
+ sess_create_p.add_argument(
143
+ "-w", "--workspace-id", dest="workspace_id", help="Target workspace ID"
144
+ )
145
+
146
+ # 5. graph
147
+ graph_parser = subparsers.add_parser(
148
+ "graph",
149
+ parents=[common_options],
150
+ help="Query and export deterministic entity graphs",
151
+ )
152
+ graph_subs = graph_parser.add_subparsers(dest="graph_action")
153
+ nodes_p = graph_subs.add_parser(
154
+ "list-nodes", parents=[common_options], help="List finding nodes"
155
+ )
156
+ nodes_p.add_argument("session_id", help="Session ID to inspect")
157
+ nodes_p.add_argument(
158
+ "-t", "--type", dest="type", help="Filter by schema_type (e.g. network.host)"
159
+ )
160
+ nodes_p.add_argument(
161
+ "--include-stale", action="store_true", help="Include decayed stale nodes in listing"
162
+ )
163
+
164
+ prune_p = graph_subs.add_parser(
165
+ "prune", parents=[common_options], help="Prune decayed stale nodes from session graph"
166
+ )
167
+ prune_p.add_argument("session_id", help="Session ID to prune")
168
+ prune_p.add_argument(
169
+ "--max-age",
170
+ dest="max_age",
171
+ type=int,
172
+ default=604800,
173
+ help="Max age in seconds for stale nodes (default: 604800 / 7 days)",
174
+ )
175
+
176
+ export_p = graph_subs.add_parser(
177
+ "export", parents=[common_options], help="Export session graph"
178
+ )
179
+ export_p.add_argument("session_id", help="Session ID to export")
180
+ export_p.add_argument("-o", "--output", dest="output", help="Output JSON or archive file path")
181
+ export_p.add_argument(
182
+ "--encrypt", action="store_true", help="Encrypt export using AES-256-GCM + Argon2id"
183
+ )
184
+ export_p.add_argument("--passphrase", dest="passphrase", help="Passphrase for encryption")
185
+
186
+ import_p = graph_subs.add_parser(
187
+ "import", parents=[common_options], help="Import findings from JSON or encrypted archive"
188
+ )
189
+ import_p.add_argument("input", help="Path to input JSON or encrypted archive (.enc)")
190
+ import_p.add_argument("-s", "--session-id", dest="session_id", help="Target session ID")
191
+ import_p.add_argument("--passphrase", dest="passphrase", help="Decryption passphrase")
192
+
193
+ search_p = graph_subs.add_parser(
194
+ "search", parents=[common_options], help="Semantic similarity search over finding entities"
195
+ )
196
+ search_p.add_argument("session_id", help="Session ID to search")
197
+ search_p.add_argument("query", help="Natural language query string")
198
+ search_p.add_argument(
199
+ "-l",
200
+ "--limit",
201
+ dest="limit",
202
+ type=int,
203
+ default=10,
204
+ help="Maximum findings to return (default: 10)",
205
+ )
206
+ search_p.add_argument(
207
+ "-m",
208
+ "--min-score",
209
+ dest="min_score",
210
+ type=float,
211
+ default=0.0,
212
+ help="Minimum cosine similarity score (default: 0.0)",
213
+ )
214
+ search_p.add_argument(
215
+ "-t", "--type", dest="type", help="Filter by schema_type (e.g. network.service)"
216
+ )
217
+
218
+ # 6. telemetry
219
+ telemetry_parser = subparsers.add_parser(
220
+ "telemetry",
221
+ parents=[common_options],
222
+ help="Agent telemetry protocol: knapsack snapshots and zero-token diffs",
223
+ )
224
+ telemetry_subs = telemetry_parser.add_subparsers(dest="telemetry_action")
225
+ snap_p = telemetry_subs.add_parser(
226
+ "snapshot", parents=[common_options], help="Compile token-budgeted snapshot"
227
+ )
228
+ snap_p.add_argument("session_id", help="Session ID")
229
+ snap_p.add_argument(
230
+ "--max-tokens", dest="max_tokens", type=int, default=4000, help="Max token budget"
231
+ )
232
+ snap_p.add_argument("--entity-id", dest="entity_id", help="Selected entity node ID")
233
+
234
+ diff_p = telemetry_subs.add_parser(
235
+ "diff", parents=[common_options], help="Compute graph diff by action ID or since baseline"
236
+ )
237
+ diff_p.add_argument("session_id", help="Session ID")
238
+ diff_p.add_argument("--action-id", dest="action_id", help="Action ID to diff")
239
+ diff_p.add_argument("--baseline", dest="baseline", help="Baseline timestamp")
240
+
241
+ # 7. logs
242
+ logs_parser = subparsers.add_parser(
243
+ "logs",
244
+ parents=[common_options],
245
+ help="Inspect system runtime logs and crash traces",
246
+ )
247
+ logs_parser.add_argument("--limit", type=int, default=50, help="Number of lines to tail")
248
+ logs_parser.add_argument(
249
+ "--crashes", action="store_true", help="Show recent unhandled crash summary"
250
+ )
251
+
252
+ # 8. mcp
253
+ mcp_parser = subparsers.add_parser(
254
+ "mcp",
255
+ parents=[common_options],
256
+ help="Launch Native Model Context Protocol (MCP) server for AI agents",
257
+ )
258
+ mcp_parser.add_argument(
259
+ "--transport",
260
+ choices=["stdio", "sse"],
261
+ default="stdio",
262
+ help="MCP protocol transport (default: stdio)",
263
+ )
264
+ mcp_parser.add_argument(
265
+ "-s",
266
+ "--session-id",
267
+ dest="session_id",
268
+ help="Bind MCP server to specific investigation session ID",
269
+ )
270
+ mcp_parser.add_argument(
271
+ "--port",
272
+ type=int,
273
+ default=8000,
274
+ help="Port for SSE transport (default: 8000)",
275
+ )
276
+ mcp_parser.add_argument(
277
+ "--host",
278
+ default="127.0.0.1",
279
+ help="Host for SSE transport (default: 127.0.0.1)",
280
+ )
281
+
282
+ return parser
283
+
284
+
285
+ def _run_coroutine(coro):
286
+ """Run an async coroutine, safely handling environments where an event loop is already running."""
287
+ try:
288
+ loop = asyncio.get_running_loop()
289
+ except RuntimeError:
290
+ loop = None
291
+
292
+ if loop and loop.is_running():
293
+ import concurrent.futures
294
+
295
+ with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
296
+ return pool.submit(asyncio.run, coro).result()
297
+ return asyncio.run(coro)
298
+
299
+
300
+ def main(argv: Optional[List[str]] = None) -> int:
301
+ """CLI execution entrypoint."""
302
+ parser = build_parser()
303
+ args = parser.parse_args(argv)
304
+
305
+ if not args.subcommand:
306
+ parser.print_help()
307
+ return EXIT_SUCCESS
308
+
309
+ context = CliContext.from_args(args)
310
+
311
+ try:
312
+ if args.subcommand == "doctor":
313
+ return _run_coroutine(handle_doctor(args, context))
314
+
315
+ elif args.subcommand == "tool":
316
+ if args.tool_action == "info":
317
+ return handle_tool_info(args, context)
318
+ return handle_tool_list(args, context)
319
+
320
+ elif args.subcommand == "run":
321
+ return _run_coroutine(handle_run(args, context))
322
+
323
+ elif args.subcommand == "session":
324
+ if args.session_action == "create":
325
+ return _run_coroutine(handle_session_create(args, context))
326
+ return _run_coroutine(handle_session_list(args, context))
327
+
328
+ elif args.subcommand == "graph":
329
+ if args.graph_action == "export":
330
+ return _run_coroutine(handle_graph_export(args, context))
331
+ elif args.graph_action == "import":
332
+ return _run_coroutine(handle_graph_import(args, context))
333
+ elif args.graph_action == "prune":
334
+ return _run_coroutine(handle_graph_prune(args, context))
335
+ elif args.graph_action == "search":
336
+ return _run_coroutine(handle_graph_search(args, context))
337
+ return _run_coroutine(handle_graph_list_nodes(args, context))
338
+
339
+ elif args.subcommand == "telemetry":
340
+ if args.telemetry_action == "diff":
341
+ return _run_coroutine(handle_telemetry_diff(args, context))
342
+ return _run_coroutine(handle_telemetry_snapshot(args, context))
343
+
344
+ elif args.subcommand == "logs":
345
+ return handle_logs(args, context)
346
+
347
+ elif args.subcommand == "mcp":
348
+ return _run_coroutine(handle_mcp(args, context))
349
+
350
+ else:
351
+ parser.print_help()
352
+ return EXIT_USAGE_ERROR
353
+
354
+ except KeyboardInterrupt:
355
+ print("\n[!] Ether operation interrupted by user.", file=sys.stderr)
356
+ return EXIT_RUNTIME_ERROR
357
+ except Exception as exc:
358
+ if context.verbose:
359
+ import traceback
360
+
361
+ traceback.print_exc(file=sys.stderr)
362
+ else:
363
+ print_error(str(exc))
364
+ return EXIT_RUNTIME_ERROR
365
+
366
+
367
+ if __name__ == "__main__":
368
+ sys.exit(main())
@@ -0,0 +1,201 @@
1
+ """Common shared algorithmic and string primitives for Ether."""
2
+
3
+ import re
4
+ from typing import List
5
+
6
+ from ether.common.algorithms import (
7
+ BloomFilter,
8
+ DisjointSet,
9
+ IPRadixTrie,
10
+ MinHash,
11
+ knapsack_01,
12
+ )
13
+ from ether.common.crypto import (
14
+ CryptoError,
15
+ InvalidArchiveFormatError,
16
+ InvalidPassphraseError,
17
+ TamperedArchiveError,
18
+ decrypt_bytes,
19
+ decrypt_file,
20
+ derive_key_argon2id,
21
+ encrypt_bytes,
22
+ encrypt_file,
23
+ )
24
+ from ether.common.secure_memory import SecureBuffer, wipe_buffer, wipe_credentials
25
+
26
+ __all__ = [
27
+ "ANSI_ESCAPE_RE",
28
+ "BloomFilter",
29
+ "CTF_FLAG_RE",
30
+ "CryptoError",
31
+ "DisjointSet",
32
+ "IPRadixTrie",
33
+ "InvalidArchiveFormatError",
34
+ "InvalidPassphraseError",
35
+ "MinHash",
36
+ "SecureBuffer",
37
+ "TamperedArchiveError",
38
+ "decrypt_bytes",
39
+ "decrypt_file",
40
+ "derive_key_argon2id",
41
+ "dfa_strip_ansi",
42
+ "encrypt_bytes",
43
+ "encrypt_file",
44
+ "extract_ctf_flags",
45
+ "knapsack_01",
46
+ "sanitize_untrusted_output",
47
+ "strip_ansi",
48
+ "strip_scanner_noise",
49
+ "wipe_buffer",
50
+ "wipe_credentials",
51
+ ]
52
+
53
+ ANSI_ESCAPE_RE = re.compile(r"\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
54
+ CTF_FLAG_RE = re.compile(r"(?:flag|FLAG|ctf|CTF|htb|HTB|thm|THM)\{[A-Za-z0-9_!@#$%^&*+=?.-]+\}")
55
+
56
+ _STATE_TEXT = 0
57
+ _STATE_ESC = 1
58
+ _STATE_CSI = 2
59
+ _STATE_OSC = 3
60
+ _STATE_OSC_ESC = 4
61
+
62
+
63
+ def strip_ansi(text: str) -> str:
64
+ """Strip ANSI color codes, cursor sequences, and OSC title strings in strict linear time O(N)
65
+ using an unrolled state machine without regex engine overhead.
66
+ """
67
+ if not text or "\x1b" not in text:
68
+ return text
69
+
70
+ out: List[str] = []
71
+ state = _STATE_TEXT
72
+ chunk_start = 0
73
+
74
+ for i, ch in enumerate(text):
75
+ if state == _STATE_TEXT:
76
+ if ch == "\x1b":
77
+ if i > chunk_start:
78
+ out.append(text[chunk_start:i])
79
+ state = _STATE_ESC
80
+ elif state == _STATE_ESC:
81
+ if ch == "[":
82
+ state = _STATE_CSI
83
+ elif ch == "]":
84
+ state = _STATE_OSC
85
+ else:
86
+ state = _STATE_TEXT
87
+ chunk_start = i + 1
88
+ elif state == _STATE_CSI:
89
+ ord_c = ord(ch)
90
+ if 0x40 <= ord_c <= 0x7E:
91
+ state = _STATE_TEXT
92
+ chunk_start = i + 1
93
+ elif state == _STATE_OSC:
94
+ if ch == "\x07":
95
+ state = _STATE_TEXT
96
+ chunk_start = i + 1
97
+ elif ch == "\x1b":
98
+ state = _STATE_OSC_ESC
99
+ elif state == _STATE_OSC_ESC:
100
+ if ch == "\\":
101
+ state = _STATE_TEXT
102
+ chunk_start = i + 1
103
+ else:
104
+ state = _STATE_OSC
105
+
106
+ if state == _STATE_TEXT and chunk_start < len(text):
107
+ out.append(text[chunk_start:])
108
+
109
+ return "".join(out)
110
+
111
+
112
+ dfa_strip_ansi = strip_ansi
113
+
114
+
115
+ def extract_ctf_flags(text: str) -> List[str]:
116
+ """Extract distinct CTF flag strings from text in order of appearance."""
117
+ if not text:
118
+ return []
119
+ flags: List[str] = []
120
+ seen = set()
121
+ for match in CTF_FLAG_RE.finditer(text):
122
+ f = match.group(0)
123
+ if f not in seen:
124
+ seen.add(f)
125
+ flags.append(f)
126
+ return flags
127
+
128
+
129
+ def strip_scanner_noise(raw_text: str) -> str:
130
+ """Filter out repetitive scanner banner headers, ASCII art, and progress bars."""
131
+ cleaned_text = ANSI_ESCAPE_RE.sub("", raw_text)
132
+ lines = cleaned_text.splitlines()
133
+ cleaned = []
134
+ noise_prefixes = (
135
+ "Starting Nmap",
136
+ "Nmap done:",
137
+ "Gobuster v",
138
+ "by OJ Reeves",
139
+ "[-] Loaded",
140
+ "[-] Target:",
141
+ "[-] Flags:",
142
+ "[-] Method:",
143
+ "[-] Wordlist:",
144
+ "[-] Extensions:",
145
+ "[-] Mode:",
146
+ "[-] Threads:",
147
+ "[-] Timeout:",
148
+ "- Nikto v",
149
+ "+ Target IP:",
150
+ "+ Target Hostname:",
151
+ "+ Target Port:",
152
+ "+ Start Time:",
153
+ "+ End Time:",
154
+ "+ 0 host(s) tested",
155
+ ":: Method :",
156
+ ":: URL :",
157
+ ":: Wordlist :",
158
+ ":: Header :",
159
+ ":: Output :",
160
+ ":: Follow :",
161
+ "[INF] Current nuclei version:",
162
+ "[INF] New templates added in nuclei-templates",
163
+ "[INF] Loading templates...",
164
+ "[INF] Using",
165
+ "[INF] Target:",
166
+ "[INF] Templates cluster",
167
+ "[INF] Scan stats:",
168
+ "[INF] Enumerating subdomains for",
169
+ "% This is the RIPE Database",
170
+ "% Rights restricted",
171
+ "# whois.arin.net",
172
+ "NOTICE: The expiration date",
173
+ "___",
174
+ "---",
175
+ "===",
176
+ "***",
177
+ )
178
+ for line in lines:
179
+ stripped = line.strip()
180
+ if not stripped:
181
+ continue
182
+ if all(c in "=-_*~#./\\ " for c in stripped) and len(stripped) > 4:
183
+ continue
184
+ if "Progress:" in stripped or "Stats:" in stripped or "ETA:" in stripped:
185
+ continue
186
+ normalized = re.sub(r"^\[[\+\*\-\!]\]\s*", "", stripped)
187
+ if any(stripped.startswith(p) or normalized.startswith(p) for p in noise_prefixes):
188
+ continue
189
+ if sum(1 for c in stripped if c in "/\\|`_") > len(stripped) * 0.5 and len(stripped) > 5:
190
+ continue
191
+ cleaned.append(stripped)
192
+
193
+ return "\n".join(cleaned[-60:]) if cleaned else raw_text[-1500:]
194
+
195
+
196
+ def sanitize_untrusted_output(raw_text: str) -> str:
197
+ """Wrap untrusted scanner output in protective boundary tags and neutralize breakout attempts."""
198
+ if not raw_text:
199
+ return "<untrusted_scan_output>\n</untrusted_scan_output>"
200
+ neutralized = raw_text.replace("</untrusted_scan_output>", r"<\/untrusted_scan_output>")
201
+ return f"<untrusted_scan_output>\n{neutralized}\n</untrusted_scan_output>"