Run Monit as a non-root user on OpenBSD

       282 words, 2 minutes

On OpenBSD, Monit seems to natively run as root ; maybe on other systems too. Anyway, I’d rather have it running as a non-root user. It’s not that difficult to achieve. Here’s how.

Prepare for first run

First of all, simply install the package.

# pkg_add monit</span>

Then set-up the running environnement.

# useradd -c "Monit daemon" -d /var/monit -g =uid -s /sbin/nologin _monit
# vi /etc/login.conf
(...)
monit:\
 :openfiles=512:\
 :tc=daemon:
# cap_mkdb /etc/login.conf
# usermod -L monit _monit

# chown _monit:_monit /etc/monitrc /var/monit

# rcctl set monit user _monit
# rcctl enable monit

Finally, configure Monit and start the daemon.

# vi /etc/monitrc
(...)
set pidfile /var/monit/monit.pid

# rcctl start monit
monit(ok)

Monit will now be able to check various services running as non-root. The only glitch is that it won’t be able to restart any system services. To solve this, we need doas(1) help.

Allow Monit to restart services

OpenBSD folks don’t recommend to restart faulty services automatically. You’d rather solve the software. But there are cases when I still want to restart the service if/when it dies.

Enable the _monit user to start/stop services using doas:

# viĀ /etc/doas.conf
(...)
permit nopass _monit as root cmd "/usr/sbin/rcctl start sshd"
permit nopass _monit as root cmd "/usr/sbin/rcctl stop sshd"

Configure Monit to use doas:

# vi /etc/monitrc
(...)
check process sshd with pidfile "/var/run/sshd.pid"
  start program = "/usr/bin/doas /usr/sbin/rcctl start sshd"
  stop program = "/usr/bin/doas /usr/sbin/rcctl stop sshd"
  if failed port 22 protocol ssh then restart
  if 3 restarts within 5 cycles then exec /home/scripts/monit_SMS.sh
  group server

Note that this configuration allows anyone that gains access to the _monit user and/or the Monit Web interface to restart the configured services.