systemd 加固 ¶
使用 systemd-run 可以临时运行服务,Timer等系统单元 ¶
#!/bin/bash
[ $UID -ne 0 ] && {
exec sudo "$0" "$@"
exit $?
}
WorkDir=$(cd $(dirname $0);pwd)
APP=wiki-go
pushd $WorkDir
systemctl reset-failed
systemd-run -p User=hsiaotien \
-p WorkingDirectory=$WorkDir \
-p Group=hsiaotien \
-p NoNewPrivileges=yes \
-p ProtectSystem=full \
-p ReadOnlyPaths=/home/hsiaotien \
-p ReadWritePaths=$WorkDir \
-u wiki-go \
./$APP
- 一般要求运行服务的用户为ROOT
- 但服务程序以普通用户运行,User=app/Group=app
- 将系统目录设置为只读
- 仅指定服务需要操作的目录为可写
- NoNewPrivilege=yes, 禁止提权
- 这样设置后,系统暴露值由9.7下降至8.7,能一定程度提升安全性
- 使用 systemd-run 命令运行的临时服务会放到 /run/systemd/transit/*.service 下,使用 systemctl stop xxx.service 后消失
编写 .service 服务文件并运行 ¶
用户服务文件位置:
- ~/.config/systemd/user
系统服务文件位置 - /etc/systemd/system
一个服务文件基本格式如下
[Unit]
Description=Start open webui service
[Service]
User=hsiaotien
Group=hsiaotien
Restart=on-failure
RestartSec=15
ExecStart=/home/hsiaotien/app/openwebui/service.sh
WorkingDirectory=/home/hsiaotien/app/openwebui
ProtectSystem=full
NoNewPrivileges=yes
ReadOnlyPaths=/home/hsiaotien
ReadWritePaths=/home/hsiaotien/app/openwebui
ReadWritePaths=/home/hsiaotien/.cache
ReadWritePaths=/home/hsiaotien/.local
[Install]
WantedBy=default.target
- /[Service/] 节下的很多属性和使用 systemd-run -p 中指定的一样
- 将文件保存到 /etc/systemd/system 下后
- 使用 systemctl daemon-reload 重新读取配置
- 使用 systemctl enable xxx.service 启用服务
- 使用 systemctl start xxx.service 开启服务
- 使用 journalctl -exu xxx.service --no-pager 查看服务日志
- 在用户态下,命令基本一致,但在用户态需要开启
- loginctl enable-linger 启动用户服务的自动运行
- systemctl --user daemon-reload
- systemctl --user enable xxx
- systemctl --user start xxx
- journalctl --user -exu xxx --no-pager
- 用户态有些安全特性是无法使用的,比如 ProtectSystem 等,另外用户态服务文件应放在 ~/.config/systemd/user 下
评论
请登录后发表评论。
暂无评论。成为第一个评论者!