Systemd

Systemd 服務失敗,退出程式碼狀態 = 203/EXEC

  • August 17, 2021

我正在嘗試創建一個在啟動時執行的服務。該服務是我用 C++ 編寫並編譯的程序,位於我的使用者主目錄中。該程序打開一些 UDP 套接字並處於無限循環中,因此它不會自動退出。我可以手動執行程序,一切都按預期執行,但是當我執行時systemctl start myservice檢查狀態,我發現它沒有執行。以下錯誤結果+其他有用資訊。僅供參考,作業系統是 CentOS Stream。

輸出自systemctl status myservice

myservice.service - my serivce
   Loaded: loaded (/etc/systemd/system/myservice.service; disabled; vendor present: disabled)
   Active: failed (Result: exit-code) since <redacted unnecessary timestamp>
   Process 2101 ExecStart=/home/user/program (code=exited, status=203/EXEC)
 Main PID: 2101 (code=exited, status=203/EXEC)

來自 journalctl 的錯誤消息

myservice.service: Main process exited, code=exited, status=203/EXEC
myservice.service: Failed with result 'exit-code'
myservice.service: Service RestartSec=2s expired, scheduling restart

系統單元文件

[Unit]
Description=my service
After=network.target

[Service]
Type=simple
ExecStart=/home/user/program
User=user
WorkingDirectory=/home/user/
Restart=always
RestartSec=2
KillMode=process

[Install]
WantedBy=multi-user.target

我知道 203 狀態通常意味著文件不存在或沒有適當的權限,所以下面的輸出證明它不是這些問題(希望如此)

輸出自ls -laZ /home/user/program

-rwxrwxrwx. 1 root root unconfined_u:object_r:user_home_t:s0 803168 Aug 14 23:35 /home/user/program

輸出自sestatus

SELinux status: enabled
SELinuxfs mount: /sys/fs/selinux
SELinux root directory /etc/selinux
Loaded policy name: targeted
Current mode: enforcing
Mode from config file: enforcing
Policy MLS status: enabled
Policy deny_unknown status: allowed
Memory protection checking: actual (secure)
Max kernel policy version: 33

輸出自ausearch -ts recent -m avc -i

type=PROCTITLE msg=audit(08/16/2021 20:14:04.216:698) : proctitle=(ster_myservice)
type=SYSCALL msg=audit(08/16/2021 20:14:04.216:698) : arch=x86_64 syscall=execve success=no exit=EACCES(Permission denied) a0=0x5572ff82e7a0 a1=0x5572ff6ff6d0 a2=0x5572ff7f54b0 a3=0x1 items=0 ppid=1 pid=2568 auid=unset uid=user gid=user euid=user suid=user fsuid=user egid=user sgid=user fsgid=user tty=(none) ses=unset comm=(ster_myservice) exe=/usr/lib/systemd/systemd subj=system_u:system_r:init_t:s0 key=(null)
type=AVC msg=audit(08/16/2021 20:14:04.216:698) : avc:  denied  { execute } for  pid=2568 comm=(ster_myservice) name=program dev="dm-2" ino=137 scontext=system_u:system_r:init_t:s0 tcontext=unconfined_u:object_r:user_home_t:s0 tclass=file permissive=0

SELinux 正在阻止您的程序執行:AVC 拒絕狀態type=AVC msg=audit(08/16/2021 20:14:04.216:698) : avc: denied { execute } for pid=2568 comm=(ster_myservice) name=program dev="dm-2" ino=137 scontext=system_u:system_r:init_t:s0 tcontext=unconfined_u:object_r:user_home_t:s0 tclass=file permissive=0

這意味著在init_t程序上下文下執行的 systemd 不允許啟動您的程序,標記為user_home_t.

為了減輕影響,請將您的程序移至標準二進制目錄,例如/usr/local/bin,然後記住重新標記,使用restorecon -Rv /usr/local/bin.

或者,如果您需要程序在主目錄之外執行,請編譯自定義 SELinux 策略模組:

ausearch -m avc -ts recent --comm ster_myservice | audit2allow -a -M ster-myservice
semodule -i ster-myservice.pp

引用自:https://unix.stackexchange.com/questions/664811