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.
- ether/__init__.py +32 -0
- ether/assets/wordlists/common_dirs.txt.gz +0 -0
- ether/assets/wordlists/common_params.txt.gz +0 -0
- ether/assets/wordlists/common_passwords.txt.gz +0 -0
- ether/assets/wordlists/common_usernames.txt.gz +0 -0
- ether/assets/wordlists/subdomains_500.txt.gz +0 -0
- ether/cli/__init__.py +5 -0
- ether/cli/__main__.py +8 -0
- ether/cli/commands/__init__.py +1 -0
- ether/cli/commands/doctor.py +21 -0
- ether/cli/commands/graph.py +311 -0
- ether/cli/commands/logs.py +45 -0
- ether/cli/commands/mcp.py +49 -0
- ether/cli/commands/run.py +146 -0
- ether/cli/commands/session.py +61 -0
- ether/cli/commands/telemetry.py +51 -0
- ether/cli/commands/tool.py +131 -0
- ether/cli/context.py +71 -0
- ether/cli/formatters.py +39 -0
- ether/cli/router.py +368 -0
- ether/common/__init__.py +201 -0
- ether/common/algorithms.py +407 -0
- ether/common/canonicalize.py +93 -0
- ether/common/context.py +25 -0
- ether/common/crypto.py +183 -0
- ether/common/embeddings.py +93 -0
- ether/common/exceptions.py +13 -0
- ether/common/logging.py +386 -0
- ether/common/secure_memory.py +159 -0
- ether/common/ssrf.py +93 -0
- ether/core/__init__.py +25 -0
- ether/core/diagnostics.py +368 -0
- ether/core/executor.py +296 -0
- ether/core/sandbox.py +118 -0
- ether/core/session.py +956 -0
- ether/gateway/__init__.py +21 -0
- ether/gateway/gate.py +392 -0
- ether/gateway/network.py +98 -0
- ether/gateway/preflight.py +802 -0
- ether/graph/__init__.py +13 -0
- ether/graph/analytics.py +334 -0
- ether/graph/store.py +1615 -0
- ether/graph/telemetry.py +334 -0
- ether/graph/timeline.py +185 -0
- ether/mcp/__init__.py +5 -0
- ether/mcp/server.py +382 -0
- ether/paths.py +176 -0
- ether/py.typed +0 -0
- ether/registry/__init__.py +7 -0
- ether/registry/adapter.py +194 -0
- ether/registry/manifest.py +53 -0
- ether/registry/registry.py +150 -0
- ether/registry/wordlists.py +156 -0
- ether/schemas/__init__.py +50 -0
- ether/schemas/base.py +122 -0
- ether/schemas/credential.py +50 -0
- ether/schemas/dns.py +116 -0
- ether/schemas/host_internal.py +58 -0
- ether/schemas/network.py +142 -0
- ether/schemas/power.py +68 -0
- ether/schemas/vulnerability.py +221 -0
- ether/schemas/web.py +172 -0
- ether_core-0.1.0.dist-info/METADATA +440 -0
- ether_core-0.1.0.dist-info/RECORD +104 -0
- ether_core-0.1.0.dist-info/WHEEL +4 -0
- ether_core-0.1.0.dist-info/entry_points.txt +2 -0
- ether_core-0.1.0.dist-info/licenses/LICENSE +21 -0
- tools/__init__.py +0 -0
- tools/dnspython/__init__.py +1 -0
- tools/dnspython/adapter.py +302 -0
- tools/dnspython/cli.py +202 -0
- tools/dnspython/manifest.toml +138 -0
- tools/ffuf/__init__.py +1 -0
- tools/ffuf/adapter.py +183 -0
- tools/ffuf/manifest.toml +121 -0
- tools/gobuster/__init__.py +0 -0
- tools/gobuster/adapter.py +90 -0
- tools/gobuster/manifest.toml +104 -0
- tools/http_probe/adapter.py +256 -0
- tools/http_probe/manifest.toml +40 -0
- tools/netexec/__init__.py +1 -0
- tools/netexec/adapter.py +163 -0
- tools/netexec/manifest.toml +83 -0
- tools/nikto/__init__.py +0 -0
- tools/nikto/adapter.py +145 -0
- tools/nikto/manifest.toml +108 -0
- tools/nmap/__init__.py +0 -0
- tools/nmap/adapter.py +97 -0
- tools/nmap/manifest.toml +159 -0
- tools/nuclei/__init__.py +1 -0
- tools/nuclei/adapter.py +171 -0
- tools/nuclei/manifest.toml +117 -0
- tools/searchsploit/__init__.py +1 -0
- tools/searchsploit/adapter.py +139 -0
- tools/searchsploit/manifest.toml +103 -0
- tools/sqlmap/__init__.py +1 -0
- tools/sqlmap/adapter.py +214 -0
- tools/sqlmap/manifest.toml +89 -0
- tools/subfinder/__init__.py +0 -0
- tools/subfinder/adapter.py +71 -0
- tools/subfinder/manifest.toml +104 -0
- tools/whois/__init__.py +0 -0
- tools/whois/adapter.py +80 -0
- tools/whois/manifest.toml +95 -0
|
@@ -0,0 +1,407 @@
|
|
|
1
|
+
"""High-performance mathematical and algorithmic primitives for Ether.
|
|
2
|
+
|
|
3
|
+
This unified deep module provides foundational data structures and discrete algorithms:
|
|
4
|
+
1. IPRadixTrie: O(W) binary Patricia Radix Trie for IPv4 & IPv6 longest-prefix matching.
|
|
5
|
+
2. BloomFilter: Space-efficient probabilistic set with zero false negatives for database query pre-filtering.
|
|
6
|
+
3. DisjointSet: Disjoint-Set Union (Union-Find) with path compression and rank optimization.
|
|
7
|
+
4. MinHash: Locality-Sensitive Hashing for O(K) Jaccard similarity estimation across token sets.
|
|
8
|
+
5. knapsack_01: Dynamic programming 0/1 Knapsack solver for optimal context budgeting under token constraints.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import hashlib
|
|
12
|
+
import ipaddress
|
|
13
|
+
import math
|
|
14
|
+
import struct
|
|
15
|
+
from typing import (
|
|
16
|
+
Any,
|
|
17
|
+
Callable,
|
|
18
|
+
Dict,
|
|
19
|
+
Generic,
|
|
20
|
+
Iterable,
|
|
21
|
+
List,
|
|
22
|
+
Optional,
|
|
23
|
+
Sequence,
|
|
24
|
+
TypeVar,
|
|
25
|
+
Union,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
T = TypeVar("T")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
# ============================================================================
|
|
32
|
+
# 1. Binary Patricia Radix Trie for IP & CIDR Prefix Matching
|
|
33
|
+
# ============================================================================
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class _TrieNode:
|
|
37
|
+
__slots__ = ("children", "is_terminal", "data")
|
|
38
|
+
|
|
39
|
+
def __init__(self) -> None:
|
|
40
|
+
self.children: list[Optional[_TrieNode]] = [None, None]
|
|
41
|
+
self.is_terminal: bool = False
|
|
42
|
+
self.data: Any = None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class IPRadixTrie:
|
|
46
|
+
"""A bitwise binary radix trie supporting exact and longest-prefix IP and CIDR matching.
|
|
47
|
+
|
|
48
|
+
Matches IPv4 (32-bit) and IPv6 (128-bit) addresses in strict O(W) bitwise steps
|
|
49
|
+
where W <= 32 for IPv4 and W <= 128 for IPv6, eliminating O(N) list-scanning.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
def __init__(self) -> None:
|
|
53
|
+
self._root_v4 = _TrieNode()
|
|
54
|
+
self._root_v6 = _TrieNode()
|
|
55
|
+
self._count = 0
|
|
56
|
+
|
|
57
|
+
def insert(
|
|
58
|
+
self,
|
|
59
|
+
network: Union[
|
|
60
|
+
str,
|
|
61
|
+
ipaddress.IPv4Network,
|
|
62
|
+
ipaddress.IPv6Network,
|
|
63
|
+
ipaddress.IPv4Address,
|
|
64
|
+
ipaddress.IPv6Address,
|
|
65
|
+
],
|
|
66
|
+
data: Any = True,
|
|
67
|
+
) -> None:
|
|
68
|
+
"""Insert an IP address, CIDR string, or network object into the trie."""
|
|
69
|
+
if isinstance(network, str):
|
|
70
|
+
net = ipaddress.ip_network(network.strip(), strict=False)
|
|
71
|
+
elif isinstance(network, (ipaddress.IPv4Address, ipaddress.IPv6Address)):
|
|
72
|
+
net = ipaddress.ip_network(f"{network}/{network.max_prefixlen}")
|
|
73
|
+
else:
|
|
74
|
+
net = network
|
|
75
|
+
|
|
76
|
+
root = self._root_v4 if net.version == 4 else self._root_v6
|
|
77
|
+
total_bits = 32 if net.version == 4 else 128
|
|
78
|
+
net_int = int(net.network_address)
|
|
79
|
+
prefix_len = net.prefixlen
|
|
80
|
+
|
|
81
|
+
curr = root
|
|
82
|
+
for i in range(prefix_len):
|
|
83
|
+
bit = (net_int >> (total_bits - 1 - i)) & 1
|
|
84
|
+
if curr.children[bit] is None:
|
|
85
|
+
curr.children[bit] = _TrieNode()
|
|
86
|
+
curr = curr.children[bit]
|
|
87
|
+
|
|
88
|
+
curr.is_terminal = True
|
|
89
|
+
curr.data = data
|
|
90
|
+
self._count += 1
|
|
91
|
+
|
|
92
|
+
def contains(
|
|
93
|
+
self, ip: Union[str, ipaddress.IPv4Address, ipaddress.IPv6Address, int], version: int = 4
|
|
94
|
+
) -> bool:
|
|
95
|
+
"""Check if an IP address falls within any inserted CIDR prefix."""
|
|
96
|
+
return self.match_longest(ip, version=version) is not None
|
|
97
|
+
|
|
98
|
+
def match_longest(
|
|
99
|
+
self, ip: Union[str, ipaddress.IPv4Address, ipaddress.IPv6Address, int], version: int = 4
|
|
100
|
+
) -> Optional[Any]:
|
|
101
|
+
"""Find the longest matching prefix for the given IP address, returning associated data."""
|
|
102
|
+
if isinstance(ip, str):
|
|
103
|
+
try:
|
|
104
|
+
ip_obj = ipaddress.ip_address(ip.strip())
|
|
105
|
+
version = ip_obj.version
|
|
106
|
+
ip_int = int(ip_obj)
|
|
107
|
+
except ValueError:
|
|
108
|
+
return None
|
|
109
|
+
elif isinstance(ip, (ipaddress.IPv4Address, ipaddress.IPv6Address)):
|
|
110
|
+
version = ip.version
|
|
111
|
+
ip_int = int(ip)
|
|
112
|
+
else:
|
|
113
|
+
ip_int = int(ip)
|
|
114
|
+
|
|
115
|
+
root = self._root_v4 if version == 4 else self._root_v6
|
|
116
|
+
total_bits = 32 if version == 4 else 128
|
|
117
|
+
|
|
118
|
+
curr = root
|
|
119
|
+
longest_match = curr.data if curr.is_terminal else None
|
|
120
|
+
|
|
121
|
+
for i in range(total_bits):
|
|
122
|
+
bit = (ip_int >> (total_bits - 1 - i)) & 1
|
|
123
|
+
curr = curr.children[bit]
|
|
124
|
+
if curr is None:
|
|
125
|
+
break
|
|
126
|
+
if curr.is_terminal:
|
|
127
|
+
longest_match = curr.data
|
|
128
|
+
|
|
129
|
+
return longest_match
|
|
130
|
+
|
|
131
|
+
def __contains__(self, ip: Union[str, ipaddress.IPv4Address, ipaddress.IPv6Address]) -> bool:
|
|
132
|
+
return self.contains(ip)
|
|
133
|
+
|
|
134
|
+
def __len__(self) -> int:
|
|
135
|
+
return self._count
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
# ============================================================================
|
|
139
|
+
# 2. Optimal In-Memory Bloom Filter for Query Pre-Filtering
|
|
140
|
+
# ============================================================================
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
class BloomFilter:
|
|
144
|
+
"""A space-efficient probabilistic set with zero false negatives.
|
|
145
|
+
|
|
146
|
+
Uses optimal bit array size m = - (n * ln(p)) / (ln(2)^2) and
|
|
147
|
+
optimal number of hash functions k = (m / n) * ln(2).
|
|
148
|
+
"""
|
|
149
|
+
|
|
150
|
+
def __init__(self, capacity: int = 10000, error_rate: float = 0.01) -> None:
|
|
151
|
+
self.capacity = max(100, capacity)
|
|
152
|
+
self.error_rate = min(0.5, max(0.0001, error_rate))
|
|
153
|
+
|
|
154
|
+
# Optimal bit array size (m) and hash function count (k)
|
|
155
|
+
num_bits = -1.0 * (self.capacity * math.log(self.error_rate)) / (math.log(2) ** 2)
|
|
156
|
+
self.size = max(64, int(math.ceil(num_bits)))
|
|
157
|
+
num_hashes = (self.size / self.capacity) * math.log(2)
|
|
158
|
+
self.hash_count = max(1, int(round(num_hashes)))
|
|
159
|
+
|
|
160
|
+
# Using a bytearray as compact bitvector
|
|
161
|
+
self._bytes = bytearray(math.ceil(self.size / 8))
|
|
162
|
+
self._count = 0
|
|
163
|
+
|
|
164
|
+
def _get_hashes(self, item: str) -> list[int]:
|
|
165
|
+
"""Generate k hash indices using Kirsch-Mitzenmacher double hashing from a single 128-bit hash."""
|
|
166
|
+
digest = hashlib.md5(item.encode("utf-8")).digest()
|
|
167
|
+
h1, h2 = struct.unpack(">QQ", digest)
|
|
168
|
+
indices = []
|
|
169
|
+
for i in range(self.hash_count):
|
|
170
|
+
combined = (h1 + i * h2) % self.size
|
|
171
|
+
indices.append(combined)
|
|
172
|
+
return indices
|
|
173
|
+
|
|
174
|
+
def add(self, item: str) -> None:
|
|
175
|
+
"""Add an item key to the Bloom filter."""
|
|
176
|
+
for bit_index in self._get_hashes(item):
|
|
177
|
+
byte_idx = bit_index // 8
|
|
178
|
+
bit_offset = bit_index % 8
|
|
179
|
+
self._bytes[byte_idx] |= 1 << bit_offset
|
|
180
|
+
self._count += 1
|
|
181
|
+
|
|
182
|
+
def contains(self, item: str) -> bool:
|
|
183
|
+
"""Test whether an item may be in the set.
|
|
184
|
+
|
|
185
|
+
Returns False if the item is DEFINITELY NOT in the set (zero false negatives).
|
|
186
|
+
Returns True if the item is probably in the set.
|
|
187
|
+
"""
|
|
188
|
+
for bit_index in self._get_hashes(item):
|
|
189
|
+
byte_idx = bit_index // 8
|
|
190
|
+
bit_offset = bit_index % 8
|
|
191
|
+
if not (self._bytes[byte_idx] & (1 << bit_offset)):
|
|
192
|
+
return False
|
|
193
|
+
return True
|
|
194
|
+
|
|
195
|
+
def __contains__(self, item: str) -> bool:
|
|
196
|
+
return self.contains(item)
|
|
197
|
+
|
|
198
|
+
def __len__(self) -> int:
|
|
199
|
+
return self._count
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
# ============================================================================
|
|
203
|
+
# 3. Disjoint-Set Union (Union-Find)
|
|
204
|
+
# ============================================================================
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
class DisjointSet(Generic[T]):
|
|
208
|
+
"""Disjoint-Set Union (DSU) data structure with near O(α(N)) inverse Ackermann complexity.
|
|
209
|
+
|
|
210
|
+
Supports dynamic entity equivalence partitioning, host alias resolution, and
|
|
211
|
+
deterministic canonical representative selection.
|
|
212
|
+
"""
|
|
213
|
+
|
|
214
|
+
def __init__(self) -> None:
|
|
215
|
+
self._parent: Dict[T, T] = {}
|
|
216
|
+
self._rank: Dict[T, int] = {}
|
|
217
|
+
self._count = 0
|
|
218
|
+
|
|
219
|
+
def add(self, item: T) -> None:
|
|
220
|
+
"""Register a new element if not already present."""
|
|
221
|
+
if item not in self._parent:
|
|
222
|
+
self._parent[item] = item
|
|
223
|
+
self._rank[item] = 0
|
|
224
|
+
self._count += 1
|
|
225
|
+
|
|
226
|
+
def find(self, item: T) -> T:
|
|
227
|
+
"""Find the canonical representative of the partition containing item (with path compression)."""
|
|
228
|
+
if item not in self._parent:
|
|
229
|
+
self.add(item)
|
|
230
|
+
return item
|
|
231
|
+
|
|
232
|
+
# Two-pass path compression
|
|
233
|
+
root = item
|
|
234
|
+
while root != self._parent[root]:
|
|
235
|
+
root = self._parent[root]
|
|
236
|
+
|
|
237
|
+
curr = item
|
|
238
|
+
while curr != root:
|
|
239
|
+
nxt = self._parent[curr]
|
|
240
|
+
self._parent[curr] = root
|
|
241
|
+
curr = nxt
|
|
242
|
+
|
|
243
|
+
return root
|
|
244
|
+
|
|
245
|
+
def union(self, a: T, b: T) -> T:
|
|
246
|
+
"""Merge the sets containing elements a and b using union-by-rank.
|
|
247
|
+
|
|
248
|
+
Returns the resulting canonical representative.
|
|
249
|
+
"""
|
|
250
|
+
root_a = self.find(a)
|
|
251
|
+
root_b = self.find(b)
|
|
252
|
+
|
|
253
|
+
if root_a == root_b:
|
|
254
|
+
return root_a
|
|
255
|
+
|
|
256
|
+
rank_a = self._rank[root_a]
|
|
257
|
+
rank_b = self._rank[root_b]
|
|
258
|
+
|
|
259
|
+
if rank_a < rank_b:
|
|
260
|
+
self._parent[root_a] = root_b
|
|
261
|
+
winner = root_b
|
|
262
|
+
elif rank_a > rank_b:
|
|
263
|
+
self._parent[root_b] = root_a
|
|
264
|
+
winner = root_a
|
|
265
|
+
else:
|
|
266
|
+
# Deterministic tie-breaking: prefer lexicographically lower str representation
|
|
267
|
+
if str(root_a) <= str(root_b):
|
|
268
|
+
self._parent[root_b] = root_a
|
|
269
|
+
self._rank[root_a] += 1
|
|
270
|
+
winner = root_a
|
|
271
|
+
else:
|
|
272
|
+
self._parent[root_a] = root_b
|
|
273
|
+
self._rank[root_b] += 1
|
|
274
|
+
winner = root_b
|
|
275
|
+
|
|
276
|
+
self._count -= 1
|
|
277
|
+
return winner
|
|
278
|
+
|
|
279
|
+
def connected(self, a: T, b: T) -> bool:
|
|
280
|
+
"""Check if elements a and b belong to the same equivalence partition."""
|
|
281
|
+
return self.find(a) == self.find(b)
|
|
282
|
+
|
|
283
|
+
def get_components(self) -> Dict[T, List[T]]:
|
|
284
|
+
"""Return a mapping of canonical representative -> list of connected member elements."""
|
|
285
|
+
groups: Dict[T, List[T]] = {}
|
|
286
|
+
for item in self._parent:
|
|
287
|
+
root = self.find(item)
|
|
288
|
+
groups.setdefault(root, []).append(item)
|
|
289
|
+
return groups
|
|
290
|
+
|
|
291
|
+
def __len__(self) -> int:
|
|
292
|
+
"""Return the number of disjoint sets / components."""
|
|
293
|
+
return self._count
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
# ============================================================================
|
|
297
|
+
# 4. Locality-Sensitive Hashing (MinHash)
|
|
298
|
+
# ============================================================================
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
class MinHash:
|
|
302
|
+
"""MinHash signature generator for estimating Jaccard similarity between text/token sets in O(K) time.
|
|
303
|
+
|
|
304
|
+
Uses universal hash family: h_i(x) = (a_i * x + b_i) mod p.
|
|
305
|
+
"""
|
|
306
|
+
|
|
307
|
+
# Large Mersenne prime 2^61 - 1
|
|
308
|
+
PRIME = (1 << 61) - 1
|
|
309
|
+
|
|
310
|
+
def __init__(self, num_perm: int = 64, seed: int = 42) -> None:
|
|
311
|
+
self.num_perm = num_perm
|
|
312
|
+
self.seed = seed
|
|
313
|
+
self._a, self._b = self._init_permutations(num_perm, seed)
|
|
314
|
+
self.signature = [self.PRIME] * num_perm
|
|
315
|
+
|
|
316
|
+
@staticmethod
|
|
317
|
+
def _init_permutations(num_perm: int, seed: int) -> tuple[List[int], List[int]]:
|
|
318
|
+
import random
|
|
319
|
+
|
|
320
|
+
rng = random.Random(seed)
|
|
321
|
+
a: List[int] = []
|
|
322
|
+
b: List[int] = []
|
|
323
|
+
for _ in range(num_perm):
|
|
324
|
+
val_a = rng.randint(1, MinHash.PRIME - 1)
|
|
325
|
+
val_b = rng.randint(0, MinHash.PRIME - 1)
|
|
326
|
+
a.append(val_a)
|
|
327
|
+
b.append(val_b)
|
|
328
|
+
return a, b
|
|
329
|
+
|
|
330
|
+
def update(self, tokens: Iterable[str]) -> None:
|
|
331
|
+
"""Update the MinHash signature with a collection of string tokens or shingles."""
|
|
332
|
+
for token in tokens:
|
|
333
|
+
h = struct.unpack(">Q", hashlib.sha256(token.encode("utf-8")).digest()[:8])[0]
|
|
334
|
+
for i in range(self.num_perm):
|
|
335
|
+
ph = ((self._a[i] * h) + self._b[i]) % self.PRIME
|
|
336
|
+
if ph < self.signature[i]:
|
|
337
|
+
self.signature[i] = ph
|
|
338
|
+
|
|
339
|
+
def jaccard_similarity(self, other: "MinHash") -> float:
|
|
340
|
+
"""Estimate the Jaccard similarity J(A, B) = |A ∩ B| / |A ∪ B| against another MinHash."""
|
|
341
|
+
if self.num_perm != other.num_perm:
|
|
342
|
+
raise ValueError(f"Permutations mismatch: {self.num_perm} vs {other.num_perm}")
|
|
343
|
+
matches = sum(1 for i in range(self.num_perm) if self.signature[i] == other.signature[i])
|
|
344
|
+
return matches / self.num_perm
|
|
345
|
+
|
|
346
|
+
@classmethod
|
|
347
|
+
def from_text(cls, text: str, k_shingle: int = 3, num_perm: int = 64) -> "MinHash":
|
|
348
|
+
"""Convenience factory creating a MinHash signature from a string via k-shingling."""
|
|
349
|
+
clean = text.strip().lower()
|
|
350
|
+
shingles = [clean[i : i + k_shingle] for i in range(max(1, len(clean) - k_shingle + 1))]
|
|
351
|
+
mh = cls(num_perm=num_perm)
|
|
352
|
+
mh.update(shingles)
|
|
353
|
+
return mh
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
# ============================================================================
|
|
357
|
+
# 5. 0/1 Knapsack Dynamic Programming Optimizer
|
|
358
|
+
# ============================================================================
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def knapsack_01(
|
|
362
|
+
items: Sequence[T],
|
|
363
|
+
max_weight: int,
|
|
364
|
+
weight_fn: Callable[[T], int],
|
|
365
|
+
value_fn: Callable[[T], float],
|
|
366
|
+
) -> List[T]:
|
|
367
|
+
"""Solve the 0/1 Knapsack problem using dynamic programming to find the maximum-utility
|
|
368
|
+
|
|
369
|
+
subset of items whose total weight (e.g. token cost) does not exceed max_weight.
|
|
370
|
+
|
|
371
|
+
Returns the selected subset of items in their original relative order.
|
|
372
|
+
"""
|
|
373
|
+
if max_weight <= 0 or not items:
|
|
374
|
+
return []
|
|
375
|
+
|
|
376
|
+
n = len(items)
|
|
377
|
+
weights = [max(1, int(weight_fn(item))) for item in items]
|
|
378
|
+
values = [float(value_fn(item)) for item in items]
|
|
379
|
+
|
|
380
|
+
if sum(weights) <= max_weight:
|
|
381
|
+
return list(items)
|
|
382
|
+
|
|
383
|
+
dp = [[0.0] * (max_weight + 1) for _ in range(n + 1)]
|
|
384
|
+
|
|
385
|
+
for i in range(1, n + 1):
|
|
386
|
+
w_i = weights[i - 1]
|
|
387
|
+
v_i = values[i - 1]
|
|
388
|
+
for w in range(max_weight + 1):
|
|
389
|
+
if w_i <= w:
|
|
390
|
+
candidate = dp[i - 1][w - w_i] + v_i
|
|
391
|
+
if candidate > dp[i - 1][w]:
|
|
392
|
+
dp[i][w] = candidate
|
|
393
|
+
else:
|
|
394
|
+
dp[i][w] = dp[i - 1][w]
|
|
395
|
+
else:
|
|
396
|
+
dp[i][w] = dp[i - 1][w]
|
|
397
|
+
|
|
398
|
+
# Backtrack to reconstruct selected items
|
|
399
|
+
selected: List[T] = []
|
|
400
|
+
curr_w = max_weight
|
|
401
|
+
for i in range(n, 0, -1):
|
|
402
|
+
if dp[i][curr_w] != dp[i - 1][curr_w]:
|
|
403
|
+
selected.append(items[i - 1])
|
|
404
|
+
curr_w -= weights[i - 1]
|
|
405
|
+
|
|
406
|
+
selected.reverse()
|
|
407
|
+
return selected
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Normalization filters for finding data."""
|
|
2
|
+
|
|
3
|
+
from urllib.parse import urlparse, urlunparse
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def canonicalize(value):
|
|
7
|
+
"""Apply normalization rules based on the type of value."""
|
|
8
|
+
if isinstance(value, str):
|
|
9
|
+
# General string cleaning
|
|
10
|
+
value = value.strip()
|
|
11
|
+
|
|
12
|
+
# Lowercase hostnames (heuristic: no spaces, contains dots or is localhost)
|
|
13
|
+
if "." in value or value.lower() == "localhost":
|
|
14
|
+
if " " not in value and ":" not in value:
|
|
15
|
+
return value.lower()
|
|
16
|
+
|
|
17
|
+
return value
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def canonicalize_host(ip_or_name: str) -> str:
|
|
21
|
+
"""Normalize IP addresses and hostnames."""
|
|
22
|
+
val = ip_or_name.strip().lower()
|
|
23
|
+
if val in ("localhost", "127.0.0.1", "::1"):
|
|
24
|
+
return "127.0.0.1"
|
|
25
|
+
# Basic IP normalization (lowercase IPv6, etc)
|
|
26
|
+
return val
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def canonicalize_url(url: str) -> str:
|
|
30
|
+
"""Normalize a URL: lowercase scheme/host, strip default ports."""
|
|
31
|
+
try:
|
|
32
|
+
parsed = urlparse(url)
|
|
33
|
+
scheme = parsed.scheme.lower()
|
|
34
|
+
netloc = parsed.netloc.lower()
|
|
35
|
+
|
|
36
|
+
# Strip default ports
|
|
37
|
+
if scheme == "http" and netloc.endswith(":80"):
|
|
38
|
+
netloc = netloc[:-3]
|
|
39
|
+
elif scheme == "https" and netloc.endswith(":443"):
|
|
40
|
+
netloc = netloc[:-4]
|
|
41
|
+
|
|
42
|
+
return urlunparse(
|
|
43
|
+
(scheme, netloc, parsed.path, parsed.params, parsed.query, parsed.fragment)
|
|
44
|
+
)
|
|
45
|
+
except Exception:
|
|
46
|
+
return url
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def canonicalize_port(port) -> int:
|
|
50
|
+
"""Ensure port is an integer."""
|
|
51
|
+
try:
|
|
52
|
+
return int(port)
|
|
53
|
+
except (ValueError, TypeError):
|
|
54
|
+
return 0
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def canonicalize_field(key: str, value) -> object:
|
|
58
|
+
"""Normalize a specific key-value pair based on semantic key naming conventions."""
|
|
59
|
+
if value is None:
|
|
60
|
+
return None
|
|
61
|
+
|
|
62
|
+
k = str(key).lower()
|
|
63
|
+
if k in ("ip", "host_ip", "resolved_ip", "target_ip"):
|
|
64
|
+
if isinstance(value, str):
|
|
65
|
+
return canonicalize_host(value)
|
|
66
|
+
elif k in ("port",):
|
|
67
|
+
return canonicalize_port(value)
|
|
68
|
+
elif k in ("url", "endpoint"):
|
|
69
|
+
if isinstance(value, str):
|
|
70
|
+
return canonicalize_url(value)
|
|
71
|
+
elif k in ("protocol",):
|
|
72
|
+
if isinstance(value, str):
|
|
73
|
+
return value.strip().lower()
|
|
74
|
+
|
|
75
|
+
return canonicalize(value)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def canonicalize_mapping(data: dict) -> dict:
|
|
79
|
+
"""Recursively canonicalize keys and values in a dictionary."""
|
|
80
|
+
normalized = {}
|
|
81
|
+
for k, v in data.items():
|
|
82
|
+
if isinstance(v, dict):
|
|
83
|
+
normalized[k] = canonicalize_mapping(v)
|
|
84
|
+
elif isinstance(v, list):
|
|
85
|
+
normalized[k] = [
|
|
86
|
+
canonicalize_mapping(item)
|
|
87
|
+
if isinstance(item, dict)
|
|
88
|
+
else canonicalize_field(k, item)
|
|
89
|
+
for item in v
|
|
90
|
+
]
|
|
91
|
+
else:
|
|
92
|
+
normalized[k] = canonicalize_field(k, v)
|
|
93
|
+
return normalized
|
ether/common/context.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Execution context for unified tool execution across coroutines and subprocesses."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import Any, Awaitable, Callable, Dict, Optional
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@dataclass
|
|
8
|
+
class ExecutionContext:
|
|
9
|
+
"""Runtime context passed to ToolAdapter.execute_action."""
|
|
10
|
+
|
|
11
|
+
action_id: str
|
|
12
|
+
session_id: str
|
|
13
|
+
policy: str = "safe"
|
|
14
|
+
cwd: str = "."
|
|
15
|
+
env: Optional[Dict[str, str]] = None
|
|
16
|
+
use_shell: bool = False
|
|
17
|
+
shell_path: Optional[str] = None
|
|
18
|
+
timeout_seconds: Optional[int] = None
|
|
19
|
+
runner: Optional[Any] = None
|
|
20
|
+
spool_fn: Optional[Callable[[str, bool], Awaitable[None]]] = None
|
|
21
|
+
|
|
22
|
+
async def spool_line(self, line: str, is_error: bool = False) -> None:
|
|
23
|
+
"""Stream raw wire or process output text to disk spooler and listeners."""
|
|
24
|
+
if self.spool_fn is not None:
|
|
25
|
+
await self.spool_fn(line, is_error)
|
ether/common/crypto.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"""Authenticated AES-256-GCM encryption with Argon2id key derivation for Ether archives.
|
|
2
|
+
|
|
3
|
+
Provides tamper-resistant, authenticated encryption for session database exports
|
|
4
|
+
and state archives, ensuring confidentiality and cryptographic integrity.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import os
|
|
8
|
+
from typing import Union
|
|
9
|
+
|
|
10
|
+
from cryptography.exceptions import InvalidTag
|
|
11
|
+
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
|
12
|
+
from cryptography.hazmat.primitives.kdf.argon2 import Argon2id
|
|
13
|
+
|
|
14
|
+
from ether.common.exceptions import EtherError
|
|
15
|
+
|
|
16
|
+
MAGIC_HEADER = b"ETHER_SECURE_ARC" # 16 bytes
|
|
17
|
+
CURRENT_VERSION = 1 # 1 byte
|
|
18
|
+
AAD_TAG = b"ETHER_AUTHENTICATED_DATABASE_V1"
|
|
19
|
+
SALT_SIZE = 16
|
|
20
|
+
NONCE_SIZE = 12
|
|
21
|
+
HEADER_SIZE = len(MAGIC_HEADER) + 1 + SALT_SIZE + NONCE_SIZE # 16 + 1 + 16 + 12 = 45 bytes
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class CryptoError(EtherError):
|
|
25
|
+
"""Base exception for cryptographic operations in Ether."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class InvalidArchiveFormatError(CryptoError):
|
|
29
|
+
"""Raised when an encrypted archive has invalid headers, length, or version."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class TamperedArchiveError(CryptoError):
|
|
33
|
+
"""Raised when ciphertext authentication fails (bit-flip, truncation, or wrong key)."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class InvalidPassphraseError(CryptoError):
|
|
37
|
+
"""Raised when a passphrase is empty or invalid."""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def derive_key_argon2id(
|
|
41
|
+
passphrase: Union[str, bytes],
|
|
42
|
+
salt: bytes,
|
|
43
|
+
iterations: int = 3,
|
|
44
|
+
lanes: int = 4,
|
|
45
|
+
memory_cost: int = 65536,
|
|
46
|
+
) -> bytes:
|
|
47
|
+
"""Derive a 256-bit (32-byte) key using Argon2id with memory-hard parameters."""
|
|
48
|
+
if isinstance(passphrase, str):
|
|
49
|
+
passphrase_bytes = passphrase.encode("utf-8")
|
|
50
|
+
else:
|
|
51
|
+
passphrase_bytes = passphrase
|
|
52
|
+
|
|
53
|
+
if not passphrase_bytes:
|
|
54
|
+
raise InvalidPassphraseError("Passphrase cannot be empty.")
|
|
55
|
+
|
|
56
|
+
kdf = Argon2id(
|
|
57
|
+
salt=salt,
|
|
58
|
+
length=32,
|
|
59
|
+
iterations=iterations,
|
|
60
|
+
lanes=lanes,
|
|
61
|
+
memory_cost=memory_cost,
|
|
62
|
+
)
|
|
63
|
+
return kdf.derive(passphrase_bytes)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def encrypt_bytes(
|
|
67
|
+
data: bytes,
|
|
68
|
+
passphrase: str,
|
|
69
|
+
iterations: int = 3,
|
|
70
|
+
memory_cost: int = 65536,
|
|
71
|
+
) -> bytes:
|
|
72
|
+
"""Encrypt payload using AES-256-GCM and Argon2id key derivation."""
|
|
73
|
+
if not isinstance(data, (bytes, bytearray)):
|
|
74
|
+
raise TypeError(f"Expected bytes or bytearray, got {type(data).__name__}")
|
|
75
|
+
|
|
76
|
+
salt = os.urandom(SALT_SIZE)
|
|
77
|
+
nonce = os.urandom(NONCE_SIZE)
|
|
78
|
+
key = derive_key_argon2id(passphrase, salt, iterations=iterations, memory_cost=memory_cost)
|
|
79
|
+
|
|
80
|
+
aesgcm = AESGCM(key)
|
|
81
|
+
ciphertext = aesgcm.encrypt(nonce, bytes(data), AAD_TAG)
|
|
82
|
+
|
|
83
|
+
# Format: MAGIC (16B) + VERSION (1B) + SALT (16B) + NONCE (12B) + CIPHERTEXT (incl 16B tag)
|
|
84
|
+
header = MAGIC_HEADER + bytes([CURRENT_VERSION]) + salt + nonce
|
|
85
|
+
return header + ciphertext
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def decrypt_bytes(
|
|
89
|
+
archive_bytes: bytes,
|
|
90
|
+
passphrase: str,
|
|
91
|
+
iterations: int = 3,
|
|
92
|
+
memory_cost: int = 65536,
|
|
93
|
+
) -> bytes:
|
|
94
|
+
"""Decrypt payload using AES-256-GCM, verifying integrity and authentication tag."""
|
|
95
|
+
if len(archive_bytes) < HEADER_SIZE + 16: # Must have header + at least 16-byte auth tag
|
|
96
|
+
raise InvalidArchiveFormatError(
|
|
97
|
+
"Archive data is too short to be a valid Ether secure archive."
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
# 1. Verify Magic Header
|
|
101
|
+
magic = archive_bytes[: len(MAGIC_HEADER)]
|
|
102
|
+
if magic != MAGIC_HEADER:
|
|
103
|
+
raise InvalidArchiveFormatError(
|
|
104
|
+
f"Invalid magic header: expected {MAGIC_HEADER!r}, got {magic!r}"
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
# 2. Verify Version
|
|
108
|
+
offset = len(MAGIC_HEADER)
|
|
109
|
+
version = archive_bytes[offset]
|
|
110
|
+
if version != CURRENT_VERSION:
|
|
111
|
+
raise InvalidArchiveFormatError(
|
|
112
|
+
f"Unsupported archive version: {version} (expected {CURRENT_VERSION})"
|
|
113
|
+
)
|
|
114
|
+
offset += 1
|
|
115
|
+
|
|
116
|
+
# 3. Extract Salt & Nonce
|
|
117
|
+
salt = archive_bytes[offset : offset + SALT_SIZE]
|
|
118
|
+
offset += SALT_SIZE
|
|
119
|
+
nonce = archive_bytes[offset : offset + NONCE_SIZE]
|
|
120
|
+
offset += NONCE_SIZE
|
|
121
|
+
|
|
122
|
+
ciphertext = archive_bytes[offset:]
|
|
123
|
+
|
|
124
|
+
# 4. Derive key and decrypt
|
|
125
|
+
key = derive_key_argon2id(passphrase, salt, iterations=iterations, memory_cost=memory_cost)
|
|
126
|
+
aesgcm = AESGCM(key)
|
|
127
|
+
|
|
128
|
+
try:
|
|
129
|
+
plaintext = aesgcm.decrypt(nonce, ciphertext, AAD_TAG)
|
|
130
|
+
return plaintext
|
|
131
|
+
except InvalidTag as exc:
|
|
132
|
+
raise TamperedArchiveError(
|
|
133
|
+
"Decryption failed: archive is corrupted, tampered with, or passphrase is wrong."
|
|
134
|
+
) from exc
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def encrypt_file(
|
|
138
|
+
input_path: str,
|
|
139
|
+
output_path: str,
|
|
140
|
+
passphrase: str,
|
|
141
|
+
iterations: int = 3,
|
|
142
|
+
memory_cost: int = 65536,
|
|
143
|
+
) -> None:
|
|
144
|
+
"""Encrypt file contents atomically with 0o600 permissions."""
|
|
145
|
+
with open(input_path, "rb") as f:
|
|
146
|
+
data = f.read()
|
|
147
|
+
|
|
148
|
+
encrypted = encrypt_bytes(data, passphrase, iterations=iterations, memory_cost=memory_cost)
|
|
149
|
+
|
|
150
|
+
# Atomic write with 0o600 permissions
|
|
151
|
+
out_dir = os.path.dirname(os.path.abspath(output_path))
|
|
152
|
+
if out_dir:
|
|
153
|
+
os.makedirs(out_dir, exist_ok=True)
|
|
154
|
+
|
|
155
|
+
flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
|
|
156
|
+
fd = os.open(output_path, flags, 0o600)
|
|
157
|
+
with open(fd, "wb") as f:
|
|
158
|
+
f.write(encrypted)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def decrypt_file(
|
|
162
|
+
input_path: str,
|
|
163
|
+
output_path: str,
|
|
164
|
+
passphrase: str,
|
|
165
|
+
iterations: int = 3,
|
|
166
|
+
memory_cost: int = 65536,
|
|
167
|
+
) -> None:
|
|
168
|
+
"""Decrypt archive contents and write to output_path atomically with 0o600 permissions."""
|
|
169
|
+
with open(input_path, "rb") as f:
|
|
170
|
+
archive_bytes = f.read()
|
|
171
|
+
|
|
172
|
+
plaintext = decrypt_bytes(
|
|
173
|
+
archive_bytes, passphrase, iterations=iterations, memory_cost=memory_cost
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
out_dir = os.path.dirname(os.path.abspath(output_path))
|
|
177
|
+
if out_dir:
|
|
178
|
+
os.makedirs(out_dir, exist_ok=True)
|
|
179
|
+
|
|
180
|
+
flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
|
|
181
|
+
fd = os.open(output_path, flags, 0o600)
|
|
182
|
+
with open(fd, "wb") as f:
|
|
183
|
+
f.write(plaintext)
|