﻿#! /bin/bash

# NOT TESTED YET 2023/04/04

# set -x

if [ "$UID" -ne "0" ]
then
  echo "You are not root. Exiting.."
  exit 1
fi

apt update && apt -y upgrade
apt install -y openssl

UNIXTIMENOW=$(date +%s)

# CERTIFICATE

mkdir -p /etc/certificate
cd /etc/certificate

if [ -f "private.key" ]
then
  mv private.key private.key.$UNIXTIMENOW
fi

openssl genrsa  -passout pass:foobar -aes128 -out private.key 2048

if [ -f "request.csr" ]
then
  mv request.csr request.csr.$UNIXTIMENOW
fi

SUBJ="/C=EE/ST=Harju/L=Tallinn/O=TPT/OU=T237/CN=ufo.mars/emailAddress=n@n"
openssl req -new -key private.key -passin pass:foobar -out request.csr -subj="$SUBJ"

if [ -f "certificate.crt" ]
then
  mv certificate.crt certificate.crt.$UNIXTIMENOW
fi

openssl x509 -in request.csr -out certificate.crt -req -signkey private.key -days 365  -passin pass:foobar

cd -
```

# PROTOCOL ACTIVATION

SSLPARAMS="/etc/apache2/conf-available/ssl-params.conf"

if [ -f "$SSLPARAMS" ]
then
  mv "$SSLPARAMS" "$SSLPARAMS.$UNIXTIMENOW"
fi

cat << 'BASTA' > "$SSLPARAMS"
SSLCipherSuite EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH
SSLProtocol All -SSLv2 -SSLv3 -TLSv1 -TLSv1.1
SSLHonorCipherOrder On
Header always set X-Frame-Options DENY
Header always set X-Content-Type-Options nosniff
    
# Requires Apache >= 2.4
    
SSLCompression off
SSLUseStapling on
SSLStaplingCache "shmcb:logs/stapling-cache(150000)"

# Requires Apache >= 2.4.11

SSLSessionTickets Off
BASTA

DEFAULTSSL="/etc/apache2/sites-available/default-ssl.conf"

cp "$DEFAULTSSL" "$DEFAULTSSL.$UNIXTIMENOW"

cat << 'BASTA' > "$DEFAULTSSL"
<IfModule mod_ssl.c>
        <VirtualHost _default_:443>
                ServerAdmin nobody@nowhere
                ServerName  ufo.mars
                DocumentRoot /var/www/html
                
                ErrorLog ${APACHE_LOG_DIR}/error.log
                CustomLog ${APACHE_LOG_DIR}/access.log combined

                SSLEngine on

                SSLCertificateFile    /etc/certificate/certificate.crt
                SSLCertificateKeyFile /etc/certificate/private.key
                     
                <FilesMatch "\.(cgi|shtml|phtml|php)$">
                        SSLOptions +StdEnvVars
                </FilesMatch>
    
                <Directory /usr/lib/cgi-bin>
                        SSLOptions +StdEnvVars
                </Directory>
        </VirtualHost>    
</IfModule>
BASTA

sudo a2enmod ssl
sudo a2enmod headers
sudo a2enconf ssl-params
sudo a2ensite default-ssl

# sudo apache2ctl configtest

sudo systemctl restart apache2
