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/__init__.py ADDED
@@ -0,0 +1,32 @@
1
+ """Ether: Reactive process supervisor and graph telemetry engine for security tools."""
2
+
3
+ from ether.common.exceptions import EtherError
4
+ from ether.core.executor import Executor, LogSpooler, sanitize_subprocess_env
5
+ from ether.core.session import ExecutionSession
6
+ from ether.gateway.gate import ActionGateway, ActionValidationError, GatePolicy
7
+ from ether.graph.analytics import GraphAnalyticsEngine
8
+ from ether.graph.store import GraphStore
9
+ from ether.graph.timeline import ActionTimelineRepository
10
+ from ether.registry.adapter import ToolAdapter
11
+ from ether.registry.registry import ToolRegistry
12
+ from ether.schemas.base import BaseFinding
13
+
14
+ __version__ = "0.1.0"
15
+
16
+ __all__ = [
17
+ "ActionGateway",
18
+ "ActionTimelineRepository",
19
+ "ActionValidationError",
20
+ "BaseFinding",
21
+ "EtherError",
22
+ "ExecutionSession",
23
+ "Executor",
24
+ "GatePolicy",
25
+ "GraphAnalyticsEngine",
26
+ "GraphStore",
27
+ "LogSpooler",
28
+ "ToolAdapter",
29
+ "ToolRegistry",
30
+ "__version__",
31
+ "sanitize_subprocess_env",
32
+ ]
ether/cli/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Ether headless command-line interface."""
2
+
3
+ from ether.cli.router import build_parser, main
4
+
5
+ __all__ = ["build_parser", "main"]
ether/cli/__main__.py ADDED
@@ -0,0 +1,8 @@
1
+ """Main module entrypoint for python -m ether.cli."""
2
+
3
+ import sys
4
+
5
+ from ether.cli.router import main
6
+
7
+ if __name__ == "__main__":
8
+ sys.exit(main())
@@ -0,0 +1 @@
1
+ """CLI Subcommand handlers for Ether."""
@@ -0,0 +1,21 @@
1
+ """Handler for 'ether doctor' diagnostic command."""
2
+
3
+ import sys
4
+ from typing import Any
5
+
6
+ from ether.cli.context import EXIT_RUNTIME_ERROR, EXIT_SUCCESS, CliContext
7
+ from ether.cli.formatters import print_json
8
+ from ether.core.diagnostics import DiagnosticEngine
9
+
10
+
11
+ async def handle_doctor(args: Any, context: CliContext) -> int:
12
+ """Run system, database, and tool diagnostics."""
13
+ engine = DiagnosticEngine(db_path=context.db_path, tools_dir=context.tools_dir)
14
+ report = await engine.run()
15
+
16
+ if context.is_json:
17
+ print_json(report.to_dict())
18
+ else:
19
+ print(DiagnosticEngine.format_terminal_report(report), file=sys.stdout)
20
+
21
+ return EXIT_SUCCESS if report.healthy else EXIT_RUNTIME_ERROR
@@ -0,0 +1,311 @@
1
+ """Handlers for 'ether graph' subcommands."""
2
+
3
+ import getpass
4
+ import json
5
+ import os
6
+ from typing import Any
7
+
8
+ from ether.cli.context import EXIT_RUNTIME_ERROR, EXIT_SUCCESS, CliContext
9
+ from ether.cli.formatters import print_error, print_json, print_table
10
+ from ether.common.crypto import decrypt_bytes, encrypt_bytes
11
+ from ether.schemas.base import BaseFinding
12
+
13
+
14
+ async def handle_graph_list_nodes(args: Any, context: CliContext) -> int:
15
+ """List finding nodes recorded in an investigation session."""
16
+ session_id = getattr(args, "session_id", None)
17
+ if not session_id:
18
+ print_error("session_id is required. Run 'ether session list' to find session IDs.")
19
+ return EXIT_RUNTIME_ERROR
20
+
21
+ schema_type = getattr(args, "type", None)
22
+ include_stale = bool(getattr(args, "include_stale", False))
23
+
24
+ async with context.open_store() as store:
25
+ if schema_type:
26
+ nodes = await store.query(
27
+ schema_type, session_id=session_id, include_stale=include_stale
28
+ )
29
+ else:
30
+ nodes = await store.get_all_nodes(session_id, include_stale=include_stale)
31
+
32
+ if context.is_json:
33
+ parsed_nodes = []
34
+ for n in nodes:
35
+ item = dict(n)
36
+ if "pik_json" in item and isinstance(item["pik_json"], str):
37
+ try:
38
+ item["pik"] = json.loads(item["pik_json"])
39
+ except Exception:
40
+ pass
41
+ if "data_json" in item and isinstance(item["data_json"], str):
42
+ try:
43
+ item["data"] = json.loads(item["data_json"])
44
+ except Exception:
45
+ pass
46
+ parsed_nodes.append(item)
47
+ print_json(parsed_nodes)
48
+ return EXIT_SUCCESS
49
+
50
+ headers = ["NODE ID", "SCHEMA TYPE", "TARGET / PIK", "STATUS"]
51
+ rows = []
52
+ for n in nodes:
53
+ pik_display = ""
54
+ try:
55
+ pik = json.loads(n.get("pik_json", "{}"))
56
+ pik_display = ", ".join(f"{k}={v}" for k, v in pik.items())
57
+ except Exception:
58
+ pik_display = n.get("pik_json", "")
59
+ if len(pik_display) > 40:
60
+ pik_display = pik_display[:37] + "..."
61
+ rows.append(
62
+ [
63
+ n.get("id", "")[:12],
64
+ n.get("schema_type", ""),
65
+ pik_display,
66
+ n.get("status", "confirmed"),
67
+ ]
68
+ )
69
+
70
+ print_table(headers, rows)
71
+ return EXIT_SUCCESS
72
+
73
+
74
+ async def handle_graph_export(args: Any, context: CliContext) -> int:
75
+ """Export session finding graph and relations to JSON or encrypted archive."""
76
+ session_id = getattr(args, "session_id", None)
77
+ output_path = getattr(args, "output", None)
78
+ encrypt = bool(getattr(args, "encrypt", False))
79
+ passphrase = getattr(args, "passphrase", None)
80
+
81
+ if not session_id:
82
+ print_error("session_id is required.")
83
+ return EXIT_RUNTIME_ERROR
84
+
85
+ if encrypt and not passphrase:
86
+ try:
87
+ passphrase = getpass.getpass("Enter archive encryption passphrase: ")
88
+ except Exception:
89
+ print_error("Encryption requested but no passphrase supplied.")
90
+ return EXIT_RUNTIME_ERROR
91
+
92
+ async with context.open_store() as store:
93
+ nodes = await store.get_all_nodes(session_id)
94
+ edges = await store.get_all_edges(session_id)
95
+
96
+ export_data = {
97
+ "session_id": session_id,
98
+ "nodes": [
99
+ {
100
+ "id": n["id"],
101
+ "schema_type": n["schema_type"],
102
+ "pik": json.loads(n["pik_json"]) if "pik_json" in n else {},
103
+ "data": json.loads(n["data_json"]) if "data_json" in n else {},
104
+ "status": n.get("status", "confirmed"),
105
+ }
106
+ for n in nodes
107
+ ],
108
+ "edges": [
109
+ {
110
+ "source_id": e["source_id"],
111
+ "target_id": e["target_id"],
112
+ "relation_type": e.get("relation_type", "relates_to"),
113
+ }
114
+ for e in edges
115
+ ],
116
+ }
117
+
118
+ raw_json = json.dumps(export_data, indent=2)
119
+
120
+ if output_path:
121
+ out_dir = os.path.dirname(os.path.abspath(output_path))
122
+ if out_dir:
123
+ os.makedirs(out_dir, exist_ok=True)
124
+
125
+ if encrypt:
126
+ encrypted_payload = encrypt_bytes(raw_json.encode("utf-8"), passphrase)
127
+ flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
128
+ fd = os.open(output_path, flags, 0o600)
129
+ with open(fd, "wb") as f:
130
+ f.write(encrypted_payload)
131
+ print(
132
+ f"[+] Exported {len(nodes)} nodes and {len(edges)} edges to encrypted archive '{output_path}'"
133
+ )
134
+ else:
135
+ with open(output_path, "w", encoding="utf-8") as f:
136
+ f.write(raw_json)
137
+ print(f"[+] Exported {len(nodes)} nodes and {len(edges)} edges to '{output_path}'")
138
+ else:
139
+ if encrypt:
140
+ print_error("Encrypted export requires an output file path (-o <path>).")
141
+ return EXIT_RUNTIME_ERROR
142
+ print_json(export_data)
143
+
144
+ return EXIT_SUCCESS
145
+
146
+
147
+ async def handle_graph_import(args: Any, context: CliContext) -> int:
148
+ """Import findings from a JSON file or encrypted archive into an investigation session."""
149
+ input_path = getattr(args, "input", None)
150
+ session_id = getattr(args, "session_id", None)
151
+ passphrase = getattr(args, "passphrase", None)
152
+
153
+ if not input_path or not os.path.exists(input_path):
154
+ print_error(f"Input file '{input_path}' not found.")
155
+ return EXIT_RUNTIME_ERROR
156
+
157
+ with open(input_path, "rb") as f:
158
+ file_bytes = f.read()
159
+
160
+ # Detect if encrypted archive (starts with ETHER_SECURE_ARC)
161
+ if file_bytes.startswith(b"ETHER_SECURE_ARC"):
162
+ if not passphrase:
163
+ try:
164
+ passphrase = getpass.getpass("Enter archive decryption passphrase: ")
165
+ except Exception:
166
+ print_error("Encrypted archive detected but no passphrase supplied.")
167
+ return EXIT_RUNTIME_ERROR
168
+
169
+ try:
170
+ plaintext = decrypt_bytes(file_bytes, passphrase)
171
+ data = json.loads(plaintext.decode("utf-8"))
172
+ except Exception as exc:
173
+ print_error(f"Failed to decrypt archive: {exc}")
174
+ return EXIT_RUNTIME_ERROR
175
+ else:
176
+ try:
177
+ data = json.loads(file_bytes.decode("utf-8"))
178
+ except Exception as exc:
179
+ print_error(f"Failed to parse JSON input file: {exc}")
180
+ return EXIT_RUNTIME_ERROR
181
+
182
+ async with context.open_store() as store:
183
+ if not session_id:
184
+ # Use session_id from export data or create a new session
185
+ orig_id = data.get("session_id")
186
+ if orig_id:
187
+ session_id = orig_id
188
+ # Ensure session exists
189
+ existing = await store.get_session(session_id)
190
+ if not existing:
191
+ ws_id, _ = await store.get_or_create_default_session()
192
+ await store.create_session(
193
+ ws_id, f"Imported {session_id[:8]}", session_id=session_id
194
+ )
195
+ else:
196
+ ws_id, sess_id = await store.get_or_create_default_session()
197
+ session_id = sess_id
198
+
199
+ imported_count = 0
200
+ findings_to_upsert = []
201
+ for n in data.get("nodes", []):
202
+ try:
203
+ f = BaseFinding(
204
+ schema_type=n["schema_type"],
205
+ pik=n["pik"],
206
+ data=n.get("data", {}),
207
+ status=n.get("status", "confirmed"),
208
+ )
209
+ findings_to_upsert.append(f)
210
+ except Exception:
211
+ continue
212
+
213
+ if findings_to_upsert:
214
+ await store.upsert_findings_batch(session_id, findings_to_upsert)
215
+ imported_count = len(findings_to_upsert)
216
+
217
+ if context.is_json:
218
+ print_json({"session_id": session_id, "imported_nodes": imported_count})
219
+ else:
220
+ print(f"[+] Successfully imported {imported_count} nodes into session '{session_id}'")
221
+
222
+ return EXIT_SUCCESS
223
+
224
+
225
+ async def handle_graph_prune(args: Any, context: CliContext) -> int:
226
+ """Prune decayed stale nodes older than max_age_seconds from a session."""
227
+ session_id = getattr(args, "session_id", None)
228
+ if not session_id:
229
+ print_error("session_id is required.")
230
+ return EXIT_RUNTIME_ERROR
231
+
232
+ max_age = int(getattr(args, "max_age", 604800))
233
+
234
+ async with context.open_store() as store:
235
+ pruned_count = await store.prune_stale_nodes(session_id, max_age_seconds=max_age)
236
+
237
+ if context.is_json:
238
+ print_json({"session_id": session_id, "pruned_nodes": pruned_count})
239
+ else:
240
+ print(f"[+] Successfully pruned {pruned_count} stale node(s) from session '{session_id}'.")
241
+
242
+ return EXIT_SUCCESS
243
+
244
+
245
+ async def handle_graph_search(args: Any, context: CliContext) -> int:
246
+ """Perform offline semantic search against finding entities in an investigation session."""
247
+ session_id = getattr(args, "session_id", None)
248
+ query = getattr(args, "query", None)
249
+ if not session_id or not query:
250
+ print_error(
251
+ "session_id and query are required. Usage: ether graph search <session_id> '<query>'"
252
+ )
253
+ return EXIT_RUNTIME_ERROR
254
+
255
+ limit = int(getattr(args, "limit", 10) or 10)
256
+ min_score = float(getattr(args, "min_score", 0.0) or 0.0)
257
+ schema_type = getattr(args, "type", None)
258
+
259
+ async with context.open_store() as store:
260
+ results = await store.semantic_search(
261
+ session_id=session_id,
262
+ query=query,
263
+ limit=limit,
264
+ min_score=min_score,
265
+ schema_type=schema_type,
266
+ )
267
+
268
+ if context.is_json:
269
+ print_json(results)
270
+ return EXIT_SUCCESS
271
+
272
+ if not results:
273
+ print(f"No semantic matches found for query '{query}' in session {session_id}.")
274
+ return EXIT_SUCCESS
275
+
276
+ headers = ["SCORE", "NODE ID", "SCHEMA TYPE", "TARGET / SUMMARY"]
277
+ rows = []
278
+ for r in results:
279
+ score = f"{r.get('similarity', 0.0):.3f}"
280
+ nid = r.get("id", "")[:12]
281
+ st = r.get("schema_type", "")
282
+ summary = ""
283
+ pik = r.get("pik") or {}
284
+ data = r.get("data") or {}
285
+ if st == "network.host":
286
+ summary = pik.get("ip") or data.get("ip", "")
287
+ elif st == "network.service":
288
+ summary = f"{data.get('service_name', 'svc')} on {pik.get('host_ip')}:{pik.get('port')}"
289
+ if data.get("banner"):
290
+ summary += f" ({data['banner']})"
291
+ elif st == "web.endpoint":
292
+ summary = pik.get("url") or data.get("url", "")
293
+ if data.get("title"):
294
+ summary += f" [{data['title']}]"
295
+ elif st == "web.technology":
296
+ summary = f"{data.get('technology_name')} on {pik.get('url')}"
297
+ elif st == "vulnerability.found":
298
+ summary = (
299
+ f"{pik.get('vuln_id')} ({data.get('severity', 'UNKNOWN')}): {data.get('title', '')}"
300
+ )
301
+ elif st == "credential.found":
302
+ summary = f"User '{pik.get('username')}' in context '{pik.get('context')}'"
303
+ else:
304
+ summary = ", ".join(f"{k}={v}" for k, v in pik.items())
305
+
306
+ if len(summary) > 60:
307
+ summary = summary[:57] + "..."
308
+ rows.append([score, nid, st, summary])
309
+
310
+ print_table(headers, rows)
311
+ return EXIT_SUCCESS
@@ -0,0 +1,45 @@
1
+ """Handlers for 'ether logs' subcommands."""
2
+
3
+ import os
4
+ from typing import Any
5
+
6
+ from ether import paths
7
+ from ether.cli.context import EXIT_SUCCESS, CliContext
8
+ from ether.cli.formatters import print_json
9
+ from ether.common.logging import get_recent_crash_summary
10
+
11
+
12
+ def handle_logs(args: Any, context: CliContext) -> int:
13
+ """Display system log records or recent crash reports."""
14
+ show_crashes = bool(getattr(args, "crashes", False))
15
+ lines_limit = int(getattr(args, "limit", 50))
16
+
17
+ if show_crashes:
18
+ crash = get_recent_crash_summary(context.data_dir, max_lines=lines_limit)
19
+ if context.is_json:
20
+ print_json(crash or {})
21
+ elif crash:
22
+ print(f"Recent Crash [{crash['timestamp']}]:")
23
+ print(f"Summary: {crash['summary']}")
24
+ print("\nTraceback:")
25
+ print(crash["traceback"])
26
+ else:
27
+ print("[+] No unhandled crashes recorded in system log.")
28
+ return EXIT_SUCCESS
29
+
30
+ log_path = paths.get_system_log_path(context.data_dir)
31
+ if not os.path.exists(log_path):
32
+ print(f"[+] No system log file at '{log_path}'.")
33
+ return EXIT_SUCCESS
34
+
35
+ with open(log_path, "r", encoding="utf-8", errors="replace") as f:
36
+ all_lines = f.readlines()
37
+ tail = all_lines[-lines_limit:]
38
+
39
+ if context.is_json:
40
+ print_json({"log_file": log_path, "lines": [line.rstrip() for line in tail]})
41
+ else:
42
+ for line in tail:
43
+ print(line, end="")
44
+
45
+ return EXIT_SUCCESS
@@ -0,0 +1,49 @@
1
+ """Handler for 'ether mcp' command."""
2
+
3
+ import asyncio
4
+ import logging
5
+ from typing import Any
6
+
7
+ from ether.cli.context import EXIT_RUNTIME_ERROR, EXIT_SUCCESS, CliContext
8
+ from ether.cli.formatters import print_error
9
+ from ether.gateway.gate import GatePolicy
10
+ from ether.mcp.server import create_mcp_server
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ async def handle_mcp(args: Any, context: CliContext) -> int:
16
+ """Launch the Native Model Context Protocol (MCP) server."""
17
+ transport = getattr(args, "transport", "stdio")
18
+ session_id = getattr(args, "session_id", None)
19
+ port = int(getattr(args, "port", 8000))
20
+ host = getattr(args, "host", "127.0.0.1")
21
+ policy_str = getattr(
22
+ args, "policy", context.policy.value if hasattr(context, "policy") else "safe"
23
+ )
24
+ policy = GatePolicy.UNRESTRICTED if policy_str == "unrestricted" else GatePolicy.SAFE
25
+
26
+ registry = context.get_registry()
27
+ async with context.open_store() as store:
28
+ server = create_mcp_server(
29
+ store=store,
30
+ default_session_id=session_id,
31
+ policy=policy,
32
+ registry=registry,
33
+ )
34
+
35
+ try:
36
+ if transport == "stdio":
37
+ await server.run_stdio_async()
38
+ elif transport == "sse":
39
+ await server.run_sse_async(host=host, port=port)
40
+ else:
41
+ print_error(f"Unsupported transport '{transport}'. Use 'stdio' or 'sse'.")
42
+ return EXIT_RUNTIME_ERROR
43
+ except (KeyboardInterrupt, asyncio.CancelledError):
44
+ pass
45
+ except Exception as e:
46
+ print_error(f"MCP server runtime error: {e}")
47
+ return EXIT_RUNTIME_ERROR
48
+
49
+ return EXIT_SUCCESS
@@ -0,0 +1,146 @@
1
+ """Handler for 'ether run <tool> <target>' command."""
2
+
3
+ import ipaddress
4
+ import shlex
5
+ import sys
6
+ from typing import Any, List
7
+ from uuid import UUID
8
+
9
+ from ether.cli.context import EXIT_RUNTIME_ERROR, EXIT_SUCCESS, CliContext
10
+ from ether.cli.formatters import print_error, print_json
11
+ from ether.core.session import (
12
+ ExecutionChunk,
13
+ ExecutionCompleted,
14
+ ExecutionFailed,
15
+ ExecutionStarted,
16
+ )
17
+ from ether.gateway.gate import ActionGateway
18
+ from ether.schemas.base import BaseFinding
19
+ from ether.schemas.dns import DomainInfo
20
+ from ether.schemas.network import NetworkHost
21
+ from ether.schemas.power import ActionRequest
22
+ from ether.schemas.web import WebEndpoint
23
+
24
+
25
+ def _infer_target_finding(target: str) -> BaseFinding:
26
+ """Infer the typed BaseFinding entity from a raw CLI target string."""
27
+ # Check IP
28
+ try:
29
+ ipaddress.ip_address(target)
30
+ return NetworkHost.create(ip=target)
31
+ except ValueError:
32
+ pass
33
+
34
+ # Check Web URL
35
+ if target.startswith("http://") or target.startswith("https://"):
36
+ return WebEndpoint.create(url=target)
37
+
38
+ # Check CIDR
39
+ if "/" in target:
40
+ try:
41
+ ipaddress.ip_network(target, strict=False)
42
+ return BaseFinding(
43
+ schema_type="network.netblock", pik={"cidr": target}, data={"cidr": target}
44
+ )
45
+ except ValueError:
46
+ pass
47
+
48
+ # Default to DomainInfo
49
+ return DomainInfo.create(domain=target)
50
+
51
+
52
+ async def handle_run(args: Any, context: CliContext) -> int:
53
+ """Execute a tool action through the preflight gate, gateway, and execution session."""
54
+ tool_name = getattr(args, "tool", None)
55
+ target = getattr(args, "target", None)
56
+ raw_flags = getattr(args, "flags", None) or []
57
+ flags: List[str] = []
58
+ for f in raw_flags:
59
+ flags.extend(shlex.split(f) if isinstance(f, str) else [str(f)])
60
+
61
+ if not tool_name or not target:
62
+ print_error(
63
+ "Both tool and target are required. Usage: ether run <tool> <target> [flags...]"
64
+ )
65
+ return EXIT_RUNTIME_ERROR
66
+
67
+ registry = context.get_registry()
68
+ if not registry.get_tool(tool_name):
69
+ print_error(f"Tool '{tool_name}' is not registered.")
70
+ return EXIT_RUNTIME_ERROR
71
+
72
+ # 1. Preflight Verification Gate via ActionGateway
73
+ gateway = ActionGateway(registry=registry, policy=context.policy)
74
+ flags_str = " ".join(flags)
75
+ report = gateway.preflight_verify(tool_name=tool_name, target=target, flags=flags_str)
76
+
77
+ if not report.is_valid:
78
+ print_error(f"Preflight validation failed for '{tool_name}':")
79
+ for err in report.errors:
80
+ print(f" [-] {err.code}: {err.message}", file=sys.stderr)
81
+ if err.remedy:
82
+ print(f" Remedy: {err.remedy}", file=sys.stderr)
83
+ return EXIT_RUNTIME_ERROR
84
+
85
+ if report.has_warnings and not context.is_json:
86
+ for warn in report.warnings:
87
+ print(f" [!] Warning ({warn.code}): {warn.message}", file=sys.stderr)
88
+
89
+ # 2. Database & Target Finding Setup
90
+ async with context.open_store() as store:
91
+ gateway.store = store
92
+ session_id = getattr(args, "session_id", None)
93
+ if not session_id:
94
+ _, sess_id = await store.get_or_create_default_session()
95
+ session_id = sess_id
96
+
97
+ target_finding = _infer_target_finding(target)
98
+ target_node_id = await store.upsert_finding(session_id, target_finding)
99
+
100
+ # 3. Execution Session Setup via Gateway
101
+ session = gateway.create_session()
102
+
103
+ action = ActionRequest(
104
+ session_id=UUID(session_id),
105
+ tool_name=tool_name,
106
+ target_entity_id=target_node_id,
107
+ params={"target": target, "flags": flags},
108
+ )
109
+
110
+ if not context.is_json:
111
+ print(f"[*] Dispatching {tool_name} against {target} (Session: {session_id[:8]}...)")
112
+
113
+ # 4. Dispatch and Stream Events
114
+ action_id = await session.dispatch(action)
115
+ exit_code = EXIT_SUCCESS
116
+
117
+ async for event in session.subscribe(action_id):
118
+ if isinstance(event, ExecutionStarted):
119
+ if not context.is_json and context.verbose:
120
+ print(f"[*] Command: {' '.join(event.command)}")
121
+ elif isinstance(event, ExecutionChunk):
122
+ if not context.is_json:
123
+ sys.stdout.write(event.text)
124
+ sys.stdout.flush()
125
+ elif isinstance(event, ExecutionFailed):
126
+ print_error(f"Execution failed: {event.error}")
127
+ exit_code = EXIT_RUNTIME_ERROR
128
+ elif isinstance(event, ExecutionCompleted):
129
+ if not context.is_json:
130
+ print(
131
+ f"\n[*] Execution finished (Status: {event.status.value}, Findings: {event.findings_count}, Duration: {event.duration_seconds:.2f}s)"
132
+ )
133
+ elif context.is_json:
134
+ print_json(
135
+ {
136
+ "action_id": str(action_id),
137
+ "session_id": str(session_id),
138
+ "tool_name": tool_name,
139
+ "status": event.status.value,
140
+ "findings_count": event.findings_count,
141
+ "duration_seconds": event.duration_seconds,
142
+ }
143
+ )
144
+
145
+ await session.shutdown()
146
+ return exit_code