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
@@ -0,0 +1,93 @@
1
+ """Deterministic offline vector embedding engine for Ether."""
2
+
3
+ import hashlib
4
+ import math
5
+ import re
6
+ from typing import List, Optional
7
+
8
+
9
+ class VectorEmbeddingEngine:
10
+ """Generates 384-dimensional normalized float vectors for offline similarity search.
11
+
12
+ Uses a deterministic feature-hashing algorithm (token unigrams, bigrams, and character
13
+ trigrams with SHA-256 random projections and L2 normalization). Guarantees zero network
14
+ egress, zero external model downloads, and sub-millisecond execution.
15
+ """
16
+
17
+ DIMENSION: int = 384
18
+
19
+ def __init__(self, dimension: int = DIMENSION) -> None:
20
+ self.dimension = dimension
21
+
22
+ def embed_text(self, text: str) -> List[float]:
23
+ """Convert a text string into a 384-dimensional unit vector."""
24
+ if not text or not text.strip():
25
+ vec = [0.0] * self.dimension
26
+ vec[0] = 1.0
27
+ return vec
28
+
29
+ cleaned = text.lower()
30
+ tokens = re.findall(r"\w+", cleaned)
31
+ if not tokens:
32
+ vec = [0.0] * self.dimension
33
+ vec[0] = 1.0
34
+ return vec
35
+
36
+ vec = [0.0] * self.dimension
37
+
38
+ # 1. Word unigrams (3 independent random projections, weight = 2.0)
39
+ for token in tokens:
40
+ for h_idx in range(3):
41
+ self._hash_feature(f"{h_idx}:{token}", weight=2.0, vector=vec)
42
+
43
+ # 2. Word bigrams (2 independent random projections, weight = 1.5)
44
+ for i in range(len(tokens) - 1):
45
+ bigram = f"{tokens[i]}_{tokens[i + 1]}"
46
+ for h_idx in range(2):
47
+ self._hash_feature(f"bg:{h_idx}:{bigram}", weight=1.5, vector=vec)
48
+
49
+ # 3. Character 4-grams for subword robustness (weight = 0.5)
50
+ for token in tokens:
51
+ if len(token) >= 4:
52
+ for i in range(len(token) - 3):
53
+ ngram = token[i : i + 4]
54
+ self._hash_feature(f"ng:{ngram}", weight=0.5, vector=vec)
55
+
56
+ # 4. L2 Normalization to ensure ||v||_2 = 1.0
57
+ norm_sq = sum(x * x for x in vec)
58
+ if norm_sq <= 1e-12:
59
+ vec[0] = 1.0
60
+ return vec
61
+
62
+ norm = math.sqrt(norm_sq)
63
+ return [float(x / norm) for x in vec]
64
+
65
+ def _hash_feature(self, feature: str, weight: float, vector: List[float]) -> None:
66
+ """Hash feature into dimension bucket with signed projection."""
67
+ digest = hashlib.sha256(feature.encode("utf-8")).digest()
68
+ bucket = int.from_bytes(digest[:4], byteorder="big") % self.dimension
69
+ sign = 1.0 if digest[4] % 2 == 0 else -1.0
70
+ vector[bucket] += sign * weight
71
+
72
+ def embed_batch(self, texts: List[str]) -> List[List[float]]:
73
+ """Batch embedding of text strings."""
74
+ return [self.embed_text(t) for t in texts]
75
+
76
+ @staticmethod
77
+ def cosine_similarity(v1: List[float], v2: List[float]) -> float:
78
+ """Calculate cosine similarity between two unit vectors: dot(v1, v2)."""
79
+ if len(v1) != len(v2):
80
+ raise ValueError(f"Vector dimensions do not match: {len(v1)} vs {len(v2)}")
81
+ dot = sum(a * b for a, b in zip(v1, v2, strict=True))
82
+ return max(-1.0, min(1.0, dot))
83
+
84
+
85
+ _default_engine: Optional[VectorEmbeddingEngine] = None
86
+
87
+
88
+ def get_embedding_engine() -> VectorEmbeddingEngine:
89
+ """Retrieve or initialize the global VectorEmbeddingEngine singleton."""
90
+ global _default_engine
91
+ if _default_engine is None:
92
+ _default_engine = VectorEmbeddingEngine()
93
+ return _default_engine
@@ -0,0 +1,13 @@
1
+ """Root domain exceptions for Ether."""
2
+
3
+
4
+ class EtherError(Exception):
5
+ """Base exception for all domain errors raised by the Ether engine."""
6
+
7
+ pass
8
+
9
+
10
+ class PolicyViolationError(EtherError):
11
+ """Raised when an operation violates security policy boundaries (e.g. SSRF, metadata access)."""
12
+
13
+ pass
@@ -0,0 +1,386 @@
1
+ """Centralized diagnostic logging, flight recorder breadcrumbs, and crash trap monitoring for Ether.
2
+
3
+ Provides:
4
+ 1. Secure Rotating File Logging: ~/.ether/logs/ether.log created atomically with mode 0o600.
5
+ 2. Sanitizing Formatter: Automatic redaction of operator API keys, passwords, and private keys.
6
+ 3. In-Memory Flight Recorder: Bounded ring buffer of recent execution state breadcrumbs.
7
+ 4. Exception Traps: Intercepts Python unhandled exceptions and asyncio task errors.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import asyncio
13
+ import logging
14
+ import logging.handlers
15
+ import os
16
+ import re
17
+ import sys
18
+ import threading
19
+ import traceback
20
+ from collections import deque
21
+ from dataclasses import dataclass, field
22
+ from datetime import UTC, datetime
23
+ from typing import Any, Callable, Dict, List, Optional
24
+
25
+ from ether.common.secure_memory import (
26
+ sanitize_text_secrets,
27
+ )
28
+ from ether.paths import get_default_logs_dir, get_system_log_path
29
+
30
+ logger = logging.getLogger("ether")
31
+
32
+
33
+ class SecureRotatingFileHandler(logging.handlers.RotatingFileHandler):
34
+ """Rotating file handler that guarantees atomic 0o600 permissions upon file creation
35
+
36
+ to prevent TOCTOU permission races and secret leakage.
37
+ """
38
+
39
+ def _open(self):
40
+ # Guarantee parent directory exists with 0o700 permissions
41
+ dirname = os.path.dirname(self.baseFilename)
42
+ if dirname:
43
+ try:
44
+ os.makedirs(dirname, mode=0o700, exist_ok=True)
45
+ except OSError:
46
+ pass
47
+
48
+ # Open file atomically with restricted permissions (0o600: user read/write only)
49
+ fd = os.open(
50
+ self.baseFilename,
51
+ os.O_CREAT | os.O_WRONLY | os.O_APPEND,
52
+ 0o600,
53
+ )
54
+ return open(fd, self.mode, encoding=self.encoding)
55
+
56
+ def doRollover(self) -> None:
57
+ """Perform rollover while strictly preserving 0o600 permissions on all rotated log files."""
58
+ super().doRollover()
59
+ # Enforce 0o600 on current file if recreated
60
+ if os.path.exists(self.baseFilename):
61
+ try:
62
+ os.chmod(self.baseFilename, 0o600)
63
+ except OSError:
64
+ pass
65
+
66
+
67
+ class SanitizingLogFormatter(logging.Formatter):
68
+ """Log formatter that automatically scrubs sensitive credentials, tokens, and keys."""
69
+
70
+ def format(self, record: logging.LogRecord) -> str:
71
+ return sanitize_text_secrets(super().format(record))
72
+
73
+
74
+ @dataclass
75
+ class Breadcrumb:
76
+ """Lightweight operational state breadcrumb recorded in memory."""
77
+
78
+ timestamp: str
79
+ category: str
80
+ message: str
81
+ metadata: Dict[str, Any] = field(default_factory=dict)
82
+
83
+ def format_line(self) -> str:
84
+ meta_str = f" | {self.metadata}" if self.metadata else ""
85
+ return f"[{self.timestamp}] [{self.category.upper()}] {self.message}{meta_str}"
86
+
87
+
88
+ class FlightRecorder:
89
+ """In-memory bounded ring buffer recording recent state transitions, command executions,
90
+
91
+ and async lifecycle events for forensic post-mortem analysis during unexpected crashes.
92
+ """
93
+
94
+ _instance: Optional[FlightRecorder] = None
95
+
96
+ def __init__(self, maxlen: int = 200) -> None:
97
+ self._buffer: deque[Breadcrumb] = deque(maxlen=maxlen)
98
+ self._lock = threading.Lock()
99
+
100
+ @classmethod
101
+ def get_instance(cls) -> FlightRecorder:
102
+ if cls._instance is None:
103
+ cls._instance = FlightRecorder()
104
+ return cls._instance
105
+
106
+ def record(self, category: str, message: str, **metadata: Any) -> None:
107
+ """Record an operational breadcrumb into the bounded buffer."""
108
+ # Sanitize metadata string values to avoid storing plain secrets
109
+ safe_meta = {}
110
+ for k, v in metadata.items():
111
+ if isinstance(v, str):
112
+ v = sanitize_text_secrets(v)
113
+ safe_meta[k] = v
114
+
115
+ crumb = Breadcrumb(
116
+ timestamp=datetime.now(UTC).strftime("%Y-%m-%d %H:%M:%S.%f")[:-3],
117
+ category=category,
118
+ message=message,
119
+ metadata=safe_meta,
120
+ )
121
+ with self._lock:
122
+ self._buffer.append(crumb)
123
+
124
+ def get_breadcrumbs(self, limit: int = 50) -> List[Breadcrumb]:
125
+ """Return the most recent breadcrumbs up to limit."""
126
+ with self._lock:
127
+ crumbs = list(self._buffer)
128
+ return crumbs[-limit:] if limit > 0 else crumbs
129
+
130
+ def format_breadcrumbs(self, limit: int = 50) -> str:
131
+ """Format recent breadcrumbs as a clean text block."""
132
+ crumbs = self.get_breadcrumbs(limit=limit)
133
+ if not crumbs:
134
+ return "No recorded flight breadcrumbs."
135
+ lines = [c.format_line() for c in crumbs]
136
+ return "\n".join(lines)
137
+
138
+ def clear(self) -> None:
139
+ with self._lock:
140
+ self._buffer.clear()
141
+
142
+
143
+ def record_breadcrumb(category: str, message: str, **metadata: Any) -> None:
144
+ """Global convenience helper to record an operational breadcrumb in memory and log to file."""
145
+ FlightRecorder.get_instance().record(category, message, **metadata)
146
+ meta_str = f" | {metadata}" if metadata else ""
147
+ logger.info("[%s] %s%s", category.upper(), message, meta_str)
148
+
149
+
150
+ _LOGGING_INITIALIZED = False
151
+ _ORIGINAL_EXCEPTHOOK: Optional[Callable] = None
152
+ _ORIGINAL_THREADING_EXCEPTHOOK: Optional[Callable] = None
153
+
154
+
155
+ def setup_system_logging(
156
+ data_dir: Optional[str] = None,
157
+ verbose: bool = False,
158
+ log_to_stderr: bool = False,
159
+ force: bool = False,
160
+ ) -> logging.Logger:
161
+ """Configure system-wide centralized application logging to ~/.ether/logs/ether.log.
162
+
163
+ Guarantees atomic 0o600 permissions, log rotation (5MB cap, 3 backups),
164
+ and credential sanitization.
165
+ """
166
+ global _LOGGING_INITIALIZED
167
+ if _LOGGING_INITIALIZED and not force:
168
+ return logger
169
+
170
+ # Ensure log directory exists
171
+ get_default_logs_dir(data_dir)
172
+ log_file_path = get_system_log_path(data_dir)
173
+
174
+ log_level = logging.DEBUG if (verbose or os.environ.get("ETHER_DEBUG")) else logging.INFO
175
+ logger.setLevel(log_level)
176
+
177
+ # Avoid duplicate handlers if re-called
178
+ for h in list(logger.handlers):
179
+ h.close()
180
+ logger.handlers.clear()
181
+
182
+ formatter = SanitizingLogFormatter(
183
+ fmt="%(asctime)s [%(levelname)s] [%(name)s] [%(threadName)s] %(message)s",
184
+ datefmt="%Y-%m-%d %H:%M:%S",
185
+ )
186
+
187
+ # 1. Secure rotating file handler
188
+ file_handler = SecureRotatingFileHandler(
189
+ filename=log_file_path,
190
+ maxBytes=5 * 1024 * 1024, # 5 MB
191
+ backupCount=3,
192
+ encoding="utf-8",
193
+ )
194
+ file_handler.setLevel(log_level)
195
+ file_handler.setFormatter(formatter)
196
+ logger.addHandler(file_handler)
197
+
198
+ # 2. Optional stderr stream handler (e.g. for CLI verbose mode)
199
+ if log_to_stderr:
200
+ stderr_handler = logging.StreamHandler(sys.stderr)
201
+ stderr_handler.setLevel(log_level)
202
+ stderr_handler.setFormatter(formatter)
203
+ logger.addHandler(stderr_handler)
204
+
205
+ # Prevent propagation to root logger unless desired
206
+ logger.propagate = False
207
+
208
+ _LOGGING_INITIALIZED = True
209
+ try:
210
+ from ether import __version__
211
+
212
+ ver_str = f"v{__version__}"
213
+ except Exception:
214
+ ver_str = "unknown"
215
+
216
+ logger.info(
217
+ "Ether centralized logging initialized (%s, pid=%d, log=%s)",
218
+ ver_str,
219
+ os.getpid(),
220
+ log_file_path,
221
+ )
222
+ record_breadcrumb(
223
+ "system",
224
+ "Flight recorder active",
225
+ log_path=log_file_path,
226
+ level=logging.getLevelName(log_level),
227
+ )
228
+ for h in logger.handlers:
229
+ h.flush()
230
+ return logger
231
+
232
+
233
+ def install_global_exception_traps(loop: Optional[asyncio.AbstractEventLoop] = None) -> None:
234
+ """Install global crash hooks into sys.excepthook, threading.excepthook, and asyncio loop."""
235
+ global _ORIGINAL_EXCEPTHOOK, _ORIGINAL_THREADING_EXCEPTHOOK
236
+
237
+ def _global_excepthook(exc_type, exc_value, exc_traceback):
238
+ # Ignore normal process exits and keyboard interrupts
239
+ if issubclass(exc_type, (KeyboardInterrupt, SystemExit)):
240
+ if _ORIGINAL_EXCEPTHOOK:
241
+ _ORIGINAL_EXCEPTHOOK(exc_type, exc_value, exc_traceback)
242
+ else:
243
+ sys.__excepthook__(exc_type, exc_value, exc_traceback)
244
+ return
245
+
246
+ breadcrumbs = FlightRecorder.get_instance().format_breadcrumbs(35)
247
+ tb_str = "".join(traceback.format_exception(exc_type, exc_value, exc_traceback))
248
+
249
+ logger.critical(
250
+ "FATAL UNHANDLED EXCEPTION ESCAPED TO PYTHON INTERPRETER:\n"
251
+ "%s\n"
252
+ "=== FLIGHT RECORDER BREADCRUMBS ===\n"
253
+ "%s\n"
254
+ "====================================",
255
+ tb_str.strip(),
256
+ breadcrumbs,
257
+ )
258
+
259
+ for handler in logger.handlers:
260
+ handler.flush()
261
+
262
+ if _ORIGINAL_EXCEPTHOOK:
263
+ _ORIGINAL_EXCEPTHOOK(exc_type, exc_value, exc_traceback)
264
+ else:
265
+ sys.__excepthook__(exc_type, exc_value, exc_traceback)
266
+
267
+ if _ORIGINAL_EXCEPTHOOK is None:
268
+ _ORIGINAL_EXCEPTHOOK = sys.excepthook
269
+ sys.excepthook = _global_excepthook
270
+
271
+ def _threading_excepthook(args):
272
+ if issubclass(args.exc_type, (KeyboardInterrupt, SystemExit)):
273
+ return
274
+
275
+ breadcrumbs = FlightRecorder.get_instance().format_breadcrumbs(35)
276
+ tb_str = "".join(
277
+ traceback.format_exception(args.exc_type, args.exc_value, args.exc_traceback)
278
+ )
279
+
280
+ logger.critical(
281
+ "FATAL UNHANDLED EXCEPTION IN BACKGROUND THREAD '%s':\n"
282
+ "%s\n"
283
+ "=== FLIGHT RECORDER BREADCRUMBS ===\n"
284
+ "%s\n"
285
+ "====================================",
286
+ args.thread.name if args.thread else "Unknown",
287
+ tb_str.strip(),
288
+ breadcrumbs,
289
+ )
290
+
291
+ for handler in logger.handlers:
292
+ handler.flush()
293
+
294
+ if _ORIGINAL_THREADING_EXCEPTHOOK:
295
+ _ORIGINAL_THREADING_EXCEPTHOOK(args)
296
+
297
+ if hasattr(threading, "excepthook") and _ORIGINAL_THREADING_EXCEPTHOOK is None:
298
+ _ORIGINAL_THREADING_EXCEPTHOOK = threading.excepthook
299
+ threading.excepthook = _threading_excepthook
300
+
301
+ if loop is not None:
302
+ _attach_asyncio_exception_handler(loop)
303
+
304
+
305
+ def _attach_asyncio_exception_handler(loop: asyncio.AbstractEventLoop) -> None:
306
+ """Attach defensive crash logger to asyncio event loop."""
307
+ orig_handler = loop.get_exception_handler()
308
+
309
+ def _async_exception_handler(
310
+ current_loop: asyncio.AbstractEventLoop, context: Dict[str, Any]
311
+ ) -> None:
312
+ exc = context.get("exception")
313
+ msg = context.get("message", "Unhandled asyncio event loop exception")
314
+
315
+ # Suppress noise from expected normal task cancellations during shutdown
316
+ if isinstance(exc, asyncio.CancelledError):
317
+ logger.debug("Asyncio task was cancelled: %s", msg)
318
+ return
319
+
320
+ breadcrumbs = FlightRecorder.get_instance().format_breadcrumbs(35)
321
+ tb_str = ""
322
+ if exc is not None:
323
+ tb_str = "".join(traceback.format_exception(type(exc), exc, exc.__traceback__))
324
+
325
+ logger.error(
326
+ "UNHANDLED ASYNCIO EXCEPTION IN EVENT LOOP: %s\n"
327
+ "%s\n"
328
+ "=== FLIGHT RECORDER BREADCRUMBS ===\n"
329
+ "%s\n"
330
+ "====================================",
331
+ msg,
332
+ tb_str.strip() if tb_str else f"Context: {context}",
333
+ breadcrumbs,
334
+ )
335
+
336
+ for handler in logger.handlers:
337
+ handler.flush()
338
+
339
+ if orig_handler:
340
+ orig_handler(current_loop, context)
341
+ else:
342
+ current_loop.default_exception_handler(context)
343
+
344
+ loop.set_exception_handler(_async_exception_handler)
345
+
346
+
347
+ def get_recent_crash_summary(
348
+ data_dir: Optional[str] = None, max_lines: int = 150
349
+ ) -> Optional[Dict[str, Any]]:
350
+ """Scan ~/.ether/logs/ether.log for the most recent critical crash traceback block.
351
+
352
+ Returns structured summary if found, or None.
353
+ """
354
+ log_path = get_system_log_path(data_dir)
355
+ if not os.path.exists(log_path):
356
+ return None
357
+
358
+ try:
359
+ with open(log_path, "r", encoding="utf-8", errors="replace") as f:
360
+ # Read last chunk
361
+ f.seek(0, os.SEEK_END)
362
+ size = f.tell()
363
+ chunk_size = min(size, 65536)
364
+ f.seek(size - chunk_size)
365
+ lines = f.readlines()
366
+ except Exception:
367
+ return None
368
+
369
+ crash_marker_indices = [i for i, l in enumerate(lines) if "FATAL UNHANDLED EXCEPTION" in l]
370
+
371
+ if not crash_marker_indices:
372
+ return None
373
+
374
+ latest_idx = crash_marker_indices[-1]
375
+ crash_block = lines[latest_idx : latest_idx + 60]
376
+
377
+ # Extract timestamp from the marker line
378
+ marker_line = lines[latest_idx]
379
+ timestamp_match = re.match(r"^(\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2})", marker_line)
380
+ timestamp = timestamp_match.group(1) if timestamp_match else "Unknown"
381
+
382
+ return {
383
+ "timestamp": timestamp,
384
+ "summary": marker_line.strip(),
385
+ "block": "".join(crash_block).strip(),
386
+ }
@@ -0,0 +1,159 @@
1
+ """Zero-leakage in-memory credential and secret scrubbing primitives for Ether.
2
+
3
+ Uses ctypes.memset to overwrite sensitive cryptographic keys, passwords, and tokens
4
+ directly in process memory upon task finalization, preventing residual keys from
5
+ lingering in the Python heap or process core dumps.
6
+ """
7
+
8
+ import ctypes
9
+ import re
10
+ from typing import Any, List, Optional, Set, Tuple, Union
11
+
12
+ DEFAULT_SENSITIVE_KEYS: Set[str] = {
13
+ "password",
14
+ "passphrase",
15
+ "token",
16
+ "auth_token",
17
+ "access_token",
18
+ "bearer",
19
+ "api_key",
20
+ "secret",
21
+ "secret_key",
22
+ "private_key",
23
+ "ssh_key",
24
+ "id_rsa",
25
+ "authorization",
26
+ "credential",
27
+ "credentials",
28
+ }
29
+
30
+ DEFAULT_REDACT_PATTERNS: List[Tuple[re.Pattern, str]] = [
31
+ (
32
+ re.compile(
33
+ r"(?i)(api[_-]?key|secret|token|password|passwd|auth)\s*[:=]\s*['\"]?([^\s'\"]{6,})['\"]?"
34
+ ),
35
+ r"\1=***REDACTED***",
36
+ ),
37
+ (re.compile(r"Bearer\s+[A-Za-z0-9_\-\.]{15,}"), "Bearer ***REDACTED***"),
38
+ (re.compile(r"sk-[A-Za-z0-9]{20,}"), "sk-***REDACTED***"),
39
+ (re.compile(r"ghp_[A-Za-z0-9]{20,}"), "ghp_***REDACTED***"),
40
+ (re.compile(r"://([^:]+):([^@]+)@"), r"://\1:***@"),
41
+ (
42
+ re.compile(r"-----BEGIN [A-Z ]+PRIVATE KEY-----[\s\S]*?-----END [A-Z ]+PRIVATE KEY-----"),
43
+ "-----BEGIN PRIVATE KEY----- [***REDACTED***] -----END PRIVATE KEY-----",
44
+ ),
45
+ ]
46
+
47
+
48
+ def sanitize_text_secrets(
49
+ text: str, patterns: Optional[List[Tuple[re.Pattern, str]]] = None
50
+ ) -> str:
51
+ """Scrub sensitive credentials, tokens, and private keys from an unstructured text stream."""
52
+ if not text:
53
+ return text
54
+ active_patterns = patterns or DEFAULT_REDACT_PATTERNS
55
+ sanitized = text
56
+ for pattern, replacement in active_patterns:
57
+ sanitized = pattern.sub(replacement, sanitized)
58
+ return sanitized
59
+
60
+
61
+ def wipe_buffer(buf: Union[bytearray, ctypes.Array, Any]) -> None:
62
+ """Zero out the memory of a mutable buffer in-place using ctypes.memset."""
63
+ if isinstance(buf, bytearray):
64
+ if len(buf) > 0:
65
+ char_arr = (ctypes.c_char * len(buf)).from_buffer(buf)
66
+ ctypes.memset(ctypes.addressof(char_arr), 0, len(buf))
67
+ elif hasattr(buf, "_type_") and hasattr(buf, "_length_"):
68
+ # Ctypes array
69
+ size = ctypes.sizeof(buf)
70
+ ctypes.memset(ctypes.addressof(buf), 0, size)
71
+
72
+
73
+ class SecureBuffer:
74
+ """A mutable byte buffer with guaranteed in-place memory zeroing.
75
+
76
+ Zeroes memory on context exit (__exit__), explicit wipe(), or finalization (__del__).
77
+ """
78
+
79
+ def __init__(self, data: Union[bytes, bytearray, str]) -> None:
80
+ if isinstance(data, str):
81
+ encoded = data.encode("utf-8")
82
+ elif isinstance(data, (bytes, bytearray)):
83
+ encoded = bytes(data)
84
+ else:
85
+ raise TypeError(
86
+ f"SecureBuffer accepts bytes, bytearray, or str, got {type(data).__name__}"
87
+ )
88
+
89
+ self._buf: bytearray = bytearray(encoded)
90
+ self._wiped: bool = False
91
+
92
+ @property
93
+ def is_wiped(self) -> bool:
94
+ return self._wiped
95
+
96
+ def get_bytes(self) -> bytes:
97
+ if self._wiped:
98
+ raise ValueError("SecureBuffer has already been wiped.")
99
+ return bytes(self._buf)
100
+
101
+ def get_string(self) -> str:
102
+ if self._wiped:
103
+ raise ValueError("SecureBuffer has already been wiped.")
104
+ return self._buf.decode("utf-8", errors="replace")
105
+
106
+ def wipe(self) -> None:
107
+ """Overwrite the internal memory with null bytes immediately."""
108
+ if not self._wiped and len(self._buf) > 0:
109
+ wipe_buffer(self._buf)
110
+ self._wiped = True
111
+
112
+ def __enter__(self) -> "SecureBuffer":
113
+ return self
114
+
115
+ def __exit__(self, exc_type, exc_val, exc_tb) -> None:
116
+ self.wipe()
117
+
118
+ def __del__(self) -> None:
119
+ try:
120
+ self.wipe()
121
+ except Exception:
122
+ pass
123
+
124
+ def __len__(self) -> int:
125
+ return len(self._buf)
126
+
127
+ def __repr__(self) -> str:
128
+ return "<SecureBuffer: [WIPED]>" if self._wiped else f"<SecureBuffer: len={len(self._buf)}>"
129
+
130
+
131
+ def wipe_credentials(target: Any, sensitive_keys: Optional[Set[str]] = None) -> None:
132
+ """Recursively traverse a dictionary or list, wiping sensitive values in-place."""
133
+ keys = sensitive_keys or DEFAULT_SENSITIVE_KEYS
134
+
135
+ if isinstance(target, dict):
136
+ for k in list(target.keys()):
137
+ val = target[k]
138
+ key_lower = str(k).lower()
139
+ is_sensitive = any(sk in key_lower for sk in keys)
140
+
141
+ if isinstance(val, (dict, list)):
142
+ wipe_credentials(val, sensitive_keys=keys)
143
+ elif is_sensitive:
144
+ if isinstance(val, SecureBuffer):
145
+ val.wipe()
146
+ elif isinstance(val, bytearray):
147
+ wipe_buffer(val)
148
+ elif isinstance(val, (bytes, str)):
149
+ target[k] = "[WIPED]"
150
+
151
+ elif isinstance(target, list):
152
+ for _idx, item in enumerate(target):
153
+ if isinstance(item, (bytearray, SecureBuffer)):
154
+ if isinstance(item, SecureBuffer):
155
+ item.wipe()
156
+ else:
157
+ wipe_buffer(item)
158
+ elif isinstance(item, (dict, list)):
159
+ wipe_credentials(item, sensitive_keys=keys)