network-sandbox-engine 2.1.0__tar.gz → 2.1.1__tar.gz

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 (38) hide show
  1. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/PKG-INFO +3 -3
  2. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/README.md +2 -2
  3. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/network_sandbox_engine.egg-info/PKG-INFO +3 -3
  4. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/network_sandbox_engine.egg-info/SOURCES.txt +2 -0
  5. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/nse/core/mock_listener.py +8 -2
  6. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/nse/core/netns_controller.py +54 -45
  7. network_sandbox_engine-2.1.1/nse/core/paths.py +155 -0
  8. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/nse/core/pipeline.py +6 -5
  9. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/nse/core/rule_engine.py +7 -5
  10. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/nse/core/scapy_injector.py +7 -5
  11. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/nse/core/trace_harvester.py +11 -2
  12. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/pyproject.toml +1 -1
  13. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/tests/test_engine_internals.py +29 -20
  14. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/tests/test_netns.py +18 -17
  15. network_sandbox_engine-2.1.1/tests/test_paths.py +302 -0
  16. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/tests/test_pipeline_unit.py +2 -1
  17. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/tests/test_trace_harvester.py +8 -4
  18. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/LICENSE +0 -0
  19. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/network_sandbox_engine.egg-info/dependency_links.txt +0 -0
  20. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/network_sandbox_engine.egg-info/entry_points.txt +0 -0
  21. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/network_sandbox_engine.egg-info/requires.txt +0 -0
  22. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/network_sandbox_engine.egg-info/top_level.txt +0 -0
  23. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/nse/__init__.py +0 -0
  24. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/nse/cli/__init__.py +0 -0
  25. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/nse/cli/runner.py +0 -0
  26. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/nse/core/__init__.py +0 -0
  27. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/nse/core/naming.py +0 -0
  28. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/nse/core/sniffer.py +0 -0
  29. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/nse/core/utils.py +0 -0
  30. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/nse/models/__init__.py +0 -0
  31. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/nse/models/test_request.py +0 -0
  32. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/nse/models/trace_event.py +0 -0
  33. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/setup.cfg +0 -0
  34. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/tests/test_docs_examples.py +0 -0
  35. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/tests/test_oracle_e2e.py +0 -0
  36. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/tests/test_runner_cli.py +0 -0
  37. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/tests/test_runner_logic.py +0 -0
  38. {network_sandbox_engine-2.1.0 → network_sandbox_engine-2.1.1}/tests/test_trace_parser.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: network-sandbox-engine
3
- Version: 2.1.0
3
+ Version: 2.1.1
4
4
  Summary: Headless Python engine for isolated network namespace testing and PCAP assertions.
5
5
  Author: onyks
6
6
  License-Expression: MIT
@@ -55,7 +55,7 @@ SPDX-License-Identifier: MIT
55
55
  <img src="https://img.shields.io/badge/OS-Linux-blue?style=for-the-badge&logo=linux" alt="Linux">
56
56
  <img src="https://img.shields.io/badge/Python-3.10+-yellow?style=for-the-badge&logo=python" alt="Python">
57
57
  <a href="https://github.com/onyks-os/NetworkSandboxEngine/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/onyks-os/NetworkSandboxEngine/ci.yml?style=for-the-badge&logo=github" alt="CI Status"></a>
58
- <a href="https://onyks-os.github.io/NetworkSandboxEngine/"><img src="https://img.shields.io/badge/docs-mkdocs-526CFE?style=for-the-badge&logo=materialformkdocs&logoColor=white" alt="Documentation"></a>
58
+ <a href="https://onyks-os.github.io/nse/"><img src="https://img.shields.io/badge/docs-mkdocs-526CFE?style=for-the-badge&logo=materialformkdocs&logoColor=white" alt="Documentation"></a>
59
59
  <a href="https://pypi.org/project/network-sandbox-engine/"><img src="https://img.shields.io/pypi/v/network-sandbox-engine?style=for-the-badge&logo=pypi" alt="PyPI"></a>
60
60
  <img src="https://img.shields.io/badge/License-MIT-green?style=for-the-badge" alt="License">
61
61
  </p>
@@ -348,7 +348,7 @@ See [docs/RELEASING.md](docs/RELEASING.md).
348
348
  ## Documentation
349
349
 
350
350
  Full interactive web documentation is available at:
351
- [https://onyks-os.github.io/NetworkSandboxEngine/](https://onyks-os.github.io/NetworkSandboxEngine/)
351
+ [https://onyks-os.github.io/nse/](https://onyks-os.github.io/nse/)
352
352
 
353
353
  Build the documentation locally:
354
354
 
@@ -13,7 +13,7 @@ SPDX-License-Identifier: MIT
13
13
  <img src="https://img.shields.io/badge/OS-Linux-blue?style=for-the-badge&logo=linux" alt="Linux">
14
14
  <img src="https://img.shields.io/badge/Python-3.10+-yellow?style=for-the-badge&logo=python" alt="Python">
15
15
  <a href="https://github.com/onyks-os/NetworkSandboxEngine/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/onyks-os/NetworkSandboxEngine/ci.yml?style=for-the-badge&logo=github" alt="CI Status"></a>
16
- <a href="https://onyks-os.github.io/NetworkSandboxEngine/"><img src="https://img.shields.io/badge/docs-mkdocs-526CFE?style=for-the-badge&logo=materialformkdocs&logoColor=white" alt="Documentation"></a>
16
+ <a href="https://onyks-os.github.io/nse/"><img src="https://img.shields.io/badge/docs-mkdocs-526CFE?style=for-the-badge&logo=materialformkdocs&logoColor=white" alt="Documentation"></a>
17
17
  <a href="https://pypi.org/project/network-sandbox-engine/"><img src="https://img.shields.io/pypi/v/network-sandbox-engine?style=for-the-badge&logo=pypi" alt="PyPI"></a>
18
18
  <img src="https://img.shields.io/badge/License-MIT-green?style=for-the-badge" alt="License">
19
19
  </p>
@@ -306,7 +306,7 @@ See [docs/RELEASING.md](docs/RELEASING.md).
306
306
  ## Documentation
307
307
 
308
308
  Full interactive web documentation is available at:
309
- [https://onyks-os.github.io/NetworkSandboxEngine/](https://onyks-os.github.io/NetworkSandboxEngine/)
309
+ [https://onyks-os.github.io/nse/](https://onyks-os.github.io/nse/)
310
310
 
311
311
  Build the documentation locally:
312
312
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: network-sandbox-engine
3
- Version: 2.1.0
3
+ Version: 2.1.1
4
4
  Summary: Headless Python engine for isolated network namespace testing and PCAP assertions.
5
5
  Author: onyks
6
6
  License-Expression: MIT
@@ -55,7 +55,7 @@ SPDX-License-Identifier: MIT
55
55
  <img src="https://img.shields.io/badge/OS-Linux-blue?style=for-the-badge&logo=linux" alt="Linux">
56
56
  <img src="https://img.shields.io/badge/Python-3.10+-yellow?style=for-the-badge&logo=python" alt="Python">
57
57
  <a href="https://github.com/onyks-os/NetworkSandboxEngine/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/onyks-os/NetworkSandboxEngine/ci.yml?style=for-the-badge&logo=github" alt="CI Status"></a>
58
- <a href="https://onyks-os.github.io/NetworkSandboxEngine/"><img src="https://img.shields.io/badge/docs-mkdocs-526CFE?style=for-the-badge&logo=materialformkdocs&logoColor=white" alt="Documentation"></a>
58
+ <a href="https://onyks-os.github.io/nse/"><img src="https://img.shields.io/badge/docs-mkdocs-526CFE?style=for-the-badge&logo=materialformkdocs&logoColor=white" alt="Documentation"></a>
59
59
  <a href="https://pypi.org/project/network-sandbox-engine/"><img src="https://img.shields.io/pypi/v/network-sandbox-engine?style=for-the-badge&logo=pypi" alt="PyPI"></a>
60
60
  <img src="https://img.shields.io/badge/License-MIT-green?style=for-the-badge" alt="License">
61
61
  </p>
@@ -348,7 +348,7 @@ See [docs/RELEASING.md](docs/RELEASING.md).
348
348
  ## Documentation
349
349
 
350
350
  Full interactive web documentation is available at:
351
- [https://onyks-os.github.io/NetworkSandboxEngine/](https://onyks-os.github.io/NetworkSandboxEngine/)
351
+ [https://onyks-os.github.io/nse/](https://onyks-os.github.io/nse/)
352
352
 
353
353
  Build the documentation locally:
354
354
 
@@ -14,6 +14,7 @@ nse/core/__init__.py
14
14
  nse/core/mock_listener.py
15
15
  nse/core/naming.py
16
16
  nse/core/netns_controller.py
17
+ nse/core/paths.py
17
18
  nse/core/pipeline.py
18
19
  nse/core/rule_engine.py
19
20
  nse/core/scapy_injector.py
@@ -27,6 +28,7 @@ tests/test_docs_examples.py
27
28
  tests/test_engine_internals.py
28
29
  tests/test_netns.py
29
30
  tests/test_oracle_e2e.py
31
+ tests/test_paths.py
30
32
  tests/test_pipeline_unit.py
31
33
  tests/test_runner_cli.py
32
34
  tests/test_runner_logic.py
@@ -16,6 +16,8 @@ import sys
16
16
  import threading
17
17
  import time
18
18
 
19
+ from nse.core.paths import resolve
20
+
19
21
  logger = logging.getLogger("nse.core.mock_listener")
20
22
 
21
23
 
@@ -45,6 +47,10 @@ def run_tcp_server(host: str, port: int) -> None:
45
47
  break
46
48
  c.sendall(data)
47
49
  except OSError:
50
+ # The client hung up, reset the connection, or timed out.
51
+ # None of that is this listener's problem: it exists only to
52
+ # give injected packets something to arrive at, so a dead
53
+ # peer is an ordinary end of conversation, not an error.
48
54
  pass
49
55
  finally:
50
56
  c.close()
@@ -87,9 +93,9 @@ def start_mock_listener(
87
93
  """Spawns a mock listener inside the namespace in a background process."""
88
94
  cmd = []
89
95
  if use_nsenter:
90
- cmd += ["nsenter", f"--net=/var/run/netns/{netns_name}", "--"]
96
+ cmd += [resolve("nsenter"), f"--net=/var/run/netns/{netns_name}", "--"]
91
97
  else:
92
- cmd += ["ip", "netns", "exec", netns_name]
98
+ cmd += [resolve("ip"), "netns", "exec", netns_name]
93
99
  cmd += [
94
100
  sys.executable,
95
101
  "-u",
@@ -19,6 +19,7 @@ from dataclasses import dataclass, field
19
19
  from typing import TYPE_CHECKING, Any, cast
20
20
 
21
21
  from nse.core.naming import NETNS_SWEEP_PREFIXES, VETH_SWEEP_PREFIXES
22
+ from nse.core.paths import resolve
22
23
  from nse.core.utils import is_in_container
23
24
 
24
25
  if TYPE_CHECKING:
@@ -130,7 +131,11 @@ class NetnsController:
130
131
  """Clean up orphan namespaces and veth pairs left behind by previous crashes."""
131
132
  try:
132
133
  res = subprocess.run(
133
- ["ip", "netns", "list"], capture_output=True, text=True, check=False, timeout=5.0
134
+ [resolve("ip"), "netns", "list"],
135
+ capture_output=True,
136
+ text=True,
137
+ check=False,
138
+ timeout=5.0,
134
139
  )
135
140
  if res.returncode == 0:
136
141
  for line in res.stdout.splitlines():
@@ -138,7 +143,7 @@ class NetnsController:
138
143
  if ns_name.startswith(NETNS_SWEEP_PREFIXES):
139
144
  logger.info("Startup sweep: removing orphan netns %s", ns_name)
140
145
  subprocess.run(
141
- ["ip", "netns", "del", ns_name],
146
+ [resolve("ip"), "netns", "del", ns_name],
142
147
  capture_output=True,
143
148
  check=False,
144
149
  timeout=5.0,
@@ -148,7 +153,11 @@ class NetnsController:
148
153
 
149
154
  try:
150
155
  res = subprocess.run(
151
- ["ip", "link", "show"], capture_output=True, text=True, check=False, timeout=5.0
156
+ [resolve("ip"), "link", "show"],
157
+ capture_output=True,
158
+ text=True,
159
+ check=False,
160
+ timeout=5.0,
152
161
  )
153
162
  if res.returncode == 0:
154
163
  for line in res.stdout.splitlines():
@@ -158,7 +167,7 @@ class NetnsController:
158
167
  if iface.startswith(VETH_SWEEP_PREFIXES):
159
168
  logger.info("Startup sweep: removing orphan veth link %s", iface)
160
169
  subprocess.run(
161
- ["ip", "link", "del", iface],
170
+ [resolve("ip"), "link", "del", iface],
162
171
  capture_output=True,
163
172
  check=False,
164
173
  timeout=5.0,
@@ -168,9 +177,9 @@ class NetnsController:
168
177
 
169
178
  def exec_prefix(self, name: str) -> list[str]:
170
179
  if self.use_nsenter:
171
- return ["nsenter", f"--net=/var/run/netns/{name}", "--"]
180
+ return [resolve("nsenter"), f"--net=/var/run/netns/{name}", "--"]
172
181
  else:
173
- return ["ip", "netns", "exec", name]
182
+ return [resolve("ip"), "netns", "exec", name]
174
183
 
175
184
  def _run_in_netns(self, name: str, cmd: list[str]) -> subprocess.CompletedProcess[str]:
176
185
  return _run(self.exec_prefix(name) + cmd)
@@ -182,14 +191,14 @@ class NetnsController:
182
191
  def create_netns(self, name: str) -> None:
183
192
  """Create a new network namespace. Raises on failure."""
184
193
  logger.debug("Creating netns: %s", name)
185
- _run(["ip", "netns", "add", name])
194
+ _run([resolve("ip"), "netns", "add", name])
186
195
  self._active_ns.add(name)
187
196
  # Disable DAD inside the netns to speed up IPv6 interface readiness
188
197
  try:
189
198
  self._run_in_netns(
190
199
  name,
191
200
  [
192
- "sysctl",
201
+ resolve("sysctl"),
193
202
  "-w",
194
203
  "net.ipv6.conf.all.accept_dad=0",
195
204
  ],
@@ -197,7 +206,7 @@ class NetnsController:
197
206
  self._run_in_netns(
198
207
  name,
199
208
  [
200
- "sysctl",
209
+ resolve("sysctl"),
201
210
  "-w",
202
211
  "net.ipv6.conf.default.accept_dad=0",
203
212
  ],
@@ -211,7 +220,7 @@ class NetnsController:
211
220
  delays = [0.1, 0.5, 1.0]
212
221
  for idx, delay in enumerate(delays):
213
222
  try:
214
- _run(["ip", "netns", "del", name])
223
+ _run([resolve("ip"), "netns", "del", name])
215
224
  break
216
225
  except subprocess.CalledProcessError as err:
217
226
  stderr = err.stderr or ""
@@ -243,7 +252,7 @@ class NetnsController:
243
252
  self.create_netns(name)
244
253
 
245
254
  # Bring loopback interface up
246
- self._run_in_netns(name, ["ip", "link", "set", "lo", "up"])
255
+ self._run_in_netns(name, [resolve("ip"), "link", "set", "lo", "up"])
247
256
 
248
257
  # Setup links
249
258
  self.create_veth_pair(
@@ -259,7 +268,7 @@ class NetnsController:
259
268
  finally:
260
269
  # Cleanup links
261
270
  with contextlib.suppress(subprocess.CalledProcessError, OSError):
262
- _run(["ip", "link", "del", sandbox.ext_iface])
271
+ _run([resolve("ip"), "link", "del", sandbox.ext_iface])
263
272
 
264
273
  # Cleanup netns
265
274
  self.destroy_netns(name)
@@ -311,23 +320,23 @@ class NetnsController:
311
320
  v6_peer = "fd00::2/64"
312
321
 
313
322
  # Create veth pair in the root namespace
314
- _run(["ip", "link", "add", veth_host, "type", "veth", "peer", "name", veth_peer])
323
+ _run([resolve("ip"), "link", "add", veth_host, "type", "veth", "peer", "name", veth_peer])
315
324
  # Move the peer end into the target namespace
316
- _run(["ip", "link", "set", veth_peer, "netns", netns_name])
325
+ _run([resolve("ip"), "link", "set", veth_peer, "netns", netns_name])
317
326
 
318
327
  # --- Host side ---
319
328
  if v4_host:
320
- _run(["ip", "addr", "add", v4_host, "dev", veth_host])
329
+ _run([resolve("ip"), "addr", "add", v4_host, "dev", veth_host])
321
330
  if v6_host:
322
- _run(["ip", "addr", "add", v6_host, "dev", veth_host])
323
- _run(["ip", "link", "set", veth_host, "up"])
331
+ _run([resolve("ip"), "addr", "add", v6_host, "dev", veth_host])
332
+ _run([resolve("ip"), "link", "set", veth_host, "up"])
324
333
 
325
334
  # --- Namespace side ---
326
335
  if v4_peer:
327
336
  self._run_in_netns(
328
337
  netns_name,
329
338
  [
330
- "ip",
339
+ resolve("ip"),
331
340
  "addr",
332
341
  "add",
333
342
  v4_peer,
@@ -339,7 +348,7 @@ class NetnsController:
339
348
  self._run_in_netns(
340
349
  netns_name,
341
350
  [
342
- "ip",
351
+ resolve("ip"),
343
352
  "addr",
344
353
  "add",
345
354
  v6_peer,
@@ -347,8 +356,8 @@ class NetnsController:
347
356
  veth_peer,
348
357
  ],
349
358
  )
350
- self._run_in_netns(netns_name, ["ip", "link", "set", veth_peer, "up"])
351
- self._run_in_netns(netns_name, ["ip", "link", "set", "lo", "up"])
359
+ self._run_in_netns(netns_name, [resolve("ip"), "link", "set", veth_peer, "up"])
360
+ self._run_in_netns(netns_name, [resolve("ip"), "link", "set", "lo", "up"])
352
361
 
353
362
  def create_gateway_topology(
354
363
  self,
@@ -377,11 +386,11 @@ class NetnsController:
377
386
  self.create_netns(server_ns)
378
387
 
379
388
  # Enable IPv4/IPv6 forwarding on router namespace
380
- self._run_in_netns(router_ns, ["sysctl", "-w", "net.ipv4.ip_forward=1"])
389
+ self._run_in_netns(router_ns, [resolve("sysctl"), "-w", "net.ipv4.ip_forward=1"])
381
390
  self._run_in_netns(
382
391
  router_ns,
383
392
  [
384
- "sysctl",
393
+ resolve("sysctl"),
385
394
  "-w",
386
395
  "net.ipv6.conf.all.forwarding=1",
387
396
  ],
@@ -390,7 +399,7 @@ class NetnsController:
390
399
  # 1. Create Host <-> Router veth pair
391
400
  _run(
392
401
  [
393
- "ip",
402
+ resolve("ip"),
394
403
  "link",
395
404
  "add",
396
405
  veth_host,
@@ -401,16 +410,16 @@ class NetnsController:
401
410
  veth_router_host,
402
411
  ]
403
412
  )
404
- _run(["ip", "link", "set", veth_router_host, "netns", router_ns])
413
+ _run([resolve("ip"), "link", "set", veth_router_host, "netns", router_ns])
405
414
 
406
- _run(["ip", "addr", "add", host_v4, "dev", veth_host])
407
- _run(["ip", "addr", "add", host_v6, "dev", veth_host])
408
- _run(["ip", "link", "set", veth_host, "up"])
415
+ _run([resolve("ip"), "addr", "add", host_v4, "dev", veth_host])
416
+ _run([resolve("ip"), "addr", "add", host_v6, "dev", veth_host])
417
+ _run([resolve("ip"), "link", "set", veth_host, "up"])
409
418
 
410
419
  self._run_in_netns(
411
420
  router_ns,
412
421
  [
413
- "ip",
422
+ resolve("ip"),
414
423
  "addr",
415
424
  "add",
416
425
  router_host_v4,
@@ -421,7 +430,7 @@ class NetnsController:
421
430
  self._run_in_netns(
422
431
  router_ns,
423
432
  [
424
- "ip",
433
+ resolve("ip"),
425
434
  "addr",
426
435
  "add",
427
436
  router_host_v6,
@@ -432,7 +441,7 @@ class NetnsController:
432
441
  self._run_in_netns(
433
442
  router_ns,
434
443
  [
435
- "ip",
444
+ resolve("ip"),
436
445
  "link",
437
446
  "set",
438
447
  veth_router_host,
@@ -444,7 +453,7 @@ class NetnsController:
444
453
  self._run_in_netns(
445
454
  router_ns,
446
455
  [
447
- "ip",
456
+ resolve("ip"),
448
457
  "link",
449
458
  "add",
450
459
  veth_router_server,
@@ -458,7 +467,7 @@ class NetnsController:
458
467
  self._run_in_netns(
459
468
  router_ns,
460
469
  [
461
- "ip",
470
+ resolve("ip"),
462
471
  "link",
463
472
  "set",
464
473
  veth_server,
@@ -470,7 +479,7 @@ class NetnsController:
470
479
  self._run_in_netns(
471
480
  router_ns,
472
481
  [
473
- "ip",
482
+ resolve("ip"),
474
483
  "addr",
475
484
  "add",
476
485
  router_server_v4,
@@ -481,7 +490,7 @@ class NetnsController:
481
490
  self._run_in_netns(
482
491
  router_ns,
483
492
  [
484
- "ip",
493
+ resolve("ip"),
485
494
  "addr",
486
495
  "add",
487
496
  router_server_v6,
@@ -492,7 +501,7 @@ class NetnsController:
492
501
  self._run_in_netns(
493
502
  router_ns,
494
503
  [
495
- "ip",
504
+ resolve("ip"),
496
505
  "link",
497
506
  "set",
498
507
  veth_router_server,
@@ -503,7 +512,7 @@ class NetnsController:
503
512
  self._run_in_netns(
504
513
  server_ns,
505
514
  [
506
- "ip",
515
+ resolve("ip"),
507
516
  "addr",
508
517
  "add",
509
518
  server_v4,
@@ -514,7 +523,7 @@ class NetnsController:
514
523
  self._run_in_netns(
515
524
  server_ns,
516
525
  [
517
- "ip",
526
+ resolve("ip"),
518
527
  "addr",
519
528
  "add",
520
529
  server_v6,
@@ -522,20 +531,20 @@ class NetnsController:
522
531
  veth_server,
523
532
  ],
524
533
  )
525
- self._run_in_netns(server_ns, ["ip", "link", "set", veth_server, "up"])
534
+ self._run_in_netns(server_ns, [resolve("ip"), "link", "set", veth_server, "up"])
526
535
 
527
536
  # Bring up loopbacks
528
- self._run_in_netns(router_ns, ["ip", "link", "set", "lo", "up"])
529
- self._run_in_netns(server_ns, ["ip", "link", "set", "lo", "up"])
537
+ self._run_in_netns(router_ns, [resolve("ip"), "link", "set", "lo", "up"])
538
+ self._run_in_netns(server_ns, [resolve("ip"), "link", "set", "lo", "up"])
530
539
 
531
540
  # 3. Setup transit routing
532
541
  # Route on Host: Server subnet via Router host IP
533
542
  host_rt_via = router_host_v4.split("/")[0]
534
543
  host_rt_via6 = router_host_v6.split("/")[0]
535
- _run(["ip", "route", "add", "10.0.2.0/24", "via", host_rt_via, "dev", veth_host])
544
+ _run([resolve("ip"), "route", "add", "10.0.2.0/24", "via", host_rt_via, "dev", veth_host])
536
545
  _run(
537
546
  [
538
- "ip",
547
+ resolve("ip"),
539
548
  "-6",
540
549
  "route",
541
550
  "add",
@@ -553,7 +562,7 @@ class NetnsController:
553
562
  self._run_in_netns(
554
563
  server_ns,
555
564
  [
556
- "ip",
565
+ resolve("ip"),
557
566
  "route",
558
567
  "add",
559
568
  "default",
@@ -566,7 +575,7 @@ class NetnsController:
566
575
  self._run_in_netns(
567
576
  server_ns,
568
577
  [
569
- "ip",
578
+ resolve("ip"),
570
579
  "-6",
571
580
  "route",
572
581
  "add",
@@ -0,0 +1,155 @@
1
+ # Copyright (c) 2026 onyks-os
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """Trusted resolution of the external binaries NSE executes as root.
5
+
6
+ Why this module exists
7
+ ----------------------
8
+
9
+ NSE runs as root - it has to, to create network namespaces and read kernel
10
+ trace events - and shells out to ``ip``, ``nft`` and ``nsenter``. Passing a bare name to :mod:`subprocess` makes the kernel resolve it
11
+ through ``$PATH`` - so anyone who can influence the environment of the ``sudo``
12
+ invocation can put their own ``nft`` earlier in the search order and have it
13
+ executed with full privileges. That is a local privilege escalation in a tool whose entire job is to be
14
+ trusted about what a firewall does.
15
+
16
+ ``sudo`` usually blunts this with ``secure_path``, but "usually" is not a
17
+ security property: it is a distribution default an administrator can disable.
18
+
19
+ So NSE does not use ``$PATH``. It resolves every binary against a fixed list of
20
+ root-owned system directories, and refuses to execute one that is writable by
21
+ anybody but root.
22
+
23
+ Usage
24
+ -----
25
+
26
+ from nse.core.paths import resolve
27
+
28
+ subprocess.run([resolve("nft"), "list", "ruleset"], ...)
29
+
30
+ The result is cached, so the cost is one ``stat`` per binary per process.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import os
36
+ import stat
37
+ from functools import cache
38
+ from pathlib import Path
39
+
40
+ #: Where a system binary may legitimately live, in search order.
41
+ #:
42
+ #: sbin first: ``nft``, ``ip`` and ``systemctl`` live there on every supported
43
+ #: distribution, and on merged-/usr systems the bin entries are symlinks to the
44
+ #: same files. ``/usr/local`` is included last because a locally built ``nft`` is
45
+ #: a legitimate setup, and excluded from nothing else: it is still checked for
46
+ #: safe ownership like every other candidate.
47
+ TRUSTED_DIRS: tuple[str, ...] = (
48
+ "/usr/sbin",
49
+ "/sbin",
50
+ "/usr/bin",
51
+ "/bin",
52
+ "/usr/local/sbin",
53
+ "/usr/local/bin",
54
+ )
55
+
56
+
57
+ class BinaryNotFoundError(FileNotFoundError):
58
+ """
59
+ A required external binary is absent from every trusted directory.
60
+
61
+ A :class:`FileNotFoundError`, because that is exactly what it is: callers
62
+ that already handle a missing tool keep working unchanged. TTP learned this
63
+ the hard way - a bespoke exception type turned graceful degradation into a
64
+ crash on every distribution that did not ship the binary.
65
+ """
66
+
67
+
68
+ class UnsafeBinaryError(Exception):
69
+ """A binary was found, but its permissions let a non-root user replace it."""
70
+
71
+
72
+ def _is_safely_owned(path: Path) -> bool:
73
+ """
74
+ True when only root can modify *path*.
75
+
76
+ A binary that is group- or world-writable can be swapped by whoever holds
77
+ that access, which defeats the point of resolving it from a fixed directory
78
+ in the first place. The same applies to the directory holding it: write
79
+ access there is enough to replace the file by rename.
80
+ """
81
+ for target in (path, path.parent):
82
+ try:
83
+ info = target.stat()
84
+ except OSError:
85
+ return False
86
+ if info.st_uid != 0:
87
+ return False
88
+ if info.st_mode & (stat.S_IWGRP | stat.S_IWOTH):
89
+ return False
90
+ return True
91
+
92
+
93
+ @cache
94
+ def resolve(binary: str) -> str:
95
+ """
96
+ Return the absolute path of *binary*, searched in :data:`TRUSTED_DIRS`.
97
+
98
+ Args:
99
+ binary: A bare executable name, e.g. ``"nft"``.
100
+
101
+ Returns:
102
+ The absolute path to execute.
103
+
104
+ Raises:
105
+ ValueError: if *binary* is not a bare name. A caller passing a path has
106
+ usually made a mistake, and silently accepting it would reopen the
107
+ hole this module closes.
108
+ BinaryNotFoundError: if no trusted directory holds it.
109
+ UnsafeBinaryError: if the one found could be replaced by a non-root user.
110
+ """
111
+ if not binary or "/" in binary:
112
+ raise ValueError(f"resolve() takes a bare binary name, not {binary!r}")
113
+
114
+ searched: list[str] = []
115
+ for directory in TRUSTED_DIRS:
116
+ candidate = Path(directory) / binary
117
+ searched.append(str(candidate))
118
+ if not candidate.is_file() or not os.access(candidate, os.X_OK):
119
+ continue
120
+ if not _is_safely_owned(candidate):
121
+ raise UnsafeBinaryError(
122
+ f"{candidate} is executable but not owned exclusively by root, so a "
123
+ f"non-root user could replace it before NSE runs it with full "
124
+ f"privileges. Refusing to execute it."
125
+ )
126
+ return str(candidate)
127
+
128
+ raise BinaryNotFoundError(
129
+ f"Required binary '{binary}' was not found in any trusted directory. "
130
+ f"Searched: {', '.join(searched)}. "
131
+ f"NSE deliberately does not consult $PATH, because a caller-controlled "
132
+ f"PATH would let an attacker choose which program runs as root."
133
+ )
134
+
135
+
136
+ def resolve_optional(binary: str) -> str | None:
137
+ """
138
+ Like :func:`resolve`, but ``None`` when the binary is simply absent.
139
+
140
+ For tools NSE can work without - ``conntrack`` when the host has no
141
+ connection tracking to read.
142
+
143
+ :class:`UnsafeBinaryError` still propagates: a binary that is present but
144
+ replaceable is a finding, not an absence, and must never be silently
145
+ skipped.
146
+ """
147
+ try:
148
+ return resolve(binary)
149
+ except BinaryNotFoundError:
150
+ return None
151
+
152
+
153
+ def clear_cache() -> None:
154
+ """Forget resolved paths. For tests, and for after a package installation."""
155
+ resolve.cache_clear()
@@ -38,6 +38,7 @@ from typing import Any, cast
38
38
  from nse.core.mock_listener import start_mock_listener
39
39
  from nse.core.naming import derive_names
40
40
  from nse.core.netns_controller import NetnsController, TestRun
41
+ from nse.core.paths import resolve
41
42
  from nse.core.rule_engine import RuleEngine, RuleValidationError
42
43
  from nse.core.scapy_injector import ScapyInjector
43
44
  from nse.core.trace_harvester import TraceHarvester
@@ -125,13 +126,13 @@ def parse_conntrack_line(line: str) -> dict[str, Any] | None:
125
126
 
126
127
  def read_conntrack_table(netns: str, use_nsenter: bool = False) -> list[dict[str, Any]]:
127
128
  exec_cmd = (
128
- ["nsenter", f"--net=/var/run/netns/{netns}", "--"]
129
+ [resolve("nsenter"), f"--net=/var/run/netns/{netns}", "--"]
129
130
  if use_nsenter
130
- else ["ip", "netns", "exec", netns]
131
+ else [resolve("ip"), "netns", "exec", netns]
131
132
  )
132
133
  try:
133
134
  res = subprocess.run(
134
- [*exec_cmd, "cat", "/proc/net/nf_conntrack"],
135
+ [*exec_cmd, resolve("cat"), "/proc/net/nf_conntrack"],
135
136
  capture_output=True,
136
137
  text=True,
137
138
  check=True,
@@ -140,7 +141,7 @@ def read_conntrack_table(netns: str, use_nsenter: bool = False) -> list[dict[str
140
141
  except (subprocess.CalledProcessError, OSError):
141
142
  try:
142
143
  res = subprocess.run(
143
- [*exec_cmd, "cat", "/proc/net/ip_conntrack"],
144
+ [*exec_cmd, resolve("cat"), "/proc/net/ip_conntrack"],
144
145
  capture_output=True,
145
146
  text=True,
146
147
  check=True,
@@ -514,7 +515,7 @@ async def run_test_pipeline(
514
515
  await loop.run_in_executor(
515
516
  None,
516
517
  lambda: subprocess.run(
517
- ["ip", "link", "del", veth_host],
518
+ [resolve("ip"), "link", "del", veth_host],
518
519
  capture_output=True,
519
520
  check=False,
520
521
  ),