Systemd namespaces: what PrivateNetwork=yes isolates and what still works inside the service
| |

Systemd namespaces and network filters, with a tested lab

Systemd namespaces and filters explained with a tested lab: PrivateNetwork=, RestrictNamespaces=, RestrictAddressFamilies= and IP filters.

Systemd namespaces and network filters decide what a service can see and whom it can talk to. A compromised service that still shares the host network, the host IPC objects and the whole list of socket families has a lot of room to move. This fifth part of the series “Systemd hardening, directive by directive” covers thirteen settings that shrink that room, and it tests every one of them on a real machine.

Every output below comes from a real run, so you can compare it with your own results. When a result differs from the manual, the text says so. The article covers PrivateNetwork=, NetworkNamespacePath=, JoinsNamespaceOf=, PrivateUsers=, PrivateIPC=, IPCNamespacePath=, RestrictNamespaces=, RestrictAddressFamilies=, IPAddressAllow=, IPAddressDeny=, IPAccounting=, SocketBindAllow= and SocketBindDeny=. The mount namespace directives belong to part 2 of the series.

Before you start

  • Level: you can write a unit file and read a journal. You do not need to know anything about namespaces yet.
  • Machine and rights: a test machine or a virtual machine that runs systemd as PID 1, with root access (sudo -i). Never run this lab on a production server.
  • Tools: systemctl, journalctl, systemd-analyze, python3, curl, ip, unshare, nsenter and ipcmk.

Tested on Rocky Linux 10.2, systemd 257, WSL2 kernel 6.18.54.1-microsoft-standard-WSL2. SELinux is not available on that bench, so no result below involves SELinux. The bench kernel supports cgroup BPF, so the IP filters and the bind filters really worked there. A different kernel can give different results.

The words you need

Systemd namespaces rest on a few kernel ideas. Read this table once, then come back to it when a term feels unclear.

TermPlain meaning
NamespaceA private view of one kind of kernel resource. Two processes in different namespaces see different interfaces, users or IPC objects on the same kernel.
Network namespaceA private set of network interfaces, addresses, routes and ports. A new one contains only a loopback interface.
Address familyThe kind of socket: AF_UNIX for local sockets, AF_INET and AF_INET6 for IPv4 and IPv6, AF_NETLINK to talk to the kernel, AF_PACKET for raw packets.
Abstract socketA local socket with a name that starts with a null byte. It lives in the network namespace, not in the file system.

Systemd namespaces and filters at a glance

The thirteen settings fall into four groups: private copies of a resource, limits on creating namespaces, a filter on socket types, and filters on addresses and ports. The table sums up their effect, their risk, and their meaning for my own stack.

DirectiveEffectRisk of breakingImpact on my stack
PrivateNetwork=Own network namespace with only loHigh: no outside networkMy web apps need nginx and PostgreSQL, so it does not fit them
NetworkNamespacePath=Join a namespace you builtMedium: the loopback stays downNot used (WireGuard runs on the host)
JoinsNamespaceOf=Share a private namespace between unitsLowNot used
PrivateUsers=Own user namespace, minimal ID mapMedium: no sudo, no low portsNot used; my hardening role blocks user namespaces
PrivateIPC=Own System V and POSIX queue IPC objectsLowNothing I checked shares IPC objects
IPCNamespacePath=Join an IPC namespace you builtLowNot used
RestrictNamespaces=Forbids creating or joining namespacesMedium: containers, browser enginesNo unit I checked starts containers
RestrictAddressFamilies=Filters socket() by familyMedium: ip and logger breakThe IDS mode of my Suricata role needs AF_PACKET
IPAddressAllow= / IPAddressDeny=Filters packets by addressMedium: drops look like timeoutsFits internal services, not the mail server
IPAccounting=Counts bytes and packets per unitNoneUseful on the reverse proxy
SocketBindAllow= / SocketBindDeny=Filters bind() by portMedium: a wrong port stops the serviceThe mail server opens seven fixed TCP ports

Build the lab

The lab uses a harmless probe script that opens sockets and prints one line per test, and a second script that plays the host side with listeners on the loopback, the LAN address, an abstract socket and a socket file. Every name starts with demo-hardening-sd5-, and the two accounts are sd5demo and sd5other, so the cleanup removes exactly what the lab created. Save the script below as lab-setup.sh and run it as root.

#!/bin/bash
# Creates the harmless demo files and units of the lab (all named demo-hardening-sd5-*).
set -e
id sd5demo >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin sd5demo
id sd5other >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin sd5other

mkdir -p /run/demo-hardening-sd5
chmod 755 /run/demo-hardening-sd5
: > /run/demo-hardening-sd5/owned-by-root
: > /run/demo-hardening-sd5/owned-by-sd5demo
: > /run/demo-hardening-sd5/owned-by-sd5other
chown sd5demo /run/demo-hardening-sd5/owned-by-sd5demo
chown sd5other /run/demo-hardening-sd5/owned-by-sd5other
chmod 644 /run/demo-hardening-sd5/owned-by-*

cat > /usr/local/bin/demo-hardening-sd5-probe.py <<'EOF'
#!/usr/bin/python3
# Harmless probe: opens a few sockets, reads a few files, prints one line per test.
import errno, os, socket, subprocess, sys


def err(e):
    n = getattr(e, "errno", None)
    return f"{errno.errorcode.get(n, '?')} ({os.strerror(n)})" if n else type(e).__name__


def tcp(addr, port):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(2)
    try:
        s.connect((addr, port))
        s.sendall(b"ping\n")
        return "connected, reply: " + s.recv(64).decode().strip()
    except OSError as e:
        return "failed: " + err(e)
    finally:
        s.close()


def unix(path):
    s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    s.settimeout(2)
    try:
        s.connect(path)
        s.sendall(b"ping\n")
        return "connected, reply: " + s.recv(64).decode().strip()
    except OSError as e:
        return "failed: " + err(e)
    finally:
        s.close()


def own_loopback():
    srv = socket.socket()
    try:
        srv.bind(("127.0.0.1", 18090))
        srv.listen(1)
    except OSError as e:
        return "failed to listen: " + err(e)
    c = socket.socket()
    c.settimeout(2)
    try:
        c.connect(("127.0.0.1", 18090))
        return "listen and connect on 127.0.0.1: ok"
    except OSError as e:
        return "failed to connect: " + err(e)
    finally:
        c.close()
        srv.close()


mode = sys.argv[1]
if mode == "net":
    host_ns = sys.argv[2] if len(sys.argv) > 2 else ""
    ns = os.readlink("/proc/self/ns/net")
    print("network namespace:", ns, "| same as the host:", "yes" if ns == host_ns else "no")
    names = [l.split(":")[0].strip() for l in open("/proc/net/dev").read().splitlines()[2:]]
    print("interfaces:", " ".join(names))
    print("own loopback:", own_loopback())
    print("host loopback port 18080:", tcp("127.0.0.1", 18080))
    print("host LAN address port 18081:", tcp(os.environ["HOSTIP"], 18081))
    print("host abstract socket:", unix("\0demo-hardening-sd5-abstract"))
    print("host file socket:", unix("/run/demo-hardening-sd5/sock"))
elif mode == "families":
    for name in ("AF_UNIX", "AF_INET", "AF_INET6", "AF_NETLINK", "AF_PACKET"):
        fam = getattr(socket, name)
        typ = socket.SOCK_RAW if name in ("AF_NETLINK", "AF_PACKET") else socket.SOCK_STREAM
        try:
            s = socket.socket(fam, typ, 0)
            s.close()
            print(f"{name:11} socket(): ok")
        except OSError as e:
            print(f"{name:11} socket(): failed: {err(e)}")
    try:
        a, b = socket.socketpair()
        a.close()
        b.close()
        print("socketpair() AF_UNIX: ok")
    except OSError as e:
        print("socketpair() AF_UNIX: failed:", err(e))
elif mode == "resolve":
    for flags, label in ((0, "getaddrinfo(localhost)"), (socket.AI_ADDRCONFIG, "getaddrinfo(localhost, AI_ADDRCONFIG)")):
        try:
            r = socket.getaddrinfo("localhost", 80, 0, socket.SOCK_STREAM, 0, flags)
            print(f"{label}: ok, {len(r)} result(s)")
        except OSError as e:
            print(f"{label}: failed: {e}")
elif mode == "bind":
    for kind, addr, port in (("tcp", "127.0.0.1", 18090), ("tcp", "127.0.0.1", 18091), ("udp", "127.0.0.1", 18090), ("tcp6", "::1", 18090), ("tcp", "127.0.0.1", 18095)):
        fam = socket.AF_INET6 if kind == "tcp6" else socket.AF_INET
        typ = socket.SOCK_DGRAM if kind == "udp" else socket.SOCK_STREAM
        s = socket.socket(fam, typ)
        try:
            s.bind((addr, port))
            print(f"bind {kind:4} port {port}: ok")
        except OSError as e:
            print(f"bind {kind:4} port {port}: failed: {err(e)}")
        finally:
            s.close()
elif mode == "users":
    print("id:", subprocess.run(["id"], capture_output=True, text=True).stdout.strip())
    print("uid_map:", " | ".join(" ".join(l.split()) for l in open("/proc/self/uid_map").read().splitlines()))
    print("gid_map:", " | ".join(" ".join(l.split()) for l in open("/proc/self/gid_map").read().splitlines()))
    for l in open("/proc/self/status"):
        if l.startswith(("CapEff", "CapBnd")):
            print(l.strip())
    for f in ("owned-by-root", "owned-by-sd5demo", "owned-by-sd5other"):
        st = os.stat("/run/demo-hardening-sd5/" + f)
        print(f"file {f}: owner uid {st.st_uid}, group gid {st.st_gid}")
    target = "/run/demo-hardening-sd5/owned-by-sd5demo"
    original = os.stat(target).st_uid
    try:
        os.chown(target, int(sys.argv[2]), -1)
        print("chown to another user: ok")
        os.chown(target, original, -1)
    except OSError as e:
        print("chown to another user: failed:", err(e))
    s = socket.socket()
    try:
        s.bind(("127.0.0.1", 80))
        print("bind port 80: ok")
    except OSError as e:
        print("bind port 80: failed:", err(e))
    finally:
        s.close()
elif mode == "ipc":
    print("ipc namespace:", os.readlink("/proc/self/ns/ipc"))
    out = subprocess.run(["ipcs", "-m"], capture_output=True, text=True).stdout.rstrip().splitlines()
    print("\n".join(out))
EOF
chmod 755 /usr/local/bin/demo-hardening-sd5-probe.py

cat > /usr/local/bin/demo-hardening-sd5-listener.py <<'EOF'
#!/usr/bin/python3
# Host-side fixture: four listeners that answer "ping" with a fixed line.
import os, socket, sys, threading

hostip = sys.argv[1]


def serve(sock, reply):
    sock.listen(8)
    while True:
        c, _ = sock.accept()
        try:
            c.recv(64)
            c.sendall(reply)
        finally:
            c.close()


def tcp(addr, port, reply):
    s = socket.socket()
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((addr, port))
    return s, reply


path = "/run/demo-hardening-sd5/sock"
if os.path.exists(path):
    os.unlink(path)
u = socket.socket(socket.AF_UNIX)
u.bind(path)
os.chmod(path, 0o666)
a = socket.socket(socket.AF_UNIX)
a.bind("\0demo-hardening-sd5-abstract")
items = [tcp("127.0.0.1", 18080, b"hello-from-host-loopback\n"), tcp(hostip, 18081, b"hello-from-host-lan\n"), (u, b"hello-from-host-file-socket\n"), (a, b"hello-from-host-abstract-socket\n")]
for s, r in items:
    threading.Thread(target=serve, args=(s, r), daemon=True).start()
threading.Event().wait()
EOF
chmod 755 /usr/local/bin/demo-hardening-sd5-listener.py

cat > /usr/local/bin/demo-hardening-sd5-app.py <<'EOF'
#!/usr/bin/python3
# Tiny demo "application": answers every HTTP request with one line on 127.0.0.1:18085.
from http.server import BaseHTTPRequestHandler, HTTPServer


class H(BaseHTTPRequestHandler):
    def do_GET(self):
        body = b"hello from the demo app\n"
        self.send_response(200)
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, *a):
        pass


HTTPServer(("127.0.0.1", 18085), H).serve_forever()
EOF
chmod 755 /usr/local/bin/demo-hardening-sd5-app.py

HOSTIP=$(ip -4 -o addr show dev eth0 | awk '{print $4}' | cut -d/ -f1 | head -1)
cat > /etc/systemd/system/demo-hardening-sd5-listener.service <<EOF
[Unit]
Description=Demo hardening sd5: host-side listeners used as test targets

[Service]
ExecStart=/usr/local/bin/demo-hardening-sd5-listener.py $HOSTIP
EOF

cat > /etc/systemd/system/demo-hardening-sd5-app.service <<'EOF'
[Unit]
Description=Demo hardening sd5: tiny HTTP application

[Service]
User=sd5demo
ExecStart=/usr/local/bin/demo-hardening-sd5-app.py
EOF
systemctl daemon-reload
systemctl start demo-hardening-sd5-listener.service
sleep 1
bash lab-setup.sh

Then define the variables and the helper. The helper runs a command in a temporary service with the properties you give it. Change eth0 if your interface has another name.

HOSTIP=$(ip -4 -o addr show dev eth0 | awk '{print $4}' | cut -d/ -f1 | head -1)
HOSTNS=$(readlink /proc/self/ns/net)
PROBE=/usr/local/bin/demo-hardening-sd5-probe.py
sd() { systemd-run --quiet --collect --wait --pipe -E HOSTIP="$HOSTIP" "$@"; }

My wrapper also printed the exit status after each run. I removed those lines; everything else is real output.

Network isolation with systemd namespaces

Baseline: no isolation

First, run the probe with no hardening. Every test succeeds because the service shares the host network.

sd -- $PROBE net "$HOSTNS"
network namespace: net:[4026531833] | same as the host: yes
interfaces: lo loopback0 eth0 eth1 eth2 eth3 eth4 br-5496b403fe34 docker0
own loopback: listen and connect on 127.0.0.1: ok
host loopback port 18080: connected, reply: hello-from-host-loopback
host LAN address port 18081: connected, reply: hello-from-host-lan
host abstract socket: connected, reply: hello-from-host-abstract-socket
host file socket: connected, reply: hello-from-host-file-socket

PrivateNetwork=: a network with only a loopback

PrivateNetwork=yes starts the service in a new network namespace that holds only the loopback interface. According to the manual, it also cuts the service off from the host for every socket family, including AF_NETLINK and abstract AF_UNIX sockets, and it implies PrivateMounts= and remounts /sys. The page I read gives no “added in” version for it.

sd -p PrivateNetwork=yes -- $PROBE net "$HOSTNS"
network namespace: net:[4026532291] | same as the host: no
interfaces: lo
own loopback: listen and connect on 127.0.0.1: ok
host loopback port 18080: failed: ECONNREFUSED (Connection refused)
host LAN address port 18081: failed: ENETUNREACH (Network is unreachable)
host abstract socket: failed: ECONNREFUSED (Connection refused)
host file socket: connected, reply: hello-from-host-file-socket
Systemd namespaces: what PrivateNetwork=yes isolates and what still works inside the service
What PrivateNetwork=yes isolates, measured on the test bench.

The result matches the manual. The service has one interface, and its own loopback works. The host loopback answers “connection refused”, the LAN address is unreachable, and the abstract socket is invisible. Only the socket file in the file system still works: a namespace changes the network view, not the files.

sd -p PrivateNetwork=yes -- ip -o link
sd -p PrivateNetwork=yes -- ip -o addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000\    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
1: lo    inet 127.0.0.1/8 scope host lo\       valid_lft forever preferred_lft forever
1: lo    inet6 ::1/128 scope host noprefixroute \       valid_lft forever preferred_lft forever

The implied mount namespace is real too: the unit has its own, while a unit without isolation shares the host one.

sd -p PrivateNetwork=yes -- /bin/bash -c 'echo mount namespace: $(readlink /proc/self/ns/mnt)'
echo "host mount namespace: $(readlink /proc/self/ns/mnt)"
sd -- /bin/bash -c 'echo mount namespace without any isolation: $(readlink /proc/self/ns/mnt)'
mount namespace: mnt:[4026532472]
host mount namespace: mnt:[4026532217]
mount namespace without any isolation: mnt:[4026532217]

One surprise: systemctl show -p PrivateMounts still prints no. The implication is internal, so trust the namespace inode, not that property.

What it breaks. Anything that talks to another machine, to a database on the host loopback, or to a local resolver stub such as 127.0.0.53. The symptoms are ECONNREFUSED for the host loopback and ENETUNREACH for the rest. A reverse proxy cannot reach an application with this setting, and the reverse is also true.

How to test. Run the probe, or compare /proc/PID/ns/net with the one of PID 1.

Effect on my stack. My web applications, such as Kavita on a local port and Etherpad on port 9001 with a PostgreSQL backend, sit behind nginx, so this directive would cut their links. It fits batch jobs that need no network. None of the units in my notes sets it.

NetworkNamespacePath=: join a namespace you built

NetworkNamespacePath= (since systemd 242) joins a namespace file such as /run/netns/name. The manual says PrivateNetwork= then has no effect. Use it to place a service in a namespace that holds a VPN interface or a special route.

Create an empty named namespace with ip netns, run the probe in it, and compare the inode with the one of the file.

ip netns add demo-hardening-sd5-ns
sd -p NetworkNamespacePath=/run/netns/demo-hardening-sd5-ns -- /bin/bash -c "echo network namespace: \$(readlink /proc/self/ns/net); echo interfaces: \$(cut -d: -f1 /proc/net/dev | tail -n +3 | tr -d ' ' | tr '\n' ' ')"
echo "namespace of the named file: $(ip netns exec demo-hardening-sd5-ns readlink /proc/self/ns/net)"
network namespace: net:[4026532446]
interfaces: lo
namespace of the named file: net:[4026532446]

Both inodes are identical, so the service joined it. With both directives set, the path wins, as the manual says.

sd -p PrivateNetwork=yes -p NetworkNamespacePath=/run/netns/demo-hardening-sd5-ns -- /bin/bash -c 'echo network namespace: $(readlink /proc/self/ns/net)'
network namespace: net:[4026532446]

Now the key difference with PrivateNetwork=yes: in a namespace you created yourself, the loopback is down, and systemd does not raise it. Even a connection to the own loopback fails.

sd -p NetworkNamespacePath=/run/netns/demo-hardening-sd5-ns -- $PROBE net "$HOSTNS" | sed -n 3p
sd -p NetworkNamespacePath=/run/netns/demo-hardening-sd5-ns -- ip -o link
sd -p PrivateNetwork=yes -- ip -o link
own loopback: failed to connect: ENETUNREACH (Network is unreachable)
1: lo: <LOOPBACK> mtu 65536 qdisc noop state DOWN mode DEFAULT group default qlen 1000\    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000\    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00

So bring the loopback up when you build the namespace (ip netns exec NAME ip link set lo up).

If the path does not exist, or points to a regular file, the unit fails at the step NETWORK with exit status 225.

systemd-run --collect --wait -p NetworkNamespacePath=/run/netns/demo-hardening-sd5-missing --unit demo-hardening-sd5-badns /bin/true
journalctl -u demo-hardening-sd5-badns -o cat --no-pager
touch /run/demo-hardening-sd5/not-a-namespace
systemd-run --collect --wait -p NetworkNamespacePath=/run/demo-hardening-sd5/not-a-namespace --unit demo-hardening-sd5-badns2 /bin/true
journalctl -u demo-hardening-sd5-badns2 -o cat --no-pager
[...]
demo-hardening-sd5-badns.service: Failed to open network namespace path /run/netns/demo-hardening-sd5-missing: No such file or directory
[...]
demo-hardening-sd5-badns.service: Main process exited, code=exited, status=225/NETWORK
[...]
[...]
demo-hardening-sd5-badns2.service: Failed to open network namespace path /run/demo-hardening-sd5/not-a-namespace: Invalid argument
[...]
demo-hardening-sd5-badns2.service: Main process exited, code=exited, status=225/NETWORK
[...]

Effect on my stack. I run WireGuard on the host with wg-quick@wg0, so I do not use this design, and I did not test it with a VPN interface.

JoinsNamespaceOf=: share a private namespace between units

JoinsNamespaceOf= (in the [Unit] section, since systemd 209) tells a unit to join the private namespaces of another unit. It covers the network, IPC and temporary directories, and both units need the matching private directive. A typical use is a sidecar, such as an exporter next to the service it scrapes.

The lab uses four units: a server a with PrivateNetwork=yes, a client b that joins it, a client c with its own namespace and no join, and a client d with the join but no PrivateNetwork=.

# demo-hardening-sd5-a.service: the server
[Service]
User=sd5demo
PrivateNetwork=yes
ExecStart=/usr/local/bin/demo-hardening-sd5-app.py

# demo-hardening-sd5-b.service: a client that joins the namespace of unit a
[Unit]
JoinsNamespaceOf=demo-hardening-sd5-a.service

[Service]
Type=oneshot
PrivateNetwork=yes
ExecStart=/bin/bash -c 'echo "network namespace: $(readlink /proc/self/ns/net)"; curl -sS --max-time 3 http://127.0.0.1:18085/ || true'
StandardOutput=journal

Unit c is a copy of b without the join line, and unit d is a copy without PrivateNetwork=yes. A small function starts a client and prints its journal.

run1() { systemctl start "$1"; sleep 1; journalctl -u "$1" -o cat --no-pager --since -10s | grep -vE '^(Starting |Finished |Started |.*: Deactivated successfully)'; }
systemctl daemon-reload
systemctl start demo-hardening-sd5-a; sleep 1
systemctl is-active demo-hardening-sd5-a
echo "namespace of unit a: $(readlink /proc/$(systemctl show -p MainPID --value demo-hardening-sd5-a)/ns/net)"
run1 demo-hardening-sd5-b
run1 demo-hardening-sd5-c
run1 demo-hardening-sd5-d
active
namespace of unit a: net:[4026532291]
network namespace: net:[4026532291]
hello from the demo app
network namespace: net:[4026532473]
curl: (7) Failed to connect to 127.0.0.1 port 18085 after 0 ms: Could not connect to server
network namespace: net:[4026531833]
curl: (28) Connection timed out after 3002 milliseconds

Unit b shares the namespace of the server and gets its answer. Unit c gets a refusal. Unit d proves the manual: without its own private namespace, the join does nothing, and the unit stays in the host namespace.

Two details are not in the manual. The join adds no dependency: no After=, Requires= or Wants= names unit a. And when unit a is stopped, unit b still starts, creates its own namespace, and the call fails.

for p in After Requires Wants BindsTo; do echo "$p: $(systemctl show demo-hardening-sd5-b --value -p $p | tr ' ' '\n' | grep -c sd5-a) entries naming unit a"; done
systemctl stop demo-hardening-sd5-a
run1 demo-hardening-sd5-b
After: 0 entries naming unit a
Requires: 0 entries naming unit a
Wants: 0 entries naming unit a
BindsTo: 0 entries naming unit a
network namespace: net:[4026532441]
curl: (7) Failed to connect to 127.0.0.1 port 18085 after 0 ms: Could not connect to server

Effect on my stack. I found nothing in my notes that uses it. If you run a PHP-FPM pool and an exporter that reads its status page, a shared private network keeps both off the host network.

User and IPC systemd namespaces

PrivateUsers=: a minimal user map

PrivateUsers=yes (since systemd 232) starts the service in a new user namespace where only root, the service user and group, and nobody exist. Files of anyone else appear as owned by nobody. The latest manual also documents the values self, identity, full and managed, with no version given on the page I read.

Systemd 257 rejects all four. The bench prints the same error each time, shown here for self. Use only yes or no on this version, and check systemctl --version before you copy from a newer manual.

sd -p User=sd5demo -p PrivateUsers=self -- $PROBE users $(id -u sd5other)
Failed to parse PrivateUsers: self

The probe prints the ID map, the capabilities, the owner of three files, a chown to another user, and a bind on port 80. First as root without a user namespace, then with PrivateUsers=yes.

sd -- $PROBE users $(id -u sd5other)
sd -p PrivateUsers=yes -- $PROBE users $(id -u sd5other)
--- no PrivateUsers=
id: uid=0(root) gid=0(root) groups=0(root)
uid_map: 0 0 4294967295
gid_map: 0 0 4294967295
CapEff:	000001ffffffffff
CapBnd:	000001ffffffffff
file owned-by-root: owner uid 0, group gid 0
file owned-by-sd5demo: owner uid 987, group gid 0
file owned-by-sd5other: owner uid 986, group gid 0
chown to another user: ok
bind port 80: ok

--- PrivateUsers=yes
id: uid=0(root) gid=0(root) groups=0(root)
uid_map: 0 0 1
gid_map: 0 0 1
CapEff:	000001ffffffffff
CapBnd:	000001ffffffffff
file owned-by-root: owner uid 0, group gid 0
file owned-by-sd5demo: owner uid 65534, group gid 0
file owned-by-sd5other: owner uid 65534, group gid 0
chown to another user: failed: EINVAL (Invalid argument)
bind port 80: failed: EACCES (Permission denied)

In the second block, the map has one entry (0 0 1), so only root maps to itself, and the files of other users belong to 65534 (nobody). A chown to another user fails with EINVAL. The last line is the surprise: root cannot bind port 80, although CapEff still shows every capability, because those capabilities now apply only inside the new user namespace while the network namespace belongs to the host.

With a dedicated user, the map has two entries and the capabilities are empty.

sd -p User=sd5demo -p PrivateUsers=yes -- $PROBE users $(id -u sd5other)
id: uid=987(sd5demo) gid=987(sd5demo) groups=987(sd5demo)
uid_map: 0 0 1 | 987 987 1
[...]
CapEff:	0000000000000000
[...]

Programs that change user by themselves break. The next runs use runuser inside and outside the user namespace.

sd -p PrivateUsers=yes -- runuser -u sd5other -- id
sd -- runuser -u sd5other -- id
runuser: cannot set groups: Operation not permitted
uid=986(sd5other) gid=986(sd5other) groups=986(sd5other)

What it breaks. sudo, su, runuser and every daemon that starts as root and drops to a worker user. Ownership checks differ because other users become nobody, and low ports fail even for root.

Effect on my stack. I do not use it, and my hardening role already blocks unprivileged user namespaces on the host. I did not test how that setting interacts with PrivateUsers=. If you run a web server that starts as root and drops to a worker user, expect trouble.

PrivateIPC= and IPCNamespacePath=: separate shared memory

PrivateIPC=yes (since systemd 248) gives the service its own IPC namespace: System V shared memory, semaphores, message queues, and the POSIX message queue file system. The manual states two limits: it isolates neither AF_UNIX sockets nor POSIX shared memory. IPCNamespacePath= (since 248) joins an IPC namespace you built.

The lab creates a System V segment on the host with ipcmk, and a POSIX shared memory file in /dev/shm, then lists the segments from the probe.

ipcmk -M 4096
echo hello > /dev/shm/demo-hardening-sd5-posix
sd -- $PROBE ipc
sd -p PrivateIPC=yes -- $PROBE ipc
--- without PrivateIPC=
ipc namespace: ipc:[4026532205]
------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status      
0xd97a51ce 0          root       644        4096       0

--- PrivateIPC=yes
ipc namespace: ipc:[4026532291]
------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status

Without the directive, the host segment is visible. With it, the segment is gone, while the POSIX file in /dev/shm stays visible, as the manual warns.

sd -p PrivateIPC=yes -- /bin/bash -c 'ls /dev/shm; cat /dev/shm/demo-hardening-sd5-posix'
demo-hardening-sd5-posix
hello

For IPCNamespacePath=, create a named IPC namespace with unshare --ipc=FILE and point the directive at it. The path wins over PrivateIPC=yes.

touch /run/demo-hardening-sd5/ipcns
unshare --ipc=/run/demo-hardening-sd5/ipcns true
echo "namespace of the file: $(nsenter --ipc=/run/demo-hardening-sd5/ipcns readlink /proc/self/ns/ipc)"
sd -p IPCNamespacePath=/run/demo-hardening-sd5/ipcns -- $PROBE ipc
sd -p PrivateIPC=yes -p IPCNamespacePath=/run/demo-hardening-sd5/ipcns -- $PROBE ipc | sed -n 1p
namespace of the file: ipc:[4026532291]
ipc namespace: ipc:[4026532291]
------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status
ipc namespace: ipc:[4026532291]

All three inodes are identical. One remark: a sentence of the IPCNamespacePath= paragraph seems to say “network namespace” where it means IPC. The lab shows IPC behaviour, so I read it as a typo.

What it breaks. Two units that exchange data through System V shared memory or semaphores stop seeing each other. Old database software and some middleware work this way. POSIX shared memory and sockets keep working.

Effect on my stack. I found no unit in my notes that shares IPC objects with another one, so PrivateIPC=yes would cost nothing there, and it would also gain little.

RestrictNamespaces=: forbid creating or joining namespaces

RestrictNamespaces= (since systemd 233) limits which systemd namespaces the service may create with unshare() or clone(), or join with setns(). The value yes forbids all, and no is the default. Otherwise you list types: cgroup, ipc, net, mnt, pid, user, uts and time. A plain list is an allow-list, and a list that starts with ~ is a deny-list.

In a unit file, repeated plain lines add up, and a line with ~ removes from the result. The filter only works on x86, x86-64 and a few other architectures.

The probe tries each type with unshare, then joins the network namespace of PID 1 with nsenter. Save it as ns-inner.sh.

#!/bin/bash
# Try to create each namespace type, then to join the net namespace of PID 1.
last=""
for t in cgroup ipc net mount pid user uts time; do
  if out=$(unshare --$t true 2>&1); then echo "unshare --$t: allowed"; else echo "unshare --$t: blocked"; last="$out"; fi
done
if out=$(nsenter --target 1 --net true 2>&1); then echo "setns (join the net namespace of PID 1): allowed"; else echo "setns (join the net namespace of PID 1): blocked"; last="$out"; fi
if [ -n "$last" ]; then echo "message: $last"; fi
sd -p RestrictNamespaces=yes -- bash ns-inner.sh
unshare --cgroup: blocked
unshare --ipc: blocked
unshare --net: blocked
unshare --mount: blocked
unshare --pid: blocked
unshare --user: blocked
unshare --uts: blocked
unshare --time: blocked
setns (join the net namespace of PID 1): blocked
message: nsenter: reassociate to namespace 'ns/net' failed: Operation not permitted

Everything is blocked, with the classic Operation not permitted. The table sums up five settings, each from its own run.

RestrictNamespaces=cgroupipcnetmountpiduserutstimesetns
noneallowedallowedallowedallowedallowedallowedallowedallowedallowed
yesblockedblockedblockedblockedblockedblockedblockedblockedblocked
netblockedblockedallowedblockedblockedblockedblockedblockedallowed
~userallowedallowedallowedallowedallowedblockedallowedblockedallowed
~net ipcallowedblockedblockedallowedallowedallowedallowedblockedblocked

Four observations. A plain list such as net allows only that type, including the join of the network namespace of PID 1. A deny-list such as ~user allows the rest, except time: on systemd 257, every deny-list blocks the time namespace, and systemctl show confirms it by printing cgroup mnt pid user uts for ~net ipc. The token time itself is accepted in an allow-list. I found nothing about that deny-list case in the manual, so treat it as an observation of this version.

for v in '~net ipc' yes net; do
  systemd-run --quiet --collect -p "RestrictNamespaces=$v" --unit demo-hardening-sd5-show sleep 30
  systemctl show demo-hardening-sd5-show -p RestrictNamespaces
  systemctl stop demo-hardening-sd5-show
done
RestrictNamespaces=cgroup mnt pid user uts
RestrictNamespaces=yes
RestrictNamespaces=net

The manual’s example for repeated lines holds in a unit file: cgroup ipc then cgroup net allows three types, and cgroup ipc then ~cgroup net leaves only ipc.

# /etc/systemd/system/demo-hardening-sd5-ns.service
[Service]
Type=oneshot
StandardOutput=journal
RestrictNamespaces=cgroup ipc
RestrictNamespaces=cgroup net
ExecStart=/bin/bash /root/ns-inner.sh

systemctl daemon-reload
systemctl show demo-hardening-sd5-ns.service -p RestrictNamespaces

# now change the second line to: RestrictNamespaces=~cgroup net
systemctl daemon-reload
systemctl show demo-hardening-sd5-ns.service -p RestrictNamespaces
RestrictNamespaces=cgroup ipc net
RestrictNamespaces=ipc

A trap: systemd-run -p with the same property twice does not add up, since the last assignment wins. Test repeated lines in a real unit file.

The restriction does not block the namespaces that systemd creates for you. A unit with PrivateTmp=yes, PrivateNetwork=yes, PrivateIPC=yes and RestrictNamespaces=yes started fine, with its own network, IPC and mount namespaces, and only its own attempt to create one failed.

sd -p PrivateTmp=yes -p PrivateNetwork=yes -p PrivateIPC=yes -p RestrictNamespaces=yes -- bash -c 'echo net namespace: $(readlink /proc/self/ns/net); echo ipc namespace: $(readlink /proc/self/ns/ipc); echo mount namespace: $(readlink /proc/self/ns/mnt); bash ns-inner.sh | sed -n 3p'
echo "host namespaces: net $(readlink /proc/self/ns/net), ipc $(readlink /proc/self/ns/ipc), mnt $(readlink /proc/self/ns/mnt)"
net namespace: net:[4026532291]
ipc namespace: ipc:[4026532472]
mount namespace: mnt:[4026532473]
unshare --net: blocked
host namespaces: net net:[4026531833], ipc ipc:[4026532205], mnt mnt:[4026532217]

What it breaks. Container engines, browser engines with their own sandbox, and tools such as bubblewrap. They all call unshare() or clone() with namespace flags, and fail with Operation not permitted.

Effect on my stack. In the notes I checked, no unit starts containers or a browser engine, so this directive should cost nothing there, but I have not applied it. If you run a service that builds containers or starts a headless browser, expect it to fail.

RestrictAddressFamilies= and systemd namespaces of sockets

RestrictAddressFamilies= (since systemd 211) creates no namespace, yet it belongs here: one line removes whole classes of network access by filtering the socket() call. A plain list is an allow-list, a list that starts with ~ is a deny-list, and none denies everything. The manual advises keeping AF_UNIX, and it lists limits: socketpair(), sockets from socket activation and io_uring are not filtered, and only x86-64 and a few architectures are covered.

Systemd namespaces and sockets: RestrictAddressFamilies= allows AF_UNIX, AF_INET and AF_INET6 and blocks the rest
RestrictAddressFamilies= filters socket() by address family.

The probe creates one socket per family.

sd -p RestrictAddressFamilies=AF_UNIX -- $PROBE families
sd -p 'RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6' -- $PROBE families
sd -p 'RestrictAddressFamilies=~AF_PACKET AF_NETLINK' -- $PROBE families
--- RestrictAddressFamilies=AF_UNIX
AF_UNIX     socket(): ok
AF_INET     socket(): failed: EAFNOSUPPORT (Address family not supported by protocol)
AF_INET6    socket(): failed: EAFNOSUPPORT (Address family not supported by protocol)
AF_NETLINK  socket(): failed: EAFNOSUPPORT (Address family not supported by protocol)
AF_PACKET   socket(): failed: EAFNOSUPPORT (Address family not supported by protocol)
socketpair() AF_UNIX: ok

--- RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
AF_UNIX     socket(): ok
AF_INET     socket(): ok
AF_INET6    socket(): ok
AF_NETLINK  socket(): failed: EAFNOSUPPORT (Address family not supported by protocol)
AF_PACKET   socket(): failed: EAFNOSUPPORT (Address family not supported by protocol)
socketpair() AF_UNIX: ok

Blocked families answer EAFNOSUPPORT, “address family not supported by protocol”, and socketpair() keeps working, as the manual says. The third command, a deny-list ~AF_PACKET AF_NETLINK, denied exactly those two.

AF_UNIX     socket(): ok
AF_INET     socket(): ok
AF_INET6    socket(): ok
AF_NETLINK  socket(): failed: EAFNOSUPPORT (Address family not supported by protocol)
AF_PACKET   socket(): failed: EAFNOSUPPORT (Address family not supported by protocol)
socketpair() AF_UNIX: ok

The value none, and how it displays

none works in a unit file, but systemd-run -p RestrictAddressFamilies=none fails with “Invalid argument” on systemd 257. The unit-file form has the expected effect, yet systemctl show prints an empty value.

# /etc/systemd/system/demo-hardening-sd5-af.service
[Service]
Type=oneshot
StandardOutput=journal
RestrictAddressFamilies=none
ExecStart=/usr/local/bin/demo-hardening-sd5-probe.py families

systemctl daemon-reload
systemctl start demo-hardening-sd5-af.service
journalctl -u demo-hardening-sd5-af.service -o cat --no-pager --since -10s | grep -vE '^(Starting |Finished |Started |.*: Deactivated successfully)'
systemctl show demo-hardening-sd5-af.service -p RestrictAddressFamilies
AF_UNIX     socket(): failed: EAFNOSUPPORT (Address family not supported by protocol)
AF_INET     socket(): failed: EAFNOSUPPORT (Address family not supported by protocol)
AF_INET6    socket(): failed: EAFNOSUPPORT (Address family not supported by protocol)
AF_NETLINK  socket(): failed: EAFNOSUPPORT (Address family not supported by protocol)
AF_PACKET   socket(): failed: EAFNOSUPPORT (Address family not supported by protocol)
socketpair() AF_UNIX: ok
RestrictAddressFamilies=

An empty property looks like “no restriction” but means the opposite here, so run the probe instead of trusting the property.

Typos in the family list

A typo is only a warning at load time. If other names remain, systemd drops the misspelled one.

# change the line of the unit above to: RestrictAddressFamilies=AF_UNIX AF_TYPO
systemctl daemon-reload
systemctl show demo-hardening-sd5-af.service -p RestrictAddressFamilies
systemd-analyze verify /etc/systemd/system/demo-hardening-sd5-af.service
RestrictAddressFamilies=AF_UNIX
/etc/systemd/system/demo-hardening-sd5-af.service:4: Failed to parse address family, ignoring: AF_TYPO

The service keeps AF_UNIX only. When the only name is misspelled, the list ends up empty, and the service gets no family at all.

# change the line to: RestrictAddressFamilies=AF_INETT
systemctl daemon-reload
systemctl show demo-hardening-sd5-af.service -p RestrictAddressFamilies
systemd-analyze verify /etc/systemd/system/demo-hardening-sd5-af.service
systemctl start demo-hardening-sd5-af.service
journalctl -u demo-hardening-sd5-af.service -o cat --no-pager --since -10s | grep 'socket()'
RestrictAddressFamilies=
demo-hardening-sd5-af.service:4: Failed to parse address family, ignoring: AF_INETT
AF_UNIX     socket(): failed: EAFNOSUPPORT (Address family not supported by protocol)
AF_INET     socket(): failed: EAFNOSUPPORT (Address family not supported by protocol)
AF_INET6    socket(): failed: EAFNOSUPPORT (Address family not supported by protocol)
AF_NETLINK  socket(): failed: EAFNOSUPPORT (Address family not supported by protocol)
AF_PACKET   socket(): failed: EAFNOSUPPORT (Address family not supported by protocol)

So a typo fails closed when it is alone, and in a confusing way when it is not. Run systemd-analyze verify on every edited unit. Lowercase names are accepted: af_unix af_inet loaded as AF_INET AF_UNIX.

What breaks without AF_NETLINK and without AF_UNIX

Common tools use more families than you think. ip speaks netlink, and logger writes to a local socket.

V='RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6'
sd -p "$V" -- ip -o link show lo
sd -p "$V" -- $PROBE resolve
sd -p "$V" -- getent ahosts localhost
sd -p "$V AF_NETLINK" -- ip -o link show lo
sd -p 'RestrictAddressFamilies=AF_INET AF_INET6' -- logger -t demo-hardening-sd5 'test message'
[...]
Cannot open netlink socket: Address family not supported by protocol
[...]
logger: socket /dev/log: Address family not supported by protocol
[...]

Name resolution survived without netlink on the bench: getaddrinfo with and without AI_ADDRCONFIG, and getent ahosts, answered normally. Do not assume the same for other resolvers.

What it breaks. A missing AF_UNIX breaks logging and every local socket, such as the socket between a web server and PHP-FPM. A missing AF_NETLINK breaks tools that read or change the network configuration. A missing AF_PACKET breaks packet capture.

Effect on my stack. The IDS mode of my Suricata role captures with af-packet, so a hardened unit must keep AF_PACKET. If you run an IPS on NFQUEUE, expect it to need AF_NETLINK too. For a mail server, a reverse proxy or a database, expect AF_UNIX AF_INET AF_INET6 to be enough, which makes that line my default starting point.

IP address filters and bind filters

This group filters traffic itself. The service keeps the host network, and a BPF program attached to its control group inspects each packet or bind() call.

IPAddressAllow= and IPAddressDeny=: packet filters per unit

IPAddressDeny= and IPAddressAllow= (since systemd 235) filter the IPv4 and IPv6 packets a service sends or receives. They take addresses, ranges such as 192.0.2.0/24, or the names any, localhost, link-local and multicast. A match in the allow list lets the packet through; otherwise a match in the deny list blocks it; otherwise it passes. The filter needs eBPF and works per control group.

Systemd namespaces and IP filters: the order in which IPAddressAllow= and IPAddressDeny= decide
Allow first, then deny, then pass by default.

So IPAddressDeny=any alone blocks everything, and the allow list adds exceptions. The probe connects to the host loopback and to the LAN address in three configurations. The output shows only the two lines that concern the filter.

sd -p IPAddressDeny=any -- $PROBE net "$HOSTNS"
sd -p IPAddressDeny=any -p IPAddressAllow=localhost -- $PROBE net "$HOSTNS"
sd -p IPAddressDeny=localhost -- $PROBE net "$HOSTNS"
--- IPAddressDeny=any
host loopback port 18080: failed: TimeoutError
host LAN address port 18081: failed: TimeoutError

--- IPAddressDeny=any + IPAddressAllow=localhost
host loopback port 18080: connected, reply: hello-from-host-loopback
host LAN address port 18081: failed: TimeoutError

--- IPAddressDeny=localhost
host loopback port 18080: failed: TimeoutError
host LAN address port 18081: connected, reply: hello-from-host-lan

Two things stand out. A blocked connection does not fail at once: it times out, because the filter drops packets silently. And localhost covers 127.0.0.0/8 and ::1, as the property shows.

systemd-run --quiet --collect -p IPAddressDeny=any -p IPAddressAllow=localhost -p IPAccounting=yes --unit demo-hardening-sd5-show sleep 30
systemctl show demo-hardening-sd5-show -p IPIngressBytes -p IPEgressBytes -p IPAccounting -p IPAddressAllow -p IPAddressDeny
systemctl stop demo-hardening-sd5-show
IPIngressBytes=0
IPEgressBytes=0
IPAccounting=yes
IPAddressAllow=127.0.0.0/8 ::1/128
IPAddressDeny=0.0.0.0/0 ::/0

The filter also works for incoming traffic. A web server listens on all addresses with both settings, and a client on the host calls it through the loopback and through the LAN address.

c() { printf '%-34s' "$1"; curl -sS -o /dev/null -w 'HTTP %{http_code}\n' --max-time 3 "http://$2:18082/owned-by-root" 2>&1; }
systemd-run --quiet --collect --unit demo-hardening-sd5-ipsrv -p IPAccounting=yes -p IPAddressDeny=any -p IPAddressAllow=localhost -p WorkingDirectory=/run/demo-hardening-sd5 python3 -m http.server 18082 --bind 0.0.0.0
c 'client via 127.0.0.1' 127.0.0.1
c 'client via the LAN address' "$HOSTIP"
systemctl show demo-hardening-sd5-ipsrv -p IPIngressBytes -p IPEgressBytes
systemctl stop demo-hardening-sd5-ipsrv
client via 127.0.0.1              HTTP 200
client via the LAN address        curl: (28) Connection timed out after 3002 milliseconds
HTTP 000
IPIngressBytes=360
IPEgressBytes=468

The loopback call returns the page. The LAN call times out.

IPAccounting=: count the traffic of a unit

IPAccounting=yes (since systemd 235) counts the IP bytes and packets of the unit in IPIngressBytes and IPEgressBytes, and systemd-run prints the total when a transient unit ends.

systemd-run --collect --wait --pipe -E HOSTIP="$HOSTIP" -p IPAccounting=yes -- $PROBE net "$HOSTNS"
[...]
IP traffic received: 741B sent: 770B

A server with both a filter and accounting counted 360 bytes in and 468 bytes out for one loopback request.

systemd-run --quiet --collect --unit demo-hardening-sd5-ipsrv -p IPAccounting=yes -p IPAddressDeny=any -p IPAddressAllow=localhost -p WorkingDirectory=/run/demo-hardening-sd5 python3 -m http.server 18082 --bind 0.0.0.0
curl -sS -o /dev/null -w 'client via 127.0.0.1: HTTP %{http_code}\n' --max-time 3 http://127.0.0.1:18082/owned-by-root
systemctl show demo-hardening-sd5-ipsrv -p IPIngressBytes -p IPEgressBytes
systemctl stop demo-hardening-sd5-ipsrv
client via 127.0.0.1: HTTP 200
IPIngressBytes=360
IPEgressBytes=468

One oddity: with a filter that dropped a connection, the counters varied from run to run (360 and 468 bytes, 504 and 468, zero, or no data). I could not explain it, so I do not trust them for dropped traffic.

What it breaks. A deny list without the right allow entries cuts the service from the database, the DNS server or the time source. Dropped packets look like timeouts, so the symptom is slowness, not an error. Keep the loopback, the DNS server and the next hop in the allow list.

Effect on my stack. My mail server must reach the whole internet on port 25, so an allow list does not fit it. An internal service such as a metrics exporter, which only answers a monitoring host, is a better candidate. The counters would be cheap and useful on the reverse proxy.

SocketBindAllow= and SocketBindDeny=: which ports a service may open

SocketBindDeny= and SocketBindAllow= (since systemd 249) restrict the bind() call. A rule can name the family (ipv4 or ipv6), the transport (tcp or udp), and a port or a range. The word any matches everything. The order is the same as for the IP filters: allow, then deny, then default allow. The manual accepts up to 128 rules per directive.

The probe tries five binds: TCP 18090, TCP 18091, UDP 18090, TCP over IPv6 on 18090, and TCP 18095.

sd -p SocketBindDeny=any -p SocketBindAllow=tcp:18090 -- $PROBE bind
sd -p SocketBindDeny=any -p SocketBindAllow=18090-18095 -- $PROBE bind
sd -p SocketBindDeny=ipv6 -- $PROBE bind
sd -p SocketBindDeny=ipv4:tcp:18090 -- $PROBE bind
--- SocketBindDeny=any + SocketBindAllow=tcp:18090
bind tcp  port 18090: ok
bind tcp  port 18091: failed: EPERM (Operation not permitted)
bind udp  port 18090: failed: EPERM (Operation not permitted)
bind tcp6 port 18090: ok
bind tcp  port 18095: failed: EPERM (Operation not permitted)

--- SocketBindDeny=any + SocketBindAllow=18090-18095
bind tcp  port 18090: ok
bind tcp  port 18091: ok
bind udp  port 18090: ok
bind tcp6 port 18090: ok
bind tcp  port 18095: ok

--- SocketBindDeny=ipv6
bind tcp  port 18090: ok
bind tcp  port 18091: ok
bind udp  port 18090: ok
bind tcp6 port 18090: failed: EPERM (Operation not permitted)
bind tcp  port 18095: ok

--- SocketBindDeny=ipv4:tcp:18090
bind tcp  port 18090: failed: EPERM (Operation not permitted)
bind tcp  port 18091: ok
bind udp  port 18090: ok
bind tcp6 port 18090: ok
bind tcp  port 18095: ok

A rule without a family covers IPv4 and IPv6: tcp:18090 also allowed the IPv6 bind. A rule without a transport covers TCP and UDP, so the range 18090-18095 opened all five binds. A denied bind fails at once with EPERM, unlike the silent drop of the IP filter.

systemd-run --collect --wait -p SocketBindAllow=tpc:18090 /bin/true
Failed to parse SocketBindAllow

A mistake in a rule is not silent here: SocketBindAllow=tpc:18090 failed with “Failed to parse SocketBindAllow”. Also, SocketBindDeny=any only filters bind(), so a client can still connect out, but a service cannot open its own listener, as the next run shows.

sd -p SocketBindDeny=any -p IPAddressDeny=any -p IPAddressAllow=localhost -- $PROBE net "$HOSTNS"
own loopback: failed to listen: EPERM (Operation not permitted)
host loopback port 18080: connected, reply: hello-from-host-loopback

What it breaks. A service that opens a port you forgot, such as a second metrics port or a UDP socket, stops with EPERM at bind(), usually at startup.

Effect on my stack. My mail server opens seven fixed TCP ports: 25, 465, 587, 143, 993, 80 and 443. That list is a ready-made SocketBindAllow= set behind SocketBindDeny=any, and a useful second layer next to CAP_NET_BIND_SERVICE, which allows low ports without naming them. I did not test it on the mail server itself.

Put the systemd namespaces and filters together

Systemd namespaces and filters add up, so the lab ends with a tiny HTTP application on 127.0.0.1:18085, run as sd5demo. First measure its exposure, then add one drop-in with the directives of this article, and measure again.

systemd-analyze security --no-pager demo-hardening-sd5-app.service | grep -E 'Overall'
→ Overall exposure level for demo-hardening-sd5-app.service: 9.2 UNSAFE 😨

The drop-in has a comment on every line. It does not use PrivateNetwork=, because the reverse proxy must reach the application.

mkdir -p /etc/systemd/system/demo-hardening-sd5-app.service.d
cat > /etc/systemd/system/demo-hardening-sd5-app.service.d/10-network.conf <<'EOF'
[Service]
# Own IPC namespace: no access to the host's System V shared memory and message queues.
PrivateIPC=yes
# Own user namespace: every other user shows up as nobody; no host capabilities.
PrivateUsers=yes
# The service may not create or enter any namespace.
RestrictNamespaces=yes
# Only the socket families an HTTP server needs.
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
# Network filter: loopback only, nothing else, in both directions.
IPAddressDeny=any
IPAddressAllow=localhost
# Bind filter: this one TCP port and nothing else.
SocketBindDeny=any
SocketBindAllow=tcp:18085
EOF
systemctl daemon-reload
systemd-analyze security --no-pager demo-hardening-sd5-app.service | grep -E 'Overall'
systemctl start demo-hardening-sd5-app.service; sleep 1
systemctl is-active demo-hardening-sd5-app.service
curl -sS --max-time 3 http://127.0.0.1:18085/
pid=$(systemctl show -p MainPID --value demo-hardening-sd5-app.service)
echo "uid_map of the service: $(tr -s ' ' < /proc/$pid/uid_map | tr '\n' '|')"
echo "ipc namespace differs from the host: $([ "$(readlink /proc/$pid/ns/ipc)" != "$(readlink /proc/1/ns/ipc)" ] && echo yes || echo no)"
systemctl stop demo-hardening-sd5-app.service
→ Overall exposure level for demo-hardening-sd5-app.service: 7.7 EXPOSED 🙁
active
hello from the demo app
uid_map of the service:  0 0 1| 987 987 1|
ipc namespace differs from the host: yes

The application still answers, and the exposure level went from 9.2 to 7.7. The service now has a two-entry user map, its own IPC namespace, and no right to create namespaces. The network penalties remain, because the application needs a network, and the filter line still costs 0.1: the report says “allow list with only localhost entries”.

To see the cost of PrivateNetwork=yes, add it in a second drop-in. The service starts and stays active, yet the call from the host fails, and the score drops to 7.3.

printf '[Service]\nPrivateNetwork=yes\n' > /etc/systemd/system/demo-hardening-sd5-app.service.d/20-private-network.conf
systemctl daemon-reload
systemctl start demo-hardening-sd5-app.service; sleep 1
systemctl is-active demo-hardening-sd5-app.service
curl -sS --max-time 3 http://127.0.0.1:18085/
systemd-analyze security --no-pager demo-hardening-sd5-app.service | grep -E 'Overall'
systemctl stop demo-hardening-sd5-app.service
active
curl: (7) Failed to connect to 127.0.0.1 port 18085 after 1 ms: Could not connect to server
→ Overall exposure level for demo-hardening-sd5-app.service: 7.3 MEDIUM 😐

Two ways to be too strict: a wrong port in SocketBindAllow= kills the service at startup, and a missing IPAddressAllow=localhost keeps it running but unreachable.

rm /etc/systemd/system/demo-hardening-sd5-app.service.d/20-private-network.conf
sed -i 's/SocketBindAllow=tcp:18085/SocketBindAllow=tcp:18086/' /etc/systemd/system/demo-hardening-sd5-app.service.d/10-network.conf
systemctl daemon-reload
systemctl start demo-hardening-sd5-app.service; sleep 1
systemctl is-active demo-hardening-sd5-app.service
journalctl -u demo-hardening-sd5-app.service -o cat --no-pager -n 4 | grep -vE '^(Started|Starting)'
systemctl stop demo-hardening-sd5-app.service
failed
    self.socket.bind(self.server_address)
PermissionError: [Errno 1] Operation not permitted
demo-hardening-sd5-app.service: Main process exited, code=exited, status=1/FAILURE
demo-hardening-sd5-app.service: Failed with result 'exit-code'.

For the second case, restore the port, comment out IPAddressAllow=localhost, reload, start the unit, and call it.

curl -sS --max-time 3 http://127.0.0.1:18085/
curl: (28) Connection timed out after 3002 milliseconds

Complete drop-ins to copy

These drop-ins combine the systemd namespaces and filters of this article. Replace app01, appuser and the port with your own values, and keep the comments.

Drop-in 1: an HTTP service behind a reverse proxy

This is the drop-in measured above, with a user line. The lab ran it in full.

# /etc/systemd/system/app01.service.d/10-network.conf
[Service]
# Never root.
User=appuser
# Own IPC namespace.
PrivateIPC=yes
# Own user namespace (only valid values on systemd 257: yes or no).
PrivateUsers=yes
# No namespace creation, no setns().
RestrictNamespaces=yes
# Local sockets, IPv4 and IPv6 only.
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
# Only the loopback may talk to this service.
IPAddressDeny=any
IPAddressAllow=localhost
# One port, TCP.
SocketBindDeny=any
SocketBindAllow=tcp:8080

Drop-in 2: an internal service that calls a few known hosts

This is the pattern for an exporter or an agent. The ranges are documentation ranges, so replace them. The logic was tested with localhost and ranges, not with a real monitoring server.

# /etc/systemd/system/exporter01.service.d/10-network.conf
[Service]
# IPv4 and IPv6 plus local sockets.
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
# Deny everything by default...
IPAddressDeny=any
# ...then allow the loopback and the one network that needs the service.
IPAddressAllow=localhost
IPAddressAllow=192.0.2.0/24
# No namespace creation.
RestrictNamespaces=yes

Common mistakes with systemd namespaces

  • Trusting a green start. A service with PrivateNetwork=yes starts and stays active, but nobody can reach it.
  • Forgetting the loopback in the allow list. With IPAddressDeny=any and no IPAddressAllow=localhost, even the local reverse proxy times out.
  • Forgetting AF_UNIX. logger and every local socket fail with EAFNOSUPPORT.
  • Judging RestrictAddressFamilies=none by systemctl show. The property is empty, and the restriction is total.
  • Copying a value from a newer manual. PrivateUsers=self and its siblings fail on systemd 257.
  • Joining a namespace you built without bringing up its loopback. The service cannot even talk to itself.
  • Testing a repeated directive with systemd-run -p. The last assignment replaces the others. Use a unit file.

Final checklist for systemd namespaces

Go through this list for every service you protect with systemd namespaces and filters.

  1. Does the service need the network at all? If not, set PrivateNetwork=yes.
  2. Which socket families does it use? Write exactly that list in RestrictAddressFamilies=, and keep AF_UNIX.
  3. Does it start containers or a browser engine? If not, set RestrictNamespaces=yes.
  4. Does it share System V shared memory with another unit? If not, set PrivateIPC=yes.
  5. Which addresses must it reach? Write them in IPAddressAllow= after IPAddressDeny=any, and include the loopback and the DNS server.
  6. Which ports must it open? Write them in SocketBindAllow= after SocketBindDeny=any.
  7. After every edit, run systemctl daemon-reload and systemd-analyze verify.
  8. Read the result with systemctl show, then run the real client against the service.

What this lab did not test

  • IPIngressFilterPath= and IPEgressFilterPath= were not tested.
  • PrivateUsers= with the values self, identity, full and managed was not possible: systemd 257 rejects them.
  • Socket activation with PrivateNetwork= or NetworkNamespacePath= was not tested, and neither was JoinsNamespaceOf= with sockets.
  • No real application was hardened, only the demo service. The effect on my own stack therefore comes from my notes and not from tests.
  • The results come from a WSL2 kernel, so a native kernel can differ.

Clean up the lab

Run the script below as root. It removes only the units, files and accounts that the lab created.

for u in listener app show a b c d ns af ipsrv badns badns2 badaf badbind; do
  systemctl stop "demo-hardening-sd5-$u.service" 2>/dev/null
  systemctl reset-failed "demo-hardening-sd5-$u.service" 2>/dev/null
  rm -rf "/etc/systemd/system/demo-hardening-sd5-$u.service" "/etc/systemd/system/demo-hardening-sd5-$u.service.d"
done
rm -f /usr/local/bin/demo-hardening-sd5-probe.py /usr/local/bin/demo-hardening-sd5-listener.py /usr/local/bin/demo-hardening-sd5-app.py
mountpoint -q /run/demo-hardening-sd5/ipcns && umount /run/demo-hardening-sd5/ipcns
rm -rf /run/demo-hardening-sd5
ip netns del demo-hardening-sd5-ns 2>/dev/null
rm -f /dev/shm/demo-hardening-sd5-posix
id sd5demo >/dev/null 2>&1 && userdel sd5demo
id sd5other >/dev/null 2>&1 && userdel sd5other
systemctl daemon-reload
ls -d /etc/systemd/system/*sd5* /usr/local/bin/*sd5* /run/*sd5* /dev/shm/*sd5* 2>/dev/null; getent passwd sd5demo sd5other

What I take away

  • Systemd namespaces change the view of one resource and leave the others alone. A socket file is still reachable from a private network.
  • Start with RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 and RestrictNamespaces=yes. They break the least and remove a lot of attack surface.
  • Keep PrivateNetwork=yes for jobs that really need no network, and use the IP and bind filters for the others.

Sources

Earlier in this series

Related articles

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *