NetNSEnter ignores setns() failures. A failed entry therefore executes the with block in the original namespace, and a failed restoration is also silent. This violates the context's namespace-switching contract. Enable ctypes errno preservation and check both switches. Close the saved namespace file after failed entry or a restoration attempt. Run this as root from tools/testing/selftests/net. The private fixture uses a child without CAP_SYS_ADMIN. The original prints the error marker; the fix raises PermissionError before executing the body: unshare -mn --propagation private sh -ec ' mount -t tmpfs tmpfs /run; mkdir /run/netns ip netns add review-target exec capsh --drop=cap_sys_admin -- -c "python3 -" ' <<'PYCODE' from lib.py import NetNSEnter with NetNSEnter("review-target"): print("ERROR: body ran without permission to enter target") PYCODE Found by AI-assisted inspection. This real permission-denial reproducer and five real-syscall scenarios confirm the fix: successful entry/return, a body exception, a missing target, entry EPERM and restoration EPERM. The original meets two of five checks and the fix meets all five. Failed restoration still leaves the thread in the target namespace; raising an error does not recover permissions or guarantee that a test runner will stop subsequent tests. No kernel instrumentation, simulated syscall returns or fault injection was used. No hardware suite was run. Fixes: 030329416232 ("selftests: net: Add python context manager for netns entering") Signed-off-by: Jingjing Xu --- tools/testing/selftests/net/lib/py/netns.py | 22 ++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/tools/testing/selftests/net/lib/py/netns.py b/tools/testing/selftests/net/lib/py/netns.py index 526f6aa80077..472b51c29be2 100644 --- a/tools/testing/selftests/net/lib/py/netns.py +++ b/tools/testing/selftests/net/lib/py/netns.py @@ -10,7 +10,7 @@ from pathlib import Path from .utils import ip -libc = ctypes.cdll.LoadLibrary('libc.so.6') +libc = ctypes.CDLL('libc.so.6', use_errno=True) class NetNS: @@ -111,12 +111,24 @@ class NetNSEnter: def __init__(self, ns_name): self.ns_path = f"/run/netns/{ns_name}" + @staticmethod + def _setns(fd): + if libc.setns(fd, 0) == -1: + err = ctypes.get_errno() + raise OSError(err, os.strerror(err)) + def __enter__(self): self.saved = open("/proc/thread-self/ns/net") - with open(self.ns_path) as ns_file: - libc.setns(ns_file.fileno(), 0) + try: + with open(self.ns_path) as ns_file: + self._setns(ns_file.fileno()) + except BaseException: + self.saved.close() + raise return self def __exit__(self, exc_type, exc_value, traceback): - libc.setns(self.saved.fileno(), 0) - self.saved.close() + try: + self._setns(self.saved.fileno()) + finally: + self.saved.close() base-commit: 2208ab00f4f213ade91ab775e7f8c4dacdcc856e -- 2.53.0