diff mbox series

[[RFC] 1/2] utils: Add landlock_restrict_network function

Message ID 20260612-landlock-v1-1-77891f63ed7f@est.tech
State New
Headers show
Series [[RFC] 1/2] utils: Add landlock_restrict_network function | expand

Commit Message

David Nyström June 12, 2026, 11:38 a.m. UTC
Add landlock_restrict_network() which blocks TCP bind/connect using
Landlock LSM (ABI v4+, kernel 6.7+). Designed to stack with the
existing disable_network() namespace isolation, covering the case
where disable_network() is skipped for non-local UIDs.

Gracefully returns False on older kernels (ABI < 4).

Signed-off-by: David Nyström <david.nystrom@est.tech>
---
 lib/bb/utils.py | 26 ++++++++++++++++++++++++++
 1 file changed, 26 insertions(+)
diff mbox series

Patch

diff --git a/lib/bb/utils.py b/lib/bb/utils.py
index 181082c95..1347c29d0 100644
--- a/lib/bb/utils.py
+++ b/lib/bb/utils.py
@@ -2054,6 +2054,32 @@  def disable_network(uid=None, gid=None):
     with open("/proc/self/gid_map", "w") as f:
         f.write("%s %s 1" % (gid, gid))
 
+def landlock_restrict_network():
+    """Block TCP bind/connect using Landlock LSM (ABI v4+, kernel 6.7+).
+    Gracefully skipped on older kernels. Stacks with disable_network()."""
+
+    NR_CREATE = 444  # landlock_create_ruleset
+    NR_SELF   = 446  # landlock_restrict_self
+    NET_TCP   = 0x3  # BIND_TCP | CONNECT_TCP
+
+    libc = ctypes.CDLL('libc.so.6')
+
+    abi = libc.syscall(NR_CREATE, 0, 0, 1)
+    if abi < 4:
+        return False
+
+    attr = struct.pack("QQ", 0, NET_TCP)
+    buf = ctypes.create_string_buffer(attr)
+    fd = libc.syscall(NR_CREATE, buf, len(attr), 0)
+    if fd < 0:
+        return False
+
+    libc.prctl(38, 1, 0, 0, 0)  # PR_SET_NO_NEW_PRIVS
+    r = libc.syscall(NR_SELF, fd, 0)
+    os.close(fd)
+    return r == 0
+
+
 def export_proxies(d):
     from bb.fetch2 import get_fetcher_environment
     """ export common proxies variables from datastore to environment """