# http://www.stunnel.org/faq/certs.html

# Execute this as root, step by step, do not run it in batch mode!
# Watch out for errors!

# Redhat+CentOS : yum install gcc make openssl-devel
#
# Debian+Ubuntu : apt-get install gcc make libssl-dev

# openssl s_client -help 2>&1 | grep 'use TLS'

# need at least stunnel 5.63 because of TLSv1.2 support
STUNNEL=stunnel-5.65
mkdir -p /opt/src 
cd /opt/src/
wget https://ftp.nluug.nl/pub/networking/stunnel/archive/5.x/$STUNNEL.tar.gz
tar xvf $STUNNEL.tar.gz
cd $STUNNEL
./configure --disable-fips --disable-libwrap --prefix=/opt/$STUNNEL
make
make install
ln -f -s $STUNNEL /opt/stunnel

mkdir /home/fex/etc
cd /home/fex/etc/

# see doc/letsencrypt for creating TLS certificate for HTTPS!

## OLD: create self-signed certificate
## see http://www.infodrom.org/Debian/tips/stunnel.html
#openssl req -new -x509 -days 365 -nodes -out stunnel.pem -keyout stunnel.pem
#dd if=/dev/urandom count=2 | openssl dhparam -rand - 1024 >> stunnel.pem
#openssl x509 -text -in stunnel.pem
#chmod 600 stunnel.pem

cat <<EOD>stunnel.conf
debug = warning
output = /home/fex/spool/stunnel.log
cert = /home/fex/etc/stunnel.pem
;sslVersion = all
sslVersionMin = TLSv1.2
fips = no
TIMEOUTclose = 10
exec = /usr/bin/perl
execargs = perl -T /home/fex/bin/fexsrv stunnel
EOD

chown fex stunnel.conf

cat >/etc/systemd/system/fexs.socket<<EOD
[Unit]
Description=FileEXchange Server HTTPS Socket

[Socket]
ListenStream=443
Accept=yes

[Install]
WantedBy=sockets.target
EOD

# https://www.freedesktop.org/software/systemd/man/latest/systemd.service.html
# If the executable path is prefixed with "-", an exit code of the command 
# normally considered a failure (i.e. non-zero exit status or abnormal exit
# due to signal) is recorded, but has no further effect and is considered 
# equivalent to success.

cat >/etc/systemd/system/fexs@.service<<EOD
[Unit]
Description=FileEXchange Server HTTPS Socket

[Service]
ExecStart=-/opt/stunnel/bin/stunnel /home/fex/etc/stunnel.conf
User=fex
Group=fex
StandardInput=socket
EOD

systemctl enable fexs.socket
systemctl start  fexs.socket
systemctl status fexs.socket

## OLD: use xinetd
#cat <<EOD>/etc/xinetd.d/fexs
## default: on
## description: fex web server with SSL
## note: only possible on port 443!
#service fexs
#{
#        socket_type     = stream
#        wait            = no
#        type            = unlisted
#        protocol        = tcp
#        port            = 443
#        cps             = 10 2
#        user            = fex
#        groups          = yes
#        server          = /opt/$STUNNEL/bin/stunnel
#        server_args     = /home/fex/etc/stunnel.conf
#        nice            = 0
#        disable         = no
#}
#EOD
#
## Hint: on some systems stunnel works not well with xinetd
##       you can also run stunnel without xinetd, in server daemon mode
#/etc/init.d/xinetd restart

# To enforce https, add to fex.ph:
# $force_https = 1;
