For quite some time I've had a laptop, running stretch, with stunnel4
installed, with a single /etc/stunnel/foo.conf file, and after network
changes (switch WiFi network, fix broken DNS, etc.), I've found that
'systemctl restart stunnel4.service' doesn't actually restart the
stunnel4 process, and that I have to resort to manual 'killall -9
stunnel4'.

Today I decided to look at the state of stunnel and systemd, and I am
now running a setup that works quite well, utilizing systemd socket
activation introduced in stunnel 5.05.  Server is running jessie, with
stunnel4 3:5.30-1~bpo8+1 jessie-backports package, and systemd
215-17+deb8u6 jessie packages.  Clients are running stretch, with
stunnel4 3:5.39-2 and systemd 232-22.  Each host has two services
defined in /etc/stunnel/stunnel.conf, thus the stunnel4.socket unit has
two ListenStream= directives that match the the 'accept' parameters in
the stunnel.conf.

Initially I had thought this setup wouldn't work, I had been worried
that stunnel's systemd socket activation would behave exactly like inetd
activation, wherein the stunnel manual explains that INETD MODE is
basically one-stunnel-daemon-per-port and cannot distinguish multiple
services in a single configuration.  However after review of the source
code and some experimentation I found this is not the case.  The stunnel
daemon will enumerate the services defined in it's config and verify
that an equal number of FD's have been passed via sd_listen_fds.
However there is a caveat that the order of service declaration has to
match the order of ListenStream= directives, but luckily according to
sd_listen_fds(3) "If a daemon receives more than one file descriptor,
they will be passed in the same order as configured in the systemd
socket unit file".

I love it!  stunnel now starts on-demand, rather than at boot up, and
should the need to restart ever arise, 'systemctl stop stunnel4.service'
is reliable.

Furthermore, I added various systemd hardening directives.

Attached are the socket and service files.

-- 
Gerald Turner <gtur...@unzane.com>        Encrypted mail preferred!
OpenPGP: 4096R / CA89 B27A 30FA 66C5 1B80  3858 EC94 2276 FDB8 716D
[Unit]
Description=TLS tunnel for network daemons server socket

[Socket]
ListenStream=53128
ListenStream=58118
NoDelay=yes

[Install]
WantedBy=sockets.target
[Unit]
Description=TLS tunnel for network daemons
After=network.target syslog.target

[Service]
Type=forking
ExecStart=/usr/bin/stunnel4 /etc/stunnel/stunnel.conf
CapabilityBoundingSet=CAP_SETUID CAP_SETGID CAP_SYS_CHROOT
PrivateTmp=yes
PrivateDevices=yes
ProtectSystem=full
ProtectHome=yes
ProtectKernelTunables=yes
ProtectControlGroups=yes
NoNewPrivileges=yes
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
RestrictNamespaces=yes
ProtectKernelModules=yes
MemoryDenyWriteExecute=yes
RestrictRealtime=yes

[Install]
WantedBy=multi-user.target
Also=stunnel4.socket

Attachment: signature.asc
Description: PGP signature

Reply via email to