basforge

Search titles, text and the “If it doesn’t work” cases.

    RU
    ManualLinuxsystemd

    systemd sandbox: CrowdSec bouncer with nftables access only

    The CrowdSec bouncer runs as root and can do anything root can. A drop-in file next to its unit leaves it with one capability out of 41 — modifying nftables — and one address, LAPI, while making the rest of the filesystem read-only. The systemd-analyze security score drops from 9.6 to 1.7.

    Without a sandbox, a bug in the bouncer is a bug in a full-privilege root process. In /proc, its CapBnd is 000001ffffffffff — all 41 root capabilities — touch /etc/… succeeds from its mount namespace, and /home exposes every user directory. The bouncer itself does three things: pulls decisions from LAPI, applies bans in nftables, and notifies systemd when it is ready. Keep those rights and strip the rest.

    What the bouncer needs and what to strip

    What the bouncer does How What to keep
    fetches decisions from LAPI HTTP to 127.0.0.1:8080 AF_INET, AF_INET6 sockets and only localhost
    applies bans in nftables netlink socket, CAP_NET_ADMIN AF_NETLINK and 1 capability out of 41
    notifies systemd on startup (Type=notify) UNIX socket /run/systemd/notify AF_UNIX
    writes logs file in /var/log nothing — route logs to the journal

    Take away everything else: filesystem writes, home directories, kernel modules and tunables, the other root capabilities, and privileged syscalls. Apply this via a drop-in file in crowdsec-firewall-bouncer.service.d/ instead of editing the unit directly: the unit is a package conffile (dpkg-query -W -f='${Conffiles}' crowdsec-firewall-bouncer-nftables lists it), so upgrades would prompt over conflicts. A file in .service.d/ does not belong to the package, and reinstalling the package leaves it untouched.

    Setup

    This assumes the bouncer is already installed and banning, as in CrowdSec against SSH brute force and Protection.

    1. Score before

      systemd-analyze security crowdsec-firewall-bouncer --no-pager | tail -1
      # → Overall exposure level for crowdsec-firewall-bouncer.service: 9.6 UNSAFE :-{

      systemd scores a unit’s configuration rather than its runtime behavior: every ✗ line is an unused protection, with its weight on the right. The scale runs from 0 to 10; the lower the score, the less the service can do. 9.6 means “almost everything”. See systemd-analyze security for what the score misses.

    2. Move logs to the journal

      sudo sed -i 's/^log_mode: file/log_mode: stdout/' /etc/crowdsec/bouncers/crowdsec-firewall-bouncer.yaml
      sudo systemctl restart crowdsec-firewall-bouncer
      sudo journalctl -u crowdsec-firewall-bouncer -n 3 -o cat
      # time="…" level=info msg="Processing new and deleted decisions . . ."

      With log_mode: file, the bouncer writes to /var/log/crowdsec-firewall-bouncer.log, and the sandbox makes /var/log read-only. Adding ReadWritePaths=/var/log would open the entire directory — including auth.log, which CrowdSec reads to detect brute-force attempts. In the journal, bouncer logs sit next to systemd’s own service messages, and journal size is already capped in the “Base” setup (Swap, journal and time). Remove the old log file once stdout logging works: sudo rm /var/log/crowdsec-firewall-bouncer*.log.

    3. Create the sandbox drop-in

      sudo mkdir -p /etc/systemd/system/crowdsec-firewall-bouncer.service.d
      sudo nano /etc/systemd/system/crowdsec-firewall-bouncer.service.d/sandbox.conf

      Use the Copy button above the file to grab the contents:

      /etc/systemd/system/crowdsec-firewall-bouncer.service.d/sandbox.conf
      [Service]
      # Файлы: всё только для чтения, /home и чужой /tmp не видно
      ProtectSystem=strict
      ProtectHome=yes
      PrivateTmp=yes
      PrivateDevices=yes

      [Service] uses the same directives as a unit file; systemd merges them onto the packaged unit. strict mounts the whole filesystem read-only except /dev, /proc, and /sys — the lines below lock those down. ProtectHome gives empty /home and /root, PrivateTmp gives a private /tmp, and PrivateDevices leaves only null, zero, random, and similar nodes in /dev. No write exceptions are needed because logs now go to the journal.

      # Ядро и /proc: ничего не меняет и не читает
      ProtectKernelTunables=yes
      ProtectKernelModules=yes
      ProtectKernelLogs=yes
      ProtectControlGroups=yes
      ProtectClock=yes
      ProtectHostname=yes
      ProtectProc=invisible
      ProcSubset=pid

      Kernel surface: /proc/sys is read-only, modules cannot be loaded, the kernel log is hidden, cgroups cannot be modified, and the clock and hostname cannot be changed. /proc shows only the service’s own processes. The bouncer needs none of this.

      # Права root: из всех — только CAP_NET_ADMIN для nftables
      NoNewPrivileges=yes
      CapabilityBoundingSet=CAP_NET_ADMIN
      RestrictSUIDSGID=yes
      Key part

      Out of 41 root capabilities, only CAP_NET_ADMIN remains — enough to modify network settings, including nftables tables. Without it, the bouncer crashes on startup with netlink receive: operation not permitted. NoNewPrivileges stops child processes from gaining privileges (for example via sudo); RestrictSUIDSGID blocks creating setuid/setgid files.

      # Сеть: IP — до LAPI, netlink — nftables, unix — systemd
      RestrictAddressFamilies=AF_INET AF_INET6 AF_NETLINK AF_UNIX
      IPAddressDeny=any
      IPAddressAllow=localhost
      Key part

      Sockets are limited to the three families from the table above. IPAddressDeny=any plus IPAddressAllow=localhost restricts network traffic to 127.0.0.0/8 and ::1, where the containerized LAPI listens on 127.0.0.1:8080. If LAPI runs on another host, allow its IP instead: IPAddressAllow=10.0.0.5.

      # Системные вызовы — обычные для службы
      SystemCallArchitectures=native
      SystemCallFilter=@system-service
      SystemCallFilter=~@privileged @resources
      LockPersonality=yes
      MemoryDenyWriteExecute=yes
      RestrictRealtime=yes
      RestrictNamespaces=yes
      UMask=0077

      @system-service is systemd’s baseline syscall set for regular services; the second line subtracts privileged calls (switching users, loading modules, rebooting) and resource-limit changes. MemoryDenyWriteExecute forbids memory pages that are writable and executable at the same time; RestrictNamespaces prevents creating namespaces. The bouncer is written in Go and runs fine under these limits.

    4. Apply the drop-in

      sudo systemctl daemon-reload
      sudo systemctl restart crowdsec-firewall-bouncer
      systemctl status crowdsec-firewall-bouncer --no-pager | head -5
      #     Drop-In: /etc/systemd/system/crowdsec-firewall-bouncer.service.d
      #              └─sandbox.conf
      #      Active: active (running) since …

      Seeing Drop-In with sandbox.conf confirms systemd picked up the file. Without daemon-reload, that line is missing and systemctl reminds you: changed on disk. Run 'systemctl daemon-reload'. If status stays on activating or failed instead of active (running), the first level=fatal line in journalctl -u crowdsec-firewall-bouncer tells you what was blocked (“If it doesn’t work”).

    5. Score after

      systemd-analyze security crowdsec-firewall-bouncer --no-pager | grep -E '^✗|Overall'
      # ✗ User=/DynamicUser=                       Service runs as root user
      # ✗ RestrictAddressFamilies=~AF_NETLINK      Service may allocate netlink sockets
      # ✗ CapabilityBoundingSet=~CAP_NET_ADMIN     Service has network configuration privileges
      # ✗ PrivateNetwork=                          Service has access to the host's network
      # ✗ PrivateUsers=                            Service has access to other users
      # …
      # → Overall exposure level for crowdsec-firewall-bouncer.service: 1.7 OK :-)

      Ten ✗ lines remain, and every one is required for the bouncer to work: root with CAP_NET_ADMIN, the host network, netlink, and a UNIX socket. PrivateNetwork=yes cuts the service off from LAPI, and PrivateUsers=yes strips host nftables rights — both break startup. You cannot drive the score to zero, and there is no reason to: it measures what a service is blocked from doing, not how exploitable it is.

    Sandboxing another service

    The same workflow applies to any service. First list what it needs: where it writes, which addresses it connects to, and which root capabilities it requires. Then enable everything from the drop-in above except what it needs, and restart. The service logs whatever is missing: operation not permitted points to a capability, address family not supported to a socket family, and read-only file system to a write path — open only that directory with ReadWritePaths=, not all of /var. The ✗ lines in systemd-analyze security show what else you can strip.

    How to remove

    sudo rm -r /etc/systemd/system/crowdsec-firewall-bouncer.service.d
    sudo systemctl daemon-reload && sudo systemctl restart crowdsec-firewall-bouncer

    Logs stay in the journal. Set log_mode: file in the bouncer config and restart again if you want file logging back.

    If it doesn’t work

    Bouncer fails to start; journal shows nftables: failed to flush conn: netlink receive: operation not permitted

    Cause
    CapabilityBoundingSet is missing CAP_NET_ADMIN. The same error happens if you add PrivateUsers=yes: the service’s root maps to an unprivileged user inside the namespace and loses host nftables rights.
    Fix
    Set CapabilityBoundingSet=CAP_NET_ADMIN, remove PrivateUsers, then run daemon-reload and restart.

    Bouncer fails to start; journal shows nftables: failed to flush conn: socket: address family not supported by protocol

    Cause
    RestrictAddressFamilies is missing AF_NETLINK: the bouncer updates nftables rules over a netlink socket.
    Fix
    Put AF_NETLINK back in the line.

    systemctl restart hangs for 90 seconds and ends with start operation timed out

    Cause
    RestrictAddressFamilies is missing AF_UNIX. The service uses Type=notify and signals readiness to systemd over /run/systemd/notify; the journal logs Failed to notify systemd: … address family not supported by protocol. systemd waits 90 s and kills it.
    Fix
    Put AF_UNIX back in the line.

    Bouncer cycles between active and activating; journal shows dial tcp 127.0.0.1:8080: i/o timeout

    Cause
    The LAPI address is missing from IPAddressAllow, so packets to it are dropped. After about 20 s the bouncer exits, systemd restarts it 10 s later, and the loop repeats.
    Fix
    Add the address from api_url to IPAddressAllow. For LAPI on the same server, localhost is enough.

    Journal shows dial tcp 127.0.0.1:8080: connect: connection refused, even though CrowdSec is running

    Cause
    PrivateNetwork=yes was added to the file: the service gets an isolated network namespace with its own lo, and LAPI is not there.
    Fix
    Remove PrivateNetwork: the bouncer needs the host network.

    Journal is flooded with Failed to write to log, can't rename log file … read-only file system

    Cause
    The bouncer writes logs to a file (log_mode: file), and ProtectSystem=strict made /var/log read-only. Bans still apply; only the log is lost.
    Fix
    Switch to log_mode: stdout in the bouncer config (step 2) and restart.

    Edited sandbox.conf, and nothing changed

    Cause
    systemd has not reloaded the file: systemctl prints Warning: The unit file, source configuration file or drop-ins of crowdsec-firewall-bouncer.service changed on disk.
    Fix
    Run sudo systemctl daemon-reload, then restart.

    How to check

    Inspect capabilities and the filesystem from inside the service: nsenter --mount runs a command using the bouncer’s mount view.

    P=$(pidof crowdsec-firewall-bouncer)
    sudo grep CapBnd /proc/$P/status
    # CapBnd:	0000000000001000
    capsh --decode=0000000000001000
    # 0x0000000000001000=cap_net_admin
    sudo nsenter --target $P --mount touch /etc/sandbox-test
    # touch: cannot touch '/etc/sandbox-test': Read-only file system
    sudo nsenter --target $P --mount ls /home
    # (empty)

    Without the sandbox, CapBnd is 000001ffffffffff, touch succeeds, and ls /home lists user directories.

    Verify banning in action by adding a decision for a documentation IP; within 10 s it appears in the bouncer’s nftables table:

    sudo docker exec crowdsec cscli decisions add --ip 198.51.100.7 --duration 2m --reason test
    sleep 12; sudo nft list table ip crowdsec | grep -c 198.51.100.7
    # 1
    sudo docker exec crowdsec cscli decisions delete --ip 198.51.100.7

    For a full end-to-end ban test from your phone, see Test your server’s protection by action.