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,21 @@
1
+ """Security gateway, SSRF firewall, and policy engine."""
2
+
3
+ from ether.gateway.gate import ActionGateway, ActionValidationError, GatePolicy
4
+ from ether.gateway.preflight import (
5
+ INSTALLATION_HINTS,
6
+ PreflightIssue,
7
+ PreflightReport,
8
+ PreflightVerifier,
9
+ get_tool_target_guidance,
10
+ )
11
+
12
+ __all__ = [
13
+ "ActionGateway",
14
+ "ActionValidationError",
15
+ "GatePolicy",
16
+ "INSTALLATION_HINTS",
17
+ "PreflightIssue",
18
+ "PreflightReport",
19
+ "PreflightVerifier",
20
+ "get_tool_target_guidance",
21
+ ]
ether/gateway/gate.py ADDED
@@ -0,0 +1,392 @@
1
+ """Validation and policy enforcement for tool actions."""
2
+
3
+ import ipaddress
4
+ import socket
5
+ from typing import Any, Callable, Dict, List, Optional, Tuple
6
+
7
+ from ether import paths
8
+ from ether.common.algorithms import IPRadixTrie
9
+ from ether.common.exceptions import EtherError
10
+ from ether.gateway.network import get_lhost_info
11
+ from ether.graph.store import GraphStore
12
+ from ether.registry.registry import ToolRegistry
13
+ from ether.schemas.base import BaseFinding
14
+ from ether.schemas.power import ActionRequest, ActionSource
15
+
16
+
17
+ def _resolve_lhost() -> Tuple[Optional[str], Optional[str]]:
18
+ import sys
19
+
20
+ pf = sys.modules.get("ether.facade")
21
+ resolver = getattr(pf, "get_lhost_info", get_lhost_info) if pf else get_lhost_info
22
+ try:
23
+ return resolver()
24
+ except Exception:
25
+ return None, None
26
+
27
+
28
+ BLOCKED_TARGETS = {
29
+ "169.254.", # IPv4 Link-Local / Cloud Metadata (AWS, Azure, GCP, DigitalOcean, Oracle)
30
+ "fd00:ec2::254", # AWS IPv6 IMDSv2 metadata
31
+ "100.100.100.200", # Alibaba Cloud metadata
32
+ "2852039166", # Decimal notation of 169.254.169.254
33
+ "0xa9fea9fe", # Hex notation of 169.254.169.254
34
+ "metadata.google.internal", # GCP metadata DNS
35
+ "metadata.internal", # Generic internal metadata DNS
36
+ "instance-data", # EC2 instance data hostname
37
+ }
38
+
39
+ BLOCKED_NETWORKS = [
40
+ ipaddress.ip_network("169.254.0.0/16"),
41
+ ipaddress.ip_network("fe80::/10"),
42
+ ipaddress.ip_network("fd00:ec2::/64"),
43
+ ]
44
+
45
+ _BLOCKED_TRIE = IPRadixTrie()
46
+ for _net in BLOCKED_NETWORKS:
47
+ _BLOCKED_TRIE.insert(_net)
48
+
49
+
50
+ def _parse_ip_candidate(candidate: str):
51
+ """Attempt to parse an address token into an ipaddress object, resolving alternate numerical notations."""
52
+ c = candidate.strip("\"'`()<>,;{}[]")
53
+ if "://" in c:
54
+ c = c.split("://", 1)[1]
55
+ c = c.split("/", 1)[0]
56
+ c = c.split("?", 1)[0]
57
+ c = c.split("#", 1)[0]
58
+ if c.startswith("[") and "]" in c:
59
+ c = c[1 : c.index("]")]
60
+ elif ":" in c and c.count(":") == 1:
61
+ c = c.split(":", 1)[0]
62
+
63
+ if not c:
64
+ return None
65
+
66
+ # Fast guard: valid IP candidates or alternate representations must have at least one digit or colon
67
+ if not any(ch.isdigit() or ch == ":" for ch in c):
68
+ return None
69
+
70
+ try:
71
+ return ipaddress.ip_address(c)
72
+ except ValueError:
73
+ pass
74
+
75
+ try:
76
+ raw_ip = socket.inet_ntoa(socket.inet_aton(c))
77
+ return ipaddress.ip_address(raw_ip)
78
+ except (OSError, ValueError):
79
+ pass
80
+
81
+ return None
82
+
83
+
84
+ def is_blocked_destination(text: str) -> bool:
85
+ """Check if a string contains known restricted destinations like cloud metadata,
86
+ canonicalizing alternative numerical notations (dotted-octal, dotted-hex, hex, and IPv4-mapped IPv6).
87
+ """
88
+ if not text:
89
+ return False
90
+ lower_text = text.lower()
91
+ for blocked in BLOCKED_TARGETS:
92
+ if blocked in lower_text:
93
+ return True
94
+
95
+ # Tokenize input to detect embedded IP candidates
96
+ tokens = lower_text.replace("=", " ").replace("&", " ").replace(";", " ").split()
97
+ for tok in tokens:
98
+ ip_obj = _parse_ip_candidate(tok)
99
+ if ip_obj is not None:
100
+ # Check IPv4-mapped IPv6 (e.g. ::ffff:169.254.169.254)
101
+ if hasattr(ip_obj, "ipv4_mapped") and ip_obj.ipv4_mapped:
102
+ ip_obj = ip_obj.ipv4_mapped
103
+
104
+ if _BLOCKED_TRIE.contains(ip_obj):
105
+ return True
106
+
107
+ return False
108
+
109
+
110
+ from enum import Enum
111
+
112
+
113
+ class GatePolicy(str, Enum):
114
+ """Policy mode governing gateway enforcement."""
115
+
116
+ SAFE = "safe" # Strict: blocks metadata, enforces CIDR, user shell only
117
+ UNRESTRICTED = (
118
+ "unrestricted" # Unrestricted: allows any destination, autonomous shell, raw execution
119
+ )
120
+
121
+
122
+ class ActionValidationError(EtherError):
123
+ """Raised when an ActionRequest fails validation."""
124
+
125
+ pass
126
+
127
+
128
+ class ActionGateway:
129
+ """The validation and policy layer for Power Mode.
130
+
131
+ Ensures that any ActionRequest is legitimate, targets valid entities,
132
+ and respects the tool's input contract before execution.
133
+ """
134
+
135
+ def __init__(
136
+ self,
137
+ registry: ToolRegistry,
138
+ store: Optional[GraphStore] = None,
139
+ allowed_cidrs: Optional[List[str]] = None,
140
+ policy: GatePolicy = GatePolicy.SAFE,
141
+ ):
142
+ self.registry = registry
143
+ self.store = store
144
+ self.policy = policy
145
+ self._allowed_cidrs: Optional[List[Any]] = None
146
+ if allowed_cidrs:
147
+ self.set_allowed_cidrs(allowed_cidrs)
148
+
149
+ def preflight_verify(
150
+ self,
151
+ tool_name: str,
152
+ target: str,
153
+ flags: str = "",
154
+ ):
155
+ """Run preflight verification checks (binary availability, URL schemes, wordlists, and security gating)."""
156
+ from ether.gateway.preflight import PreflightVerifier
157
+
158
+ verifier = PreflightVerifier(registry=self.registry, policy=self.policy)
159
+ return verifier.verify(tool_name=tool_name, target=target, flags=flags)
160
+
161
+ async def verify_action(self, action: ActionRequest):
162
+ """Validate an action request returning a structured PreflightReport rather than raising exceptions."""
163
+ from ether.gateway.preflight import PreflightIssue
164
+
165
+ raw_flags = action.params.get("raw_flags", "") if action.params else ""
166
+ target_str = str(action.target_entity_id or "")
167
+ report = self.preflight_verify(
168
+ tool_name=action.tool_name,
169
+ target=target_str,
170
+ flags=raw_flags,
171
+ )
172
+
173
+ try:
174
+ await self.validate_action(action)
175
+ except ActionValidationError as e:
176
+ report.issues.append(
177
+ PreflightIssue(
178
+ category="security",
179
+ severity="error",
180
+ title="Action validation error",
181
+ description=str(e),
182
+ remediation_hint="Ensure target and parameters comply with policy and CIDR scope.",
183
+ )
184
+ )
185
+
186
+ return report
187
+
188
+ def create_session(
189
+ self,
190
+ command_runner: Optional[Any] = None,
191
+ user_env: Optional[Dict[str, str]] = None,
192
+ user_shell: Optional[str] = None,
193
+ ):
194
+ """Factory creating an ExecutionSession governed by this ActionGateway and its configured policies."""
195
+ from ether.core.executor import Executor
196
+ from ether.core.session import ExecutionSession, SubprocessCommandRunner
197
+
198
+ if not self.store:
199
+ raise ValueError(
200
+ "ActionGateway requires a configured GraphStore to spawn an ExecutionSession."
201
+ )
202
+
203
+ runner = command_runner or SubprocessCommandRunner(Executor())
204
+ return ExecutionSession(
205
+ store=self.store,
206
+ gateway=self,
207
+ registry=self.registry,
208
+ command_runner=runner,
209
+ user_env=user_env,
210
+ user_shell=user_shell,
211
+ )
212
+
213
+ def set_allowed_cidrs(self, allowed_cidrs: Optional[List[str]]) -> None:
214
+ """Configure declarative CIDR scope boundaries for engagements."""
215
+ if not allowed_cidrs:
216
+ self._allowed_cidrs = None
217
+ self._allowed_cidrs_trie = None
218
+ else:
219
+ self._allowed_cidrs = [
220
+ ipaddress.ip_network(c.strip(), strict=False) for c in allowed_cidrs if c.strip()
221
+ ]
222
+ self._allowed_cidrs_trie = IPRadixTrie()
223
+ for net in self._allowed_cidrs:
224
+ self._allowed_cidrs_trie.insert(net)
225
+
226
+ def validate_target_scope(self, text_or_ip: str) -> bool:
227
+ """Ensure any target IPs in text belong to the authorized engagement CIDR scope.
228
+
229
+ Returns True if within scope (or if no scope restrictions are configured).
230
+ """
231
+ if not self._allowed_cidrs or not text_or_ip:
232
+ return True
233
+
234
+ tokens = text_or_ip.replace("=", " ").replace("&", " ").replace(";", " ").split()
235
+ for tok in tokens:
236
+ ip_obj = _parse_ip_candidate(tok)
237
+ if ip_obj is not None:
238
+ if hasattr(ip_obj, "ipv4_mapped") and ip_obj.ipv4_mapped:
239
+ ip_obj = ip_obj.ipv4_mapped
240
+ trie = getattr(self, "_allowed_cidrs_trie", None)
241
+ if trie is not None:
242
+ if not trie.contains(ip_obj):
243
+ return False
244
+ else:
245
+ if not any(ip_obj in net for net in self._allowed_cidrs):
246
+ return False
247
+ return True
248
+
249
+ @staticmethod
250
+ def infer_target_finding(target: str) -> BaseFinding:
251
+ """Infer the typed BaseFinding entity from a raw target string."""
252
+ import ipaddress
253
+
254
+ from ether.schemas.base import BaseFinding
255
+ from ether.schemas.dns import DomainInfo
256
+ from ether.schemas.network import NetworkHost
257
+ from ether.schemas.web import WebEndpoint
258
+
259
+ try:
260
+ ipaddress.ip_address(target)
261
+ return NetworkHost.create(ip=target)
262
+ except ValueError:
263
+ pass
264
+
265
+ if target.startswith("http://") or target.startswith("https://"):
266
+ return WebEndpoint.create(url=target)
267
+
268
+ if "/" in target:
269
+ try:
270
+ ipaddress.ip_network(target, strict=False)
271
+ return BaseFinding(
272
+ schema_type="network.netblock", pik={"cidr": target}, data={"cidr": target}
273
+ )
274
+ except ValueError:
275
+ pass
276
+
277
+ return DomainInfo.create(domain=target)
278
+
279
+ @staticmethod
280
+ def resolve_entity_variables(
281
+ pik: Optional[Dict[str, Any]] = None,
282
+ lhost_resolver: Optional[Callable[[], Tuple[Optional[str], Optional[str]]]] = None,
283
+ ) -> Dict[str, Any]:
284
+ """Extract standard investigation variables ($TARGET, $PORT, $SERVICE, $PROTOCOL, $LHOST, $IFACE)."""
285
+ resolved: Dict[str, Any] = {}
286
+ if pik:
287
+ target = pik.get("ip") or pik.get("domain") or pik.get("host_ip")
288
+ if target:
289
+ resolved["TARGET"] = target
290
+ if "port" in pik:
291
+ resolved["PORT"] = pik["port"]
292
+ if "service" in pik:
293
+ resolved["SERVICE"] = pik["service"]
294
+ if "protocol" in pik:
295
+ resolved["PROTOCOL"] = pik["protocol"]
296
+
297
+ resolver = lhost_resolver or _resolve_lhost
298
+ try:
299
+ ip, iface = resolver()
300
+ if ip:
301
+ resolved["LHOST"] = ip
302
+ if iface:
303
+ resolved["IFACE"] = iface
304
+ except Exception:
305
+ pass
306
+
307
+ resolved["WORDLIST"] = paths.get_wordlist_path("common_dirs")
308
+ return resolved
309
+
310
+ @staticmethod
311
+ def interpolate_variables(text: str, variables: Dict[str, Any]) -> str:
312
+ """Replace $VAR placeholders in command text with resolved values."""
313
+ for var_name, val in variables.items():
314
+ placeholder = f"${var_name}"
315
+ if placeholder in text:
316
+ text = text.replace(placeholder, str(val))
317
+ return text
318
+
319
+ async def validate_action(self, action: ActionRequest) -> bool:
320
+ """Validate an action request against registry and store state.
321
+
322
+ Raises:
323
+ ActionValidationError: If validation fails.
324
+ """
325
+ # 1. If UNRESTRICTED policy, bypass destination and scope restrictions
326
+ raw_flags = action.params.get("raw_flags", "")
327
+ if self.policy != GatePolicy.UNRESTRICTED:
328
+ if is_blocked_destination(raw_flags) or is_blocked_destination(action.tool_name):
329
+ raise ActionValidationError(
330
+ "Access to cloud metadata endpoints is strictly prohibited."
331
+ )
332
+ if self._allowed_cidrs and not self.validate_target_scope(raw_flags):
333
+ raise ActionValidationError(
334
+ "Target in command arguments violates authorized engagement CIDR scope."
335
+ )
336
+
337
+ # 2. Resolve Tool
338
+ tool_data = self.registry.get_tool(action.tool_name)
339
+
340
+ # 3. Policy: Handle Shell Commands
341
+ if not tool_data:
342
+ # Only allow arbitrary shell commands if explicitly requested (!) and by a user
343
+ if action.is_explicit_shell and action.triggered_by == ActionSource.USER:
344
+ return True
345
+
346
+ # If not explicit or not user, reject
347
+ reason = "is not a registered tool"
348
+ if not action.is_explicit_shell:
349
+ reason += " and no explicit shell prefix ('!') was provided"
350
+
351
+ raise ActionValidationError(f"Action '{action.tool_name}' {reason}.")
352
+
353
+ # 4. Standard Validation for Registered Tools
354
+ manifest = tool_data["manifest"]
355
+
356
+ # 5. Check if target entity exists and is compatible
357
+ # POLICY: For manual USER actions, we allow execution without a selected entity
358
+ # as they might be providing the target in the raw_flags (e.g., 'nmap 1.1.1.1')
359
+ if not action.target_entity_id:
360
+ if action.triggered_by == ActionSource.USER:
361
+ return True
362
+ raise ActionValidationError(
363
+ f"Tool '{action.tool_name}' requires a selected target entity."
364
+ )
365
+
366
+ node = await self.store.get_node(str(action.session_id), action.target_entity_id)
367
+ if not node:
368
+ raise ActionValidationError(
369
+ f"Target entity '{action.target_entity_id}' not found in session '{action.session_id}'."
370
+ )
371
+
372
+ # Enforce destination safety on the target entity
373
+ pik_str = node.get("pik_json", "")
374
+ if is_blocked_destination(pik_str):
375
+ raise ActionValidationError(
376
+ "Target entity points to a prohibited cloud metadata endpoint."
377
+ )
378
+
379
+ if self._allowed_cidrs and not self.validate_target_scope(pik_str):
380
+ raise ActionValidationError(
381
+ "Target entity IP violates authorized engagement CIDR scope."
382
+ )
383
+
384
+ target_schema = node["schema_type"]
385
+ accepted_inputs = manifest.input.get("accepts", []) if manifest else []
386
+ if accepted_inputs and target_schema not in accepted_inputs:
387
+ raise ActionValidationError(
388
+ f"Tool '{action.tool_name}' does not accept input type '{target_schema}'. "
389
+ f"Accepted types: {', '.join(accepted_inputs)}"
390
+ )
391
+
392
+ return True
@@ -0,0 +1,98 @@
1
+ """Network interface and local host (LHOST) discovery utilities for Ether."""
2
+
3
+ import socket
4
+ import subprocess
5
+ import time
6
+ from dataclasses import dataclass
7
+ from typing import Optional, Tuple
8
+
9
+ __all__ = ["get_lhost_info", "clear_lhost_cache"]
10
+
11
+
12
+ @dataclass
13
+ class _LhostCacheEntry:
14
+ timestamp: float
15
+ ip: str
16
+ interface: str
17
+
18
+ @property
19
+ def value(self) -> Tuple[str, str]:
20
+ return (self.ip, self.interface)
21
+
22
+ def is_valid(self, ttl: float, now: float) -> bool:
23
+ return (now - self.timestamp) < ttl
24
+
25
+
26
+ _lhost_cache: Optional[_LhostCacheEntry] = None
27
+
28
+
29
+ def clear_lhost_cache() -> None:
30
+ """Explicitly invalidate the cached LHOST discovery result."""
31
+ global _lhost_cache
32
+ _lhost_cache = None
33
+
34
+
35
+ def get_lhost_info(ttl: float = 10.0, force_refresh: bool = False) -> Tuple[str, str]:
36
+ """Discover the local host IP and interface name, prioritizing VPN/tunnel interfaces.
37
+
38
+ Returns:
39
+ Tuple of (ip_address, interface_name), e.g. ("10.10.14.5", "tun0") or ("192.168.1.50", "eth0").
40
+ """
41
+ global _lhost_cache
42
+ now = time.time()
43
+ if not force_refresh and _lhost_cache is not None and _lhost_cache.is_valid(ttl, now):
44
+ return _lhost_cache.value
45
+
46
+ # 1. Try 'ip -brief -4 addr show' (Linux standard)
47
+ try:
48
+ res = subprocess.run(
49
+ ["ip", "-brief", "-4", "addr", "show"],
50
+ capture_output=True,
51
+ text=True,
52
+ timeout=1.0,
53
+ check=False,
54
+ )
55
+ if res.returncode == 0:
56
+ vpn_candidates = []
57
+ regular_candidates = []
58
+ for line in res.stdout.strip().splitlines():
59
+ parts = line.split()
60
+ if len(parts) >= 3:
61
+ iface = parts[0]
62
+ status = parts[1].upper()
63
+ cidr = parts[2]
64
+ ip = cidr.split("/")[0]
65
+ if iface == "lo":
66
+ continue
67
+ if iface.startswith(("tun", "wg", "tap", "ppp", "utun")):
68
+ vpn_candidates.append((ip, iface))
69
+ elif status == "UP":
70
+ regular_candidates.append((ip, iface))
71
+
72
+ if vpn_candidates:
73
+ ip, iface = vpn_candidates[0]
74
+ _lhost_cache = _LhostCacheEntry(now, ip, iface)
75
+ return (ip, iface)
76
+ if regular_candidates:
77
+ ip, iface = regular_candidates[0]
78
+ _lhost_cache = _LhostCacheEntry(now, ip, iface)
79
+ return (ip, iface)
80
+ except Exception:
81
+ pass
82
+
83
+ # 2. Socket routing query fallback (determines default route egress IP)
84
+ try:
85
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
86
+ s.settimeout(0.2)
87
+ s.connect(("8.8.8.8", 80))
88
+ ip = s.getsockname()[0]
89
+ s.close()
90
+ _lhost_cache = _LhostCacheEntry(now, ip, "default")
91
+ return (ip, "default")
92
+ except Exception:
93
+ pass
94
+
95
+ # 3. Ultimate loopback fallback
96
+ fallback = ("127.0.0.1", "lo")
97
+ _lhost_cache = _LhostCacheEntry(now, fallback[0], fallback[1])
98
+ return fallback