Testing Unix socket access on a dedicated server

Testing Unix socket access on a dedicated server

Testing Unix socket access on a dedicated server

When backend APIs and batch services share a physical server, switching their internal communication from TCP to Unix sockets does not automatically isolate their accounts. A socket file that exists, a process that is running, and a successful connection from an administrator account only show that the communication path works. They do not prove that other application accounts are blocked. This walkthrough sets up a test on Debian 12 without listening on a network port, then checks path permissions, connecting process identities, and behavior after the socket is recreated.

1. Define the access boundary first

This test uses a Linux pathname Unix socket, not the abstract namespace. The goal is to allow connections from a designated group while denying unrelated accounts. It is not intended to isolate programs running under the same account or to defend against processes with administrative privileges.

When a process connects to a pathname stream socket, Linux checks write permission on the socket as well as search permission on its parent directories. Being able to list a directory does not mean a connection is allowed, and a writable socket does not guarantee that its path is accessible. After accepting a connection, the application can also use SO_PEERCRED to obtain the PID, UID, and GID supplied by the kernel rather than trusting a username claimed in the request.

A Unix socket is an entry point for local communication, not a complete authorization system. If different applications share the same system account, socket permissions cannot distinguish between them.

This example handles only a fixed probe message, not application data. Run the administrative commands below from an account with the necessary privileges. First confirm that the test accounts, file paths, and unit names are not already in use by existing workloads.

2. Create separate accounts and the socket entry point

Create the service account, the account allowed to connect, and an account for the negative test. Do not add the last account to the authorized group, and do not substitute an administrator account for the denial test.

groupadd --system sockreaders
useradd --system --user-group --no-create-home socksvc
useradd --system --user-group --no-create-home sockclient
useradd --system --user-group --no-create-home sockoutsider
usermod -aG sockreaders sockclient
install -d -o root -g root -m 0755 /opt/socket-check
id sockclient
id sockoutsider

Save the following as /etc/systemd/system/socket-check.socket:

[Unit]
Description=Local socket access test

[Socket]
ListenStream=/run/socket-check/api.sock
SocketUser=socksvc
SocketGroup=sockreaders
SocketMode=0660
DirectoryMode=0755
Accept=no
RemoveOnStop=yes

[Install]
WantedBy=sockets.target

The socket unit creates the parent directory as needed. Its 0755 mode lets other accounts traverse the path but does not let unprivileged accounts replace the entry point. The socket's 0660 permissions and group ownership control who can connect. This setup does not use a shared directory writable by ordinary users, nor does it change the entry point to 0777 just to make errors disappear.

Changes to group membership do not update processes that are already running. Use runuser to start fresh processes for these tests. For production clients, verify the configuration, restart the clients, and check their actual supplementary groups.

3. Accept connections and log kernel-provided identities

Save the following as /opt/socket-check/server.py. The service receives an already-listening file descriptor from systemd instead of binding the path itself, so it does not need to delete an old file at application startup.

import os
import socket
import struct

if (
    int(os.environ.get("LISTEN_PID", "0")) != os.getpid()
    or os.environ.get("LISTEN_FDS") != "1"
):
    raise RuntimeError("Expected one activation socket")

listener = socket.socket(fileno=3)
listener.setblocking(True)

while True:
    conn, _ = listener.accept()
    with conn:
        conn.settimeout(2)
        raw = conn.getsockopt(
            socket.SOL_SOCKET,
            socket.SO_PEERCRED,
            struct.calcsize("3i"),
        )
        pid, uid, gid = struct.unpack("3i", raw)
        print(f"peer_pid={pid} peer_uid={uid} peer_gid={gid}", flush=True)
        try:
            request = b""
            while len(request) < 5 and not request.endswith(b"\n"):
                part = conn.recv(5 - len(request))
                if not part:
                    break
                request += part
            conn.sendall(b"pong\n" if request == b"ping\n" else b"reject\n")
        except (TimeoutError, ConnectionError):
            pass

Stream sockets have no message boundaries, so a single recv call is not guaranteed to receive the entire request. The code therefore reads until a newline or the length limit. The timeout prevents a connection that sends no data from blocking the test service indefinitely. This single-threaded implementation is suitable only for controlled validation, not as a template for a concurrent production service.

Save the following as /etc/systemd/system/socket-check.service:

[Unit]
Description=Local socket peer test
Requires=socket-check.socket
After=socket-check.socket

[Service]
Type=simple
User=socksvc
Group=socksvc
ExecStart=/usr/bin/python3 -u /opt/socket-check/server.py
NoNewPrivileges=yes

Confirm that the Python interpreter exists, and keep the script owned by an administrator account and non-writable by unprivileged accounts. The service and socket units share the same base name; the first connection triggers the service to start. This example only logs the peer's identity. A real API still needs to authorize requests based on the operation and the application resources involved.

4. Verify allowed and denied connections separately

Save the following as /opt/socket-check/client.py:

import socket

with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as conn:
    conn.settimeout(3)
    conn.connect("/run/socket-check/api.sock")
    conn.sendall(b"ping\n")
    response = b""
    while not response.endswith(b"\n"):
        part = conn.recv(32)
        if not part:
            break
        response += part
    if response != b"pong\n":
        raise RuntimeError("Unexpected response")
    print("accepted")

Check the unit syntax, start the entry point, and then run the tests under both accounts:

systemd-analyze verify /etc/systemd/system/socket-check.socket \
  /etc/systemd/system/socket-check.service
systemctl daemon-reload
systemctl start socket-check.socket
namei -l /run/socket-check/api.sock
stat -c '%a %U %G' /run/socket-check/api.sock
runuser -u sockclient -- /usr/bin/python3 /opt/socket-check/client.py
runuser -u sockoutsider -- /usr/bin/python3 /opt/socket-check/client.py
journalctl -u socket-check.service -n 20 --no-pager

The authorized account should print accepted. The unrelated account should receive a permission error at the connect stage and exit with a nonzero status. The UID in the log should match id -u sockclient. The GID returned by SO_PEERCRED is not a list of supplementary groups; the absence of sockreaders there does not mean group-based access control has failed.

If the unrelated account connects successfully, first check the process identity, supplementary groups, and whether file ACLs or permissions have changed. If the authorized account fails, check the path and group membership before loosening permissions. When the kernel denies a connection during connection establishment, the application never receives it and therefore produces no corresponding identity log.

5. Recreate the entry point and repeat validation

Restarting only the application does not prove that permissions will be restored after the entry point is recreated: the socket unit may keep the listening file descriptor open throughout the application restart. In a test environment with no production clients, stop both units and then recreate the entry point.

systemctl stop socket-check.service socket-check.socket
test ! -S /run/socket-check/api.sock
systemctl start socket-check.socket
stat -c '%a %U %G' /run/socket-check/api.sock
runuser -u sockclient -- /usr/bin/python3 /opt/socket-check/client.py
runuser -u sockoutsider -- /usr/bin/python3 /opt/socket-check/client.py

The recreated file should still show 660 socksvc sockreaders, and the allowed and denied connection results should match the previous test. If the socket path remains, first check the unit states and the processes holding file descriptors. Do not blindly delete an unfamiliar entry point, as doing so could remove the path of a socket that is still in use.

Finally, record the unit contents, file permissions, exit statuses of both tests, and the UID of the successful connection. When adapting this setup to a real service, retain the same positive and negative tests, then add authorization for application operations and concurrent request handling. Once validation is complete, stop both test units and confirm that no processes are running under the relevant accounts. Then remove the test files and accounts according to the asset inventory. Evidence of access isolation should come from reproducible denials, not a single successful administrator connection.

Frequently asked questions

Does socket mode 0660 isolate every process on the server?

No. Linux pathname sockets also depend on directory search permissions and process supplementary groups. Processes sharing an authorized account share its access, while privileged processes have broader capabilities. Use separate service accounts for different trust levels and retain application authorization.

Must chmod be repeated after restarting the service?

Not in this example. The systemd socket unit creates the file using SocketMode, SocketUser and SocketGroup. Stop both units, start the socket, then repeat the allowed and denied access tests.

AMD EPYC 7543P Dedicated Server

From $468/month. Total due = monthly total × number of months.

Configure the number of IP addresses for your needs

Each server includes 1 dedicated IPv4 address, with up to 255 additional addresses available. Total due = monthly total × number of months.