SELinux – How to Create SELinux Context for Systemd Script

fedoraredhatrhel8selinuxsystemd

I'm trying to create a systemd service that executes a custom script I wrote. It is just a backup script that I am using with a systemd timer. When I try to execute something simple in the systemd file like "/usr/bin/free" or something like that, it works perfectly. However when I try to execute my script "/root/scripts/mybackupscript.sh", it fails with:

Main process exited, code=exited, status=203/EXEC

If I set selinux to permissive, it will start my script with no problem.

So I know that selinux is restricting systemd from executing my script. But I don't know how to use selinux. How do I create an selinux context to allow systemd to execute my script?

Example:
This systemd file runs no problem:

[Unit]
Description=Logs system statistics to the systemd journal
Wants=myMonitor.timer

[Service]
Type=oneshot
ExecStart=/usr/bin/free

[Install]
WantedBy=multi-user.target

But this script fails (unless if I set selinux to permissive, in which case it executes fine):

[Unit]
Description=Logs system statistics to the systemd journal
Wants=myMonitor.timer

[Service]
Type=oneshot
ExecStart=/root/scripts/mybackupscript.sh

[Install]
WantedBy=multi-user.target

Any ideas would be appreciated. Thanks!

Best Answer

Move your script out of the user's home directory. SELinux rightly complains about trying to execute system services located in users' home directories.

Use a more standard location, such as /usr/local/bin:

install -m755 /root/scripts/mybackupscript.sh /usr/local/bin

And of course edit the unit file to match.

ExecStart=/usr/local/bin/mybackupscript.sh
Related Topic