剪报:systemd unit 常用最小权限隔离参数
平时写自用守护进程的 .service 文件总是只写三五行 ExecStart 就完事。今天读了一篇讲 systemd 内置沙箱的文章,顺手运行 systemd-analyze security 扫了一遍机器上的服务,把几个代价最低、兼容性最好的选项记下来。
ProtectSystem=strict mounts the entire file system hierarchy read-only, except for the API file systems /dev, /proc, and /sys. Use ReadWritePaths= to whitelist specific directories.
[Service]
User=appuser
Group=appuser
NoNewPrivileges=yes
PrivateTmp=yes
ProtectHome=yes
ProtectSystem=strict
ReadWritePaths=/var/lib/myservice /var/log/myservice
ProtectKernelTunables=yes
ProtectControlGroups=yes
RestrictSUIDSGID=yes
需要注意两个容易踩坑的地方:一是如果程序要绑定 1024 以下端口,不要再给二进制文件硬塞 root,而是配 AmbientCapabilities=CAP_NET_BIND_SERVICE;二是开了 PrivateTmp=yes 后,同机其他进程没法通过 /tmp/*.sock 跟它通信,Unix socket 得放到 /run/myservice/(配合 RuntimeDirectory=myservice 自动建目录)。